@dev-anywhere/relay 0.9.2 → 0.9.3

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.
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/jmuxer.min-BcaOPF7j.js","assets/__vite-browser-external-D7Ct-6yo.js"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/jmuxer.min-CqkQ8MXd.js","assets/__vite-browser-external-D7Ct-6yo.js"])))=>i.map(i=>d[i]);
2
2
  var K9=Object.defineProperty;var G9=(e,t,n)=>t in e?K9(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var je=(e,t,n)=>G9(e,typeof t!="symbol"?t+"":t,n);function X9(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in e)){const s=Object.getOwnPropertyDescriptor(r,i);s&&Object.defineProperty(e,i,s.get?s:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const o of s.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&r(o)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();function Vp(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function JOe(e){if(Object.prototype.hasOwnProperty.call(e,"__esModule"))return e;var t=e.default;if(typeof t=="function"){var n=function r(){return this instanceof r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return e[r]}})}),n}var tx={exports:{}},dh={};/**
3
3
  * @license React
4
4
  * react-jsx-runtime.production.js
@@ -522,7 +522,7 @@ Please change the parent <Route path="${x}"> to <Route path="${x==="/"?"*":`${x}
522
522
 
523
523
  `)}g.write("payload.value = newResult;"),g.write("return payload;");const k=g.compile();return(N,P)=>k(y,N,P)};let s;const o=kp,l=!Oz.jitless,d=l&&fG.value,f=t.catchall;let p;e._zod.parse=(y,g)=>{p??(p=r.value);const _=y.value;return o(_)?l&&d&&(g==null?void 0:g.async)===!1&&g.jitless!==!0?(s||(s=i(t.shape)),y=s(y,g),f?Zz([],_,y,g,p,e):y):n(y,g):(y.issues.push({expected:"object",code:"invalid_type",input:_,inst:e}),y)}});function sP(e,t,n,r){for(const s of e)if(s.issues.length===0)return t.value=s.value,t;const i=e.filter(s=>!Sd(s));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:e.map(s=>s.issues.map(o=>ql(o,r,Wl())))}),t)}const Qz=Qe("$ZodUnion",(e,t)=>{Br.init(e,t),ar(e._zod,"optin",()=>t.options.some(i=>i._zod.optin==="optional")?"optional":void 0),ar(e._zod,"optout",()=>t.options.some(i=>i._zod.optout==="optional")?"optional":void 0),ar(e._zod,"values",()=>{if(t.options.every(i=>i._zod.values))return new Set(t.options.flatMap(i=>Array.from(i._zod.values)))}),ar(e._zod,"pattern",()=>{if(t.options.every(i=>i._zod.pattern)){const i=t.options.map(s=>s._zod.pattern);return new RegExp(`^(${i.map(s=>hC(s.source)).join("|")})$`)}});const n=t.options.length===1,r=t.options[0]._zod.run;e._zod.parse=(i,s)=>{if(n)return r(i,s);let o=!1;const l=[];for(const u of t.options){const d=u._zod.run({value:i.value,issues:[]},s);if(d instanceof Promise)l.push(d),o=!0;else{if(d.issues.length===0)return d;l.push(d)}}return o?Promise.all(l).then(u=>sP(u,i,e,s)):sP(l,i,e,s)}}),QX=Qe("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,Qz.init(e,t);const n=e._zod.parse;ar(e._zod,"propValues",()=>{const i={};for(const s of t.options){const o=s._zod.propValues;if(!o||Object.keys(o).length===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(s)}"`);for(const[l,u]of Object.entries(o)){i[l]||(i[l]=new Set);for(const d of u)i[l].add(d)}}return i});const r=Gy(()=>{var o;const i=t.options,s=new Map;for(const l of i){const u=(o=l._zod.propValues)==null?void 0:o[t.discriminator];if(!u||u.size===0)throw new Error(`Invalid discriminated union option at index "${t.options.indexOf(l)}"`);for(const d of u){if(s.has(d))throw new Error(`Duplicate discriminator value "${String(d)}"`);s.set(d,l)}}return s});e._zod.parse=(i,s)=>{const o=i.value;if(!kp(o))return i.issues.push({code:"invalid_type",expected:"object",input:o,inst:e}),i;const l=r.value.get(o==null?void 0:o[t.discriminator]);return l?l._zod.run(i,s):t.unionFallback?n(i,s):(i.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:t.discriminator,input:o,path:[t.discriminator],inst:e}),i)}}),JX=Qe("$ZodIntersection",(e,t)=>{Br.init(e,t),e._zod.parse=(n,r)=>{const i=n.value,s=t.left._zod.run({value:i,issues:[]},r),o=t.right._zod.run({value:i,issues:[]},r);return s instanceof Promise||o instanceof Promise?Promise.all([s,o]).then(([u,d])=>oP(n,u,d)):oP(n,s,o)}});function MS(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if($d(e)&&$d(t)){const n=Object.keys(t),r=Object.keys(e).filter(s=>n.indexOf(s)!==-1),i={...e,...t};for(const s of r){const o=MS(e[s],t[s]);if(!o.valid)return{valid:!1,mergeErrorPath:[s,...o.mergeErrorPath]};i[s]=o.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<e.length;r++){const i=e[r],s=t[r],o=MS(i,s);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function oP(e,t,n){const r=new Map;let i;for(const l of t.issues)if(l.code==="unrecognized_keys"){i??(i=l);for(const u of l.keys)r.has(u)||r.set(u,{}),r.get(u).l=!0}else e.issues.push(l);for(const l of n.issues)if(l.code==="unrecognized_keys")for(const u of l.keys)r.has(u)||r.set(u,{}),r.get(u).r=!0;else e.issues.push(l);const s=[...r].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(s.length&&i&&e.issues.push({...i,keys:s}),Sd(e))return e;const o=MS(t.value,n.value);if(!o.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(o.mergeErrorPath)}`);return e.value=o.data,e}const eZ=Qe("$ZodRecord",(e,t)=>{Br.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!$d(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:e}),n;const s=[],o=t.keyType._zod.values;if(o){n.value={};const l=new Set;for(const d of o)if(typeof d=="string"||typeof d=="number"||typeof d=="symbol"){l.add(typeof d=="number"?d.toString():d);const f=t.valueType._zod.run({value:i[d],issues:[]},r);f instanceof Promise?s.push(f.then(p=>{p.issues.length&&n.issues.push(...Ed(d,p.issues)),n.value[d]=p.value})):(f.issues.length&&n.issues.push(...Ed(d,f.issues)),n.value[d]=f.value)}let u;for(const d in i)l.has(d)||(u=u??[],u.push(d));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:e,keys:u})}else{n.value={};for(const l of Reflect.ownKeys(i)){if(l==="__proto__")continue;let u=t.keyType._zod.run({value:l,issues:[]},r);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof l=="string"&&Wz.test(l)&&u.issues.length){const p=t.keyType._zod.run({value:Number(l),issues:[]},r);if(p instanceof Promise)throw new Error("Async schemas not supported in object keys currently");p.issues.length===0&&(u=p)}if(u.issues.length){t.mode==="loose"?n.value[l]=i[l]:n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(p=>ql(p,r,Wl())),input:l,path:[l],inst:e});continue}const f=t.valueType._zod.run({value:i[l],issues:[]},r);f instanceof Promise?s.push(f.then(p=>{p.issues.length&&n.issues.push(...Ed(l,p.issues)),n.value[u.value]=p.value})):(f.issues.length&&n.issues.push(...Ed(l,f.issues)),n.value[u.value]=f.value)}}return s.length?Promise.all(s).then(()=>n):n}}),tZ=Qe("$ZodEnum",(e,t)=>{Br.init(e,t);const n=Lz(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>hG.has(typeof i)).map(i=>typeof i=="string"?Hd(i):i.toString()).join("|")})$`),e._zod.parse=(i,s)=>{const o=i.value;return r.has(o)||i.issues.push({code:"invalid_value",values:n,input:o,inst:e}),i}}),nZ=Qe("$ZodLiteral",(e,t)=>{if(Br.init(e,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);e._zod.values=n,e._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?Hd(r):r?Hd(r.toString()):String(r)).join("|")})$`),e._zod.parse=(r,i)=>{const s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:t.values,input:s,inst:e}),r}}),rZ=Qe("$ZodTransform",(e,t)=>{Br.init(e,t),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Iz(e.constructor.name);const i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(o=>(n.value=o,n));if(i instanceof Promise)throw new Pd;return n.value=i,n}});function aP(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const Jz=Qe("$ZodOptional",(e,t)=>{Br.init(e,t),e._zod.optin="optional",e._zod.optout="optional",ar(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),ar(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${hC(n.source)})?$`):void 0}),e._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>aP(s,n.value)):aP(i,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),iZ=Qe("$ZodExactOptional",(e,t)=>{Jz.init(e,t),ar(e._zod,"values",()=>t.innerType._zod.values),ar(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),sZ=Qe("$ZodNullable",(e,t)=>{Br.init(e,t),ar(e._zod,"optin",()=>t.innerType._zod.optin),ar(e._zod,"optout",()=>t.innerType._zod.optout),ar(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${hC(n.source)}|null)$`):void 0}),ar(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),oZ=Qe("$ZodDefault",(e,t)=>{Br.init(e,t),e._zod.optin="optional",ar(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>lP(s,t)):lP(i,t)}});function lP(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const aZ=Qe("$ZodPrefault",(e,t)=>{Br.init(e,t),e._zod.optin="optional",ar(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),lZ=Qe("$ZodNonOptional",(e,t)=>{Br.init(e,t),ar(e._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),e._zod.parse=(n,r)=>{const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>cP(s,e)):cP(i,e)}});function cP(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t}),e}const cZ=Qe("$ZodCatch",(e,t)=>{Br.init(e,t),ar(e._zod,"optin",()=>t.innerType._zod.optin),ar(e._zod,"optout",()=>t.innerType._zod.optout),ar(e._zod,"values",()=>t.innerType._zod.values),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>(n.value=s.value,s.issues.length&&(n.value=t.catchValue({...n,error:{issues:s.issues.map(o=>ql(o,r,Wl()))},input:n.value}),n.issues=[]),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(s=>ql(s,r,Wl()))},input:n.value}),n.issues=[]),n)}}),uZ=Qe("$ZodPipe",(e,t)=>{Br.init(e,t),ar(e._zod,"values",()=>t.in._zod.values),ar(e._zod,"optin",()=>t.in._zod.optin),ar(e._zod,"optout",()=>t.out._zod.optout),ar(e._zod,"propValues",()=>t.in._zod.propValues),e._zod.parse=(n,r)=>{if(r.direction==="backward"){const s=t.out._zod.run(n,r);return s instanceof Promise?s.then(o=>Hg(o,t.in,r)):Hg(s,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(s=>Hg(s,t.out,r)):Hg(i,t.out,r)}});function Hg(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const dZ=Qe("$ZodReadonly",(e,t)=>{Br.init(e,t),ar(e._zod,"propValues",()=>t.innerType._zod.propValues),ar(e._zod,"values",()=>t.innerType._zod.values),ar(e._zod,"optin",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),ar(e._zod,"optout",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.optout}),e._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(uP):uP(i)}});function uP(e){return e.value=Object.freeze(e.value),e}const fZ=Qe("$ZodCustom",(e,t)=>{xs.init(e,t),Br.init(e,t),e._zod.parse=(n,r)=>n,e._zod.check=n=>{const r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(s=>dP(s,n,r,e));dP(i,n,r,e)}});function dP(e,t,n,r){if(!e){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),t.issues.push(Tp(i))}}var fP;class hZ{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(t)};return Object.keys(i).length?i:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function pZ(){return new hZ}(fP=globalThis).__zod_globalRegistry??(fP.__zod_globalRegistry=pZ());const Vh=globalThis.__zod_globalRegistry;function mZ(e,t){return new e({type:"string",...Qt(t)})}function gZ(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Qt(t)})}function hP(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Qt(t)})}function vZ(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Qt(t)})}function yZ(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Qt(t)})}function bZ(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Qt(t)})}function _Z(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Qt(t)})}function wZ(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Qt(t)})}function xZ(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Qt(t)})}function SZ(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Qt(t)})}function EZ(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Qt(t)})}function CZ(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Qt(t)})}function kZ(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Qt(t)})}function TZ(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Qt(t)})}function RZ(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Qt(t)})}function AZ(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Qt(t)})}function NZ(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Qt(t)})}function MZ(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Qt(t)})}function PZ(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Qt(t)})}function IZ(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Qt(t)})}function OZ(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Qt(t)})}function LZ(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Qt(t)})}function DZ(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Qt(t)})}function BZ(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Qt(t)})}function zZ(e,t){return new e({type:"string",format:"date",check:"string_format",...Qt(t)})}function jZ(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Qt(t)})}function FZ(e,t){return new e({type:"string",format:"duration",check:"string_format",...Qt(t)})}function $Z(e,t){return new e({type:"number",checks:[],...Qt(t)})}function HZ(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Qt(t)})}function UZ(e,t){return new e({type:"boolean",...Qt(t)})}function WZ(e){return new e({type:"unknown"})}function qZ(e,t){return new e({type:"never",...Qt(t)})}function pP(e,t){return new Vz({check:"less_than",...Qt(t),value:e,inclusive:!1})}function yx(e,t){return new Vz({check:"less_than",...Qt(t),value:e,inclusive:!0})}function mP(e,t){return new Yz({check:"greater_than",...Qt(t),value:e,inclusive:!1})}function bx(e,t){return new Yz({check:"greater_than",...Qt(t),value:e,inclusive:!0})}function gP(e,t){return new oX({check:"multiple_of",...Qt(t),value:e})}function ej(e,t){return new lX({check:"max_length",...Qt(t),maximum:e})}function hy(e,t){return new cX({check:"min_length",...Qt(t),minimum:e})}function tj(e,t){return new uX({check:"length_equals",...Qt(t),length:e})}function VZ(e,t){return new dX({check:"string_format",format:"regex",...Qt(t),pattern:e})}function YZ(e){return new fX({check:"string_format",format:"lowercase",...Qt(e)})}function KZ(e){return new hX({check:"string_format",format:"uppercase",...Qt(e)})}function GZ(e,t){return new pX({check:"string_format",format:"includes",...Qt(t),includes:e})}function XZ(e,t){return new mX({check:"string_format",format:"starts_with",...Qt(t),prefix:e})}function ZZ(e,t){return new gX({check:"string_format",format:"ends_with",...Qt(t),suffix:e})}function nf(e){return new vX({check:"overwrite",tx:e})}function QZ(e){return nf(t=>t.normalize(e))}function JZ(){return nf(e=>e.trim())}function eQ(){return nf(e=>e.toLowerCase())}function tQ(){return nf(e=>e.toUpperCase())}function nQ(){return nf(e=>dG(e))}function rQ(e,t,n){return new e({type:"array",element:t,...Qt(n)})}function iQ(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Qt(n)})}function sQ(e){const t=oQ(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Tp(r,n.value,t._zod.def));else{const i=r;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!t._zod.def.abort),n.issues.push(Tp(i))}},e(n.value,n)));return t}function oQ(e,t){const n=new xs({check:"custom",...Qt(t)});return n._zod.check=e,n}function nj(e){let t=(e==null?void 0:e.target)??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:e.processors??{},metadataRegistry:(e==null?void 0:e.metadata)??Vh,target:t,unrepresentable:(e==null?void 0:e.unrepresentable)??"throw",override:(e==null?void 0:e.override)??(()=>{}),io:(e==null?void 0:e.io)??"output",counter:0,seen:new Map,cycles:(e==null?void 0:e.cycles)??"ref",reused:(e==null?void 0:e.reused)??"inline",external:(e==null?void 0:e.external)??void 0}}function si(e,t,n={path:[],schemaPath:[]}){var f,p;var r;const i=e._zod.def,s=t.seen.get(e);if(s)return s.count++,n.schemaPath.includes(e)&&(s.cycle=n.path),s.schema;const o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o);const l=(p=(f=e._zod).toJSONSchema)==null?void 0:p.call(f);if(l)o.schema=l;else{const y={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,y);else{const _=o.schema,w=t.processors[i.type];if(!w)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);w(e,t,_,y)}const g=e._zod.parent;g&&(o.ref||(o.ref=g),si(g,t,y),t.seen.get(g).isParent=!0)}const u=t.metadataRegistry.get(e);return u&&Object.assign(o.schema,u),t.io==="input"&&Xi(e)&&(delete o.schema.examples,delete o.schema.default),t.io==="input"&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function rj(e,t){var o,l,u,d;const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const f of e.seen.entries()){const p=(o=e.metadataRegistry.get(f[0]))==null?void 0:o.id;if(p){const y=r.get(p);if(y&&y!==f[0])throw new Error(`Duplicate schema id "${p}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(p,f[0])}}const i=f=>{var w;const p=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){const x=(w=e.external.registry.get(f[0]))==null?void 0:w.id,S=e.external.uri??(T=>T);if(x)return{ref:S(x)};const k=f[1].defId??f[1].schema.id??`schema${e.counter++}`;return f[1].defId=k,{defId:k,ref:`${S("__shared")}#/${p}/${k}`}}if(f[1]===n)return{ref:"#"};const g=`#/${p}/`,_=f[1].schema.id??`__schema${e.counter++}`;return{defId:_,ref:g+_}},s=f=>{if(f[1].schema.$ref)return;const p=f[1],{ref:y,defId:g}=i(f);p.def={...p.schema},g&&(p.defId=g);const _=p.schema;for(const w in _)delete _[w];_.$ref=y};if(e.cycles==="throw")for(const f of e.seen.entries()){const p=f[1];if(p.cycle)throw new Error(`Cycle detected: #/${(l=p.cycle)==null?void 0:l.join("/")}/<root>
524
524
 
525
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const f of e.seen.entries()){const p=f[1];if(t===f[0]){s(f);continue}if(e.external){const g=(u=e.external.registry.get(f[0]))==null?void 0:u.id;if(t!==f[0]&&g){s(f);continue}}if((d=e.metadataRegistry.get(f[0]))==null?void 0:d.id){s(f);continue}if(p.cycle){s(f);continue}if(p.count>1&&e.reused==="ref"){s(f);continue}}}function ij(e,t){var o,l,u;const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=d=>{const f=e.seen.get(d);if(f.ref===null)return;const p=f.def??f.schema,y={...p},g=f.ref;if(f.ref=null,g){r(g);const w=e.seen.get(g),x=w.schema;if(x.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(p.allOf=p.allOf??[],p.allOf.push(x)):Object.assign(p,x),Object.assign(p,y),d._zod.parent===g)for(const k in p)k==="$ref"||k==="allOf"||k in y||delete p[k];if(x.$ref&&w.def)for(const k in p)k==="$ref"||k==="allOf"||k in w.def&&JSON.stringify(p[k])===JSON.stringify(w.def[k])&&delete p[k]}const _=d._zod.parent;if(_&&_!==g){r(_);const w=e.seen.get(_);if(w!=null&&w.schema.$ref&&(p.$ref=w.schema.$ref,w.def))for(const x in p)x==="$ref"||x==="allOf"||x in w.def&&JSON.stringify(p[x])===JSON.stringify(w.def[x])&&delete p[x]}e.override({zodSchema:d,jsonSchema:p,path:f.path??[]})};for(const d of[...e.seen.entries()].reverse())r(d[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,(o=e.external)!=null&&o.uri){const d=(l=e.external.registry.get(t))==null?void 0:l.id;if(!d)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(d)}Object.assign(i,n.def??n.schema);const s=((u=e.external)==null?void 0:u.defs)??{};for(const d of e.seen.entries()){const f=d[1];f.def&&f.defId&&(s[f.defId]=f.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?i.$defs=s:i.definitions=s);try{const d=JSON.parse(JSON.stringify(i));return Object.defineProperty(d,"~standard",{value:{...t["~standard"],jsonSchema:{input:py(t,"input",e.processors),output:py(t,"output",e.processors)}},enumerable:!1,writable:!1}),d}catch{throw new Error("Error converting schema to JSON.")}}function Xi(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Xi(r.element,n);if(r.type==="set")return Xi(r.valueType,n);if(r.type==="lazy")return Xi(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Xi(r.innerType,n);if(r.type==="intersection")return Xi(r.left,n)||Xi(r.right,n);if(r.type==="record"||r.type==="map")return Xi(r.keyType,n)||Xi(r.valueType,n);if(r.type==="pipe")return Xi(r.in,n)||Xi(r.out,n);if(r.type==="object"){for(const i in r.shape)if(Xi(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(Xi(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(Xi(i,n))return!0;return!!(r.rest&&Xi(r.rest,n))}return!1}const aQ=(e,t={})=>n=>{const r=nj({...n,processors:t});return si(e,r),rj(r,e),ij(r,e)},py=(e,t,n={})=>r=>{const{libraryOptions:i,target:s}=r??{},o=nj({...i??{},target:s,io:t,processors:n});return si(e,o),rj(o,e),ij(o,e)},lQ={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},cQ=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:s,maximum:o,format:l,patterns:u,contentEncoding:d}=e._zod.bag;if(typeof s=="number"&&(i.minLength=s),typeof o=="number"&&(i.maxLength=o),l&&(i.format=lQ[l]??l,i.format===""&&delete i.format,l==="time"&&delete i.format),d&&(i.contentEncoding=d),u&&u.size>0){const f=[...u];f.length===1?i.pattern=f[0].source:f.length>1&&(i.allOf=[...f.map(p=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},uQ=(e,t,n,r)=>{const i=n,{minimum:s,maximum:o,format:l,multipleOf:u,exclusiveMaximum:d,exclusiveMinimum:f}=e._zod.bag;typeof l=="string"&&l.includes("int")?i.type="integer":i.type="number",typeof f=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.minimum=f,i.exclusiveMinimum=!0):i.exclusiveMinimum=f),typeof s=="number"&&(i.minimum=s,typeof f=="number"&&t.target!=="draft-04"&&(f>=s?delete i.minimum:delete i.exclusiveMinimum)),typeof d=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.maximum=d,i.exclusiveMaximum=!0):i.exclusiveMaximum=d),typeof o=="number"&&(i.maximum=o,typeof d=="number"&&t.target!=="draft-04"&&(d<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof u=="number"&&(i.multipleOf=u)},dQ=(e,t,n,r)=>{n.type="boolean"},fQ=(e,t,n,r)=>{n.not={}},hQ=(e,t,n,r)=>{},pQ=(e,t,n,r)=>{const i=e._zod.def,s=Lz(i.entries);s.every(o=>typeof o=="number")&&(n.type="number"),s.every(o=>typeof o=="string")&&(n.type="string"),n.enum=s},mQ=(e,t,n,r)=>{const i=e._zod.def,s=[];for(const o of i.values)if(o===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(o))}else s.push(o);if(s.length!==0)if(s.length===1){const o=s[0];n.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[o]:n.const=o}else s.every(o=>typeof o=="number")&&(n.type="number"),s.every(o=>typeof o=="string")&&(n.type="string"),s.every(o=>typeof o=="boolean")&&(n.type="boolean"),s.every(o=>o===null)&&(n.type="null"),n.enum=s},gQ=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},vQ=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},yQ=(e,t,n,r)=>{const i=n,s=e._zod.def,{minimum:o,maximum:l}=e._zod.bag;typeof o=="number"&&(i.minItems=o),typeof l=="number"&&(i.maxItems=l),i.type="array",i.items=si(s.element,t,{...r,path:[...r.path,"items"]})},bQ=(e,t,n,r)=>{var d;const i=n,s=e._zod.def;i.type="object",i.properties={};const o=s.shape;for(const f in o)i.properties[f]=si(o[f],t,{...r,path:[...r.path,"properties",f]});const l=new Set(Object.keys(o)),u=new Set([...l].filter(f=>{const p=s.shape[f]._zod;return t.io==="input"?p.optin===void 0:p.optout===void 0}));u.size>0&&(i.required=Array.from(u)),((d=s.catchall)==null?void 0:d._zod.def.type)==="never"?i.additionalProperties=!1:s.catchall?s.catchall&&(i.additionalProperties=si(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},_Q=(e,t,n,r)=>{const i=e._zod.def,s=i.inclusive===!1,o=i.options.map((l,u)=>si(l,t,{...r,path:[...r.path,s?"oneOf":"anyOf",u]}));s?n.oneOf=o:n.anyOf=o},wQ=(e,t,n,r)=>{const i=e._zod.def,s=si(i.left,t,{...r,path:[...r.path,"allOf",0]}),o=si(i.right,t,{...r,path:[...r.path,"allOf",1]}),l=d=>"allOf"in d&&Object.keys(d).length===1,u=[...l(s)?s.allOf:[s],...l(o)?o.allOf:[o]];n.allOf=u},xQ=(e,t,n,r)=>{const i=n,s=e._zod.def;i.type="object";const o=s.keyType,l=o._zod.bag,u=l==null?void 0:l.patterns;if(s.mode==="loose"&&u&&u.size>0){const f=si(s.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(const p of u)i.patternProperties[p.source]=f}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(i.propertyNames=si(s.keyType,t,{...r,path:[...r.path,"propertyNames"]})),i.additionalProperties=si(s.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const d=o._zod.values;if(d){const f=[...d].filter(p=>typeof p=="string"||typeof p=="number");f.length>0&&(i.required=f)}},SQ=(e,t,n,r)=>{const i=e._zod.def,s=si(i.innerType,t,r),o=t.seen.get(e);t.target==="openapi-3.0"?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},EQ=(e,t,n,r)=>{const i=e._zod.def;si(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType},CQ=(e,t,n,r)=>{const i=e._zod.def;si(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},kQ=(e,t,n,r)=>{const i=e._zod.def;si(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},TQ=(e,t,n,r)=>{const i=e._zod.def;si(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=o},RQ=(e,t,n,r)=>{const i=e._zod.def,s=t.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;si(s,t,r);const o=t.seen.get(e);o.ref=s},AQ=(e,t,n,r)=>{const i=e._zod.def;si(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType,n.readOnly=!0},sj=(e,t,n,r)=>{const i=e._zod.def;si(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType},NQ=Qe("ZodISODateTime",(e,t)=>{MX.init(e,t),jr.init(e,t)});function MQ(e){return BZ(NQ,e)}const PQ=Qe("ZodISODate",(e,t)=>{PX.init(e,t),jr.init(e,t)});function IQ(e){return zZ(PQ,e)}const OQ=Qe("ZodISOTime",(e,t)=>{IX.init(e,t),jr.init(e,t)});function LQ(e){return jZ(OQ,e)}const DQ=Qe("ZodISODuration",(e,t)=>{OX.init(e,t),jr.init(e,t)});function BQ(e){return FZ(DQ,e)}const zQ=(e,t)=>{jz.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>EG(e,n)},flatten:{value:n=>SG(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,NS,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,NS,2)}},isEmpty:{get(){return e.issues.length===0}}})},fo=Qe("ZodError",zQ,{Parent:Error}),jQ=mC(fo),FQ=gC(fo),$Q=Xy(fo),HQ=Zy(fo),UQ=TG(fo),WQ=RG(fo),qQ=AG(fo),VQ=NG(fo),YQ=MG(fo),KQ=PG(fo),GQ=IG(fo),XQ=OG(fo),zr=Qe("ZodType",(e,t)=>(Br.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:py(e,"input"),output:py(e,"output")}}),e.toJSONSchema=aQ(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(ec(t,{checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0}),e.with=e.check,e.clone=(n,r)=>tc(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>jQ(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>$Q(e,n,r),e.parseAsync=async(n,r)=>FQ(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>HQ(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>UQ(e,n,r),e.decode=(n,r)=>WQ(e,n,r),e.encodeAsync=async(n,r)=>qQ(e,n,r),e.decodeAsync=async(n,r)=>VQ(e,n,r),e.safeEncode=(n,r)=>YQ(e,n,r),e.safeDecode=(n,r)=>KQ(e,n,r),e.safeEncodeAsync=async(n,r)=>GQ(e,n,r),e.safeDecodeAsync=async(n,r)=>XQ(e,n,r),e.refine=(n,r)=>e.check(HJ(n,r)),e.superRefine=n=>e.check(UJ(n)),e.overwrite=n=>e.check(nf(n)),e.optional=()=>bP(e),e.exactOptional=()=>AJ(e),e.nullable=()=>_P(e),e.nullish=()=>bP(_P(e)),e.nonoptional=n=>LJ(e,n),e.array=()=>ur(e),e.or=n=>tm([e,n]),e.and=n=>SJ(e,n),e.transform=n=>wP(e,TJ(n)),e.default=n=>PJ(e,n),e.prefault=n=>OJ(e,n),e.catch=n=>BJ(e,n),e.pipe=n=>wP(e,n),e.readonly=()=>FJ(e),e.describe=n=>{const r=e.clone();return Vh.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){var n;return(n=Vh.get(e))==null?void 0:n.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Vh.get(e);const r=e.clone();return Vh.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=n=>n(e),e)),oj=Qe("_ZodString",(e,t)=>{vC.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(r,i,s)=>cQ(e,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(VZ(...r)),e.includes=(...r)=>e.check(GZ(...r)),e.startsWith=(...r)=>e.check(XZ(...r)),e.endsWith=(...r)=>e.check(ZZ(...r)),e.min=(...r)=>e.check(hy(...r)),e.max=(...r)=>e.check(ej(...r)),e.length=(...r)=>e.check(tj(...r)),e.nonempty=(...r)=>e.check(hy(1,...r)),e.lowercase=r=>e.check(YZ(r)),e.uppercase=r=>e.check(KZ(r)),e.trim=()=>e.check(JZ()),e.normalize=(...r)=>e.check(QZ(...r)),e.toLowerCase=()=>e.check(eQ()),e.toUpperCase=()=>e.check(tQ()),e.slugify=()=>e.check(nQ())}),ZQ=Qe("ZodString",(e,t)=>{vC.init(e,t),oj.init(e,t),e.email=n=>e.check(gZ(QQ,n)),e.url=n=>e.check(wZ(JQ,n)),e.jwt=n=>e.check(DZ(pJ,n)),e.emoji=n=>e.check(xZ(eJ,n)),e.guid=n=>e.check(hP(vP,n)),e.uuid=n=>e.check(vZ(Ug,n)),e.uuidv4=n=>e.check(yZ(Ug,n)),e.uuidv6=n=>e.check(bZ(Ug,n)),e.uuidv7=n=>e.check(_Z(Ug,n)),e.nanoid=n=>e.check(SZ(tJ,n)),e.guid=n=>e.check(hP(vP,n)),e.cuid=n=>e.check(EZ(nJ,n)),e.cuid2=n=>e.check(CZ(rJ,n)),e.ulid=n=>e.check(kZ(iJ,n)),e.base64=n=>e.check(IZ(dJ,n)),e.base64url=n=>e.check(OZ(fJ,n)),e.xid=n=>e.check(TZ(sJ,n)),e.ksuid=n=>e.check(RZ(oJ,n)),e.ipv4=n=>e.check(AZ(aJ,n)),e.ipv6=n=>e.check(NZ(lJ,n)),e.cidrv4=n=>e.check(MZ(cJ,n)),e.cidrv6=n=>e.check(PZ(uJ,n)),e.e164=n=>e.check(LZ(hJ,n)),e.datetime=n=>e.check(MQ(n)),e.date=n=>e.check(IQ(n)),e.time=n=>e.check(LQ(n)),e.duration=n=>e.check(BQ(n))});function Ce(e){return mZ(ZQ,e)}const jr=Qe("ZodStringFormat",(e,t)=>{Nr.init(e,t),oj.init(e,t)}),QQ=Qe("ZodEmail",(e,t)=>{xX.init(e,t),jr.init(e,t)}),vP=Qe("ZodGUID",(e,t)=>{_X.init(e,t),jr.init(e,t)}),Ug=Qe("ZodUUID",(e,t)=>{wX.init(e,t),jr.init(e,t)}),JQ=Qe("ZodURL",(e,t)=>{SX.init(e,t),jr.init(e,t)}),eJ=Qe("ZodEmoji",(e,t)=>{EX.init(e,t),jr.init(e,t)}),tJ=Qe("ZodNanoID",(e,t)=>{CX.init(e,t),jr.init(e,t)}),nJ=Qe("ZodCUID",(e,t)=>{kX.init(e,t),jr.init(e,t)}),rJ=Qe("ZodCUID2",(e,t)=>{TX.init(e,t),jr.init(e,t)}),iJ=Qe("ZodULID",(e,t)=>{RX.init(e,t),jr.init(e,t)}),sJ=Qe("ZodXID",(e,t)=>{AX.init(e,t),jr.init(e,t)}),oJ=Qe("ZodKSUID",(e,t)=>{NX.init(e,t),jr.init(e,t)}),aJ=Qe("ZodIPv4",(e,t)=>{LX.init(e,t),jr.init(e,t)}),lJ=Qe("ZodIPv6",(e,t)=>{DX.init(e,t),jr.init(e,t)}),cJ=Qe("ZodCIDRv4",(e,t)=>{BX.init(e,t),jr.init(e,t)}),uJ=Qe("ZodCIDRv6",(e,t)=>{zX.init(e,t),jr.init(e,t)}),dJ=Qe("ZodBase64",(e,t)=>{jX.init(e,t),jr.init(e,t)}),fJ=Qe("ZodBase64URL",(e,t)=>{$X.init(e,t),jr.init(e,t)}),hJ=Qe("ZodE164",(e,t)=>{HX.init(e,t),jr.init(e,t)}),pJ=Qe("ZodJWT",(e,t)=>{WX.init(e,t),jr.init(e,t)}),aj=Qe("ZodNumber",(e,t)=>{Gz.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(r,i,s)=>uQ(e,r,i),e.gt=(r,i)=>e.check(mP(r,i)),e.gte=(r,i)=>e.check(bx(r,i)),e.min=(r,i)=>e.check(bx(r,i)),e.lt=(r,i)=>e.check(pP(r,i)),e.lte=(r,i)=>e.check(yx(r,i)),e.max=(r,i)=>e.check(yx(r,i)),e.int=r=>e.check(yP(r)),e.safe=r=>e.check(yP(r)),e.positive=r=>e.check(mP(0,r)),e.nonnegative=r=>e.check(bx(0,r)),e.negative=r=>e.check(pP(0,r)),e.nonpositive=r=>e.check(yx(0,r)),e.multipleOf=(r,i)=>e.check(gP(r,i)),e.step=(r,i)=>e.check(gP(r,i)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Lt(e){return $Z(aj,e)}const mJ=Qe("ZodNumberFormat",(e,t)=>{qX.init(e,t),aj.init(e,t)});function yP(e){return HZ(mJ,e)}const gJ=Qe("ZodBoolean",(e,t)=>{VX.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>dQ(e,n,r)});function Ln(e){return UZ(gJ,e)}const vJ=Qe("ZodUnknown",(e,t)=>{YX.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>hQ()});function Ba(){return WZ(vJ)}const yJ=Qe("ZodNever",(e,t)=>{KX.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>fQ(e,n,r)});function ns(e){return qZ(yJ,e)}const bJ=Qe("ZodArray",(e,t)=>{GX.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yQ(e,n,r,i),e.element=t.element,e.min=(n,r)=>e.check(hy(n,r)),e.nonempty=n=>e.check(hy(1,n)),e.max=(n,r)=>e.check(ej(n,r)),e.length=(n,r)=>e.check(tj(n,r)),e.unwrap=()=>e.element});function ur(e,t){return rQ(bJ,e,t)}const _J=Qe("ZodObject",(e,t)=>{ZX.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bQ(e,n,r,i),ar(e,"shape",()=>t.shape),e.keyof=()=>rn(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Ba()}),e.loose=()=>e.clone({...e._zod.def,catchall:Ba()}),e.strict=()=>e.clone({...e._zod.def,catchall:ns()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>yG(e,n),e.safeExtend=n=>bG(e,n),e.merge=n=>_G(e,n),e.pick=n=>gG(e,n),e.omit=n=>vG(e,n),e.partial=(...n)=>wG(cj,e,n[0]),e.required=(...n)=>xG(uj,e,n[0])});function qe(e,t){const n={type:"object",shape:e??{},...Qt(t)};return new _J(n)}const lj=Qe("ZodUnion",(e,t)=>{Qz.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_Q(e,n,r,i),e.options=t.options});function tm(e,t){return new lj({type:"union",options:e,...Qt(t)})}const wJ=Qe("ZodDiscriminatedUnion",(e,t)=>{lj.init(e,t),QX.init(e,t)});function Dn(e,t,n){return new wJ({type:"union",options:t,discriminator:e,...Qt(n)})}const xJ=Qe("ZodIntersection",(e,t)=>{JX.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wQ(e,n,r,i)});function SJ(e,t){return new xJ({type:"intersection",left:e,right:t})}const EJ=Qe("ZodRecord",(e,t)=>{eZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xQ(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function Ud(e,t,n){return new EJ({type:"record",keyType:e,valueType:t,...Qt(n)})}const PS=Qe("ZodEnum",(e,t)=>{tZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(r,i,s)=>pQ(e,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const s={};for(const o of r)if(n.has(o))s[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new PS({...t,checks:[],...Qt(i),entries:s})},e.exclude=(r,i)=>{const s={...t.entries};for(const o of r)if(n.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new PS({...t,checks:[],...Qt(i),entries:s})}});function rn(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new PS({type:"enum",entries:n,...Qt(t)})}const CJ=Qe("ZodLiteral",(e,t)=>{nZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>mQ(e,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Se(e,t){return new CJ({type:"literal",values:Array.isArray(e)?e:[e],...Qt(t)})}const kJ=Qe("ZodTransform",(e,t)=>{rZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vQ(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Iz(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(Tp(s,n.value,t));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),n.issues.push(Tp(o))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(s=>(n.value=s,n)):(n.value=i,n)}});function TJ(e){return new kJ({type:"transform",transform:e})}const cj=Qe("ZodOptional",(e,t)=>{Jz.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>sj(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function bP(e){return new cj({type:"optional",innerType:e})}const RJ=Qe("ZodExactOptional",(e,t)=>{iZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>sj(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function AJ(e){return new RJ({type:"optional",innerType:e})}const NJ=Qe("ZodNullable",(e,t)=>{sZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SQ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function _P(e){return new NJ({type:"nullable",innerType:e})}const MJ=Qe("ZodDefault",(e,t)=>{oZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CQ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function PJ(e,t){return new MJ({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Bz(t)}})}const IJ=Qe("ZodPrefault",(e,t)=>{aZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kQ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function OJ(e,t){return new IJ({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Bz(t)}})}const uj=Qe("ZodNonOptional",(e,t)=>{lZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EQ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function LJ(e,t){return new uj({type:"nonoptional",innerType:e,...Qt(t)})}const DJ=Qe("ZodCatch",(e,t)=>{cZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TQ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function BJ(e,t){return new DJ({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const zJ=Qe("ZodPipe",(e,t)=>{uZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RQ(e,n,r,i),e.in=t.in,e.out=t.out});function wP(e,t){return new zJ({type:"pipe",in:e,out:t})}const jJ=Qe("ZodReadonly",(e,t)=>{dZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>AQ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function FJ(e){return new jJ({type:"readonly",innerType:e})}const $J=Qe("ZodCustom",(e,t)=>{fZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gQ(e,n)});function HJ(e,t={}){return iQ($J,e,t)}function UJ(e){return sQ(e)}const WJ=256,we=Ce().min(1).max(WJ),Jy="1.0",qJ=qe({text:Ce().min(1),messageId:Ce().min(1).optional()}).strict(),VJ=qe({turnId:Ce().min(1).max(256),revision:Lt().int().positive(),text:Ce(),status:rn(["streaming","completed"])}).strict(),YJ=qe({text:Ce()}).strict(),KJ=rn(["allow_once","allow_always","reject_once","reject_always"]),dj=qe({optionId:we,name:Ce().min(1),kind:KJ}).strict(),xP=qe({toolName:Ce(),toolId:we,parameters:Ud(Ce(),Ba()),options:ur(dj).optional()}).strict(),GJ=qe({toolId:we,whitelistTool:Ln().optional(),optionId:we.optional()}),XJ=qe({toolId:we,reason:Ce().optional(),optionId:we.optional()}),ZJ=qe({toolId:we,result:Ba(),isError:Ln()}).strict(),na=["claude","codex","kimi"],fj=["local-terminal","proxy-hosted"],QJ=["pty","json"],_x={WORKING:"working",TURN_COMPLETE:"turn_complete",APPROVAL_WAIT:"approval_wait"},JJ=[_x.WORKING,_x.TURN_COMPLETE,_x.APPROVAL_WAIT],Lv=80,IS=24,yC=500,bC=200,_C=["idle","working","compacting","waiting_approval","error","terminated"],eee=["idle","thinking","tool_use","outputting","waiting_permission","error"];function hj(e){return tm([qe({...e,kind:Se("agent"),mode:Se("json"),provider:rn(na)}).strict(),qe({...e,kind:Se("agent"),mode:Se("pty"),provider:rn(na),ptyOwner:rn(fj)}).strict(),qe({...e,kind:Se("terminal"),mode:Se("pty"),provider:Se("claude"),ptyOwner:Se("local-terminal")}).strict()])}const tee=hj({sessionId:we,name:Ce().optional(),cwd:Ce(),nameLocked:Ln().optional(),state:rn(_C),lastActive:Lt()}),nee=qe({sessions:ur(tee)}).strict(),ree=qe({sessionId:we,state:rn(_C),lastActive:Lt()}).strict(),iee=qe({state:rn(JJ),seq:Lt().int().nonnegative(),title:Ce().optional(),tool:Ce().optional()}),SP=qe({provider:rn(na),phase:rn(eee),seq:Lt().int().nonnegative(),updatedAt:Lt(),toolName:Ce().optional(),toolInput:Ud(Ce(),Ba()).optional(),permissionRequest:qe({requestId:we,toolName:Ce(),input:Ud(Ce(),Ba())}).optional(),permissionResolution:qe({requestId:we,outcome:rn(["allow","deny"])}).optional(),summary:Ce().optional()}),see=qe({}).strict(),oee=qe({pairingCode:Ce().optional(),token:Ce().optional()}).strict(),aee=qe({lastSeq:Lt().int().nonnegative()}).strict(),lee=qe({messages:ur(Ud(Ce(),Ba()))}).strict(),md={seq:Lt().int().nonnegative(),timestamp:Lt(),source:rn(["proxy","client"]),version:Se(Jy)},kc={...md,sessionId:we},cee=Dn("type",[qe({...kc,type:Se("user_input"),payload:qJ}).strict(),qe({...kc,type:Se("assistant_message"),payload:VJ}).strict(),qe({...kc,type:Se("thinking"),payload:YJ}).strict(),qe({...kc,type:Se("tool_use_request"),payload:xP}).strict(),qe({...kc,type:Se("tool_result"),payload:ZJ}).strict(),qe({...kc,type:Se("assistant_tool_use"),payload:xP}).strict(),qe({...md,type:Se("session_list"),payload:nee}).strict(),qe({...kc,type:Se("session_status"),payload:ree}).strict(),qe({...md,type:Se("heartbeat"),payload:see}).strict(),qe({...md,type:Se("auth"),payload:oee}).strict(),qe({...md,type:Se("sync_request"),payload:aee}).strict(),qe({...md,type:Se("sync_response"),payload:lee}).strict()]),pj=["aliyun-bailian"],wC=["cn","intl"],uee=["official","custom"],dee=["male","female","unknown"],EP=qe({provider:rn(pj),configured:Ln(),region:rn(wC),asrModel:Ce().min(1),ttsModel:Ce().min(1),ttsVoice:Ce().min(1),turnIdleSeconds:Lt().int().positive().safe().default(3)}).strict(),CP=qe({provider:rn(pj).optional(),apiKey:Ce().min(1).optional(),clearApiKey:Ln().optional(),region:rn(wC).optional(),asrModel:Ce().min(1).optional(),ttsModel:Ce().min(1).optional(),ttsVoice:Ce().min(1).optional(),turnIdleSeconds:Lt().int().positive().safe().optional()}).strict(),wx=qe({value:Ce().min(1),label:Ce().min(1),description:Ce().min(1).optional(),gender:rn(dee).optional(),age:Ce().min(1).optional(),model:Ce().min(1).optional(),source:rn(uee)}).strict(),fee=qe({asrModels:ur(wx),ttsModels:ur(wx),ttsVoices:ur(wx),fetchedAt:Lt().optional()}).strict(),hee=[{value:"qwen3-asr-flash-realtime",label:"Qwen3 ASR Flash Realtime",source:"official"},{value:"qwen3-asr-flash-realtime-2026-02-10",label:"Qwen3 ASR Flash Realtime · 2026-02-10",source:"official"},{value:"qwen3-asr-flash-realtime-2025-10-27",label:"Qwen3 ASR Flash Realtime · 2025-10-27",source:"official"}],pee=[{value:"cosyvoice-v3-flash",label:"CosyVoice V3 Flash · 系统音色",source:"official"},{value:"cosyvoice-v3-plus",label:"CosyVoice V3 Plus · 系统音色",source:"official"},{value:"cosyvoice-v3.5-flash",label:"CosyVoice V3.5 Flash · 自定义音色",source:"official"},{value:"cosyvoice-v3.5-plus",label:"CosyVoice V3.5 Plus · 自定义音色",source:"official"}],mee=[{value:"longanyang",label:"龙安洋 · 男 · 阳光大男孩 · 年龄 20-30",gender:"male",age:"20-30",model:"cosyvoice-v3-flash",source:"official"},{value:"longanhuan",label:"龙安欢 · 女 · 欢脱元气 · 年龄 20-30",gender:"female",age:"20-30",model:"cosyvoice-v3-flash",source:"official"},{value:"longhuhu_v3",label:"龙呼呼 · 女 · 天真烂漫女童 · 年龄 6-10",gender:"female",age:"6-10",model:"cosyvoice-v3-flash",source:"official"},{value:"longpaopao_v3",label:"龙泡泡 · 未知 · 飞天泡泡音 · 年龄 6-15",gender:"unknown",age:"6-15",model:"cosyvoice-v3-flash",source:"official"},{value:"longjielidou_v3",label:"龙杰力豆 · 男 · 阳光顽皮 · 年龄 10",gender:"male",age:"10",model:"cosyvoice-v3-flash",source:"official"},{value:"longxian_v3",label:"龙仙 · 女 · 豪放可爱 · 年龄 12",gender:"female",age:"12",model:"cosyvoice-v3-flash",source:"official"},{value:"longling_v3",label:"龙铃 · 女 · 稚气呆板 · 年龄 10",gender:"female",age:"10",model:"cosyvoice-v3-flash",source:"official"},{value:"longjiaxin_v3",label:"龙嘉欣 · 女 · 优雅粤语 · 年龄 30-35",gender:"female",age:"30-35",model:"cosyvoice-v3-flash",source:"official"},{value:"longanyue_v3",label:"龙安粤 · 男 · 欢脱粤语 · 年龄 25-35",gender:"male",age:"25-35",model:"cosyvoice-v3-flash",source:"official"},{value:"longlaotie_v3",label:"龙老铁 · 男 · 东北直率 · 年龄 25-30",gender:"male",age:"25-30",model:"cosyvoice-v3-flash",source:"official"},{value:"longanyang",label:"龙安洋 · 男 · 阳光大男孩 · 年龄 20-30",gender:"male",age:"20-30",model:"cosyvoice-v3-plus",source:"official"},{value:"longanhuan",label:"龙安欢 · 女 · 欢脱元气 · 年龄 20-30",gender:"female",age:"20-30",model:"cosyvoice-v3-plus",source:"official"}];function xx(e){return{...e}}function Wg(e){return{asrModels:hee.map(xx),ttsModels:pee.map(xx),ttsVoices:mee.map(xx)}}const gee=rn(["code","table","diff","log","stack_trace","long_list","long_text","mixed","approval"]),on=qe({proxyId:we,bindingId:we}).strict(),vee=1,yee=Ce().regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/);qe({bootstrapVersion:Se(vee),relayVersion:yee,controlProtocolVersion:Lt().int().positive()});const xC=4096,bee=4096,_ee=65536,wee=256,mj=4096,xee=1e3,OS=Ce().trim().min(1).max(wee),See=["cloudflare","cpolar"],gj=rn(See),Yc=Ce().min(1).max(xC);function SC(e){try{return new URL(e)}catch{return null}}const vj=Ce().min(1).max(bee).url().refine(e=>{const t=SC(e);return!t||t.protocol!=="http:"||t.username!==""||t.password!==""?!1:t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]"},"Local preview URL must use http:// with a loopback host and no credentials"),Eee=Ce().min(1).max(_ee).url().refine(e=>{const t=SC(e);return t?t.protocol==="https:"&&t.username===""&&t.password===""&&t.port==="":!1},"Preview public URL must use standard HTTPS without credentials"),yj="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",Cee=new RegExp(`^${yj}\\.trycloudflare\\.com$`,"i"),kee=new RegExp(`^(?:${yj}\\.)+cpolar\\.(?:top|cn|io)$`,"i"),kP=ur(Ce().min(1).max(xC)).max(32).optional(),TP=Dn("available",[qe({available:Se(!0),command:Ce().min(1).max(xC),version:Ce().min(1).max(256).optional(),error:ns().optional(),suggestions:kP}).strict(),qe({available:Se(!1),command:ns().optional(),version:ns().optional(),error:Ce().min(1).max(mj),suggestions:kP}).strict()]),Tee=qe({cloudflared:TP,cpolar:TP}).strict(),Ree=Dn("kind",[qe({kind:Se("local"),url:vj}).strict(),qe({kind:Se("static"),path:Yc,entryPath:Yc}).strict()]),Aee=Dn("kind",[qe({kind:Se("local"),url:vj}).strict(),qe({kind:Se("static"),rootPath:Yc,entryPath:Yc}).strict()]),Nee=["starting","ready","disconnected","failed","stopping"];rn(Nee);const vh=qe({previewId:we,name:OS,source:Aee,tunnelProvider:gj,createdAt:Lt().int().nonnegative(),updatedAt:Lt().int().nonnegative()}),Sx={publicUrl:ns().optional(),error:ns().optional()},Ex=Dn("state",[vh.extend({state:Se("starting"),...Sx}).strict(),vh.extend({state:Se("ready"),publicUrl:Eee,error:ns().optional()}).strict(),vh.extend({state:Se("disconnected"),...Sx}).strict(),vh.extend({state:Se("failed"),publicUrl:ns().optional(),error:Ce().min(1).max(mj)}).strict(),vh.extend({state:Se("stopping"),...Sx}).strict()]).superRefine((e,t)=>{if(e.state!=="ready")return;const n=SC(e.publicUrl);if(!n)return;const r=n.hostname,i=e.tunnelProvider;(i==="cloudflare"?Cee.test(r):kee.test(r))||t.addIssue({code:"custom",path:["publicUrl"],message:`Preview public URL hostname does not match tunnel provider ${i}`})}),Mee=ur(Yc).max(xee),LS=4096,Pee=4096,DS=4096,my=256,gy=256,Iee=16384,BS=Ce().trim().min(1).max(my),Oee=["jpeg","h264_annex_b"],Lee=rn(Oee),Dee=["ios","android"],bj=rn(Dee),Cx=ur(Ce().min(1).max(LS)).max(32).optional(),RP=tm([qe({supported:Se(!1),available:Se(!1),interactive:Se(!1),command:ns().optional(),version:ns().optional(),error:Ce().min(1).max(DS),suggestions:Cx}).strict(),qe({supported:Se(!0),available:Se(!1),interactive:Se(!1),command:Ce().min(1).max(LS).optional(),version:Ce().min(1).max(gy).optional(),error:Ce().min(1).max(DS),suggestions:Cx}).strict(),qe({supported:Se(!0),available:Se(!0),interactive:Se(!0),command:Ce().min(1).max(LS),version:Ce().min(1).max(gy).optional(),error:ns().optional(),suggestions:Cx}).strict()]),Bee=qe({ios:RP,android:RP}).strict(),AP=qe({targetId:we,platform:bj,name:Ce().min(1).max(my),model:Ce().min(1).max(my),osVersion:Ce().min(1).max(gy),interactive:Ln()}),NP=Lt().int().positive().max(Iee),zee=tm([AP.extend({width:NP,height:NP}).strict(),AP.extend({width:ns().optional(),height:ns().optional()}).strict()]);rn(["ready","disconnected"]);const MP=qe({previewId:we,name:BS,platform:bj,targetId:we,model:Ce().min(1).max(my),osVersion:Ce().min(1).max(gy),interactive:Ln(),createdAt:Lt().int().nonnegative(),updatedAt:Lt().int().nonnegative()}),kx=Dn("state",[MP.extend({state:Se("ready"),error:ns().optional()}).strict(),MP.extend({state:Se("disconnected"),error:ns().optional()}).strict()]),_j=qe({format:Se("jpeg"),maxFps:Lt().int().min(1).max(30).optional()}).strict(),wj=qe({format:Se("h264_annex_b")}).strict(),jee=Dn("format",[_j,wj]),Fee=["client_closed","preview_closed","proxy_offline","relay_shutdown","stream_error"],$ee=rn(Fee),PP=Lt().finite().min(0).max(1),Hee=["down","move","up"],Uee=rn(Hee),Wee=["portrait","landscape_left","landscape_right","portrait_upside_down","auto"],qee=rn(Wee),Vee=Dn("kind",[qe({kind:Se("touch"),phase:Uee,x:PP,y:PP}).strict(),qe({kind:Se("text"),text:Ce().min(1).max(Pee)}).strict(),qe({kind:Se("button"),button:rn(["home","back"])}).strict(),qe({kind:Se("orientation"),orientation:qee}).strict()]);qe({type:Se("device_preview_stream_register"),proxyId:we,connectionId:we}).strict();const Yee=Dn("success",[qe({type:Se("device_preview_stream_register_response"),success:Se(!0)}).strict(),qe({type:Se("device_preview_stream_register_response"),success:Se(!1),error:Ce().min(1).max(DS)}).strict()]),IP=qe({type:Se("device_preview_stream_flow"),streamId:we}),Kee=Dn("paused",[IP.extend({paused:Se(!0),resyncRequired:Se(!1)}).strict(),IP.extend({paused:Se(!1),resyncRequired:Ln()}).strict()]);tm([Yee,Kee]);const Gee=rn(["pcm_s16le","mulaw"]),Xee=qe({type:Se("start"),sessionId:Ce().min(1),attemptId:Ce().min(1),sampleRate:Lt().int().positive(),encoding:Gee}),Zee=qe({type:Se("stop"),attemptId:Ce().min(1)});Dn("type",[Xee,Zee]);const Qee=Dn("type",[qe({type:Se("ready"),attemptId:Ce().min(1)}),qe({type:Se("audio_ack"),attemptId:Ce().min(1),encodedBytes:Lt().int().nonnegative(),pcmBytes:Lt().int().nonnegative(),chunks:Lt().int().nonnegative()}),qe({type:Se("partial"),attemptId:Ce().min(1),text:Ce()}),qe({type:Se("final"),attemptId:Ce().min(1),text:Ce()}),qe({type:Se("closed"),attemptId:Ce().min(1),code:Lt().int().optional(),reason:Ce().optional()}),qe({type:Se("error"),attemptId:Ce().min(1),error:Ce().optional(),errorCode:Ce().optional()})]);function OP(e){return/^\/compact(?:\s|$)/.test(e.trimStart())}const Jee=/((?:authorization|api[_-]?key|token|password|secret)\s*[:=]\s*)(?:bearer\s+)?[^\s'"]+/giu,ete=/(--(?:api-key|token|password|secret)(?:=|\s+))[^\s'"]+/giu;function Pa(e){return typeof e=="string"?e:""}function Ku(e,t=140){const n=e.replace(/\s+/gu," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Gu(e){return e.replace(Jee,"$1[redacted]").replace(ete,"$1[redacted]")}function Tc(e){return Pa(e.file_path)||Pa(e.path)||Pa(e.notebook_path)}function tte(e,t){switch(e){case"Bash":{const n=Ku(Gu(Pa(t.command)));return n?`运行命令:${n}`:"运行命令"}case"BashBatch":{const n=Array.isArray(t.commands)?t.commands.filter(r=>typeof r=="string"):[];return n.length>0?`批量运行命令:${n.length} 条`:"批量运行命令"}case"ProcessWait":return"等待命令完成";case"ProcessInput":{const n=Ku(Gu(Pa(t.input)),80);return n?`发送终端输入:${n}`:"发送终端输入"}case"Read":{const n=Tc(t);return n?`读取文件:${n}`:"读取文件"}case"Write":{const n=Tc(t);return n?`写入文件:${n}`:"写入文件"}case"Edit":case"MultiEdit":{const n=Tc(t);return n?`编辑文件:${n}`:"编辑文件"}case"LS":{const n=Tc(t);return n?`列出目录:${n}`:"列出目录"}case"Grep":{const n=Ku(Gu(Pa(t.pattern)),80),r=Tc(t);return n&&r?`搜索:${n} in ${r}`:n?`搜索:${n}`:"搜索文本"}case"Glob":{const n=Ku(Gu(Pa(t.pattern)),80);return n?`查找文件:${n}`:"查找文件"}case"WebFetch":{const n=Ku(Gu(Pa(t.url)),100);return n?`读取网页:${n}`:"读取网页"}case"WebSearch":{const n=Ku(Gu(Pa(t.query)),100);return n?`网页搜索:${n}`:"网页搜索"}case"ViewImage":{const n=Tc(t);return n?`查看图片:${n}`:"查看图片"}case"ViewImageBatch":{const n=Array.isArray(t.paths)?t.paths.filter(r=>typeof r=="string"):[];return n.length>0?`批量查看图片:${n.length} 张`:"批量查看图片"}case"Web":return"访问网页";case"ToolScript":return"执行工具编排";case"TodoWrite":return"更新任务列表";case"Patch":{const n=Tc(t);if(n)return`应用补丁:${n}`;const r=Array.isArray(t.paths)?t.paths.filter(i=>typeof i=="string"):[];return r.length===1?`应用补丁:${r[0]}`:r.length>1?`应用补丁:${r[0]} 等 ${r.length} 个文件`:"应用补丁"}default:return`使用工具:${e}`}}const nte={NOT_REGISTERED:"NOT_REGISTERED",NOT_BOUND:"NOT_BOUND",PROXY_OFFLINE:"PROXY_OFFLINE",INVALID_MESSAGE:"INVALID_MESSAGE",STALE_BINDING:"STALE_BINDING",UNSUPPORTED:"UNSUPPORTED",INVALID_RANGE:"INVALID_RANGE"},Rr={INVALID_PATH:"INVALID_PATH",PATH_NOT_FOUND:"PATH_NOT_FOUND",PATH_NOT_DIRECTORY:"PATH_NOT_DIRECTORY",PATH_ACCESS_DENIED:"PATH_ACCESS_DENIED",PROXY_OFFLINE:"PROXY_OFFLINE",PROXY_NOT_FOUND:"PROXY_NOT_FOUND",PROXY_ONLINE:"PROXY_ONLINE",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_ALREADY_ACTIVE:"SESSION_ALREADY_ACTIVE",PROVIDER_UNSUPPORTED:"PROVIDER_UNSUPPORTED",APPROVAL_POLICY_UNSUPPORTED:"APPROVAL_POLICY_UNSUPPORTED",WORKER_START_FAILED:"WORKER_START_FAILED",PROCESS_START_FAILED:"PROCESS_START_FAILED",STREAM_CAPACITY_EXCEEDED:"STREAM_CAPACITY_EXCEEDED",CONTROL_LEASE_INVALID:"CONTROL_LEASE_INVALID",OPERATION_CONFLICT:"OPERATION_CONFLICT",RATE_LIMITED:"RATE_LIMITED",UNKNOWN:"UNKNOWN"},$l=1,rte=qe({proxyId:we,name:Ce().optional(),version:Ce().min(1).max(64),online:Ln(),sessions:ur(Ce())}),ite=qe({clientId:we,proxyId:we.optional(),connectedAt:Lt().int().nonnegative(),current:Ln().optional(),userAgent:Ce().optional(),platform:Ce().optional(),maxTouchPoints:Lt().int().nonnegative().optional(),browserName:Ce().min(1),osName:Ce().min(1),deviceKind:rn(["desktop","tablet","phone","unknown"]),remoteAddress:Ce().optional()}),Tx=qe({available:Ln(),command:Ce().optional(),error:Ce().optional(),suggestions:ur(Ce()).optional()}),xj=qe({claude:Tx,codex:Tx,kimi:Tx}),Sj=qe({name:Ce(),isDir:Ln()}),LP=qe({path:Ce(),entries:ur(Sj)}),DP=qe({name:Ce(),description:Ce(),argumentHint:Ce().optional(),source:Ce()}),ste=qe({id:Ce(),title:Ce(),projectDir:Ce(),updatedAt:Lt(),provider:rn(na),preferredMode:rn(QJ).optional()}),BP={timestamp:Lt().optional(),cursor:Ce().optional()},ote=Dn("role",[qe({role:rn(["user","assistant","system"]),text:Ce(),...BP}),qe({role:Se("activity"),text:Ce(),toolId:we,toolName:Ce(),parameters:Ud(Ce(),Ba()).optional(),status:rn(["running","done","error"]),...BP})]),ir={requestId:we.optional()},Dt={requestId:we},EC=rn(Object.values(Rr)),Jr={error:Ce().optional(),errorCode:EC.optional()},Bi={error:Ce().min(1),errorCode:EC},zP=rn(["inline","download"]),jP=rn(["clipboard_image","file"]);function xt(e,t,n){return{type:e,directions:new Set(Array.isArray(n)?n:n?[n]:[]),schema:qe({type:Se(e),...t??{}})}}function Yn(e,t,n){return{type:e,directions:new Set(Array.isArray(n)?n:n?[n]:[]),schema:qe({type:Se(e),...t}).strict()}}function Cr(e,t,n){return{type:e,directions:new Set(Array.isArray(n)?n:n?[n]:[]),schema:t}}const ate=Dn("success",[qe({type:Se("proxy_select_response"),...ir,success:Se(!0),proxyId:we,bindingId:we}).strict(),qe({type:Se("proxy_select_response"),...ir,success:Se(!1),...Jr}).strict()]),lte=Dn("status",[qe({type:Se("client_register_response"),protocolVersion:Se($l),status:Se("restored"),proxyId:we,bindingId:we}).strict(),qe({type:Se("client_register_response"),protocolVersion:Se($l),status:Se("proxy_offline"),proxyId:we,bindingId:we}).strict(),qe({type:Se("client_register_response"),protocolVersion:Se($l),status:Se("new")}).strict()]),cte=Dn("accepted",[qe({type:Se("preview_create_response"),...Dt,scope:on,operationId:we,accepted:Se(!0),previewId:we}).strict(),qe({type:Se("preview_create_response"),...Dt,scope:on,operationId:we,accepted:Se(!1),...Bi}).strict()]),ute=Dn("accepted",[qe({type:Se("device_preview_create_response"),...Dt,scope:on,operationId:we,accepted:Se(!0),previewId:we}).strict(),qe({type:Se("device_preview_create_response"),...Dt,scope:on,operationId:we,accepted:Se(!1),...Bi}).strict()]),dte=Dn("success",[qe({type:Se("preview_capability_response"),...Dt,scope:on,success:Se(!0),capability:Tee}).strict(),qe({type:Se("preview_capability_response"),...Dt,scope:on,success:Se(!1),...Bi}).strict()]),fte=Dn("success",[qe({type:Se("device_preview_capability_response"),...Dt,scope:on,success:Se(!0),capability:Bee}).strict(),qe({type:Se("device_preview_capability_response"),...Dt,scope:on,success:Se(!1),...Bi}).strict()]),hte=qe({type:Se("proxy_info_request"),...ir}).strict(),pte=qe({type:Se("proxy_info"),...ir,homePath:Ce(),agentCli:xj}).strict(),mte=Dn("success",[qe({type:Se("preview_static_inspect_response"),...Dt,scope:on,success:Se(!0),entryPath:Yc.optional(),htmlEntries:Mee}).strict(),qe({type:Se("preview_static_inspect_response"),...Dt,scope:on,success:Se(!1),...Bi}).strict()]),gte=Dn("success",[qe({type:Se("preview_rename_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!0)}).strict(),qe({type:Se("preview_rename_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!1),...Bi}).strict()]),vte=Dn("success",[qe({type:Se("preview_reconnect_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!0)}).strict(),qe({type:Se("preview_reconnect_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!1),...Bi}).strict()]),yte=Dn("success",[qe({type:Se("preview_close_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!0)}).strict(),qe({type:Se("preview_close_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!1),...Bi}).strict()]),bte=Dn("success",[qe({type:Se("device_preview_targets_response"),...Dt,scope:on,success:Se(!0),targets:ur(zee).max(1024)}).strict(),qe({type:Se("device_preview_targets_response"),...Dt,scope:on,success:Se(!1),...Bi}).strict()]),_te=Dn("success",[qe({type:Se("device_preview_rename_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!0)}).strict(),qe({type:Se("device_preview_rename_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!1),...Bi}).strict()]),wte=Dn("success",[qe({type:Se("device_preview_reconnect_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!0)}).strict(),qe({type:Se("device_preview_reconnect_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!1),...Bi}).strict()]),xte=Dn("success",[qe({type:Se("device_preview_close_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!0)}).strict(),qe({type:Se("device_preview_close_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!1),...Bi}).strict()]),Ste=Dn("success",[qe({type:Se("device_preview_stream_url_response"),...Dt,scope:on,previewId:we,success:Se(!0),url:Ce().min(1).max(4096),leaseId:we,expiresAt:Lt().int().nonnegative(),controlMode:rn(["controller","view_only"])}).strict(),qe({type:Se("device_preview_stream_url_response"),...Dt,scope:on,previewId:we,success:Se(!1),...Bi}).strict()]),Ej={type:Se("device_preview_stream_start_response"),streamId:we,leaseId:we,previewId:we},Ete=qe({...Ej,success:Se(!0),format:Lee,width:Lt().int().positive().max(16384).optional(),height:Lt().int().positive().max(16384).optional()}).strict().superRefine((e,t)=>{e.width===void 0!=(e.height===void 0)&&t.addIssue({code:"custom",path:e.width===void 0?["width"]:["height"],message:"Device preview stream dimensions must include both width and height"})}),Cte=Dn("success",[Ete,qe({...Ej,success:Se(!1),...Bi}).strict()]),kte=qe({type:Se("device_preview_stream_complete"),streamId:we,leaseId:we,previewId:we,success:Se(!1),error:Ce().min(1)}).strict(),FP={type:Se("device_preview_stream_start"),streamId:we,leaseId:we,previewId:we},Tte=Dn("format",[qe({...FP,..._j.shape}).strict(),qe({...FP,...wj.shape}).strict()]),Rte=Dn("success",[qe({type:Se("device_preview_input_ack"),scope:on,leaseId:we,inputSeq:Lt().int().min(0).max(4294967295),success:Se(!0)}).strict(),qe({type:Se("device_preview_input_ack"),scope:on,leaseId:we,inputSeq:Lt().int().min(0).max(4294967295),success:Se(!1),...Bi}).strict()]),Ate=Dn("success",[qe({type:Se("device_preview_control_claim_response"),...Dt,scope:on,leaseId:we,success:Se(!0),controlMode:Se("controller")}).strict(),qe({type:Se("device_preview_control_claim_response"),...Dt,scope:on,leaseId:we,success:Se(!1),...Bi}).strict()]),Cj=rn(["default","auto","acceptEdits","plan","bypassPermissions","dontAsk"]),Nte=qe({type:Se("session_create"),...Dt,kind:Se("agent"),cwd:Ce(),name:Ce().optional(),provider:rn(na),mode:Se("json"),resumeSessionId:Ce().optional(),permissionMode:Cj.optional()}).strict(),Mte=qe({type:Se("session_create"),...Dt,kind:Se("agent"),cwd:Ce(),name:Ce().optional(),provider:rn(na),mode:Se("pty"),resumeSessionId:Ce().optional(),cols:Lt().int().positive().max(yC),rows:Lt().int().positive().max(bC),permissionMode:Cj.optional()}).strict(),Pte=qe({type:Se("session_create"),...Dt,kind:Se("terminal"),name:Ce().optional(),mode:Se("pty"),cols:Lt().int().positive().max(yC),rows:Lt().int().positive().max(bC)}).strict(),Ite=Dn("mode",[Nte,Dn("kind",[Mte,Pte])]),Rx={type:Se("session_create_response"),...Dt,success:Se(!0),sessionId:we,cwd:Ce(),lastActive:Lt(),name:Ce().optional(),nameLocked:Ln().optional()},Ote=Dn("mode",[qe({...Rx,kind:Se("agent"),mode:Se("json"),provider:rn(na)}).strict(),Dn("kind",[qe({...Rx,kind:Se("agent"),mode:Se("pty"),provider:rn(na),ptyOwner:rn(fj)}).strict(),qe({...Rx,kind:Se("terminal"),mode:Se("pty"),provider:Se("claude"),ptyOwner:Se("local-terminal")}).strict()])]),Lte=Dn("success",[Ote,qe({type:Se("session_create_response"),...Dt,success:Se(!1),...Bi,activeWriterPid:Lt().int().positive().optional()}).strict()]),CC=[Yn("proxy_register",{protocolVersion:Se($l),proxyId:we,name:Ce().optional(),proxyVersion:Ce().min(1).max(64)}),Yn("proxy_register_response",{protocolVersion:Se($l),status:rn(["new","reconnected"]),relayVersion:Ce().min(1).max(64),connectionId:we}),xt("proxy_list_request",ir),xt("proxy_list_response",{...ir,proxies:ur(rte)}),xt("proxy_remove",{...Dt,proxyId:we}),xt("proxy_remove_response",{...Dt,proxyId:we,success:Ln(),...Jr}),xt("relay_client_list_request",ir),xt("relay_client_list_response",{...ir,clients:ur(ite)}),xt("relay_client_kick",{...Dt,clientId:we}),xt("relay_client_kick_response",{...Dt,clientId:we,success:Ln(),...Jr}),xt("relay_client_kicked",{reason:Ce().optional()}),xt("remote_file_url_request",{...Dt,sessionId:we,path:Ce().min(1),disposition:zP}),xt("remote_file_url_response",{...Dt,...Jr,sessionId:we,path:Ce().optional(),success:Ln(),url:Ce().optional(),expiresAt:Lt().int().nonnegative().optional()}),xt("remote_file_metadata_request",{...Dt,sessionId:we,path:Ce().min(1)}),xt("remote_file_metadata_response",{...Dt,...Jr,sessionId:we,path:Ce().optional(),success:Ln(),mimeType:Ce().optional(),size:Lt().int().nonnegative().optional(),fileName:Ce().optional()}),xt("remote_file_stream_request",{streamId:we,sessionId:we,path:Ce().min(1),disposition:zP}),xt("remote_file_stream_response",{...Jr,streamId:we,sessionId:we,success:Ln(),path:Ce().optional(),mimeType:Ce().optional(),size:Lt().int().nonnegative().optional(),fileName:Ce().optional()}),xt("remote_file_stream_complete",{...Jr,streamId:we,success:Ln()}),xt("remote_file_stream_cancel",{streamId:we}),xt("remote_file_upload_url_request",{...Dt,sessionId:we,kind:jP,fileName:Ce().optional(),mimeType:Ce().min(1),size:Lt().int().nonnegative().optional()}),xt("remote_file_upload_url_response",{...Dt,...Jr,sessionId:we,success:Ln(),uploadUrl:Ce().optional(),expiresAt:Lt().int().nonnegative().optional()}),xt("remote_file_upload_stream_request",{uploadId:we,sessionId:we,kind:jP,fileName:Ce().optional(),mimeType:Ce().min(1),size:Lt().int().nonnegative().optional()}),xt("remote_file_upload_stream_complete",{uploadId:we}),xt("remote_file_upload_stream_cancel",{uploadId:we}),xt("remote_file_upload_stream_response",{...Jr,uploadId:we,sessionId:we,success:Ln(),path:Ce().optional()}),xt("proxy_select",{...ir,proxyId:we}),Cr("proxy_select_response",ate),xt("relay_error",{code:rn(Object.values(nte)),message:Ce(),requestId:we.optional()}),xt("voice_config_request",ir),xt("voice_config_response",{...ir,...Jr,config:EP.optional()}),xt("voice_config_update",{...ir,config:CP}),xt("voice_config_update_response",{...ir,...Jr,success:Ln(),config:EP.optional()}),xt("voice_config_test",{...ir,config:CP.optional()}),xt("voice_config_test_response",{...ir,...Jr,success:Ln(),audioBase64:Ce().optional(),audioSampleRate:Lt().int().positive().optional(),audioEncoding:Se("pcm_s16le").optional(),transcript:Ce().optional()}),xt("voice_capabilities_request",{...ir,region:rn(wC).optional()}),xt("voice_capabilities_response",{...ir,...Jr,capabilities:fee.optional()}),xt("latency_web_relay_ping",Dt),xt("latency_web_relay_pong",{...Dt,relayNow:Lt().optional()}),xt("latency_relay_proxy_request",Dt),xt("latency_relay_proxy_response",{...Dt,success:Ln(),rttMs:Lt().nonnegative().optional(),error:Ce().optional()}),xt("latency_relay_proxy_ping",{...Dt,relayNow:Lt().optional()}),xt("latency_relay_proxy_pong",{...Dt,proxyNow:Lt().optional()}),xt("latency_web_proxy_ping",Dt,"client_to_proxy"),xt("latency_web_proxy_pong",{...Dt,proxyNow:Lt().optional()},"proxy_to_client"),Yn("preview_capability_request",{...Dt,scope:on,refreshPath:Ln()},"client_to_proxy"),Cr("preview_capability_response",dte,"proxy_to_client"),Yn("preview_static_inspect_request",{...Dt,scope:on,path:Yc},"client_to_proxy"),Cr("preview_static_inspect_response",mte,"proxy_to_client"),Yn("preview_create_request",{...Dt,scope:on,operationId:we,source:Ree,tunnelProvider:gj,name:OS.optional()},"client_to_proxy"),Cr("preview_create_response",cte,"proxy_to_client"),Yn("preview_list_request",{...Dt,scope:on},"client_to_proxy"),Yn("preview_list_response",{...Dt,scope:on,epoch:we,revision:Lt().int().nonnegative(),previews:ur(Ex)},"proxy_to_client"),Yn("preview_rename_request",{...Dt,scope:on,operationId:we,previewId:we,name:OS},"client_to_proxy"),Cr("preview_rename_response",gte,"proxy_to_client"),Yn("preview_reconnect_request",{...Dt,scope:on,operationId:we,previewId:we},"client_to_proxy"),Cr("preview_reconnect_response",vte,"proxy_to_client"),Yn("preview_close_request",{...Dt,scope:on,operationId:we,previewId:we},"client_to_proxy"),Cr("preview_close_response",yte,"proxy_to_client"),Yn("preview_state_event",{epoch:we,revision:Lt().int().nonnegative(),preview:Ex}),Yn("preview_removed_event",{epoch:we,revision:Lt().int().nonnegative(),previewId:we}),Yn("preview_state_push",{scope:on,epoch:we,revision:Lt().int().nonnegative(),preview:Ex},"proxy_to_client"),Yn("preview_removed_push",{scope:on,epoch:we,revision:Lt().int().nonnegative(),previewId:we},"proxy_to_client"),Yn("device_preview_capability_request",{...Dt,scope:on,refreshPath:Ln()},"client_to_proxy"),Cr("device_preview_capability_response",fte,"proxy_to_client"),Yn("device_preview_targets_request",{...Dt,scope:on,refresh:Ln()},"client_to_proxy"),Cr("device_preview_targets_response",bte,"proxy_to_client"),Yn("device_preview_create_request",{...Dt,scope:on,operationId:we,targetId:we,name:BS.optional()},"client_to_proxy"),Cr("device_preview_create_response",ute,"proxy_to_client"),Yn("device_preview_list_request",{...Dt,scope:on},"client_to_proxy"),Yn("device_preview_list_response",{...Dt,scope:on,epoch:we,revision:Lt().int().nonnegative(),previews:ur(kx).max(1024)},"proxy_to_client"),Yn("device_preview_rename_request",{...Dt,scope:on,operationId:we,previewId:we,name:BS},"client_to_proxy"),Cr("device_preview_rename_response",_te,"proxy_to_client"),Yn("device_preview_reconnect_request",{...Dt,scope:on,operationId:we,previewId:we},"client_to_proxy"),Cr("device_preview_reconnect_response",wte,"proxy_to_client"),Yn("device_preview_close_request",{...Dt,scope:on,operationId:we,previewId:we},"client_to_proxy"),Cr("device_preview_close_response",xte,"proxy_to_client"),Yn("device_preview_state_event",{epoch:we,revision:Lt().int().nonnegative(),preview:kx}),Yn("device_preview_removed_event",{epoch:we,revision:Lt().int().nonnegative(),previewId:we}),Yn("device_preview_state_push",{scope:on,epoch:we,revision:Lt().int().nonnegative(),preview:kx},"proxy_to_client"),Yn("device_preview_removed_push",{scope:on,epoch:we,revision:Lt().int().nonnegative(),previewId:we},"proxy_to_client"),Yn("device_preview_stream_url_request",{...Dt,scope:on,previewId:we,profile:jee}),Cr("device_preview_stream_url_response",Ste),Cr("device_preview_stream_start",Tte),Cr("device_preview_stream_start_response",Cte),Yn("device_preview_stream_stop",{streamId:we,reason:$ee}),Cr("device_preview_stream_complete",kte),Yn("device_preview_input",{scope:on,leaseId:we,inputSeq:Lt().int().min(0).max(4294967295),input:Vee},"client_to_proxy"),Cr("device_preview_input_ack",Rte,"proxy_to_client"),Yn("device_preview_input_revoke",{leaseId:we,reason:Se("control_taken_over")}),Yn("device_preview_control_claim_request",{...Dt,scope:on,leaseId:we}),Cr("device_preview_control_claim_response",Ate),Yn("device_preview_control_revoked_push",{scope:on,leaseId:we,reason:rn(["taken_over","stream_closed","proxy_offline","lease_expired"])}),Yn("client_register",{protocolVersion:Se($l),clientId:we,userAgent:Ce().optional(),platform:Ce().optional(),maxTouchPoints:Lt().int().nonnegative().optional(),browserName:Ce().min(1),osName:Ce().min(1),deviceKind:rn(["desktop","tablet","phone","unknown"])}),Cr("client_register_response",lte),xt("proxy_offline",{proxyId:we}),xt("proxy_removed",{proxyId:we}),xt("proxy_disconnect",{proxyId:we}),xt("proxy_online",{proxyId:we}),Yn("dir_list_request",{...ir,path:Ce(),includeHidden:Ln()},"client_to_proxy"),xt("dir_list_response",{...ir,...Jr,entries:ur(Sj),path:Ce(),includeHidden:Ln()},"proxy_to_client"),xt("dir_create_request",{...ir,path:Ce()},"client_to_proxy"),xt("dir_create_response",{...ir,...Jr,path:Ce(),success:Ln()},"proxy_to_client"),xt("command_list_push",{sessionId:we,commands:ur(DP)},"proxy_to_client"),xt("file_tree_push",{groups:ur(LP)},"proxy_to_client"),Yn("session_list_request",{},"client_to_proxy"),xt("permission_mode_change",{mode:rn(["default","auto_accept","plan"]),sessionId:we.optional()},"client_to_proxy"),xt("session_history_request",Dt,"client_to_proxy"),xt("session_history_response",{...Dt,...Jr,success:Ln(),sessions:ur(ste)},"proxy_to_client"),xt("pty_state",{sessionId:we,payload:iee},"proxy_to_client"),xt("agent_status",{sessionId:we,payload:SP},"proxy_to_client"),xt("terminal_title",{sessionId:we,title:Ce()},"proxy_to_client"),xt("terminal_resize",{sessionId:we,cols:Lt().int().positive(),rows:Lt().int().positive(),outputSeq:Lt().int().nonnegative()},"proxy_to_client"),xt("terminal_resize_request",{sessionId:we,cols:Lt().int().positive(),rows:Lt().int().positive()},"client_to_proxy"),Yn("session_terminate",{sessionId:we},"client_to_proxy"),xt("session_rename",{...ir,sessionId:we,name:Ce()},"client_to_proxy"),xt("session_rename_response",{...ir,sessionId:we,success:Ln(),name:Ce().optional(),...Jr},"proxy_to_client"),xt("session_worker_abort",{sessionId:we},"client_to_proxy"),xt("turn_result",{sessionId:we,success:Ln(),isError:Ln(),result:Ce().optional()},"proxy_to_client"),xt("remote_input_raw",{sessionId:we,data:Ce(),traceId:we.optional()},"client_to_proxy"),Cr("proxy_info_request",hte,"client_to_proxy"),Cr("proxy_info",pte,"proxy_to_client"),xt("agent_cli_config_update",{...ir,provider:rn(na),path:Ce().min(1)},"client_to_proxy"),xt("agent_cli_config_update_response",{...ir,provider:rn(na),agentCli:xj.optional(),...Jr},"proxy_to_client"),Cr("session_create",Ite,"client_to_proxy"),Cr("session_create_response",Lte,"proxy_to_client"),xt("session_runtime_error",{sessionId:we,error:Ce(),errorCode:EC,activeWriterPid:Lt().int().positive().optional()},"proxy_to_client"),xt("session_messages_request",{...ir,sessionId:we,limit:Lt().int().min(1).max(200).optional(),before:Ce().optional()},"client_to_proxy"),xt("session_resources_request",{...Dt,sessionId:we},"client_to_proxy"),xt("session_resources_response",{...Dt,...Jr,sessionId:we,commands:ur(DP),groups:ur(LP)},"proxy_to_client"),xt("agent_status_request",{...ir,sessionId:we.optional()},"client_to_proxy"),xt("agent_status_response",{...ir,statuses:ur(qe({sessionId:we,payload:SP}))},"proxy_to_client"),xt("permission_request_delivered",{sessionId:we,requestId:we},"client_to_proxy"),xt("tool_approve",{sessionId:we,payload:GJ},"client_to_proxy"),xt("tool_deny",{sessionId:we,payload:XJ},"client_to_proxy"),xt("permission_decision_result",{sessionId:we,requestId:we,outcome:rn(["allow","deny"]),delivered:Ln(),message:Ce().optional()},"proxy_to_client"),xt("pending_approvals_push",{sessionId:we,approvals:ur(qe({requestId:we,toolName:Ce(),input:Ud(Ce(),Ba()),options:ur(dj).optional()}))},"proxy_to_client"),xt("voice_summary_request",{...ir,sessionId:we,messageId:we,text:Ce().min(1),reason:gee},"client_to_proxy"),xt("voice_summary_response",{...ir,...Jr,sessionId:we,messageId:we,success:Ln(),summary:Ce().min(1).optional()},"proxy_to_client"),xt("session_history_messages",{...ir,sessionId:we,before:Ce().optional(),messages:ur(ote),hasMore:Ln().optional(),nextBefore:Ce().optional()},"proxy_to_client"),xt("session_sync",{sessions:ur(hj({id:Ce(),cwd:Ce(),name:Ce().optional(),nameLocked:Ln().optional(),state:rn(_C)}))}),xt("session_subscribe",{sessionId:we,requestId:we},"client_to_proxy"),xt("session_snapshot",{sessionId:we,cols:Lt().int().positive(),rows:Lt().int().positive(),data:Ce(),outputSeq:Lt().int().nonnegative(),requestId:we},"proxy_to_client")],Dte=CC.map(e=>e.schema),Bte=Dn("type",Dte);new Set(CC.filter(e=>e.directions.has("proxy_to_client")).map(e=>e.type));new Set(CC.filter(e=>e.directions.has("client_to_proxy")).map(e=>e.type));const zte=3e4,jte=5e3,kC=zte+jte,yh={CLIENT_KICKED:4401,CLIENT_PROTOCOL_REJECTED:4402,DEVICE_STREAM_PROTOCOL_REJECTED:4403,DEVICE_STREAM_BINDING_REJECTED:4404,PROXY_PROTOCOL_REJECTED:4405},Wd={PAGE_OUTDATED:"page_outdated",SERVICE_OUTDATED:"service_outdated",PROTOCOL_MISMATCH:"protocol_mismatch"},bh=1,qg=4;function Fte(e){if(e.length<bh+qg)return null;const t=e[0];if(t===0||e.length<bh+t+qg)return null;const n=new TextDecoder().decode(e.subarray(bh,bh+t)),r=bh+t,i=new DataView(e.buffer,e.byteOffset+r,qg).getUint32(0,!0),s=e.subarray(r+qg);return{sessionId:n,outputSeq:i,data:s}}const zS=4,vy=2*1024*1024,$te=1,Hte=1,Ute=1,kj=2,Dv=4,Tj=$te+Hte+Ute,Wte=Tj+Dv,qte=Wte+zS,Vte=0,Yte=1,Ax=1,Nx=2,Yh=qte+kj;function Kte(e){return(e&-4)!==0||(e&(Ax|Nx))===(Ax|Nx)?null:{configuration:(e&Ax)!==0,keyframe:(e&Nx)!==0}}const _h=8;function Gte(e){if(e.length<Yh||e[0]!==Vte||e[1]!==Yte)return null;const t=Kte(e[2]);if(!t)return null;const n=new DataView(e.buffer,e.byteOffset+Tj,Dv+zS+kj),r=n.getUint32(0,!0);return r===0||r>vy?null:{annexBLength:r,packetSequence:n.getUint32(Dv,!0),...t,durationMs:n.getUint16(Dv+zS,!0)}}const Xte=132,Zte=32635;function Qte(e){let t=e;const n=t<0?128:0;t<0&&(t=-t),t=Math.min(t,Zte)+Xte;let r=7;for(let s=16384;r>0&&(t&s)===0;s>>=1)r-=1;const i=t>>r+3&15;return~(n|r<<4|i)&255}function Jte(e){const t=Math.floor(e.byteLength/2),n=new Uint8Array(t),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let i=0;i<t;i+=1)n[i]=Qte(r.getInt16(i*2,!0));return n}function ene(e){const t=new Set,n=Object.entries(e);for(const[i,s]of n)s.length===0&&t.add(i);let r=!0;for(;r;){r=!1;for(const[i,s]of n)t.has(i)||s.length>0&&s.every(o=>t.has(o))&&(t.add(i),r=!0)}return t}function $P(e){let t=e.initial;const n=ene(e.transitions),r=i=>{var l,u;const s=e.transitions[t];if(!(s!=null&&s.includes(i)))return(l=e.onRejected)==null||l.call(e,t,i,n.has(t)),!1;const o=t;return t=i,(u=e.onTransition)==null||u.call(e,o,i),!0};return{current:()=>t,is:i=>t===i,isIn:i=>i.includes(t),canTransitionTo:i=>{var s;return((s=e.transitions[t])==null?void 0:s.includes(i))??!1},transitionTo:i=>{if(!r(i))throw new Error(`Invalid FSM transition: ${t} -> ${i}`)},tryTransitionTo:r,isInAbsorbingState:()=>n.has(t)}}function TC(e,t){return!e||!t?null:`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function tne(e,t){return e.endsWith(`:${encodeURIComponent(t)}`)}function nne(){const e=Si("session",wn.ptyAutoYesSessions);if(!e)return{};try{const t=JSON.parse(e);return!t||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(n=>n[1]===!0))}catch{return{}}}function Vg(e){if(Object.entries(e).filter(([,n])=>n).length===0){Fd("session",wn.ptyAutoYesSessions);return}Tr("session",wn.ptyAutoYesSessions,JSON.stringify(e))}const Gt=$a()(Ha((e,t)=>({sessions:[],sessionListLoaded:!1,loadingProxyName:null,historySessions:[],historyLoadStatus:"idle",historyLoadGeneration:0,ptyTitles:{},ptyStateBySessionId:{},agentStatusBySessionId:{},ptyAutoYesBySessionKey:nne(),codexActiveWriterConflict:null,setSessions:n=>e(r=>{const i=new Set(n.map(s=>s.sessionId));return{sessions:n,sessionListLoaded:!0,loadingProxyName:null,agentStatusBySessionId:Object.fromEntries(Object.entries(r.agentStatusBySessionId).filter(([s])=>i.has(s))),ptyStateBySessionId:Object.fromEntries(Object.entries(r.ptyStateBySessionId).filter(([s])=>i.has(s))),ptyTitles:Object.fromEntries(Object.entries(r.ptyTitles).filter(([s])=>i.has(s)))}}),addSession:n=>e(r=>r.sessions.some(i=>i.sessionId===n.sessionId)?r:{sessions:[...r.sessions,n]}),removeSession:n=>e(r=>{const i=Object.fromEntries(Object.entries(r.ptyAutoYesBySessionKey).filter(([s])=>!tne(s,n)));return Vg(i),{sessions:r.sessions.filter(s=>s.sessionId!==n),agentStatusBySessionId:Object.fromEntries(Object.entries(r.agentStatusBySessionId).filter(([s])=>s!==n)),ptyStateBySessionId:Object.fromEntries(Object.entries(r.ptyStateBySessionId).filter(([s])=>s!==n)),ptyTitles:Object.fromEntries(Object.entries(r.ptyTitles).filter(([s])=>s!==n)),ptyAutoYesBySessionKey:i}}),updateSessionState:(n,r,i)=>e(s=>({sessions:s.sessions.map(o=>o.sessionId===n?{...o,state:r,...i!==void 0?{lastActive:i}:{}}:o)})),setAgentStatus:(n,r)=>e(i=>{const s=i.agentStatusBySessionId[n];return s&&s.seq>r.seq?i:{agentStatusBySessionId:{...i.agentStatusBySessionId,[n]:r}}}),setPtyState:(n,r)=>e(i=>{const s=i.ptyStateBySessionId[n];return s&&s.seq>r.seq?i:{ptyStateBySessionId:{...i.ptyStateBySessionId,[n]:r}}}),updateSessionName:(n,r)=>e(i=>({sessions:i.sessions.map(s=>s.sessionId===n?{...s,name:r}:s)})),renameSession:(n,r)=>e(i=>({sessions:i.sessions.map(s=>s.sessionId===n?{...s,name:r,nameLocked:!0}:s)})),setPtyTitle:(n,r)=>e(i=>({ptyTitles:{...i.ptyTitles,[n]:r}})),setPtyAutoYes:(n,r)=>e(i=>{const s={...i.ptyAutoYesBySessionKey};return r?s[n]=!0:delete s[n],Vg(s),{ptyAutoYesBySessionKey:s}}),setHistorySessions:n=>e(r=>({historySessions:n,historyLoadStatus:"loaded",historyLoadGeneration:r.historyLoadGeneration+1})),beginHistoryLoad:()=>{const n=t().historyLoadGeneration+1;return e({historyLoadStatus:"loading",historyLoadGeneration:n}),n},resolveHistoryLoad:(n,r)=>t().historyLoadGeneration!==n?!1:(e({historySessions:r,historyLoadStatus:"loaded"}),!0),rejectHistoryLoad:n=>t().historyLoadGeneration!==n?!1:(e({historyLoadStatus:"error"}),!0),cancelHistoryLoad:n=>t().historyLoadGeneration!==n?!1:(e({historyLoadStatus:"idle"}),!0),prepareForProxySwitch:n=>e(r=>({sessions:[],sessionListLoaded:!1,loadingProxyName:n,historySessions:[],historyLoadStatus:"idle",historyLoadGeneration:r.historyLoadGeneration+1,ptyTitles:{},ptyStateBySessionId:{},agentStatusBySessionId:{},codexActiveWriterConflict:null})),revokeProxyAuthorizations:n=>e(r=>{const i=`${encodeURIComponent(n)}:`,s=Object.fromEntries(Object.entries(r.ptyAutoYesBySessionKey).filter(([o])=>!o.startsWith(i)));return Vg(s),{ptyAutoYesBySessionKey:s}}),clearForProxyRemoval:n=>e(r=>{const i=`${encodeURIComponent(n)}:`,s=Object.fromEntries(Object.entries(r.ptyAutoYesBySessionKey).filter(([o])=>!o.startsWith(i)));return Vg(s),{sessions:[],sessionListLoaded:!1,loadingProxyName:null,historySessions:[],historyLoadStatus:"idle",historyLoadGeneration:r.historyLoadGeneration+1,ptyTitles:{},ptyStateBySessionId:{},agentStatusBySessionId:{},ptyAutoYesBySessionKey:s,codexActiveWriterConflict:null}}),setCodexActiveWriterConflict:n=>e({codexActiveWriterConflict:n})}),{name:"session-store"}));function eb(e,t){if(!e||/[\0\r\n]/.test(e))return null;const n=t?eb(t):null;let r,i,s;const o=/^([a-z]):[\\/]/i.exec(e),l=/^(?:\\\\|\/\/)([^\\/]+)[\\/]([^\\/]+)(?:[\\/]|$)/.exec(e);if(o)r=`${o[1].toUpperCase()}:\\`,i="\\",s=e.slice(o[0].length);else if(l&&!(e.startsWith("//")&&(n==null?void 0:n.separator)==="/")){if([l[1],l[2]].some(d=>d==="."||d===".."))return null;r=`\\\\${l[1]}\\${l[2]}\\`,i="\\",s=e.slice(l[0].length)}else if(e.startsWith("/"))r=(n==null?void 0:n.separator)==="\\"?n.root:"/",i=(n==null?void 0:n.separator)??"/",s=e;else return null;const u=[];for(const d of s.split(i==="\\"?/[\\/]/:/\//))!d||d==="."||(d===".."?u.pop():u.push(d));return{root:r,separator:i,parts:u}}function Hl(e,t){const n=eb(e,t);return n?n.root+n.parts.join(n.separator):""}function qd(e,t){var n;return((n=eb(e,t))==null?void 0:n.separator)??"/"}function wo(e,t=e){if(!e)return e;const n=qd(Hl(e,t)||t),r=n==="\\"?e.replaceAll("/","\\"):e;return r.endsWith(n)?r:`${r}${n}`}function RC(e,t){const n=eb(e,t);return n?n.root+n.parts.slice(0,-1).join(n.separator):""}function AC(e,t){const n=Hl(t,e);if(n)return n;if(/^[a-z]:/i.test(t)||t.startsWith("\\"))return"";const r=Hl(e);return r?Hl(`${wo(r)}${t}`):""}function HP(e,t){const n=Hl(e.trim()),r=t.trim();if(!n||!r||/^[a-z]:/i.test(r)||/^[\\/]/.test(r))return null;const i=qd(n)==="\\",s=r.replace(i?/[\\/]+$/:/\/+$/,"");return s.split(i?/[\\/]/:/\//).some(l=>!l||l==="."||l==="..")?null:AC(n,s)||null}const Li=$a()(Ha((e,t)=>({tree:new Map,treeWithHidden:new Map,cwd:"",homePath:"",agentCli:null,setDirEntries:(n,r,i=!1)=>{const s=Hl(n)||n;if(i){const l=new Map(t().treeWithHidden);l.set(s,r),e({treeWithHidden:l});return}const o=new Map(t().tree);o.set(s,r),e({tree:o})},setCwd:n=>e({cwd:n}),setHomePath:n=>e({homePath:n}),setAgentCli:n=>e({agentCli:n}),clearTree:()=>e({tree:new Map,treeWithHidden:new Map,cwd:""}),prepareForProxySwitch:()=>e({tree:new Map,treeWithHidden:new Map,cwd:"",homePath:"",agentCli:null})}),{name:"file-store"}));function rne(e){if(e.includes("Edg/")||e.includes("EdgiOS/"))return"Edge";if(e.includes("CriOS/")||e.includes("Chrome/"))return"Chrome";if(e.includes("FxiOS/")||e.includes("Firefox/"))return"Firefox";if(e.includes("OPiOS/"))return"Opera";if(e.includes("DuckDuckGo/"))return"DuckDuckGo";if(e.includes("Version/")&&e.includes("Safari/"))return"Safari"}function ine({userAgent:e="",platform:t,maxTouchPoints:n=0}){return t==="MacIntel"&&n>1&&(e.includes("Mac OS X")||e.includes("Macintosh"))}function sne(e){const t=e.userAgent??"";if(ine(e))return"iPad";if(t.includes("iPhone"))return"iPhone";if(t.includes("iPad"))return"iPad";if(t.includes("Mac OS X")||t.includes("Macintosh"))return"macOS";if(t.includes("Windows"))return"Windows";if(t.includes("Android"))return"Android"}function one(e){return e==="iPad"?"tablet":e==="iPhone"||e==="Android"?"phone":e==="macOS"||e==="Windows"?"desktop":"unknown"}function Rj(e){const t=e.browserName??(e.userAgent?rne(e.userAgent):void 0)??"浏览器",n=e.osName??sne(e)??"未知系统";return{...e,browserName:t,osName:n,deviceKind:e.deviceKind??one(n)}}function rf(){const e=typeof navigator>"u"?null:navigator;return Rj({...e!=null&&e.userAgent?{userAgent:e.userAgent}:{},...e!=null&&e.platform?{platform:e.platform}:{},...typeof(e==null?void 0:e.maxTouchPoints)=="number"?{maxTouchPoints:e.maxTouchPoints}:{}})}function ane(e){return`${e.browserName} · ${e.osName}`}function lne(e,t=$l){return e>t?Wd.PAGE_OUTDATED:e<t?Wd.SERVICE_OUTDATED:null}function Aj(e){return Object.values(Wd).some(t=>t===e)}const cne=1e4,une=5e3,Mx=15e3,dne=2e3,fne=1e4;class hne{constructor(t={}){je(this,"ws",null);je(this,"url","");je(this,"transportOpen",!1);je(this,"protocolReady",!1);je(this,"closed",!1);je(this,"reconnectTimer",null);je(this,"readyTimeoutTimer",null);je(this,"reconnectAttempt",0);je(this,"admissionSent",!1);je(this,"messageHandlers",new Set);je(this,"binarySubscribers",new Map);je(this,"statusHandlers",new Set);je(this,"pendingQueue",[]);je(this,"wakeListenersAttached",!1);je(this,"backgroundedAt",null);je(this,"connectionProbe",null);je(this,"connectionProbeSeq",0);je(this,"foregroundWatchdogTimer",null);je(this,"lastInboundAt",0);je(this,"probeConnectionLiveness");je(this,"visibilityListener",()=>{if(document.visibilityState==="hidden"){this.markBackgrounded();return}document.visibilityState==="visible"&&this.resumeFromBackground()});je(this,"onlineListener",()=>this.wakeReconnect(!0));je(this,"blurListener",()=>this.markBackgrounded());je(this,"focusListener",()=>{document.visibilityState!=="hidden"&&this.resumeFromBackground()});je(this,"pageHideListener",()=>this.markBackgrounded());je(this,"pageShowListener",()=>this.resumeFromBackground());const n=rf().deviceKind;this.probeConnectionLiveness=t.probeConnectionAfterBackground??(n==="phone"||n==="tablet")}markBackgrounded(){this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.backgroundedAt??(this.backgroundedAt=Date.now())}resumeFromBackground(){const t=this.backgroundedAt;this.backgroundedAt=null;const n=t!==null&&Date.now()-t>=une;if(this.probeConnectionLiveness&&n){this.probeConnection();return}this.wakeReconnect(),this.ensureForegroundWatchdog()}cancelConnectionProbe(t){const n=this.connectionProbe;!n||t&&n.socket!==t||(clearTimeout(n.timeout),this.connectionProbe=null)}cancelForegroundWatchdog(){this.foregroundWatchdogTimer&&(clearTimeout(this.foregroundWatchdogTimer),this.foregroundWatchdogTimer=null)}canRunForegroundWatchdog(){return this.probeConnectionLiveness&&!this.closed&&this.backgroundedAt===null&&(typeof document>"u"||document.visibilityState!=="hidden")}armForegroundWatchdog(t=Mx){this.cancelForegroundWatchdog(),!(!this.canRunForegroundWatchdog()||this.connectionProbe)&&(this.foregroundWatchdogTimer=setTimeout(()=>{this.foregroundWatchdogTimer=null,this.runForegroundWatchdog()},Math.max(0,t)))}ensureForegroundWatchdog(){this.foregroundWatchdogTimer||this.connectionProbe||this.armForegroundWatchdog()}runForegroundWatchdog(){if(!this.canRunForegroundWatchdog())return;const t=this.ws;if(!t||!this.transportOpen||!this.protocolReady||t.readyState!==WebSocket.OPEN){this.wakeReconnect(!0);return}const n=Date.now()-this.lastInboundAt;if(n<Mx){this.armForegroundWatchdog(Mx-n);return}this.probeConnection()}probeConnection(){if(this.closed)return;const t=this.ws;if(!this.transportOpen||!this.protocolReady||!t||t.readyState!==WebSocket.OPEN){this.wakeReconnect(!0);return}this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.connectionProbeSeq+=1;const n=`connection-liveness-${Date.now().toString(36)}-${this.connectionProbeSeq.toString(36)}`,r=setTimeout(()=>{const i=this.connectionProbe;!i||i.socket!==t||i.requestId!==n||(this.connectionProbe=null,!(this.ws!==t||this.closed)&&this.wakeReconnect(!0))},dne);this.connectionProbe={socket:t,requestId:n,timeout:r};try{t.send(JSON.stringify({type:"latency_web_relay_ping",requestId:n}))}catch{this.cancelConnectionProbe(t),this.ws===t&&!this.closed&&this.wakeReconnect(!0)}}consumeConnectionProbePong(t,n){const r=this.connectionProbe;if(!r||r.socket!==t)return!1;let i;try{i=JSON.parse(n)}catch{return!1}return i.type!=="latency_web_relay_pong"||i.requestId!==r.requestId?!1:(this.cancelConnectionProbe(t),!0)}noteInbound(t){this.ws===t&&(this.lastInboundAt=Date.now(),this.cancelConnectionProbe(t),this.ensureForegroundWatchdog())}cancelReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}cancelReadyTimeout(){this.readyTimeoutTimer&&(clearTimeout(this.readyTimeoutTimer),this.readyTimeoutTimer=null)}armReadyTimeout(t){this.cancelReadyTimeout(),this.readyTimeoutTimer=setTimeout(()=>{if(this.readyTimeoutTimer=null,!(this.closed||this.ws!==t||this.protocolReady)){this.cancelConnectionProbe(t),this.cancelForegroundWatchdog(),this.ws=null,this.transportOpen=!1,this.protocolReady=!1,this.admissionSent=!1;try{t.close()}catch{}this.statusHandlers.forEach(n=>n(!1,{willReconnect:!0,transportOpen:!1,protocolReady:!1})),this.scheduleReconnect()}},fne)}connect(t){this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.cancelReadyTimeout(),this.ws&&(this.ws.close(),this.ws=null),this.cancelReconnectTimer(),this.transportOpen=!1,this.protocolReady=!1,this.admissionSent=!1,this.url=t,this.closed=!1,this.attachWakeListeners(),this.doConnect()}attachWakeListeners(){this.wakeListenersAttached||typeof window>"u"||(this.wakeListenersAttached=!0,document.addEventListener("visibilitychange",this.visibilityListener),window.addEventListener("online",this.onlineListener),window.addEventListener("blur",this.blurListener),window.addEventListener("focus",this.focusListener),window.addEventListener("pagehide",this.pageHideListener),window.addEventListener("pageshow",this.pageShowListener))}detachWakeListeners(){!this.wakeListenersAttached||typeof window>"u"||(this.wakeListenersAttached=!1,document.removeEventListener("visibilitychange",this.visibilityListener),window.removeEventListener("online",this.onlineListener),window.removeEventListener("blur",this.blurListener),window.removeEventListener("focus",this.focusListener),window.removeEventListener("pagehide",this.pageHideListener),window.removeEventListener("pageshow",this.pageShowListener))}wakeReconnect(t=!1){if(this.closed||!t&&this.transportOpen||!t&&this.ws&&this.ws.readyState===WebSocket.CONNECTING)return;this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.cancelReadyTimeout(),this.cancelReconnectTimer();const n=this.ws,r=this.transportOpen;if(this.ws=null,this.transportOpen=!1,this.protocolReady=!1,this.admissionSent=!1,r&&this.statusHandlers.forEach(i=>i(!1,{willReconnect:!0,transportOpen:!1,protocolReady:!1})),n)try{n.close()}catch{}this.doConnect()}send(t,n={}){if(!this.protocolReady){if(n.queueWhenDisconnected&&!this.closed){if(this.pendingQueue.length>=cne){const r=this.pendingQueue.shift();console.warn("WebSocket queue overflow: dropping oldest pending message",r==null?void 0:r.slice(0,200))}this.pendingQueue.push(t)}return!this.ws&&!n.queueWhenDisconnected&&console.warn("WebSocket send dropped: no socket"),!1}return this.ws?(this.doSend(t),!0):(console.warn("WebSocket send dropped: no socket"),!1)}sendAdmission(t){return!this.ws||!this.transportOpen||this.protocolReady||this.admissionSent||this.ws.readyState!==WebSocket.OPEN?!1:(this.admissionSent=!0,this.doSend(t),!0)}close(){var t;this.closed=!0,this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.cancelReadyTimeout(),this.cancelReconnectTimer(),(t=this.ws)==null||t.close(),this.ws=null,this.transportOpen=!1,this.protocolReady=!1,this.admissionSent=!1,this.pendingQueue.length=0,this.backgroundedAt=null,this.detachWakeListeners()}onMessage(t){return this.messageHandlers.add(t),()=>this.messageHandlers.delete(t)}onStatusChange(t){return this.statusHandlers.add(t),()=>this.statusHandlers.delete(t)}isConnected(){return this.protocolReady}markProtocolReady(){!this.transportOpen||this.protocolReady||!this.ws||this.ws.readyState!==WebSocket.OPEN||(this.protocolReady=!0,this.reconnectAttempt=0,this.cancelReadyTimeout(),this.statusHandlers.forEach(t=>t(!0,{willReconnect:!1,transportOpen:!0,protocolReady:!0})),this.flushPendingQueue())}failPermanently(t){if(this.closed&&!this.ws&&!this.transportOpen)return;this.closed=!0,this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.cancelReadyTimeout(),this.cancelReconnectTimer(),this.backgroundedAt=null,this.detachWakeListeners(),this.pendingQueue.length=0;const n=this.ws,r=n!==null||this.transportOpen;this.ws=null,this.transportOpen=!1,this.protocolReady=!1,this.admissionSent=!1;try{n==null||n.close(yh.CLIENT_PROTOCOL_REJECTED,t)}catch{}r&&this.statusHandlers.forEach(i=>i(!1,{willReconnect:!1,transportOpen:!1,protocolReady:!1,closeCode:yh.CLIENT_PROTOCOL_REJECTED,disconnectReason:t}))}subscribeBinary(t,n){let r=this.binarySubscribers.get(t);return r||(r=new Set,this.binarySubscribers.set(t,r)),r.add(n),()=>{r.delete(n),r.size===0&&this.binarySubscribers.delete(t)}}doConnect(){const t=new WebSocket(this.url);t.binaryType="arraybuffer",this.ws=t,this.transportOpen=!1,this.protocolReady=!1,this.admissionSent=!1,this.armReadyTimeout(t),this.armForegroundWatchdog(),t.addEventListener("open",()=>{this.ws===t&&(this.transportOpen=!0,this.protocolReady=!1,this.lastInboundAt=Date.now(),this.armForegroundWatchdog(),this.statusHandlers.forEach(n=>n(!1,{willReconnect:!1,transportOpen:!0,protocolReady:!1})))}),t.addEventListener("message",n=>{if(this.ws===t)if(n.data instanceof ArrayBuffer){if(!this.protocolReady)return;this.noteInbound(t),this.dispatchBinary(new Uint8Array(n.data))}else{const r=n.data,i=this.consumeConnectionProbePong(t,r);if(this.noteInbound(t),i)return;this.messageHandlers.forEach(s=>s(r))}}),t.addEventListener("close",n=>{if(this.ws!==t)return;this.cancelConnectionProbe(t),this.cancelForegroundWatchdog(),this.cancelReadyTimeout(),(n.code===yh.CLIENT_KICKED||n.code===yh.CLIENT_PROTOCOL_REJECTED)&&(this.closed=!0,this.cancelReconnectTimer(),this.detachWakeListeners(),this.pendingQueue.length=0),this.transportOpen=!1,this.protocolReady=!1,this.admissionSent=!1,this.ws=null;const r=!this.closed,i=n.code===yh.CLIENT_PROTOCOL_REJECTED?Aj(n.reason)?n.reason:Wd.PROTOCOL_MISMATCH:void 0;this.statusHandlers.forEach(s=>s(!1,{willReconnect:r,transportOpen:!1,protocolReady:!1,...n.code?{closeCode:n.code}:{},...i?{disconnectReason:i}:{}})),r&&this.scheduleReconnect()}),t.addEventListener("error",()=>{})}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;const t=Math.min(1e3*Math.pow(2,this.reconnectAttempt),3e4),n=Math.random()*t;this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!this.closed&&this.doConnect()},n)}dispatchBinary(t){const n=Fte(t);if(!n)return;const r=this.binarySubscribers.get(n.sessionId);r&&r.forEach(i=>i(n.data,n.outputSeq))}doSend(t){var n;(n=this.ws)==null||n.send(t)}flushPendingQueue(){const t=this.pendingQueue.splice(0);for(const n of t)this.doSend(n)}}const pne=24,mne=48,gne=1,vne=4,yne=8,bne=8,_ne=32;function UP(e,t,n){return Math.min(n,Math.max(t,e))}function wne({viewportWidth:e,viewportHeight:t,sidebarWidth:n=0,safeAreaTop:r=0,safeAreaBottom:i=0,cellWidth:s,cellHeight:o}){if(e<=0||t<=0||s<=0||o<=0)return{cols:Lv,rows:IS};const l=Math.max(0,e-Math.max(0,n)-pne),u=Math.floor(l/s),f=u<Lv?_ne:bne,p=mne+gne+vne+yne+f+Math.max(0,r)+Math.max(0,i),y=Math.max(0,t-p),g=Math.floor(y/o);return{cols:UP(u,Lv,yC),rows:UP(g,IS,bC)}}function xne(){if(typeof document>"u"||!document.body)return{top:0,bottom:0};const e=document.createElement("div");Object.assign(e.style,{position:"fixed",visibility:"hidden",pointerEvents:"none",paddingTop:"env(safe-area-inset-top)",paddingBottom:"env(safe-area-inset-bottom)"}),document.body.append(e);const t=getComputedStyle(e),n={top:Number.parseFloat(t.paddingTop)||0,bottom:Number.parseFloat(t.paddingBottom)||0};return e.remove(),n}function Sne(e){const t={width:e*.5,height:e*1.25};if(typeof document>"u"||!document.body)return t;const n=document.createElement("span");n.textContent="W",Object.assign(n.style,{position:"fixed",left:"-9999px",top:"0",visibility:"hidden",whiteSpace:"pre",fontFamily:Az,fontSize:`${e}px`,fontWeight:"normal",fontStyle:"normal",fontVariant:"normal",letterSpacing:"0",lineHeight:"normal"}),document.body.append(n);const r=n.getBoundingClientRect();return n.remove(),{width:r.width>0?r.width:t.width,height:r.height>0?r.height:t.height}}function Ene(){if(typeof document>"u")return 0;const e=document.querySelector('[data-slot="sidebar"], [data-slot="sidebar-rail"]');if(!e)return 0;const t=e.getBoundingClientRect();return t.width>0&&t.height>0?t.width:0}function Cne(){const e=window.visualViewport,t=document.querySelector('[data-slot="app-shell"]'),n=t==null?void 0:t.getBoundingClientRect();return{width:Math.max(window.innerWidth,(e==null?void 0:e.width)??0,(n==null?void 0:n.width)??0),height:Math.max(window.innerHeight,(e==null?void 0:e.height)??0,(n==null?void 0:n.height)??0)}}function kne(e=jd){if(typeof window>"u")return{cols:Lv,rows:IS};const t=Cne(),n=xne(),r=Sne(e);return wne({viewportWidth:t.width,viewportHeight:t.height,sidebarWidth:Ene(),safeAreaTop:n.top,safeAreaBottom:n.bottom,cellWidth:r.width,cellHeight:r.height})}function Tne(e,t){if(e.length===0)throw new TypeError("PreviewScope proxyId must not be empty");if(t.length===0)throw new TypeError("PreviewScope bindingId must not be empty");return Object.freeze({proxyId:e,bindingId:t})}function tn(e,t){return e===t||e.proxyId===t.proxyId&&e.bindingId===t.bindingId}const On=1e4,Rne=2e4,Px=3e3,NC=200;function Ane(e){if(!e||typeof e!="object"||!("type"in e))return"(missing)";const t=e.type;return typeof t=="string"?t.slice(0,NC):"(invalid)"}function WP(e){return e.slice(0,2).map(t=>`${t.path.map(String).join(".")||"<root>"}:${t.code}`).join(",").slice(0,NC)}function Nne(e){let t;try{t=JSON.parse(e)}catch{return console.warn("RelayClient: invalid inbound JSON dropped",{length:e.length,preview:e.slice(0,NC)}),null}const n=cee.safeParse(t);if(n.success)return n.data;const r=Bte.safeParse(t);return r.success?r.data:(console.warn("RelayClient: malformed inbound message dropped",{type:Ane(t),envelope:WP(n.error.issues),control:WP(r.error.issues)}),null)}function Mne(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&t.type==="client_register_response"}catch{return!1}}let qP=0;function kn(e){return qP+=1,`${e}-${Date.now().toString(36)}-${qP.toString(36)}`}class Pne{constructor(t,n){je(this,"ws");je(this,"clientId");je(this,"boundProxyId",null);je(this,"previewScope",null);je(this,"messageHandlers",new Set);je(this,"pendingMessages",[]);je(this,"devicePreviewInputSequence",0);je(this,"registered",!1);this.ws=t,this.clientId=n,this.ws.onMessage(r=>{const i=Nne(r);if(!i){(!this.registered||Mne(r))&&this.ws.failPermanently(Wd.PROTOCOL_MISMATCH);return}if(i.type==="client_register_response")this.registered=!0,i.status==="restored"||i.status==="proxy_offline"?(this.boundProxyId=i.proxyId,this.previewScope=Object.freeze({proxyId:i.proxyId,bindingId:i.bindingId})):(this.boundProxyId=null,this.previewScope=null),this.ws.markProtocolReady();else if(!this.registered){this.ws.failPermanently(Wd.PROTOCOL_MISMATCH);return}if(this.messageHandlers.size===0){this.pendingMessages.push(i);return}this.dispatch(i)})}dispatch(t){this.messageHandlers.forEach(n=>{try{n(t)}catch(r){console.warn("RelayClient: message handler error:",t.type,r)}})}register(){this.registered=!1,this.boundProxyId=null,this.previewScope=null;const t=rf();this.ws.sendAdmission(JSON.stringify({type:"client_register",protocolVersion:$l,clientId:this.clientId,...t}))}listProxies(){this.ws.send(JSON.stringify({type:"proxy_list_request"}))}requestProxyList(t=On){const n=kn("proxy-list");return this.waitForMessage(r=>r.type==="proxy_list_response"&&r.requestId===n,()=>this.ws.send(JSON.stringify({type:"proxy_list_request",requestId:n})),"请求开发机列表超时",t,n).then(r=>r.proxies)}removeOfflineProxy(t,n=On){const r=kn("proxy-remove");return this.waitForMessage(i=>i.type==="proxy_remove_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"proxy_remove",requestId:r,proxyId:t})),"移除开发机超时",n,r).then(i=>(i.success&&this.clearBoundProxy(t),{proxyId:i.proxyId,success:i.success,error:i.error,errorCode:i.errorCode}))}requestRelayClients(t=On){const n=kn("relay-clients");return this.waitForMessage(r=>r.type==="relay_client_list_response"&&r.requestId===n,()=>this.ws.send(JSON.stringify({type:"relay_client_list_request",requestId:n})),"读取客户端列表超时",t,n).then(r=>r.clients)}kickRelayClient(t,n=On){const r=kn("relay-client-kick");return this.waitForMessage(i=>i.type==="relay_client_kick_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"relay_client_kick",requestId:r,clientId:t})),"断开客户端超时",n,r).then(i=>({clientId:i.clientId,success:i.success,error:i.error,errorCode:i.errorCode}))}selectProxy(t,n=On){const r=kn("proxy-select");return this.waitForMessage(i=>i.type==="proxy_select_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"proxy_select",requestId:r,proxyId:t})),"连接开发机超时",n,r).then(i=>i.success?(this.boundProxyId=i.proxyId,this.previewScope=Object.freeze({proxyId:i.proxyId,bindingId:i.bindingId}),{success:!0,proxyId:i.proxyId,bindingId:i.bindingId}):{success:!1,error:i.error,errorCode:i.errorCode})}createDirectory(t,n=On){const r=kn("dir-create");return this.waitForMessage(i=>i.type==="dir_create_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"dir_create_request",requestId:r,path:t})),"创建目录超时",n,r).then(i=>({success:i.success,path:i.path,error:i.error,errorCode:i.errorCode}))}requestDirectoryList(t,n={}){const r=kn("dir-list"),i=n.includeHidden??!1;return this.waitForMessage(s=>s.type==="dir_list_response"&&s.requestId===r,()=>this.ws.send(JSON.stringify({type:"dir_list_request",requestId:r,path:t,includeHidden:i})),"读取目录超时",n.timeoutMs??On,r).then(s=>({path:s.path,entries:s.entries,includeHidden:s.includeHidden,error:s.error,errorCode:s.errorCode}))}uploadClipboardImage(t,n){return this.uploadRemoteFile(t,n,"clipboard_image")}requestRemoteFileUrl(t,n,r,i=On){const s=kn("remote-file-url");return this.waitForMessage(o=>o.type==="remote_file_url_response"&&o.requestId===s&&o.sessionId===t,()=>this.ws.send(JSON.stringify({type:"remote_file_url_request",requestId:s,sessionId:t,path:n,disposition:r})),"读取文件地址超时",i,s).then(o=>({sessionId:o.sessionId,success:o.success,path:o.path,url:o.url,expiresAt:o.expiresAt,error:o.error,errorCode:o.errorCode}))}uploadFile(t,n){return this.uploadRemoteFile(t,n,"file")}requestRemoteFileUploadUrl(t,n,r,i=On){const s=kn("remote-file-upload-url");return this.waitForMessage(o=>o.type==="remote_file_upload_url_response"&&o.requestId===s&&o.sessionId===t,()=>this.ws.send(JSON.stringify({type:"remote_file_upload_url_request",requestId:s,sessionId:t,kind:r,fileName:n.name||"upload",mimeType:n.type||"application/octet-stream",size:n.size})),"创建上传地址超时",i,s)}async uploadRemoteFile(t,n,r){const i=await this.requestRemoteFileUploadUrl(t,n,r);if(!i.success||!i.uploadUrl)return{sessionId:i.sessionId,success:!1,error:i.error??"创建上传地址失败",errorCode:i.errorCode};const s=await fetch(i.uploadUrl,{method:"PUT",headers:{"Content-Type":n.type||"application/octet-stream"},body:n}),o=await s.json().catch(()=>({}));return s.ok?{sessionId:o.sessionId??t,success:o.success,path:o.path,error:o.error,errorCode:o.errorCode}:{sessionId:t,success:!1,error:o.error??"上传失败",errorCode:o.errorCode}}requestProxyInfo(t=On){const n=kn("proxy-info");return this.waitForMessage(r=>r.type==="proxy_info"&&r.requestId===n,()=>this.ws.send(JSON.stringify({type:"proxy_info_request",requestId:n})),"读取开发机信息超时",t,n).then(r=>({homePath:r.homePath,agentCli:r.agentCli}))}requestWebPreviewCapability(t,n=!1,r={}){const i=kn("preview-capability");return this.waitForMessage(s=>s.type==="preview_capability_response"&&s.requestId===i&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"preview_capability_request",requestId:i,refreshPath:n}),"检查网页预览支持情况超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{success:!0,capability:s.capability}:{success:!1,error:s.error,errorCode:s.errorCode})}sendPreviewRequest(t,n){const r=this.previewScope;if(!r||r.proxyId!==t.proxyId||r.bindingId!==t.bindingId)throw new Error("预览上下文已失效,请重新选择开发机");return this.ws.send(JSON.stringify({...n,scope:t}))}inspectStaticWebPreview(t,n,r={}){const i=kn("preview-static-inspect");return this.waitForMessage(s=>s.type==="preview_static_inspect_response"&&s.requestId===i&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"preview_static_inspect_request",requestId:i,path:n}),"检查本地网页超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{success:!0,entryPath:s.entryPath,htmlEntries:s.htmlEntries}:{success:!1,error:s.error,errorCode:s.errorCode})}createWebPreview(t,n,r){const i=kn("preview-create"),s=r.tunnelProvider,o=r.operationId,l=r.timeoutMs??On;return this.waitForMessage(u=>u.type==="preview_create_response"&&u.requestId===i&&u.operationId===o&&tn(u.scope,t),()=>this.sendPreviewRequest(t,{type:"preview_create_request",requestId:i,operationId:o,source:n,tunnelProvider:s,name:r.name}),"创建网页预览超时",l,i,r.signal).then(u=>u.accepted?{operationId:u.operationId,accepted:!0,previewId:u.previewId}:{operationId:u.operationId,accepted:!1,error:u.error,errorCode:u.errorCode})}requestWebPreviewList(t,n={}){const r=kn("preview-list");return this.waitForMessage(i=>i.type==="preview_list_response"&&i.requestId===r&&tn(i.scope,t),()=>this.sendPreviewRequest(t,{type:"preview_list_request",requestId:r}),"读取网页预览列表超时",n.timeoutMs??On,r,n.signal).then(i=>({epoch:i.epoch,revision:i.revision,previews:i.previews}))}renameWebPreview(t,n,r,i){const s=kn("preview-rename");return this.waitForMessage(o=>o.type==="preview_rename_response"&&o.requestId===s&&o.operationId===i.operationId&&o.previewId===n&&tn(o.scope,t),()=>this.sendPreviewRequest(t,{type:"preview_rename_request",requestId:s,operationId:i.operationId,previewId:n,name:r}),"重命名网页预览超时",i.timeoutMs??On,s,i.signal).then(o=>o.success?{operationId:o.operationId,previewId:o.previewId,success:!0}:{operationId:o.operationId,previewId:o.previewId,success:!1,error:o.error,errorCode:o.errorCode})}reconnectWebPreview(t,n,r){const i=kn("preview-reconnect");return this.waitForMessage(s=>s.type==="preview_reconnect_response"&&s.requestId===i&&s.operationId===r.operationId&&s.previewId===n&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"preview_reconnect_request",requestId:i,operationId:r.operationId,previewId:n}),"重新连接网页预览超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{operationId:s.operationId,previewId:s.previewId,success:!0}:{operationId:s.operationId,previewId:s.previewId,success:!1,error:s.error,errorCode:s.errorCode})}closeWebPreview(t,n,r){const i=kn("preview-close");return this.waitForMessage(s=>s.type==="preview_close_response"&&s.requestId===i&&s.operationId===r.operationId&&s.previewId===n&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"preview_close_request",requestId:i,operationId:r.operationId,previewId:n}),"关闭网页预览超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{operationId:s.operationId,previewId:s.previewId,success:!0}:{operationId:s.operationId,previewId:s.previewId,success:!1,error:s.error,errorCode:s.errorCode})}requestDevicePreviewCapability(t,n=!1,r={}){const i=kn("device-preview-capability");return this.waitForMessage(s=>s.type==="device_preview_capability_response"&&s.requestId===i&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_capability_request",requestId:i,refreshPath:n}),"检查模拟器支持情况超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{success:!0,capability:s.capability}:{success:!1,error:s.error,errorCode:s.errorCode})}requestDevicePreviewTargets(t,n=!1,r={}){const i=kn("device-preview-targets");return this.waitForMessage(s=>s.type==="device_preview_targets_response"&&s.requestId===i&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_targets_request",requestId:i,refresh:n}),"读取模拟器列表超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{success:!0,targets:s.targets}:{success:!1,error:s.error,errorCode:s.errorCode})}createDevicePreview(t,n,r){const i=kn("device-preview-create"),s=r.operationId;return this.waitForMessage(o=>o.type==="device_preview_create_response"&&o.requestId===i&&o.operationId===s&&tn(o.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_create_request",requestId:i,operationId:s,targetId:n,name:r.name}),"创建模拟器预览超时",r.timeoutMs??On,i,r.signal).then(o=>o.accepted?{operationId:o.operationId,accepted:!0,previewId:o.previewId}:{operationId:o.operationId,accepted:!1,error:o.error,errorCode:o.errorCode})}requestDevicePreviewList(t,n={}){const r=kn("device-preview-list");return this.waitForMessage(i=>i.type==="device_preview_list_response"&&i.requestId===r&&tn(i.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_list_request",requestId:r}),"读取模拟器预览列表超时",n.timeoutMs??On,r,n.signal).then(i=>({epoch:i.epoch,revision:i.revision,previews:i.previews}))}renameDevicePreview(t,n,r,i){const s=kn("device-preview-rename");return this.waitForMessage(o=>o.type==="device_preview_rename_response"&&o.requestId===s&&o.operationId===i.operationId&&o.previewId===n&&tn(o.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_rename_request",requestId:s,operationId:i.operationId,previewId:n,name:r}),"重命名模拟器预览超时",i.timeoutMs??On,s,i.signal).then(o=>o.success?{operationId:o.operationId,previewId:o.previewId,success:!0}:{operationId:o.operationId,previewId:o.previewId,success:!1,error:o.error,errorCode:o.errorCode})}reconnectDevicePreview(t,n,r){const i=kn("device-preview-reconnect");return this.waitForMessage(s=>s.type==="device_preview_reconnect_response"&&s.requestId===i&&s.operationId===r.operationId&&s.previewId===n&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_reconnect_request",requestId:i,operationId:r.operationId,previewId:n}),"重新连接模拟器预览超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{operationId:s.operationId,previewId:s.previewId,success:!0}:{operationId:s.operationId,previewId:s.previewId,success:!1,error:s.error,errorCode:s.errorCode})}closeDevicePreview(t,n,r){const i=kn("device-preview-close");return this.waitForMessage(s=>s.type==="device_preview_close_response"&&s.requestId===i&&s.operationId===r.operationId&&s.previewId===n&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_close_request",requestId:i,operationId:r.operationId,previewId:n}),"关闭模拟器预览超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{operationId:s.operationId,previewId:s.previewId,success:!0}:{operationId:s.operationId,previewId:s.previewId,success:!1,error:s.error,errorCode:s.errorCode})}requestDevicePreviewStream(t,n,r,i){const s=kn("device-preview-stream");return this.waitForMessage(o=>o.type==="device_preview_stream_url_response"&&o.requestId===s&&o.previewId===n&&tn(o.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_stream_url_request",requestId:s,previewId:n,profile:r}),"打开模拟器画面超时",i.timeoutMs??On,s,i.signal).then(o=>o.success?{previewId:o.previewId,success:!0,url:o.url,leaseId:o.leaseId,expiresAt:o.expiresAt,controlMode:o.controlMode}:{previewId:o.previewId,success:!1,error:o.error,errorCode:o.errorCode})}sendDevicePreviewInput(t,n,r,i){this.devicePreviewInputSequence=this.devicePreviewInputSequence+1>>>0;const s=this.devicePreviewInputSequence;return this.waitForMessage(o=>o.type==="device_preview_input_ack"&&o.leaseId===n&&o.inputSeq===s&&tn(o.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_input",leaseId:n,inputSeq:s,input:r}),"模拟器操作超时",i.timeoutMs??On,void 0,i.signal).then(o=>o.success?{leaseId:o.leaseId,inputSeq:o.inputSeq,success:!0}:{leaseId:o.leaseId,inputSeq:o.inputSeq,success:!1,error:o.error,errorCode:o.errorCode})}claimDevicePreviewControl(t,n,r){const i=kn("device-preview-control");return this.waitForMessage(s=>s.type==="device_preview_control_claim_response"&&s.requestId===i&&s.leaseId===n&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_control_claim_request",requestId:i,leaseId:n}),"获取模拟器控制权超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{success:!0,controlMode:s.controlMode}:{success:!1,error:s.error,errorCode:s.errorCode})}updateAgentCliPath(t,n,r=On){const i=kn("agent-cli-config");return this.waitForMessage(s=>s.type==="agent_cli_config_update_response"&&s.requestId===i,()=>this.ws.send(JSON.stringify({type:"agent_cli_config_update",requestId:i,provider:t,path:n})),"保存 Agent CLI 路径超时",r,i).then(s=>({provider:s.provider,agentCli:s.agentCli,error:s.error,errorCode:s.errorCode}))}requestVoiceConfig(t=On){const n=kn("voice-config");return this.waitForMessage(r=>r.type==="voice_config_response"&&r.requestId===n,()=>this.ws.send(JSON.stringify({type:"voice_config_request",requestId:n})),"读取语音设置超时",t,n).then(r=>({config:r.config,error:r.error,errorCode:r.errorCode}))}updateVoiceConfig(t,n=On){const r=kn("voice-config-update");return this.waitForMessage(i=>i.type==="voice_config_update_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"voice_config_update",requestId:r,config:t})),"保存语音设置超时",n,r).then(i=>({success:i.success,config:i.config,error:i.error,errorCode:i.errorCode}))}testVoiceConfig(t={},n=On){const r=kn("voice-config-test");return this.waitForMessage(i=>i.type==="voice_config_test_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"voice_config_test",requestId:r,config:t})),"测试语音配置超时",n,r).then(i=>({success:i.success,audioBase64:i.audioBase64,audioSampleRate:i.audioSampleRate,audioEncoding:i.audioEncoding,transcript:i.transcript,error:i.error,errorCode:i.errorCode}))}requestVoiceCapabilities(t={},n=On){const r=kn("voice-capabilities");return this.waitForMessage(i=>i.type==="voice_capabilities_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"voice_capabilities_request",requestId:r,...t.region?{region:t.region}:{}})),"读取语音能力列表超时",n,r).then(i=>({capabilities:i.capabilities,error:i.error,errorCode:i.errorCode}))}requestVoiceSummary(t,n,r,i,s=Rne){const o=kn("voice-summary");return this.waitForMessage(l=>l.type==="voice_summary_response"&&l.requestId===o&&l.sessionId===t&&l.messageId===n,()=>this.ws.send(JSON.stringify({type:"voice_summary_request",requestId:o,sessionId:t,messageId:n,text:r,reason:i})),"生成语音摘要超时",s,o).then(l=>({sessionId:l.sessionId,messageId:l.messageId,success:l.success,summary:l.summary,error:l.error,errorCode:l.errorCode}))}measureWebRelayLatency(t=Px){const n=kn("latency-web-relay"),r=performance.now();return this.waitForMessage(i=>i.type==="latency_web_relay_pong"&&i.requestId===n,()=>this.ws.send(JSON.stringify({type:"latency_web_relay_ping",requestId:n})),"Web 到 Relay 服务器测速超时",t,n).then(()=>({success:!0,rttMs:performance.now()-r}))}measureRelayProxyLatency(t=Px){const n=kn("latency-relay-proxy");return this.waitForMessage(r=>r.type==="latency_relay_proxy_response"&&r.requestId===n,()=>this.ws.send(JSON.stringify({type:"latency_relay_proxy_request",requestId:n})),"Relay 服务器到开发机测速超时",t,n).then(r=>({success:r.success,rttMs:r.rttMs,error:r.error}))}measureWebProxyLatency(t=Px){const n=kn("latency-web-proxy"),r=performance.now();return this.waitForMessage(i=>i.type==="latency_web_proxy_pong"&&i.requestId===n,()=>this.ws.send(JSON.stringify({type:"latency_web_proxy_ping",requestId:n})),"Web 到开发机测速超时",t,n).then(()=>({success:!0,rttMs:performance.now()-r}))}requestSessionHistory(t=On){const n=kn("session-history");return this.waitForMessage(r=>r.type==="session_history_response"&&r.requestId===n,()=>this.ws.send(JSON.stringify({type:"session_history_request",requestId:n})),"读取历史会话超时",t,n).then(r=>{if(!r.success)throw new Error(r.error??"读取历史会话失败");return r.sessions})}requestSessionMessages(t,n=On){return this.requestSessionMessagesPage(t,{},n).then(r=>r.messages)}requestSessionMessagesPage(t,n={},r=On){const i=kn("session-messages");return this.waitForMessage(s=>s.type==="session_history_messages"&&s.requestId===i&&s.sessionId===t,()=>this.ws.send(JSON.stringify({type:"session_messages_request",requestId:i,sessionId:t,...n.limit!==void 0?{limit:n.limit}:{},...n.before!==void 0?{before:n.before}:{}})),"读取会话消息超时",r,i).then(s=>({messages:s.messages,hasMore:s.hasMore??!1,...s.nextBefore!==void 0?{nextBefore:s.nextBefore}:{},...s.before!==void 0?{before:s.before}:{}}))}requestAgentStatuses(t,n=On){const r=kn("agent-status");return this.waitForMessage(i=>i.type==="agent_status_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"agent_status_request",requestId:r,...t?{sessionId:t}:{}})),"读取 Agent 状态超时",n,r).then(i=>i.statuses)}requestSessionResources(t,n=On){const r=kn("session-resources");return this.waitForMessage(i=>i.type==="session_resources_response"&&i.requestId===r&&i.sessionId===t,()=>this.ws.send(JSON.stringify({type:"session_resources_request",requestId:r,sessionId:t})),"读取会话资源超时",n,r).then(i=>({sessionId:i.sessionId,commands:i.commands,groups:i.groups,error:i.error,errorCode:i.errorCode}))}createSession(t,n=kC){const r=kn("session-create"),i=t.mode==="pty"?kne(Ie.getState().ptyFontSize):void 0;return this.waitForMessage(s=>s.type==="session_create_response"&&s.requestId===r,()=>this.ws.send(JSON.stringify({type:"session_create",requestId:r,...i,...t})),"创建超时,请检查开发机连接后重试",n)}renameSession(t,n,r=On){const i=kn("session-rename");return this.waitForMessage(s=>s.type==="session_rename_response"&&s.requestId===i&&s.sessionId===t,()=>this.ws.send(JSON.stringify({type:"session_rename",requestId:i,sessionId:t,name:n})),"重命名超时,请检查开发机连接后重试",r).then(s=>({sessionId:s.sessionId,success:s.success,name:s.name,error:s.error,errorCode:s.errorCode}))}sendEnvelope(t){return this.ws.send(JSON.stringify(t))}sendControl(t){return this.ws.send(JSON.stringify(t))}waitForMessage(t,n,r,i,s,o){return new Promise((l,u)=>{let d=!1,f=null,p=null,y=null;const g=()=>{f==null||f(),p==null||p(),o==null||o.removeEventListener("abort",w),y&&clearTimeout(y)},_=x=>{d||(d=!0,g(),x())},w=()=>{const x=new Error("请求已取消");x.name="AbortError",_(()=>u(x))};if(o!=null&&o.aborted){w();return}o==null||o.addEventListener("abort",w,{once:!0}),f=this.onMessage(x=>{if(t(x)){_(()=>l(x));return}if(s&&x.type==="relay_error"&&x.requestId===s){const S=x.message??"relay error";_(()=>u(new Error(`Relay 服务器拒绝请求: ${S}`)))}}),p=this.ws.onStatusChange((x,S)=>{x||(S==null?void 0:S.transportOpen)===!0||_(()=>u(new Error("连接已断开")))}),y=setTimeout(()=>{_(()=>u(new Error(r)))},i);try{n()===!1&&_(()=>u(new Error("连接已断开")))}catch(x){_(()=>u(x instanceof Error?x:new Error(String(x))))}})}getBoundProxyId(){return this.boundProxyId}getPreviewScope(){return this.previewScope}clearBoundProxy(t){(!t||this.boundProxyId===t)&&(this.boundProxyId=null,this.previewScope=null)}onMessage(t){if(this.messageHandlers.add(t),this.pendingMessages.length>0){const n=this.pendingMessages;this.pendingMessages=[];for(const r of n)this.dispatch(r)}return()=>{this.messageHandlers.delete(t)}}}var cu=uB();const Nj=Vp(cu);function Ine(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const One=e=>{switch(e){case"success":return Bne;case"info":return jne;case"warning":return zne;case"error":return Fne;default:return null}},Lne=Array(12).fill(0),Dne=({visible:e,className:t})=>ct.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ct.createElement("div",{className:"sonner-spinner"},Lne.map((n,r)=>ct.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),Bne=ct.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ct.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),zne=ct.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ct.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),jne=ct.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ct.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),Fne=ct.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ct.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),$ne=ct.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ct.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ct.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),Hne=()=>{const[e,t]=ct.useState(document.hidden);return ct.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let jS=1;class Une{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:r,...i}=t,s=typeof(t==null?void 0:t.id)=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:jS++,o=this.toasts.find(u=>u.id===s),l=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(s)&&this.dismissedToasts.delete(s),o?this.toasts=this.toasts.map(u=>u.id===s?(this.publish({...u,...t,id:s,title:r}),{...u,...t,id:s,dismissible:l,title:r}):u):this.addToast({title:r,...i,dismissible:l,id:s}),s},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const i=Promise.resolve(t instanceof Function?t():t);let s=r!==void 0,o;const l=i.then(async d=>{if(o=["resolve",d],ct.isValidElement(d))s=!1,this.create({id:r,type:"default",message:d});else if(qne(d)&&!d.ok){s=!1;const p=typeof n.error=="function"?await n.error(`HTTP error! status: ${d.status}`):n.error,y=typeof n.description=="function"?await n.description(`HTTP error! status: ${d.status}`):n.description,_=typeof p=="object"&&!ct.isValidElement(p)?p:{message:p};this.create({id:r,type:"error",description:y,..._})}else if(d instanceof Error){s=!1;const p=typeof n.error=="function"?await n.error(d):n.error,y=typeof n.description=="function"?await n.description(d):n.description,_=typeof p=="object"&&!ct.isValidElement(p)?p:{message:p};this.create({id:r,type:"error",description:y,..._})}else if(n.success!==void 0){s=!1;const p=typeof n.success=="function"?await n.success(d):n.success,y=typeof n.description=="function"?await n.description(d):n.description,_=typeof p=="object"&&!ct.isValidElement(p)?p:{message:p};this.create({id:r,type:"success",description:y,..._})}}).catch(async d=>{if(o=["reject",d],n.error!==void 0){s=!1;const f=typeof n.error=="function"?await n.error(d):n.error,p=typeof n.description=="function"?await n.description(d):n.description,g=typeof f=="object"&&!ct.isValidElement(f)?f:{message:f};this.create({id:r,type:"error",description:p,...g})}}).finally(()=>{s&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),u=()=>new Promise((d,f)=>l.then(()=>o[0]==="reject"?f(o[1]):d(o[1])).catch(f));return typeof r!="string"&&typeof r!="number"?{unwrap:u}:Object.assign(r,{unwrap:u})},this.custom=(t,n)=>{const r=(n==null?void 0:n.id)||jS++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const ys=new Une,Wne=(e,t)=>{const n=(t==null?void 0:t.id)||jS++;return ys.addToast({title:e,...t,id:n}),n},qne=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",Vne=Wne,Yne=()=>ys.toasts,Kne=()=>ys.getActiveToasts(),We=Object.assign(Vne,{success:ys.success,info:ys.info,warning:ys.warning,error:ys.error,custom:ys.custom,message:ys.message,promise:ys.promise,dismiss:ys.dismiss,loading:ys.loading},{getHistory:Yne,getToasts:Kne});Ine("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function Yg(e){return e.label!==void 0}const Gne=3,Xne="24px",Zne="16px",VP=4e3,Qne=356,Jne=14,ere=45,tre=200;function Lo(...e){return e.filter(Boolean).join(" ")}function nre(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const rre=e=>{var t,n,r,i,s,o,l,u,d;const{invert:f,toast:p,unstyled:y,interacting:g,setHeights:_,visibleToasts:w,heights:x,index:S,toasts:k,expanded:T,removeToast:N,defaultRichColors:P,closeButton:R,style:M,cancelButtonStyle:L,actionButtonStyle:X,className:U="",descriptionClassName:V="",duration:j,position:A,gap:D,expandByDefault:O,classNames:I,icons:B,closeButtonAriaLabel:F="Close toast"}=e,[Y,z]=ct.useState(null),[q,K]=ct.useState(null),[$,re]=ct.useState(!1),[Q,G]=ct.useState(!1),[Z,ae]=ct.useState(!1),[le,me]=ct.useState(!1),[ke,$e]=ct.useState(!1),[he,He]=ct.useState(0),[Nt,ye]=ct.useState(0),Ze=ct.useRef(p.duration||j||VP),Oe=ct.useRef(null),ze=ct.useRef(null),et=S===0,Ct=S+1<=w,tt=p.type,Le=p.dismissible!==!1,it=p.className||"",dt=p.descriptionClassName||"",be=ct.useMemo(()=>x.findIndex(W=>W.toastId===p.id)||0,[x,p.id]),Ve=ct.useMemo(()=>{var W;return(W=p.closeButton)!=null?W:R},[p.closeButton,R]),ft=ct.useMemo(()=>p.duration||j||VP,[p.duration,j]),St=ct.useRef(0),wt=ct.useRef(0),fn=ct.useRef(0),Xt=ct.useRef(null),[Jt,xn]=A.split("-"),mn=ct.useMemo(()=>x.reduce((W,ie,J)=>J>=be?W:W+ie.height,0),[x,be]),yt=Hne(),Zt=p.invert||f,zt=tt==="loading";wt.current=ct.useMemo(()=>be*D+mn,[be,mn]),ct.useEffect(()=>{Ze.current=ft},[ft]),ct.useEffect(()=>{re(!0)},[]),ct.useEffect(()=>{const W=ze.current;if(W){const ie=W.getBoundingClientRect().height;return ye(ie),_(J=>[{toastId:p.id,height:ie,position:p.position},...J]),()=>_(J=>J.filter(ce=>ce.toastId!==p.id))}},[_,p.id]),ct.useLayoutEffect(()=>{if(!$)return;const W=ze.current,ie=W.style.height;W.style.height="auto";const J=W.getBoundingClientRect().height;W.style.height=ie,ye(J),_(ce=>ce.find(te=>te.toastId===p.id)?ce.map(te=>te.toastId===p.id?{...te,height:J}:te):[{toastId:p.id,height:J,position:p.position},...ce])},[$,p.title,p.description,_,p.id,p.jsx,p.action,p.cancel]);const yn=ct.useCallback(()=>{G(!0),He(wt.current),_(W=>W.filter(ie=>ie.toastId!==p.id)),setTimeout(()=>{N(p)},tre)},[p,N,_,wt]);ct.useEffect(()=>{if(p.promise&&tt==="loading"||p.duration===1/0||p.type==="loading")return;let W;return T||g||yt?(()=>{if(fn.current<St.current){const ce=new Date().getTime()-St.current;Ze.current=Ze.current-ce}fn.current=new Date().getTime()})():(()=>{Ze.current!==1/0&&(St.current=new Date().getTime(),W=setTimeout(()=>{p.onAutoClose==null||p.onAutoClose.call(p,p),yn()},Ze.current))})(),()=>clearTimeout(W)},[T,g,p,tt,yt,yn]),ct.useEffect(()=>{p.delete&&(yn(),p.onDismiss==null||p.onDismiss.call(p,p))},[yn,p.delete]);function $n(){var W;if(B!=null&&B.loading){var ie;return ct.createElement("div",{className:Lo(I==null?void 0:I.loader,p==null||(ie=p.classNames)==null?void 0:ie.loader,"sonner-loader"),"data-visible":tt==="loading"},B.loading)}return ct.createElement(Dne,{className:Lo(I==null?void 0:I.loader,p==null||(W=p.classNames)==null?void 0:W.loader),visible:tt==="loading"})}const Zn=p.icon||(B==null?void 0:B[tt])||One(tt);var Jn,gn;return ct.createElement("li",{tabIndex:0,ref:ze,className:Lo(U,it,I==null?void 0:I.toast,p==null||(t=p.classNames)==null?void 0:t.toast,I==null?void 0:I.default,I==null?void 0:I[tt],p==null||(n=p.classNames)==null?void 0:n[tt]),"data-sonner-toast":"","data-rich-colors":(Jn=p.richColors)!=null?Jn:P,"data-styled":!(p.jsx||p.unstyled||y),"data-mounted":$,"data-promise":!!p.promise,"data-swiped":ke,"data-removed":Q,"data-visible":Ct,"data-y-position":Jt,"data-x-position":xn,"data-index":S,"data-front":et,"data-swiping":Z,"data-dismissible":Le,"data-type":tt,"data-invert":Zt,"data-swipe-out":le,"data-swipe-direction":q,"data-expanded":!!(T||O&&$),"data-testid":p.testId,style:{"--index":S,"--toasts-before":S,"--z-index":k.length-S,"--offset":`${Q?he:wt.current}px`,"--initial-height":O?"auto":`${Nt}px`,...M,...p.style},onDragEnd:()=>{ae(!1),z(null),Xt.current=null},onPointerDown:W=>{W.button!==2&&(zt||!Le||(Oe.current=new Date,He(wt.current),W.target.setPointerCapture(W.pointerId),W.target.tagName!=="BUTTON"&&(ae(!0),Xt.current={x:W.clientX,y:W.clientY})))},onPointerUp:()=>{var W,ie,J;if(le||!Le)return;Xt.current=null;const ce=Number(((W=ze.current)==null?void 0:W.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Te=Number(((ie=ze.current)==null?void 0:ie.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),te=new Date().getTime()-((J=Oe.current)==null?void 0:J.getTime()),se=Y==="x"?ce:Te,ue=Math.abs(se)/te;if(Math.abs(se)>=ere||ue>.11){He(wt.current),p.onDismiss==null||p.onDismiss.call(p,p),K(Y==="x"?ce>0?"right":"left":Te>0?"down":"up"),yn(),me(!0);return}else{var ge,ee;(ge=ze.current)==null||ge.style.setProperty("--swipe-amount-x","0px"),(ee=ze.current)==null||ee.style.setProperty("--swipe-amount-y","0px")}$e(!1),ae(!1),z(null)},onPointerMove:W=>{var ie,J,ce;if(!Xt.current||!Le||((ie=window.getSelection())==null?void 0:ie.toString().length)>0)return;const te=W.clientY-Xt.current.y,se=W.clientX-Xt.current.x;var ue;const ge=(ue=e.swipeDirections)!=null?ue:nre(A);!Y&&(Math.abs(se)>1||Math.abs(te)>1)&&z(Math.abs(se)>Math.abs(te)?"x":"y");let ee={x:0,y:0};const oe=de=>1/(1.5+Math.abs(de)/20);if(Y==="y"){if(ge.includes("top")||ge.includes("bottom"))if(ge.includes("top")&&te<0||ge.includes("bottom")&&te>0)ee.y=te;else{const de=te*oe(te);ee.y=Math.abs(de)<Math.abs(te)?de:te}}else if(Y==="x"&&(ge.includes("left")||ge.includes("right")))if(ge.includes("left")&&se<0||ge.includes("right")&&se>0)ee.x=se;else{const de=se*oe(se);ee.x=Math.abs(de)<Math.abs(se)?de:se}(Math.abs(ee.x)>0||Math.abs(ee.y)>0)&&$e(!0),(J=ze.current)==null||J.style.setProperty("--swipe-amount-x",`${ee.x}px`),(ce=ze.current)==null||ce.style.setProperty("--swipe-amount-y",`${ee.y}px`)}},Ve&&!p.jsx&&tt!=="loading"?ct.createElement("button",{"aria-label":F,"data-disabled":zt,"data-close-button":!0,onClick:zt||!Le?()=>{}:()=>{yn(),p.onDismiss==null||p.onDismiss.call(p,p)},className:Lo(I==null?void 0:I.closeButton,p==null||(r=p.classNames)==null?void 0:r.closeButton)},(gn=B==null?void 0:B.close)!=null?gn:$ne):null,(tt||p.icon||p.promise)&&p.icon!==null&&((B==null?void 0:B[tt])!==null||p.icon)?ct.createElement("div",{"data-icon":"",className:Lo(I==null?void 0:I.icon,p==null||(i=p.classNames)==null?void 0:i.icon)},p.promise||p.type==="loading"&&!p.icon?p.icon||$n():null,p.type!=="loading"?Zn:null):null,ct.createElement("div",{"data-content":"",className:Lo(I==null?void 0:I.content,p==null||(s=p.classNames)==null?void 0:s.content)},ct.createElement("div",{"data-title":"",className:Lo(I==null?void 0:I.title,p==null||(o=p.classNames)==null?void 0:o.title)},p.jsx?p.jsx:typeof p.title=="function"?p.title():p.title),p.description?ct.createElement("div",{"data-description":"",className:Lo(V,dt,I==null?void 0:I.description,p==null||(l=p.classNames)==null?void 0:l.description)},typeof p.description=="function"?p.description():p.description):null),ct.isValidElement(p.cancel)?p.cancel:p.cancel&&Yg(p.cancel)?ct.createElement("button",{"data-button":!0,"data-cancel":!0,style:p.cancelButtonStyle||L,onClick:W=>{Yg(p.cancel)&&Le&&(p.cancel.onClick==null||p.cancel.onClick.call(p.cancel,W),yn())},className:Lo(I==null?void 0:I.cancelButton,p==null||(u=p.classNames)==null?void 0:u.cancelButton)},p.cancel.label):null,ct.isValidElement(p.action)?p.action:p.action&&Yg(p.action)?ct.createElement("button",{"data-button":!0,"data-action":!0,style:p.actionButtonStyle||X,onClick:W=>{Yg(p.action)&&(p.action.onClick==null||p.action.onClick.call(p.action,W),!W.defaultPrevented&&yn())},className:Lo(I==null?void 0:I.actionButton,p==null||(d=p.classNames)==null?void 0:d.actionButton)},p.action.label):null)};function YP(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function ire(e,t){const n={};return[e,t].forEach((r,i)=>{const s=i===1,o=s?"--mobile-offset":"--offset",l=s?Zne:Xne;function u(d){["top","right","bottom","left"].forEach(f=>{n[`${o}-${f}`]=typeof d=="number"?`${d}px`:d})}typeof r=="number"||typeof r=="string"?u(r):typeof r=="object"?["top","right","bottom","left"].forEach(d=>{r[d]===void 0?n[`${o}-${d}`]=l:n[`${o}-${d}`]=typeof r[d]=="number"?`${r[d]}px`:r[d]}):u(l)}),n}const sre=ct.forwardRef(function(t,n){const{id:r,invert:i,position:s="bottom-right",hotkey:o=["altKey","KeyT"],expand:l,closeButton:u,className:d,offset:f,mobileOffset:p,theme:y="light",richColors:g,duration:_,style:w,visibleToasts:x=Gne,toastOptions:S,dir:k=YP(),gap:T=Jne,icons:N,containerAriaLabel:P="Notifications"}=t,[R,M]=ct.useState([]),L=ct.useMemo(()=>r?R.filter($=>$.toasterId===r):R.filter($=>!$.toasterId),[R,r]),X=ct.useMemo(()=>Array.from(new Set([s].concat(L.filter($=>$.position).map($=>$.position)))),[L,s]),[U,V]=ct.useState([]),[j,A]=ct.useState(!1),[D,O]=ct.useState(!1),[I,B]=ct.useState(y!=="system"?y:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),F=ct.useRef(null),Y=o.join("+").replace(/Key/g,"").replace(/Digit/g,""),z=ct.useRef(null),q=ct.useRef(!1),K=ct.useCallback($=>{M(re=>{var Q;return(Q=re.find(G=>G.id===$.id))!=null&&Q.delete||ys.dismiss($.id),re.filter(({id:G})=>G!==$.id)})},[]);return ct.useEffect(()=>ys.subscribe($=>{if($.dismiss){requestAnimationFrame(()=>{M(re=>re.map(Q=>Q.id===$.id?{...Q,delete:!0}:Q))});return}setTimeout(()=>{Nj.flushSync(()=>{M(re=>{const Q=re.findIndex(G=>G.id===$.id);return Q!==-1?[...re.slice(0,Q),{...re[Q],...$},...re.slice(Q+1)]:[$,...re]})})})}),[R]),ct.useEffect(()=>{if(y!=="system"){B(y);return}if(y==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?B("dark"):B("light")),typeof window>"u")return;const $=window.matchMedia("(prefers-color-scheme: dark)");try{$.addEventListener("change",({matches:re})=>{B(re?"dark":"light")})}catch{$.addListener(({matches:Q})=>{try{B(Q?"dark":"light")}catch(G){console.error(G)}})}},[y]),ct.useEffect(()=>{R.length<=1&&A(!1)},[R]),ct.useEffect(()=>{const $=re=>{var Q;if(o.every(ae=>re[ae]||re.code===ae)){var Z;A(!0),(Z=F.current)==null||Z.focus()}re.code==="Escape"&&(document.activeElement===F.current||(Q=F.current)!=null&&Q.contains(document.activeElement))&&A(!1)};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[o]),ct.useEffect(()=>{if(F.current)return()=>{z.current&&(z.current.focus({preventScroll:!0}),z.current=null,q.current=!1)}},[F.current]),ct.createElement("section",{ref:n,"aria-label":`${P} ${Y}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},X.map(($,re)=>{var Q;const[G,Z]=$.split("-");return L.length?ct.createElement("ol",{key:$,dir:k==="auto"?YP():k,tabIndex:-1,ref:F,className:d,"data-sonner-toaster":!0,"data-sonner-theme":I,"data-y-position":G,"data-x-position":Z,style:{"--front-toast-height":`${((Q=U[0])==null?void 0:Q.height)||0}px`,"--width":`${Qne}px`,"--gap":`${T}px`,...w,...ire(f,p)},onBlur:ae=>{q.current&&!ae.currentTarget.contains(ae.relatedTarget)&&(q.current=!1,z.current&&(z.current.focus({preventScroll:!0}),z.current=null))},onFocus:ae=>{ae.target instanceof HTMLElement&&ae.target.dataset.dismissible==="false"||q.current||(q.current=!0,z.current=ae.relatedTarget)},onMouseEnter:()=>A(!0),onMouseMove:()=>A(!0),onMouseLeave:()=>{D||A(!1)},onDragEnd:()=>A(!1),onPointerDown:ae=>{ae.target instanceof HTMLElement&&ae.target.dataset.dismissible==="false"||O(!0)},onPointerUp:()=>O(!1)},L.filter(ae=>!ae.position&&re===0||ae.position===$).map((ae,le)=>{var me,ke;return ct.createElement(rre,{key:ae.id,icons:N,index:le,toast:ae,defaultRichColors:g,duration:(me=S==null?void 0:S.duration)!=null?me:_,className:S==null?void 0:S.className,descriptionClassName:S==null?void 0:S.descriptionClassName,invert:i,visibleToasts:x,closeButton:(ke=S==null?void 0:S.closeButton)!=null?ke:u,interacting:D,position:$,style:S==null?void 0:S.style,unstyled:S==null?void 0:S.unstyled,classNames:S==null?void 0:S.classNames,cancelButtonStyle:S==null?void 0:S.cancelButtonStyle,actionButtonStyle:S==null?void 0:S.actionButtonStyle,closeButtonAriaLabel:S==null?void 0:S.closeButtonAriaLabel,removeToast:K,toasts:L.filter($e=>$e.position==ae.position),heights:U.filter($e=>$e.position==ae.position),setHeights:V,expandByDefault:l,gap:T,expanded:j,swipeDirections:t.swipeDirections})})):null}))});function ore(){const e=Ie(t=>t.themePreference);return m.jsx(sre,{theme:e==="auto"?"system":e,position:"top-center",toastOptions:{classNames:{toast:"bg-card text-foreground border border-border",success:"border-l-4 !border-l-[var(--color-status-success)]",error:"border-l-4 !border-l-[var(--color-status-error)]",warning:"border-l-4 !border-l-[var(--color-status-warning)]",info:"border-l-4 !border-l-[var(--color-status-working)]"}}})}function FS(e){return"error"in e}async function $S(e,t){let n=t.proxyId;if(n&&e.getBoundProxyId()===n)return{proxyId:n};if(!n&&t.sessionId){let i;try{i=await e.requestProxyList()}catch(o){return{error:o instanceof Error?o.message:String(o),code:Rr.UNKNOWN}}const s=i.find(o=>{var l;return(l=o.sessions)==null?void 0:l.includes(t.sessionId)});if(!s)return{error:`Session ${t.sessionId} not found on any proxy`,code:Rr.SESSION_NOT_FOUND};n=s.proxyId}if(!n)return{error:"No proxy specified",code:Rr.UNKNOWN};let r;try{r=await e.selectProxy(n)}catch(i){return{error:i instanceof Error?i.message:String(i),code:Rr.UNKNOWN}}return r.success?{proxyId:n}:{error:r.error||"Proxy select failed",code:r.errorCode??Rr.UNKNOWN}}function are(e){const t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function tb(e,t=globalThis.crypto??null){if(typeof(t==null?void 0:t.randomUUID)=="function")try{return`${e}-${t.randomUUID()}`}catch{}if(typeof(t==null?void 0:t.getRandomValues)=="function")try{const n=new Uint8Array(16);return t.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128,`${e}-${are(n)}`}catch{}throw new Error("当前浏览器无法生成预览操作标识")}function nb(e){return Object.freeze({operations:Object.freeze(e.slice())})}function lre(e){if(e.operationId.length===0)throw new TypeError("Preview pending operationId must not be empty");if(e.fingerprint.length===0)throw new TypeError("Preview pending fingerprint must not be empty");if(e.kind!=="create"&&e.previewId.length===0)throw new TypeError("Preview pending previewId must not be empty");if(e.previewKind!=="web"&&e.previewKind!=="device")throw new TypeError("Preview pending previewKind must be web or device");if(!Number.isFinite(e.startedAt))throw new TypeError("Preview pending startedAt must be finite")}function cre(e,t){return e.kind!==t.kind||e.previewKind!==t.previewKind||e.fingerprint!==t.fingerprint?!1:e.kind==="create"||t.kind==="create"?e.kind===t.kind:e.previewId===t.previewId}function KP(){return nb([])}function Mj(e,t,n){return e.operations.find(r=>r.operationId===n&&tn(r.scope,t))}function ure(e,t,n){return e.operations.filter(r=>r.previewKind===n&&tn(r.scope,t))}function Pj(e,t,n,r){return e.operations.filter(i=>i.kind!=="create"&&i.previewKind===n&&i.previewId===r&&tn(i.scope,t))}function dre(e,t){lre(t);const n=Mj(e,t.scope,t.operationId);if(n)return cre(n,t)?{status:"ignored",reason:"duplicate",registry:e,operation:n}:{status:"conflict",reason:"operation-id-conflict",registry:e,existing:n};const r=Object.freeze({...t});return{status:"applied",registry:nb([...e.operations,r]),operation:r}}function fre(e,t,n){const r=e.operations.findIndex(s=>s.operationId===n&&tn(s.scope,t));if(r<0)return{status:"ignored",reason:"not-found",registry:e};const i=e.operations[r];return{status:"applied",registry:nb([...e.operations.slice(0,r),...e.operations.slice(r+1)]),operation:i}}function hre(e,t){const n=e.operations.filter(r=>!tn(r.scope,t));return n.length===e.operations.length?e:nb(n)}function pre(e){return Object.freeze(e.slice())}function Ij(e,t){if(e.length===0)throw new TypeError("Preview epoch must not be empty");if(!Number.isSafeInteger(t)||t<0)throw new TypeError("Preview revision must be a non-negative safe integer")}function mre(e){const t=new Set;for(const n of e){if(n.previewId.length===0)throw new TypeError("Preview id must not be empty");if(t.has(n.previewId))throw new TypeError(`Duplicate preview id in snapshot: ${n.previewId}`);t.add(n.previewId)}}function HS(e,t,n,r){return Object.freeze({scope:e,syncStatus:"synchronized",epoch:t,revision:n,previews:pre(r)})}function US(e,t){return Object.freeze({scope:e.scope,syncStatus:"needs-resync",epoch:e.epoch,revision:e.revision,previews:e.previews,resyncCause:Object.freeze(t)})}function gre(e,t){const n=e.findIndex(r=>r.previewId===t.previewId);return n<0?[...e,t]:e.map((r,i)=>i===n?t:r)}function vre(e,t){if(Ij(t.epoch,t.revision),mre(t.previews),!tn(e.scope,t.scope))return{status:"ignored",reason:"scope-mismatch",state:e};if(e.syncStatus==="needs-resync"){const n=e.resyncCause;return t.epoch===n.observedEpoch&&t.revision<n.observedRevision?{status:"needs-resync",reason:"resync-pending",state:e}:{status:"applied",reason:e.epoch!==t.epoch?"epoch-replaced":"snapshot",state:HS(e.scope,t.epoch,t.revision,t.previews)}}if(e.syncStatus==="synchronized"&&e.epoch===t.epoch){if(t.revision<e.revision)return{status:"ignored",reason:"stale-revision",state:e};if(t.revision===e.revision)return{status:"ignored",reason:"duplicate-revision",state:e}}return{status:"applied",reason:e.syncStatus==="synchronized"&&e.epoch!==t.epoch?"epoch-replaced":"snapshot",state:HS(e.scope,t.epoch,t.revision,t.previews)}}function yre(e,t){const n=e.resyncCause,r=n.observedEpoch===t.epoch?Math.max(n.observedRevision,t.revision):t.revision;return n.observedEpoch===t.epoch&&n.observedRevision===r?e:US(e,{reason:n.observedEpoch===t.epoch?n.reason:"unknown-epoch",observedEpoch:t.epoch,observedRevision:r})}function bre(e,t){if(Ij(t.epoch,t.revision),t.kind==="state"&&t.preview.previewId.length===0)throw new TypeError("Preview id must not be empty");if(t.kind==="removed"&&t.previewId.length===0)throw new TypeError("Preview id must not be empty");if(!tn(e.scope,t.scope))return{status:"ignored",reason:"scope-mismatch",state:e};if(e.syncStatus==="needs-resync")return{status:"needs-resync",reason:"resync-pending",state:yre(e,t)};if(e.syncStatus==="awaiting-snapshot"||e.epoch!==t.epoch)return{status:"needs-resync",reason:"unknown-epoch",state:US(e,{reason:"unknown-epoch",observedEpoch:t.epoch,observedRevision:t.revision})};if(t.revision<e.revision)return{status:"ignored",reason:"stale-revision",state:e};if(t.revision===e.revision)return{status:"ignored",reason:"duplicate-revision",state:e};if(t.revision!==e.revision+1)return{status:"needs-resync",reason:"revision-gap",state:US(e,{reason:"revision-gap",observedEpoch:t.epoch,observedRevision:t.revision})};const n=t.kind==="state"?gre(e.previews,t.preview):e.previews.filter(r=>r.previewId!==t.previewId);return{status:"applied",reason:"event",state:HS(e.scope,e.epoch,t.revision,n)}}function Oj(e){return Object.freeze({scope:e,syncStatus:"awaiting-snapshot",epoch:null,revision:-1,previews:Object.freeze([])})}function Lj(e,t){return t.kind==="snapshot"?vre(e,t):bre(e,t)}const Ix={authoritative:null,targets:[],capability:null,capabilityStatus:"idle",capabilityError:null,targetsStatus:"idle",targetsError:null,listLoaded:!1};function Ox(e,t,n){const r=t().authoritative;if(!r)return null;const i=Lj(r,n),s=n.kind==="snapshot"&&tn(r.scope,n.scope);return(i.state!==r||s&&!t().listLoaded)&&e({authoritative:i.state,...s?{listLoaded:!0}:{}}),i}const Dj=e=>{var t;return((t=e.authoritative)==null?void 0:t.previews)??[]},gr=$a()(Ha((e,t)=>({...Ix,activateScope:n=>e({...Ix,authoritative:Oj(n)}),replaceSnapshot:(n,r)=>Ox(e,t,{kind:"snapshot",scope:n,epoch:r.epoch,revision:r.revision,previews:r.previews}),applyPreviewState:(n,r,i,s)=>Ox(e,t,{kind:"state",scope:n,epoch:i,revision:s,preview:r}),applyPreviewRemoved:(n,r,i,s)=>Ox(e,t,{kind:"removed",scope:n,epoch:i,revision:s,previewId:r}),setCapabilityLoading:n=>{var i;const r=(i=t().authoritative)==null?void 0:i.scope;!r||!tn(r,n)||e({capabilityStatus:"loading",capabilityError:null})},setCapability:(n,r)=>{var s;const i=(s=t().authoritative)==null?void 0:s.scope;!i||!tn(i,n)||e({capability:r,capabilityStatus:"loaded",capabilityError:null})},setCapabilityError:(n,r)=>{var s;const i=(s=t().authoritative)==null?void 0:s.scope;!i||!tn(i,n)||e({capabilityStatus:"error",capabilityError:r})},setTargetsLoading:n=>{var i;const r=(i=t().authoritative)==null?void 0:i.scope;!r||!tn(r,n)||e({targetsStatus:"loading",targetsError:null})},setTargets:(n,r)=>{var s;const i=(s=t().authoritative)==null?void 0:s.scope;!i||!tn(i,n)||e({targets:r,targetsStatus:"loaded",targetsError:null})},setTargetsError:(n,r)=>{var s;const i=(s=t().authoritative)==null?void 0:s.scope;!i||!tn(i,n)||e({targetsStatus:"error",targetsError:r})},markListLoading:n=>{var i;const r=(i=t().authoritative)==null?void 0:i.scope;!r||!tn(r,n)||e({listLoaded:!1})},clear:()=>e({...Ix})}),{name:"device-preview-store"})),qo=$a()(Ha((e,t)=>({registry:KP(),begin:n=>{const r=dre(t().registry,n);return r.registry!==t().registry&&e({registry:r.registry}),r},finish:(n,r)=>{const i=fre(t().registry,n,r);i.registry!==t().registry&&e({registry:i.registry})},clearScope:n=>{const r=hre(t().registry,n);r!==t().registry&&e({registry:r})},clear:()=>e({registry:KP()})}),{name:"preview-operation-store"}));function _re(e,t,n,r,i){return t?e.registry.operations.some(s=>s.kind!=="create"&&s.previewKind===n&&s.previewId===r&&tn(s.scope,t)&&s.kind===i):!1}const Lx={authoritative:null,listLoaded:!1,capability:null,capabilityStatus:"idle",capabilityError:null};function Dx(e,t,n){const r=t().authoritative;if(!r)return null;const i=Lj(r,n),s=n.kind==="snapshot"&&tn(r.scope,n.scope);return(i.state!==r||s&&!t().listLoaded)&&e({authoritative:i.state,...s?{listLoaded:!0}:{}}),i}const GP=e=>{var t;return((t=e.authoritative)==null?void 0:t.previews)??[]},Kr=$a()(Ha((e,t)=>({...Lx,activateScope:n=>e({...Lx,authoritative:Oj(n)}),replaceSnapshot:(n,r)=>Dx(e,t,{kind:"snapshot",scope:n,epoch:r.epoch,revision:r.revision,previews:r.previews}),applyPreviewState:(n,r,i,s)=>Dx(e,t,{kind:"state",scope:n,epoch:i,revision:s,preview:r}),applyPreviewRemoved:(n,r,i,s)=>Dx(e,t,{kind:"removed",scope:n,epoch:i,revision:s,previewId:r}),setCapabilityLoading:n=>{var i;const r=(i=t().authoritative)==null?void 0:i.scope;!r||!tn(r,n)||e({capabilityStatus:"loading",capabilityError:null})},setCapability:(n,r)=>{var s;const i=(s=t().authoritative)==null?void 0:s.scope;!i||!tn(i,n)||e({capability:r,capabilityStatus:"loaded",capabilityError:null})},setCapabilityError:(n,r)=>{var s;const i=(s=t().authoritative)==null?void 0:s.scope;!i||!tn(i,n)||e({capabilityStatus:"error",capabilityError:r})},markListLoading:n=>{var i;const r=(i=t().authoritative)==null?void 0:i.scope;!r||!tn(r,n)||e({listLoaded:!1})},clear:()=>e({...Lx})}),{name:"preview-store"})),XP=100,ZP=5e3;class Bx extends Error{constructor(n){super("预览上下文已失效,请重新选择开发机");je(this,"scope");this.name="PreviewScopeInactiveError",this.scope=n}}class QP extends Error{constructor(n,r,i){super(n==="web"?"网页预览已创建,但暂时无法确认状态,请重试":"模拟器预览已创建,但暂时无法确认状态,请重试");je(this,"previewKind");je(this,"previewId");je(this,"confirmationCause");this.name="PreviewCreateConfirmationError",this.previewKind=n,this.previewId=r,this.confirmationCause=i}}class Kg extends Error{constructor(n,r,i,s="resource-busy"){super(s==="operation-id-conflict"?"operationId 已用于不同的预览操作":r==="create"?n==="web"?"已有网页预览正在创建":"已有模拟器预览正在创建":n==="web"?"该网页预览正在处理中":"该模拟器预览正在处理中");je(this,"previewKind");je(this,"operationKind");je(this,"previewId");je(this,"reason");this.name="PreviewOperationConflictError",this.previewKind=n,this.operationKind=r,this.previewId=i,this.reason=s}}function wre(e,t){t instanceof Error&&t.name==="AbortError"||console.error(`[preview-controller] ${e} failed`,t)}function zx(e){return e instanceof Error?e.message:String(e)}function Bj(e){return e===void 0?null:e.trim()}function xre(e,t,n){const r=e.kind==="local"?[e.kind,e.url]:[e.kind,e.path,e.entryPath];return JSON.stringify([r,t,Bj(n)])}function Sre(e,t){return JSON.stringify([e,Bj(t)])}function JP(e){return JSON.stringify([e.trim()])}function e2(e,t){return e.previewKind===t.previewKind&&e.kind===t.kind&&e.previewId===t.previewId&&e.fingerprint===t.fingerprint}class Ere{constructor(t={}){je(this,"createOperationId");je(this,"now");je(this,"reportBackgroundError");je(this,"active",null);je(this,"webSnapshotFlight",null);je(this,"deviceSnapshotFlight",null);je(this,"webSnapshotSequence",0);je(this,"deviceSnapshotSequence",0);je(this,"webResyncRequested",!1);je(this,"deviceResyncRequested",!1);je(this,"webResyncAfterSequence",null);je(this,"deviceResyncAfterSequence",null);je(this,"webResyncRetryKey",null);je(this,"deviceResyncRetryKey",null);je(this,"webResyncRetryTimer",null);je(this,"deviceResyncRetryTimer",null);je(this,"webResyncRetryAttempt",0);je(this,"deviceResyncRetryAttempt",0);je(this,"operationFlights",new Map);this.createOperationId=t.createOperationId??tb,this.now=t.now??Date.now,this.reportBackgroundError=t.reportBackgroundError??wre}activate(t,n){var s;const r=t.getPreviewScope();if(!r||!tn(r,n))throw new Bx(n);if(((s=this.active)==null?void 0:s.relay)===t&&tn(this.active.scope,n))return;this.releaseActiveBinding();const i=Tne(n.proxyId,n.bindingId);this.active={relay:t,scope:i,abortController:new AbortController},this.resetTransientState(),Kr.getState().activateScope(i),gr.getState().activateScope(i)}deactivate(t,n){const r=this.active;return!r||r.relay!==t||!tn(r.scope,n)?!1:(this.releaseActiveBinding(),Kr.getState().clear(),gr.getState().clear(),!0)}dispose(){this.active&&this.releaseActiveBinding(),this.resetTransientState(),this.operationFlights.clear(),qo.getState().clear(),Kr.getState().clear(),gr.getState().clear()}getActiveScope(){return this.active&&this.isCurrent(this.active)?this.active.scope:null}isActive(t,n){const r=this.active;return r!==null&&r.relay===t&&tn(r.scope,n)&&this.isCurrent(r)}syncWebSnapshot(t){return this.startWebSnapshot(this.requireActive(t))}syncDeviceSnapshot(t){return this.startDeviceSnapshot(this.requireActive(t))}applyWebPreviewState(t,n,r,i,s){const o=this.currentForMessage(t,n);if(!o)return null;const u=Kr.getState().applyPreviewState(o.scope,r,i,s);return this.afterWebEvent(o,u),u}applyWebPreviewRemoved(t,n,r,i,s){const o=this.currentForMessage(t,n);if(!o)return null;const u=Kr.getState().applyPreviewRemoved(o.scope,r,i,s);return this.afterWebEvent(o,u),u}applyDevicePreviewState(t,n,r,i,s){const o=this.currentForMessage(t,n);if(!o)return null;const u=gr.getState().applyPreviewState(o.scope,r,i,s);return this.afterDeviceEvent(o,u),u}applyDevicePreviewRemoved(t,n,r,i,s){const o=this.currentForMessage(t,n);if(!o)return null;const u=gr.getState().applyPreviewRemoved(o.scope,r,i,s);return this.afterDeviceEvent(o,u),u}handleMessage(t,n){switch(n.type){case"preview_state_push":return this.applyWebPreviewState(t,n.scope,n.preview,n.epoch,n.revision)!==null;case"preview_removed_push":return this.applyWebPreviewRemoved(t,n.scope,n.previewId,n.epoch,n.revision)!==null;case"device_preview_state_push":return this.applyDevicePreviewState(t,n.scope,n.preview,n.epoch,n.revision)!==null;case"device_preview_removed_push":return this.applyDevicePreviewRemoved(t,n.scope,n.previewId,n.epoch,n.revision)!==null;default:return!1}}async inspectStaticWebPreview(t,n,r={}){const i=this.requireActive(t),s=this.querySignal(i,r.signal),o=await i.relay.inspectStaticWebPreview(i.scope,n,{timeoutMs:r.timeoutMs,signal:s});return s.throwIfAborted(),this.isCurrent(i)?o:null}async requestWebPreviewCapability(t,n=!1,r={}){var o;const i=this.requireActive(t),s=this.querySignal(i,r.signal);Kr.getState().setCapabilityLoading(i.scope);try{const l=await i.relay.requestWebPreviewCapability(i.scope,n,{timeoutMs:r.timeoutMs,signal:s});return s.throwIfAborted(),this.isCurrent(i)?(l.success?Kr.getState().setCapability(i.scope,l.capability):Kr.getState().setCapabilityError(i.scope,l.error),l):null}catch(l){throw this.isCurrent(i)&&!((o=r.signal)!=null&&o.aborted)&&Kr.getState().setCapabilityError(i.scope,zx(l)),l}}async requestDevicePreviewCapability(t,n=!1,r={}){var o;const i=this.requireActive(t),s=this.querySignal(i,r.signal);gr.getState().setCapabilityLoading(i.scope);try{const l=await i.relay.requestDevicePreviewCapability(i.scope,n,{timeoutMs:r.timeoutMs,signal:s});return s.throwIfAborted(),this.isCurrent(i)?(l.success?gr.getState().setCapability(i.scope,l.capability):gr.getState().setCapabilityError(i.scope,l.error),l):null}catch(l){throw this.isCurrent(i)&&!((o=r.signal)!=null&&o.aborted)&&gr.getState().setCapabilityError(i.scope,zx(l)),l}}async requestDevicePreviewTargets(t,n=!1,r={}){var o;const i=this.requireActive(t),s=this.querySignal(i,r.signal);gr.getState().setTargetsLoading(i.scope);try{const l=await i.relay.requestDevicePreviewTargets(i.scope,n,{timeoutMs:r.timeoutMs,signal:s});return s.throwIfAborted(),this.isCurrent(i)?(l.success?gr.getState().setTargets(i.scope,l.targets):gr.getState().setTargetsError(i.scope,l.error),l):null}catch(l){throw this.isCurrent(i)&&!((o=r.signal)!=null&&o.aborted)&&gr.getState().setTargetsError(i.scope,zx(l)),l}}async requestDevicePreviewStream(t,n,r,i={}){const s=this.requireActive(t),o=this.querySignal(s,i.signal),l=await s.relay.requestDevicePreviewStream(s.scope,n,r,{timeoutMs:i.timeoutMs,signal:o});return o.throwIfAborted(),this.isCurrent(s)?Object.freeze({...l,scope:s.scope,signal:o}):null}async sendDevicePreviewInput(t,n,r={}){const i=this.requireActive(t.scope),s=r.signal?AbortSignal.any([t.signal,r.signal]):t.signal,o=this.querySignal(i,s);o.throwIfAborted();const l=await i.relay.sendDevicePreviewInput(i.scope,t.leaseId,n,{timeoutMs:r.timeoutMs,signal:o});return o.throwIfAborted(),this.isCurrent(i)?l:null}async claimDevicePreviewControl(t,n={}){const r=this.requireActive(t.scope),i=n.signal?AbortSignal.any([t.signal,n.signal]):t.signal,s=this.querySignal(r,i);s.throwIfAborted();const o=await r.relay.claimDevicePreviewControl(r.scope,t.leaseId,{timeoutMs:n.timeoutMs,signal:s});return s.throwIfAborted(),this.isCurrent(r)?o:null}createWebPreview(t,n,r){const i=r.operationId??this.createOperationId("web-preview-create");return this.runCreateOperation(t,"web",i,xre(n,r.tunnelProvider,r.name),r.timeoutMs,s=>s.relay.createWebPreview(s.scope,n,{tunnelProvider:r.tunnelProvider,name:r.name,operationId:i,timeoutMs:r.timeoutMs,signal:s.abortController.signal}))}renameWebPreview(t,n,r,i={}){const s=i.operationId??this.createOperationId("web-preview-rename");return this.runMutationOperation(t,"web","rename",n,s,JP(r),o=>o.relay.renameWebPreview(o.scope,n,r,{operationId:s,timeoutMs:i.timeoutMs,signal:o.abortController.signal}))}reconnectWebPreview(t,n,r={}){const i=r.operationId??this.createOperationId("web-preview-reconnect");return this.runMutationOperation(t,"web","reconnect",n,i,"[]",s=>s.relay.reconnectWebPreview(s.scope,n,{operationId:i,timeoutMs:r.timeoutMs,signal:s.abortController.signal}))}closeWebPreview(t,n,r={}){const i=r.operationId??this.createOperationId("web-preview-close");return this.runMutationOperation(t,"web","close",n,i,"[]",s=>s.relay.closeWebPreview(s.scope,n,{operationId:i,timeoutMs:r.timeoutMs,signal:s.abortController.signal}))}createDevicePreview(t,n,r={}){const i=r.operationId??this.createOperationId("device-preview-create");return this.runCreateOperation(t,"device",i,Sre(n,r.name),r.timeoutMs,s=>s.relay.createDevicePreview(s.scope,n,{name:r.name,operationId:i,timeoutMs:r.timeoutMs,signal:s.abortController.signal}))}renameDevicePreview(t,n,r,i={}){const s=i.operationId??this.createOperationId("device-preview-rename");return this.runMutationOperation(t,"device","rename",n,s,JP(r),o=>o.relay.renameDevicePreview(o.scope,n,r,{operationId:s,timeoutMs:i.timeoutMs,signal:o.abortController.signal}))}reconnectDevicePreview(t,n,r={}){const i=r.operationId??this.createOperationId("device-preview-reconnect");return this.runMutationOperation(t,"device","reconnect",n,i,"[]",s=>s.relay.reconnectDevicePreview(s.scope,n,{operationId:i,timeoutMs:r.timeoutMs,signal:s.abortController.signal}))}closeDevicePreview(t,n,r={}){const i=r.operationId??this.createOperationId("device-preview-close");return this.runMutationOperation(t,"device","close",n,i,"[]",s=>s.relay.closeDevicePreview(s.scope,n,{operationId:i,timeoutMs:r.timeoutMs,signal:s.abortController.signal}))}requireActive(t){const n=this.active;if(!n||!tn(n.scope,t)||!this.isCurrent(n))throw new Bx(t);return n}querySignal(t,n){return n?AbortSignal.any([t.abortController.signal,n]):t.abortController.signal}currentForMessage(t,n){const r=this.active;return r&&r.relay===t&&tn(r.scope,n)&&this.isCurrent(r)?r:null}isCurrent(t){if(this.active!==t||t.abortController.signal.aborted)return!1;const n=t.relay.getPreviewScope();return n!==null&&tn(n,t.scope)}releaseActiveBinding(){const t=this.active;t&&(this.active=null,t.abortController.abort(),qo.getState().clearScope(t.scope),this.resetTransientState())}resetTransientState(){this.webResyncRetryTimer!==null&&clearTimeout(this.webResyncRetryTimer),this.deviceResyncRetryTimer!==null&&clearTimeout(this.deviceResyncRetryTimer),this.webSnapshotFlight=null,this.deviceSnapshotFlight=null,this.webResyncRequested=!1,this.deviceResyncRequested=!1,this.webResyncAfterSequence=null,this.deviceResyncAfterSequence=null,this.webResyncRetryKey=null,this.deviceResyncRetryKey=null,this.webResyncRetryTimer=null,this.deviceResyncRetryTimer=null,this.webResyncRetryAttempt=0,this.deviceResyncRetryAttempt=0}startWebSnapshot(t,n){const r=this.webSnapshotFlight;if((r==null?void 0:r.activation)===t)return r.promise;Kr.getState().markListLoading(t.scope);const i=++this.webSnapshotSequence,s=t.relay.requestWebPreviewList(t.scope,{signal:t.abortController.signal,timeoutMs:n}).then(l=>{if(t.abortController.signal.throwIfAborted(),!this.isCurrent(t))return null;const u=Kr.getState(),d=u.authoritative;return this.webResyncAfterSequence!==null&&i<=this.webResyncAfterSequence&&(d==null?void 0:d.syncStatus)==="needs-resync"&&tn(d.scope,t.scope)?{status:"needs-resync",reason:"resync-pending",state:d}:u.replaceSnapshot(t.scope,l)}),o={activation:t,sequence:i,promise:s};return this.webSnapshotFlight=o,s.then(()=>this.finishWebSnapshot(o),()=>this.finishWebSnapshot(o)),s}finishWebSnapshot(t){this.webSnapshotFlight===t&&(this.webSnapshotFlight=null,this.webResyncRequested&&this.drainWebResync(t.activation))}startDeviceSnapshot(t,n){const r=this.deviceSnapshotFlight;if((r==null?void 0:r.activation)===t)return r.promise;gr.getState().markListLoading(t.scope);const i=++this.deviceSnapshotSequence,s=t.relay.requestDevicePreviewList(t.scope,{signal:t.abortController.signal,timeoutMs:n}).then(l=>{if(t.abortController.signal.throwIfAborted(),!this.isCurrent(t))return null;const u=gr.getState(),d=u.authoritative;return this.deviceResyncAfterSequence!==null&&i<=this.deviceResyncAfterSequence&&(d==null?void 0:d.syncStatus)==="needs-resync"&&tn(d.scope,t.scope)?{status:"needs-resync",reason:"resync-pending",state:d}:u.replaceSnapshot(t.scope,l)}),o={activation:t,sequence:i,promise:s};return this.deviceSnapshotFlight=o,s.then(()=>this.finishDeviceSnapshot(o),()=>this.finishDeviceSnapshot(o)),s}finishDeviceSnapshot(t){this.deviceSnapshotFlight===t&&(this.deviceSnapshotFlight=null,this.deviceResyncRequested&&this.drainDeviceResync(t.activation))}afterWebEvent(t,n){(n==null?void 0:n.status)==="needs-resync"&&this.requestWebResync(t)}afterDeviceEvent(t,n){(n==null?void 0:n.status)==="needs-resync"&&this.requestDeviceResync(t)}requestWebResync(t){this.isCurrent(t)&&(this.webResyncRetryTimer!==null&&(clearTimeout(this.webResyncRetryTimer),this.webResyncRetryTimer=null),this.webResyncRequested=!0,this.webResyncAfterSequence=Math.max(this.webResyncAfterSequence??-1,this.webSnapshotSequence),queueMicrotask(()=>this.drainWebResync(t)))}drainWebResync(t){var o;if(!this.isCurrent(t)||!this.webResyncRequested||this.webSnapshotFlight)return;const n=this.webResyncAfterSequence,r=n!==null&&this.webSnapshotSequence<=n;if(((o=Kr.getState().authoritative)==null?void 0:o.syncStatus)!=="needs-resync"&&!r){this.webResyncRequested=!1,this.webResyncAfterSequence=null,this.webResyncRetryKey=null,this.webResyncRetryAttempt=0;return}this.webResyncRequested=!1;const i=this.startWebSnapshot(t),s=this.webSnapshotSequence;i.then(l=>{if(!this.isCurrent(t))return;if((l==null?void 0:l.status)!=="needs-resync"){this.webResyncAfterSequence!==null&&this.webResyncAfterSequence<s&&(this.webResyncAfterSequence=null),this.webResyncRetryKey=null,this.webResyncRetryAttempt=0;return}const u=l.state.resyncCause,d=`${u.observedEpoch}\0${u.observedRevision}`,f=this.webResyncRetryKey===d;this.webResyncRetryKey=d,this.webResyncAfterSequence=Math.max(this.webResyncAfterSequence??-1,s),!this.webSnapshotFlight&&(f?this.scheduleWebResyncRetry(t):this.requestWebResync(t))},l=>{this.isCurrent(t)&&(this.webResyncAfterSequence=Math.max(this.webResyncAfterSequence??-1,s),this.reportBackgroundError("web-resync",l),this.scheduleWebResyncRetry(t))})}scheduleWebResyncRetry(t){if(!this.isCurrent(t)||this.webResyncRetryTimer!==null)return;const n=Math.min(XP*2**this.webResyncRetryAttempt,ZP);this.webResyncRetryAttempt+=1,this.webResyncRetryTimer=setTimeout(()=>{this.webResyncRetryTimer=null,this.requestWebResync(t)},n)}requestDeviceResync(t){this.isCurrent(t)&&(this.deviceResyncRetryTimer!==null&&(clearTimeout(this.deviceResyncRetryTimer),this.deviceResyncRetryTimer=null),this.deviceResyncRequested=!0,this.deviceResyncAfterSequence=Math.max(this.deviceResyncAfterSequence??-1,this.deviceSnapshotSequence),queueMicrotask(()=>this.drainDeviceResync(t)))}drainDeviceResync(t){var o;if(!this.isCurrent(t)||!this.deviceResyncRequested||this.deviceSnapshotFlight)return;const n=this.deviceResyncAfterSequence,r=n!==null&&this.deviceSnapshotSequence<=n;if(((o=gr.getState().authoritative)==null?void 0:o.syncStatus)!=="needs-resync"&&!r){this.deviceResyncRequested=!1,this.deviceResyncAfterSequence=null,this.deviceResyncRetryKey=null,this.deviceResyncRetryAttempt=0;return}this.deviceResyncRequested=!1;const i=this.startDeviceSnapshot(t),s=this.deviceSnapshotSequence;i.then(l=>{if(!this.isCurrent(t))return;if((l==null?void 0:l.status)!=="needs-resync"){this.deviceResyncAfterSequence!==null&&this.deviceResyncAfterSequence<s&&(this.deviceResyncAfterSequence=null),this.deviceResyncRetryKey=null,this.deviceResyncRetryAttempt=0;return}const u=l.state.resyncCause,d=`${u.observedEpoch}\0${u.observedRevision}`,f=this.deviceResyncRetryKey===d;this.deviceResyncRetryKey=d,this.deviceResyncAfterSequence=Math.max(this.deviceResyncAfterSequence??-1,s),!this.deviceSnapshotFlight&&(f?this.scheduleDeviceResyncRetry(t):this.requestDeviceResync(t))},l=>{this.isCurrent(t)&&(this.deviceResyncAfterSequence=Math.max(this.deviceResyncAfterSequence??-1,s),this.reportBackgroundError("device-resync",l),this.scheduleDeviceResyncRetry(t))})}scheduleDeviceResyncRetry(t){if(!this.isCurrent(t)||this.deviceResyncRetryTimer!==null)return;const n=Math.min(XP*2**this.deviceResyncRetryAttempt,ZP);this.deviceResyncRetryAttempt+=1,this.deviceResyncRetryTimer=setTimeout(()=>{this.deviceResyncRetryTimer=null,this.requestDeviceResync(t)},n)}operationKey(t,n){return`${t.proxyId}\0${t.bindingId}\0${n}`}runCreateOperation(t,n,r,i,s,o){return this.trackOperation(t,n,"create",void 0,r,i,l=>this.executeCreateOperation(l,n,r,s,o))}runMutationOperation(t,n,r,i,s,o,l){return this.trackOperation(t,n,r,i,s,o,u=>this.executeMutationOperation(u,n,s,l))}trackOperation(t,n,r,i,s,o,l){let u;try{u=this.requireActive(t)}catch(T){return Promise.reject(T)}const d={kind:r,previewKind:n,operationId:s,fingerprint:o,scope:u.scope,...r==="create"?{}:{previewId:i},startedAt:this.now()},f={previewKind:n,kind:r,...i===void 0?{}:{previewId:i},fingerprint:o},p=this.operationKey(u.scope,s),y=this.operationFlights.get(p);if(y)return e2(y,f)?y.promise:Promise.reject(new Kg(n,r,i,"operation-id-conflict"));const g=qo.getState(),_=Mj(g.registry,u.scope,s);if(_)return Promise.reject(new Kg(n,r,i,e2(_,f)?"resource-busy":"operation-id-conflict"));if(r==="create"?ure(g.registry,u.scope,n).some(T=>T.kind==="create"):Pj(g.registry,u.scope,n,i).length>0)return Promise.reject(new Kg(n,r,i));const x=g.begin(d);if(x.status!=="applied")return Promise.reject(new Kg(n,r,i,x.status==="conflict"?"operation-id-conflict":"resource-busy"));const k=l(u).finally(()=>this.operationFlights.delete(p));return this.operationFlights.set(p,{...f,promise:k}),k}async executeMutationOperation(t,n,r,i){let s;try{s=await i(t),t.abortController.signal.throwIfAborted()}catch(o){throw qo.getState().finish(t.scope,r),this.reconcileAfterOperation(t,n),o}return qo.getState().finish(t.scope,r),this.reconcileAfterOperation(t,n),s}async executeCreateOperation(t,n,r,i,s){let o;try{o=await s(t),this.assertCurrentBinding(t)}catch(l){throw qo.getState().finish(t.scope,r),this.reconcileAfterOperation(t,n,i),l}if(!o.accepted)return qo.getState().finish(t.scope,r),o;try{return await this.confirmCreatedPreview(t,n,o.previewId,i),o}catch(l){throw this.reconcileAfterOperation(t,n,i),l}finally{qo.getState().finish(t.scope,r)}}async confirmCreatedPreview(t,n,r,i){if(this.assertCurrentBinding(t),this.hasAuthoritativePreview(t,n,r))return;let s;try{s=n==="web"?await this.ensureWebSnapshotAfterCurrentFlight(t,i):await this.ensureDeviceSnapshotAfterCurrentFlight(t,i)}catch(o){throw this.assertCurrentBinding(t),new QP(n,r,o)}if(this.assertCurrentBinding(t),!this.hasAuthoritativePreview(t,n,r))throw(s==null?void 0:s.status)==="needs-resync"&&(n==="web"?this.requestWebResync(t):this.requestDeviceResync(t)),new QP(n,r)}assertCurrentBinding(t){if(t.abortController.signal.throwIfAborted(),!this.isCurrent(t))throw new Bx(t.scope)}hasAuthoritativePreview(t,n,r){const i=n==="web"?Kr.getState().authoritative:gr.getState().authoritative;return i!==null&&tn(i.scope,t.scope)&&i.previews.some(s=>s.previewId===r)}async reconcileAfterOperation(t,n,r){if(this.isCurrent(t))try{const i=n==="web"?await this.ensureWebSnapshotAfterCurrentFlight(t,r):await this.ensureDeviceSnapshotAfterCurrentFlight(t,r);(i==null?void 0:i.status)==="needs-resync"&&(n==="web"?this.requestWebResync(t):this.requestDeviceResync(t))}catch(i){this.reportBackgroundError(n==="web"?"web-reconciliation":"device-reconciliation",i)}}async ensureWebSnapshotAfterCurrentFlight(t,n){const r=this.webSnapshotSequence+1;for(;this.isCurrent(t);){const i=this.webSnapshotFlight;if(!i)return this.startWebSnapshot(t,n);if(i.sequence>=r)return i.promise;try{await i.promise}catch{}}return null}async ensureDeviceSnapshotAfterCurrentFlight(t,n){const r=this.deviceSnapshotSequence+1;for(;this.isCurrent(t);){const i=this.deviceSnapshotFlight;if(!i)return this.startDeviceSnapshot(t,n);if(i.sequence>=r)return i.promise;try{await i.promise}catch{}}return null}}const Tt=new Ere;async function MC(e,t){const n=Ie.getState().selectedProxyId;if(!n)return{status:"skipped"};const r=Gt.getState().beginHistoryLoad();try{const i=t===void 0?await e.requestSessionHistory():await e.requestSessionHistory(t);return Ie.getState().selectedProxyId!==n?(Gt.getState().cancelHistoryLoad(r),{status:"stale"}):Gt.getState().resolveHistoryLoad(r,i)?{status:"loaded",sessions:i}:{status:"stale"}}catch(i){return Ie.getState().selectedProxyId!==n?(Gt.getState().cancelHistoryLoad(r),{status:"stale"}):Gt.getState().rejectHistoryLoad(r)?{status:"failed",error:i}:{status:"stale"}}}function t2(e){return typeof e=="string"?e:""}function yy(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function WS(e){switch(e){case"add":return"新增";case"delete":return"删除";case"update":return"更新";default:return"变更"}}function jx(e,t){const n=yy(t);return n?{title:e,content:n}:null}function Cre(e,t){return e?t?`${e}
525
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const f of e.seen.entries()){const p=f[1];if(t===f[0]){s(f);continue}if(e.external){const g=(u=e.external.registry.get(f[0]))==null?void 0:u.id;if(t!==f[0]&&g){s(f);continue}}if((d=e.metadataRegistry.get(f[0]))==null?void 0:d.id){s(f);continue}if(p.cycle){s(f);continue}if(p.count>1&&e.reused==="ref"){s(f);continue}}}function ij(e,t){var o,l,u;const n=e.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=d=>{const f=e.seen.get(d);if(f.ref===null)return;const p=f.def??f.schema,y={...p},g=f.ref;if(f.ref=null,g){r(g);const w=e.seen.get(g),x=w.schema;if(x.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(p.allOf=p.allOf??[],p.allOf.push(x)):Object.assign(p,x),Object.assign(p,y),d._zod.parent===g)for(const k in p)k==="$ref"||k==="allOf"||k in y||delete p[k];if(x.$ref&&w.def)for(const k in p)k==="$ref"||k==="allOf"||k in w.def&&JSON.stringify(p[k])===JSON.stringify(w.def[k])&&delete p[k]}const _=d._zod.parent;if(_&&_!==g){r(_);const w=e.seen.get(_);if(w!=null&&w.schema.$ref&&(p.$ref=w.schema.$ref,w.def))for(const x in p)x==="$ref"||x==="allOf"||x in w.def&&JSON.stringify(p[x])===JSON.stringify(w.def[x])&&delete p[x]}e.override({zodSchema:d,jsonSchema:p,path:f.path??[]})};for(const d of[...e.seen.entries()].reverse())r(d[0]);const i={};if(e.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":e.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":e.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":e.target,(o=e.external)!=null&&o.uri){const d=(l=e.external.registry.get(t))==null?void 0:l.id;if(!d)throw new Error("Schema is missing an `id` property");i.$id=e.external.uri(d)}Object.assign(i,n.def??n.schema);const s=((u=e.external)==null?void 0:u.defs)??{};for(const d of e.seen.entries()){const f=d[1];f.def&&f.defId&&(s[f.defId]=f.def)}e.external||Object.keys(s).length>0&&(e.target==="draft-2020-12"?i.$defs=s:i.definitions=s);try{const d=JSON.parse(JSON.stringify(i));return Object.defineProperty(d,"~standard",{value:{...t["~standard"],jsonSchema:{input:py(t,"input",e.processors),output:py(t,"output",e.processors)}},enumerable:!1,writable:!1}),d}catch{throw new Error("Error converting schema to JSON.")}}function Xi(e,t){const n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);const r=e._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Xi(r.element,n);if(r.type==="set")return Xi(r.valueType,n);if(r.type==="lazy")return Xi(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Xi(r.innerType,n);if(r.type==="intersection")return Xi(r.left,n)||Xi(r.right,n);if(r.type==="record"||r.type==="map")return Xi(r.keyType,n)||Xi(r.valueType,n);if(r.type==="pipe")return Xi(r.in,n)||Xi(r.out,n);if(r.type==="object"){for(const i in r.shape)if(Xi(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(Xi(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(Xi(i,n))return!0;return!!(r.rest&&Xi(r.rest,n))}return!1}const aQ=(e,t={})=>n=>{const r=nj({...n,processors:t});return si(e,r),rj(r,e),ij(r,e)},py=(e,t,n={})=>r=>{const{libraryOptions:i,target:s}=r??{},o=nj({...i??{},target:s,io:t,processors:n});return si(e,o),rj(o,e),ij(o,e)},lQ={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},cQ=(e,t,n,r)=>{const i=n;i.type="string";const{minimum:s,maximum:o,format:l,patterns:u,contentEncoding:d}=e._zod.bag;if(typeof s=="number"&&(i.minLength=s),typeof o=="number"&&(i.maxLength=o),l&&(i.format=lQ[l]??l,i.format===""&&delete i.format,l==="time"&&delete i.format),d&&(i.contentEncoding=d),u&&u.size>0){const f=[...u];f.length===1?i.pattern=f[0].source:f.length>1&&(i.allOf=[...f.map(p=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:p.source}))])}},uQ=(e,t,n,r)=>{const i=n,{minimum:s,maximum:o,format:l,multipleOf:u,exclusiveMaximum:d,exclusiveMinimum:f}=e._zod.bag;typeof l=="string"&&l.includes("int")?i.type="integer":i.type="number",typeof f=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.minimum=f,i.exclusiveMinimum=!0):i.exclusiveMinimum=f),typeof s=="number"&&(i.minimum=s,typeof f=="number"&&t.target!=="draft-04"&&(f>=s?delete i.minimum:delete i.exclusiveMinimum)),typeof d=="number"&&(t.target==="draft-04"||t.target==="openapi-3.0"?(i.maximum=d,i.exclusiveMaximum=!0):i.exclusiveMaximum=d),typeof o=="number"&&(i.maximum=o,typeof d=="number"&&t.target!=="draft-04"&&(d<=o?delete i.maximum:delete i.exclusiveMaximum)),typeof u=="number"&&(i.multipleOf=u)},dQ=(e,t,n,r)=>{n.type="boolean"},fQ=(e,t,n,r)=>{n.not={}},hQ=(e,t,n,r)=>{},pQ=(e,t,n,r)=>{const i=e._zod.def,s=Lz(i.entries);s.every(o=>typeof o=="number")&&(n.type="number"),s.every(o=>typeof o=="string")&&(n.type="string"),n.enum=s},mQ=(e,t,n,r)=>{const i=e._zod.def,s=[];for(const o of i.values)if(o===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof o=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(o))}else s.push(o);if(s.length!==0)if(s.length===1){const o=s[0];n.type=o===null?"null":typeof o,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[o]:n.const=o}else s.every(o=>typeof o=="number")&&(n.type="number"),s.every(o=>typeof o=="string")&&(n.type="string"),s.every(o=>typeof o=="boolean")&&(n.type="boolean"),s.every(o=>o===null)&&(n.type="null"),n.enum=s},gQ=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},vQ=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},yQ=(e,t,n,r)=>{const i=n,s=e._zod.def,{minimum:o,maximum:l}=e._zod.bag;typeof o=="number"&&(i.minItems=o),typeof l=="number"&&(i.maxItems=l),i.type="array",i.items=si(s.element,t,{...r,path:[...r.path,"items"]})},bQ=(e,t,n,r)=>{var d;const i=n,s=e._zod.def;i.type="object",i.properties={};const o=s.shape;for(const f in o)i.properties[f]=si(o[f],t,{...r,path:[...r.path,"properties",f]});const l=new Set(Object.keys(o)),u=new Set([...l].filter(f=>{const p=s.shape[f]._zod;return t.io==="input"?p.optin===void 0:p.optout===void 0}));u.size>0&&(i.required=Array.from(u)),((d=s.catchall)==null?void 0:d._zod.def.type)==="never"?i.additionalProperties=!1:s.catchall?s.catchall&&(i.additionalProperties=si(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},_Q=(e,t,n,r)=>{const i=e._zod.def,s=i.inclusive===!1,o=i.options.map((l,u)=>si(l,t,{...r,path:[...r.path,s?"oneOf":"anyOf",u]}));s?n.oneOf=o:n.anyOf=o},wQ=(e,t,n,r)=>{const i=e._zod.def,s=si(i.left,t,{...r,path:[...r.path,"allOf",0]}),o=si(i.right,t,{...r,path:[...r.path,"allOf",1]}),l=d=>"allOf"in d&&Object.keys(d).length===1,u=[...l(s)?s.allOf:[s],...l(o)?o.allOf:[o]];n.allOf=u},xQ=(e,t,n,r)=>{const i=n,s=e._zod.def;i.type="object";const o=s.keyType,l=o._zod.bag,u=l==null?void 0:l.patterns;if(s.mode==="loose"&&u&&u.size>0){const f=si(s.valueType,t,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(const p of u)i.patternProperties[p.source]=f}else(t.target==="draft-07"||t.target==="draft-2020-12")&&(i.propertyNames=si(s.keyType,t,{...r,path:[...r.path,"propertyNames"]})),i.additionalProperties=si(s.valueType,t,{...r,path:[...r.path,"additionalProperties"]});const d=o._zod.values;if(d){const f=[...d].filter(p=>typeof p=="string"||typeof p=="number");f.length>0&&(i.required=f)}},SQ=(e,t,n,r)=>{const i=e._zod.def,s=si(i.innerType,t,r),o=t.seen.get(e);t.target==="openapi-3.0"?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},EQ=(e,t,n,r)=>{const i=e._zod.def;si(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType},CQ=(e,t,n,r)=>{const i=e._zod.def;si(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},kQ=(e,t,n,r)=>{const i=e._zod.def;si(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},TQ=(e,t,n,r)=>{const i=e._zod.def;si(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=o},RQ=(e,t,n,r)=>{const i=e._zod.def,s=t.io==="input"?i.in._zod.def.type==="transform"?i.out:i.in:i.out;si(s,t,r);const o=t.seen.get(e);o.ref=s},AQ=(e,t,n,r)=>{const i=e._zod.def;si(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType,n.readOnly=!0},sj=(e,t,n,r)=>{const i=e._zod.def;si(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType},NQ=Qe("ZodISODateTime",(e,t)=>{MX.init(e,t),jr.init(e,t)});function MQ(e){return BZ(NQ,e)}const PQ=Qe("ZodISODate",(e,t)=>{PX.init(e,t),jr.init(e,t)});function IQ(e){return zZ(PQ,e)}const OQ=Qe("ZodISOTime",(e,t)=>{IX.init(e,t),jr.init(e,t)});function LQ(e){return jZ(OQ,e)}const DQ=Qe("ZodISODuration",(e,t)=>{OX.init(e,t),jr.init(e,t)});function BQ(e){return FZ(DQ,e)}const zQ=(e,t)=>{jz.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>EG(e,n)},flatten:{value:n=>SG(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,NS,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,NS,2)}},isEmpty:{get(){return e.issues.length===0}}})},fo=Qe("ZodError",zQ,{Parent:Error}),jQ=mC(fo),FQ=gC(fo),$Q=Xy(fo),HQ=Zy(fo),UQ=TG(fo),WQ=RG(fo),qQ=AG(fo),VQ=NG(fo),YQ=MG(fo),KQ=PG(fo),GQ=IG(fo),XQ=OG(fo),zr=Qe("ZodType",(e,t)=>(Br.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:py(e,"input"),output:py(e,"output")}}),e.toJSONSchema=aQ(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(ec(t,{checks:[...t.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0}),e.with=e.check,e.clone=(n,r)=>tc(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>jQ(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>$Q(e,n,r),e.parseAsync=async(n,r)=>FQ(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>HQ(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>UQ(e,n,r),e.decode=(n,r)=>WQ(e,n,r),e.encodeAsync=async(n,r)=>qQ(e,n,r),e.decodeAsync=async(n,r)=>VQ(e,n,r),e.safeEncode=(n,r)=>YQ(e,n,r),e.safeDecode=(n,r)=>KQ(e,n,r),e.safeEncodeAsync=async(n,r)=>GQ(e,n,r),e.safeDecodeAsync=async(n,r)=>XQ(e,n,r),e.refine=(n,r)=>e.check(HJ(n,r)),e.superRefine=n=>e.check(UJ(n)),e.overwrite=n=>e.check(nf(n)),e.optional=()=>bP(e),e.exactOptional=()=>AJ(e),e.nullable=()=>_P(e),e.nullish=()=>bP(_P(e)),e.nonoptional=n=>LJ(e,n),e.array=()=>ur(e),e.or=n=>tm([e,n]),e.and=n=>SJ(e,n),e.transform=n=>wP(e,TJ(n)),e.default=n=>PJ(e,n),e.prefault=n=>OJ(e,n),e.catch=n=>BJ(e,n),e.pipe=n=>wP(e,n),e.readonly=()=>FJ(e),e.describe=n=>{const r=e.clone();return Vh.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){var n;return(n=Vh.get(e))==null?void 0:n.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return Vh.get(e);const r=e.clone();return Vh.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=n=>n(e),e)),oj=Qe("_ZodString",(e,t)=>{vC.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(r,i,s)=>cQ(e,r,i);const n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null,e.regex=(...r)=>e.check(VZ(...r)),e.includes=(...r)=>e.check(GZ(...r)),e.startsWith=(...r)=>e.check(XZ(...r)),e.endsWith=(...r)=>e.check(ZZ(...r)),e.min=(...r)=>e.check(hy(...r)),e.max=(...r)=>e.check(ej(...r)),e.length=(...r)=>e.check(tj(...r)),e.nonempty=(...r)=>e.check(hy(1,...r)),e.lowercase=r=>e.check(YZ(r)),e.uppercase=r=>e.check(KZ(r)),e.trim=()=>e.check(JZ()),e.normalize=(...r)=>e.check(QZ(...r)),e.toLowerCase=()=>e.check(eQ()),e.toUpperCase=()=>e.check(tQ()),e.slugify=()=>e.check(nQ())}),ZQ=Qe("ZodString",(e,t)=>{vC.init(e,t),oj.init(e,t),e.email=n=>e.check(gZ(QQ,n)),e.url=n=>e.check(wZ(JQ,n)),e.jwt=n=>e.check(DZ(pJ,n)),e.emoji=n=>e.check(xZ(eJ,n)),e.guid=n=>e.check(hP(vP,n)),e.uuid=n=>e.check(vZ(Ug,n)),e.uuidv4=n=>e.check(yZ(Ug,n)),e.uuidv6=n=>e.check(bZ(Ug,n)),e.uuidv7=n=>e.check(_Z(Ug,n)),e.nanoid=n=>e.check(SZ(tJ,n)),e.guid=n=>e.check(hP(vP,n)),e.cuid=n=>e.check(EZ(nJ,n)),e.cuid2=n=>e.check(CZ(rJ,n)),e.ulid=n=>e.check(kZ(iJ,n)),e.base64=n=>e.check(IZ(dJ,n)),e.base64url=n=>e.check(OZ(fJ,n)),e.xid=n=>e.check(TZ(sJ,n)),e.ksuid=n=>e.check(RZ(oJ,n)),e.ipv4=n=>e.check(AZ(aJ,n)),e.ipv6=n=>e.check(NZ(lJ,n)),e.cidrv4=n=>e.check(MZ(cJ,n)),e.cidrv6=n=>e.check(PZ(uJ,n)),e.e164=n=>e.check(LZ(hJ,n)),e.datetime=n=>e.check(MQ(n)),e.date=n=>e.check(IQ(n)),e.time=n=>e.check(LQ(n)),e.duration=n=>e.check(BQ(n))});function Ce(e){return mZ(ZQ,e)}const jr=Qe("ZodStringFormat",(e,t)=>{Nr.init(e,t),oj.init(e,t)}),QQ=Qe("ZodEmail",(e,t)=>{xX.init(e,t),jr.init(e,t)}),vP=Qe("ZodGUID",(e,t)=>{_X.init(e,t),jr.init(e,t)}),Ug=Qe("ZodUUID",(e,t)=>{wX.init(e,t),jr.init(e,t)}),JQ=Qe("ZodURL",(e,t)=>{SX.init(e,t),jr.init(e,t)}),eJ=Qe("ZodEmoji",(e,t)=>{EX.init(e,t),jr.init(e,t)}),tJ=Qe("ZodNanoID",(e,t)=>{CX.init(e,t),jr.init(e,t)}),nJ=Qe("ZodCUID",(e,t)=>{kX.init(e,t),jr.init(e,t)}),rJ=Qe("ZodCUID2",(e,t)=>{TX.init(e,t),jr.init(e,t)}),iJ=Qe("ZodULID",(e,t)=>{RX.init(e,t),jr.init(e,t)}),sJ=Qe("ZodXID",(e,t)=>{AX.init(e,t),jr.init(e,t)}),oJ=Qe("ZodKSUID",(e,t)=>{NX.init(e,t),jr.init(e,t)}),aJ=Qe("ZodIPv4",(e,t)=>{LX.init(e,t),jr.init(e,t)}),lJ=Qe("ZodIPv6",(e,t)=>{DX.init(e,t),jr.init(e,t)}),cJ=Qe("ZodCIDRv4",(e,t)=>{BX.init(e,t),jr.init(e,t)}),uJ=Qe("ZodCIDRv6",(e,t)=>{zX.init(e,t),jr.init(e,t)}),dJ=Qe("ZodBase64",(e,t)=>{jX.init(e,t),jr.init(e,t)}),fJ=Qe("ZodBase64URL",(e,t)=>{$X.init(e,t),jr.init(e,t)}),hJ=Qe("ZodE164",(e,t)=>{HX.init(e,t),jr.init(e,t)}),pJ=Qe("ZodJWT",(e,t)=>{WX.init(e,t),jr.init(e,t)}),aj=Qe("ZodNumber",(e,t)=>{Gz.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(r,i,s)=>uQ(e,r,i),e.gt=(r,i)=>e.check(mP(r,i)),e.gte=(r,i)=>e.check(bx(r,i)),e.min=(r,i)=>e.check(bx(r,i)),e.lt=(r,i)=>e.check(pP(r,i)),e.lte=(r,i)=>e.check(yx(r,i)),e.max=(r,i)=>e.check(yx(r,i)),e.int=r=>e.check(yP(r)),e.safe=r=>e.check(yP(r)),e.positive=r=>e.check(mP(0,r)),e.nonnegative=r=>e.check(bx(0,r)),e.negative=r=>e.check(pP(0,r)),e.nonpositive=r=>e.check(yx(0,r)),e.multipleOf=(r,i)=>e.check(gP(r,i)),e.step=(r,i)=>e.check(gP(r,i)),e.finite=()=>e;const n=e._zod.bag;e.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,e.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,e.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null});function Lt(e){return $Z(aj,e)}const mJ=Qe("ZodNumberFormat",(e,t)=>{qX.init(e,t),aj.init(e,t)});function yP(e){return HZ(mJ,e)}const gJ=Qe("ZodBoolean",(e,t)=>{VX.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>dQ(e,n,r)});function Ln(e){return UZ(gJ,e)}const vJ=Qe("ZodUnknown",(e,t)=>{YX.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>hQ()});function Ba(){return WZ(vJ)}const yJ=Qe("ZodNever",(e,t)=>{KX.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>fQ(e,n,r)});function ns(e){return qZ(yJ,e)}const bJ=Qe("ZodArray",(e,t)=>{GX.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yQ(e,n,r,i),e.element=t.element,e.min=(n,r)=>e.check(hy(n,r)),e.nonempty=n=>e.check(hy(1,n)),e.max=(n,r)=>e.check(ej(n,r)),e.length=(n,r)=>e.check(tj(n,r)),e.unwrap=()=>e.element});function ur(e,t){return rQ(bJ,e,t)}const _J=Qe("ZodObject",(e,t)=>{ZX.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bQ(e,n,r,i),ar(e,"shape",()=>t.shape),e.keyof=()=>rn(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:Ba()}),e.loose=()=>e.clone({...e._zod.def,catchall:Ba()}),e.strict=()=>e.clone({...e._zod.def,catchall:ns()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>yG(e,n),e.safeExtend=n=>bG(e,n),e.merge=n=>_G(e,n),e.pick=n=>gG(e,n),e.omit=n=>vG(e,n),e.partial=(...n)=>wG(cj,e,n[0]),e.required=(...n)=>xG(uj,e,n[0])});function qe(e,t){const n={type:"object",shape:e??{},...Qt(t)};return new _J(n)}const lj=Qe("ZodUnion",(e,t)=>{Qz.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_Q(e,n,r,i),e.options=t.options});function tm(e,t){return new lj({type:"union",options:e,...Qt(t)})}const wJ=Qe("ZodDiscriminatedUnion",(e,t)=>{lj.init(e,t),QX.init(e,t)});function Dn(e,t,n){return new wJ({type:"union",options:t,discriminator:e,...Qt(n)})}const xJ=Qe("ZodIntersection",(e,t)=>{JX.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wQ(e,n,r,i)});function SJ(e,t){return new xJ({type:"intersection",left:e,right:t})}const EJ=Qe("ZodRecord",(e,t)=>{eZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xQ(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function Ud(e,t,n){return new EJ({type:"record",keyType:e,valueType:t,...Qt(n)})}const PS=Qe("ZodEnum",(e,t)=>{tZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(r,i,s)=>pQ(e,r,i),e.enum=t.entries,e.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));e.extract=(r,i)=>{const s={};for(const o of r)if(n.has(o))s[o]=t.entries[o];else throw new Error(`Key ${o} not found in enum`);return new PS({...t,checks:[],...Qt(i),entries:s})},e.exclude=(r,i)=>{const s={...t.entries};for(const o of r)if(n.has(o))delete s[o];else throw new Error(`Key ${o} not found in enum`);return new PS({...t,checks:[],...Qt(i),entries:s})}});function rn(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new PS({type:"enum",entries:n,...Qt(t)})}const CJ=Qe("ZodLiteral",(e,t)=>{nZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>mQ(e,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Se(e,t){return new CJ({type:"literal",values:Array.isArray(e)?e:[e],...Qt(t)})}const kJ=Qe("ZodTransform",(e,t)=>{rZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vQ(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new Iz(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(Tp(s,n.value,t));else{const o=s;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),n.issues.push(Tp(o))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(s=>(n.value=s,n)):(n.value=i,n)}});function TJ(e){return new kJ({type:"transform",transform:e})}const cj=Qe("ZodOptional",(e,t)=>{Jz.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>sj(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function bP(e){return new cj({type:"optional",innerType:e})}const RJ=Qe("ZodExactOptional",(e,t)=>{iZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>sj(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function AJ(e){return new RJ({type:"optional",innerType:e})}const NJ=Qe("ZodNullable",(e,t)=>{sZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SQ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function _P(e){return new NJ({type:"nullable",innerType:e})}const MJ=Qe("ZodDefault",(e,t)=>{oZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CQ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function PJ(e,t){return new MJ({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Bz(t)}})}const IJ=Qe("ZodPrefault",(e,t)=>{aZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kQ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function OJ(e,t){return new IJ({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():Bz(t)}})}const uj=Qe("ZodNonOptional",(e,t)=>{lZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EQ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function LJ(e,t){return new uj({type:"nonoptional",innerType:e,...Qt(t)})}const DJ=Qe("ZodCatch",(e,t)=>{cZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TQ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function BJ(e,t){return new DJ({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const zJ=Qe("ZodPipe",(e,t)=>{uZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RQ(e,n,r,i),e.in=t.in,e.out=t.out});function wP(e,t){return new zJ({type:"pipe",in:e,out:t})}const jJ=Qe("ZodReadonly",(e,t)=>{dZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>AQ(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function FJ(e){return new jJ({type:"readonly",innerType:e})}const $J=Qe("ZodCustom",(e,t)=>{fZ.init(e,t),zr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>gQ(e,n)});function HJ(e,t={}){return iQ($J,e,t)}function UJ(e){return sQ(e)}const WJ=256,we=Ce().min(1).max(WJ),Jy="1.0",qJ=qe({text:Ce().min(1),messageId:Ce().min(1).optional()}).strict(),VJ=qe({turnId:Ce().min(1).max(256),revision:Lt().int().positive(),text:Ce(),status:rn(["streaming","completed"])}).strict(),YJ=qe({text:Ce()}).strict(),KJ=rn(["allow_once","allow_always","reject_once","reject_always"]),dj=qe({optionId:we,name:Ce().min(1),kind:KJ}).strict(),xP=qe({toolName:Ce(),toolId:we,parameters:Ud(Ce(),Ba()),options:ur(dj).optional()}).strict(),GJ=qe({toolId:we,whitelistTool:Ln().optional(),optionId:we.optional()}),XJ=qe({toolId:we,reason:Ce().optional(),optionId:we.optional()}),ZJ=qe({toolId:we,result:Ba(),isError:Ln()}).strict(),na=["claude","codex","kimi"],fj=["local-terminal","proxy-hosted"],QJ=["pty","json"],_x={WORKING:"working",TURN_COMPLETE:"turn_complete",APPROVAL_WAIT:"approval_wait"},JJ=[_x.WORKING,_x.TURN_COMPLETE,_x.APPROVAL_WAIT],Lv=80,IS=24,yC=500,bC=200,_C=["idle","working","compacting","waiting_approval","error","terminated"],eee=["idle","thinking","tool_use","outputting","waiting_permission","error"];function hj(e){return tm([qe({...e,kind:Se("agent"),mode:Se("json"),provider:rn(na)}).strict(),qe({...e,kind:Se("agent"),mode:Se("pty"),provider:rn(na),ptyOwner:rn(fj)}).strict(),qe({...e,kind:Se("terminal"),mode:Se("pty"),provider:Se("claude"),ptyOwner:Se("proxy-hosted")}).strict()])}const tee=hj({sessionId:we,name:Ce().optional(),cwd:Ce(),nameLocked:Ln().optional(),state:rn(_C),lastActive:Lt()}),nee=qe({sessions:ur(tee)}).strict(),ree=qe({sessionId:we,state:rn(_C),lastActive:Lt()}).strict(),iee=qe({state:rn(JJ),seq:Lt().int().nonnegative(),title:Ce().optional(),tool:Ce().optional()}),SP=qe({provider:rn(na),phase:rn(eee),seq:Lt().int().nonnegative(),updatedAt:Lt(),toolName:Ce().optional(),toolInput:Ud(Ce(),Ba()).optional(),permissionRequest:qe({requestId:we,toolName:Ce(),input:Ud(Ce(),Ba())}).optional(),permissionResolution:qe({requestId:we,outcome:rn(["allow","deny"])}).optional(),summary:Ce().optional()}),see=qe({}).strict(),oee=qe({pairingCode:Ce().optional(),token:Ce().optional()}).strict(),aee=qe({lastSeq:Lt().int().nonnegative()}).strict(),lee=qe({messages:ur(Ud(Ce(),Ba()))}).strict(),md={seq:Lt().int().nonnegative(),timestamp:Lt(),source:rn(["proxy","client"]),version:Se(Jy)},kc={...md,sessionId:we},cee=Dn("type",[qe({...kc,type:Se("user_input"),payload:qJ}).strict(),qe({...kc,type:Se("assistant_message"),payload:VJ}).strict(),qe({...kc,type:Se("thinking"),payload:YJ}).strict(),qe({...kc,type:Se("tool_use_request"),payload:xP}).strict(),qe({...kc,type:Se("tool_result"),payload:ZJ}).strict(),qe({...kc,type:Se("assistant_tool_use"),payload:xP}).strict(),qe({...md,type:Se("session_list"),payload:nee}).strict(),qe({...kc,type:Se("session_status"),payload:ree}).strict(),qe({...md,type:Se("heartbeat"),payload:see}).strict(),qe({...md,type:Se("auth"),payload:oee}).strict(),qe({...md,type:Se("sync_request"),payload:aee}).strict(),qe({...md,type:Se("sync_response"),payload:lee}).strict()]),pj=["aliyun-bailian"],wC=["cn","intl"],uee=["official","custom"],dee=["male","female","unknown"],EP=qe({provider:rn(pj),configured:Ln(),region:rn(wC),asrModel:Ce().min(1),ttsModel:Ce().min(1),ttsVoice:Ce().min(1),turnIdleSeconds:Lt().int().positive().safe().default(3)}).strict(),CP=qe({provider:rn(pj).optional(),apiKey:Ce().min(1).optional(),clearApiKey:Ln().optional(),region:rn(wC).optional(),asrModel:Ce().min(1).optional(),ttsModel:Ce().min(1).optional(),ttsVoice:Ce().min(1).optional(),turnIdleSeconds:Lt().int().positive().safe().optional()}).strict(),wx=qe({value:Ce().min(1),label:Ce().min(1),description:Ce().min(1).optional(),gender:rn(dee).optional(),age:Ce().min(1).optional(),model:Ce().min(1).optional(),source:rn(uee)}).strict(),fee=qe({asrModels:ur(wx),ttsModels:ur(wx),ttsVoices:ur(wx),fetchedAt:Lt().optional()}).strict(),hee=[{value:"qwen3-asr-flash-realtime",label:"Qwen3 ASR Flash Realtime",source:"official"},{value:"qwen3-asr-flash-realtime-2026-02-10",label:"Qwen3 ASR Flash Realtime · 2026-02-10",source:"official"},{value:"qwen3-asr-flash-realtime-2025-10-27",label:"Qwen3 ASR Flash Realtime · 2025-10-27",source:"official"}],pee=[{value:"cosyvoice-v3-flash",label:"CosyVoice V3 Flash · 系统音色",source:"official"},{value:"cosyvoice-v3-plus",label:"CosyVoice V3 Plus · 系统音色",source:"official"},{value:"cosyvoice-v3.5-flash",label:"CosyVoice V3.5 Flash · 自定义音色",source:"official"},{value:"cosyvoice-v3.5-plus",label:"CosyVoice V3.5 Plus · 自定义音色",source:"official"}],mee=[{value:"longanyang",label:"龙安洋 · 男 · 阳光大男孩 · 年龄 20-30",gender:"male",age:"20-30",model:"cosyvoice-v3-flash",source:"official"},{value:"longanhuan",label:"龙安欢 · 女 · 欢脱元气 · 年龄 20-30",gender:"female",age:"20-30",model:"cosyvoice-v3-flash",source:"official"},{value:"longhuhu_v3",label:"龙呼呼 · 女 · 天真烂漫女童 · 年龄 6-10",gender:"female",age:"6-10",model:"cosyvoice-v3-flash",source:"official"},{value:"longpaopao_v3",label:"龙泡泡 · 未知 · 飞天泡泡音 · 年龄 6-15",gender:"unknown",age:"6-15",model:"cosyvoice-v3-flash",source:"official"},{value:"longjielidou_v3",label:"龙杰力豆 · 男 · 阳光顽皮 · 年龄 10",gender:"male",age:"10",model:"cosyvoice-v3-flash",source:"official"},{value:"longxian_v3",label:"龙仙 · 女 · 豪放可爱 · 年龄 12",gender:"female",age:"12",model:"cosyvoice-v3-flash",source:"official"},{value:"longling_v3",label:"龙铃 · 女 · 稚气呆板 · 年龄 10",gender:"female",age:"10",model:"cosyvoice-v3-flash",source:"official"},{value:"longjiaxin_v3",label:"龙嘉欣 · 女 · 优雅粤语 · 年龄 30-35",gender:"female",age:"30-35",model:"cosyvoice-v3-flash",source:"official"},{value:"longanyue_v3",label:"龙安粤 · 男 · 欢脱粤语 · 年龄 25-35",gender:"male",age:"25-35",model:"cosyvoice-v3-flash",source:"official"},{value:"longlaotie_v3",label:"龙老铁 · 男 · 东北直率 · 年龄 25-30",gender:"male",age:"25-30",model:"cosyvoice-v3-flash",source:"official"},{value:"longanyang",label:"龙安洋 · 男 · 阳光大男孩 · 年龄 20-30",gender:"male",age:"20-30",model:"cosyvoice-v3-plus",source:"official"},{value:"longanhuan",label:"龙安欢 · 女 · 欢脱元气 · 年龄 20-30",gender:"female",age:"20-30",model:"cosyvoice-v3-plus",source:"official"}];function xx(e){return{...e}}function Wg(e){return{asrModels:hee.map(xx),ttsModels:pee.map(xx),ttsVoices:mee.map(xx)}}const gee=rn(["code","table","diff","log","stack_trace","long_list","long_text","mixed","approval"]),on=qe({proxyId:we,bindingId:we}).strict(),vee=1,yee=Ce().regex(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/);qe({bootstrapVersion:Se(vee),relayVersion:yee,controlProtocolVersion:Lt().int().positive()});const xC=4096,bee=4096,_ee=65536,wee=256,mj=4096,xee=1e3,OS=Ce().trim().min(1).max(wee),See=["cloudflare","cpolar"],gj=rn(See),Yc=Ce().min(1).max(xC);function SC(e){try{return new URL(e)}catch{return null}}const vj=Ce().min(1).max(bee).url().refine(e=>{const t=SC(e);return!t||t.protocol!=="http:"||t.username!==""||t.password!==""?!1:t.hostname==="localhost"||t.hostname==="127.0.0.1"||t.hostname==="[::1]"},"Local preview URL must use http:// with a loopback host and no credentials"),Eee=Ce().min(1).max(_ee).url().refine(e=>{const t=SC(e);return t?t.protocol==="https:"&&t.username===""&&t.password===""&&t.port==="":!1},"Preview public URL must use standard HTTPS without credentials"),yj="[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?",Cee=new RegExp(`^${yj}\\.trycloudflare\\.com$`,"i"),kee=new RegExp(`^(?:${yj}\\.)+cpolar\\.(?:top|cn|io)$`,"i"),kP=ur(Ce().min(1).max(xC)).max(32).optional(),TP=Dn("available",[qe({available:Se(!0),command:Ce().min(1).max(xC),version:Ce().min(1).max(256).optional(),error:ns().optional(),suggestions:kP}).strict(),qe({available:Se(!1),command:ns().optional(),version:ns().optional(),error:Ce().min(1).max(mj),suggestions:kP}).strict()]),Tee=qe({cloudflared:TP,cpolar:TP}).strict(),Ree=Dn("kind",[qe({kind:Se("local"),url:vj}).strict(),qe({kind:Se("static"),path:Yc,entryPath:Yc}).strict()]),Aee=Dn("kind",[qe({kind:Se("local"),url:vj}).strict(),qe({kind:Se("static"),rootPath:Yc,entryPath:Yc}).strict()]),Nee=["starting","ready","disconnected","failed","stopping"];rn(Nee);const vh=qe({previewId:we,name:OS,source:Aee,tunnelProvider:gj,createdAt:Lt().int().nonnegative(),updatedAt:Lt().int().nonnegative()}),Sx={publicUrl:ns().optional(),error:ns().optional()},Ex=Dn("state",[vh.extend({state:Se("starting"),...Sx}).strict(),vh.extend({state:Se("ready"),publicUrl:Eee,error:ns().optional()}).strict(),vh.extend({state:Se("disconnected"),...Sx}).strict(),vh.extend({state:Se("failed"),publicUrl:ns().optional(),error:Ce().min(1).max(mj)}).strict(),vh.extend({state:Se("stopping"),...Sx}).strict()]).superRefine((e,t)=>{if(e.state!=="ready")return;const n=SC(e.publicUrl);if(!n)return;const r=n.hostname,i=e.tunnelProvider;(i==="cloudflare"?Cee.test(r):kee.test(r))||t.addIssue({code:"custom",path:["publicUrl"],message:`Preview public URL hostname does not match tunnel provider ${i}`})}),Mee=ur(Yc).max(xee),LS=4096,Pee=4096,DS=4096,my=256,gy=256,Iee=16384,BS=Ce().trim().min(1).max(my),Oee=["jpeg","h264_annex_b"],Lee=rn(Oee),Dee=["ios","android"],bj=rn(Dee),Cx=ur(Ce().min(1).max(LS)).max(32).optional(),RP=tm([qe({supported:Se(!1),available:Se(!1),interactive:Se(!1),command:ns().optional(),version:ns().optional(),error:Ce().min(1).max(DS),suggestions:Cx}).strict(),qe({supported:Se(!0),available:Se(!1),interactive:Se(!1),command:Ce().min(1).max(LS).optional(),version:Ce().min(1).max(gy).optional(),error:Ce().min(1).max(DS),suggestions:Cx}).strict(),qe({supported:Se(!0),available:Se(!0),interactive:Se(!0),command:Ce().min(1).max(LS),version:Ce().min(1).max(gy).optional(),error:ns().optional(),suggestions:Cx}).strict()]),Bee=qe({ios:RP,android:RP}).strict(),AP=qe({targetId:we,platform:bj,name:Ce().min(1).max(my),model:Ce().min(1).max(my),osVersion:Ce().min(1).max(gy),interactive:Ln()}),NP=Lt().int().positive().max(Iee),zee=tm([AP.extend({width:NP,height:NP}).strict(),AP.extend({width:ns().optional(),height:ns().optional()}).strict()]);rn(["ready","disconnected"]);const MP=qe({previewId:we,name:BS,platform:bj,targetId:we,model:Ce().min(1).max(my),osVersion:Ce().min(1).max(gy),interactive:Ln(),createdAt:Lt().int().nonnegative(),updatedAt:Lt().int().nonnegative()}),kx=Dn("state",[MP.extend({state:Se("ready"),error:ns().optional()}).strict(),MP.extend({state:Se("disconnected"),error:ns().optional()}).strict()]),_j=qe({format:Se("jpeg"),maxFps:Lt().int().min(1).max(30).optional()}).strict(),wj=qe({format:Se("h264_annex_b")}).strict(),jee=Dn("format",[_j,wj]),Fee=["client_closed","preview_closed","proxy_offline","relay_shutdown","stream_error"],$ee=rn(Fee),PP=Lt().finite().min(0).max(1),Hee=["down","move","up"],Uee=rn(Hee),Wee=["portrait","landscape_left","landscape_right","portrait_upside_down","auto"],qee=rn(Wee),Vee=Dn("kind",[qe({kind:Se("touch"),phase:Uee,x:PP,y:PP}).strict(),qe({kind:Se("text"),text:Ce().min(1).max(Pee)}).strict(),qe({kind:Se("button"),button:rn(["home","back"])}).strict(),qe({kind:Se("orientation"),orientation:qee}).strict()]);qe({type:Se("device_preview_stream_register"),proxyId:we,connectionId:we}).strict();const Yee=Dn("success",[qe({type:Se("device_preview_stream_register_response"),success:Se(!0)}).strict(),qe({type:Se("device_preview_stream_register_response"),success:Se(!1),error:Ce().min(1).max(DS)}).strict()]),IP=qe({type:Se("device_preview_stream_flow"),streamId:we}),Kee=Dn("paused",[IP.extend({paused:Se(!0),resyncRequired:Se(!1)}).strict(),IP.extend({paused:Se(!1),resyncRequired:Ln()}).strict()]);tm([Yee,Kee]);const Gee=rn(["pcm_s16le","mulaw"]),Xee=qe({type:Se("start"),sessionId:Ce().min(1),attemptId:Ce().min(1),sampleRate:Lt().int().positive(),encoding:Gee}),Zee=qe({type:Se("stop"),attemptId:Ce().min(1)});Dn("type",[Xee,Zee]);const Qee=Dn("type",[qe({type:Se("ready"),attemptId:Ce().min(1)}),qe({type:Se("audio_ack"),attemptId:Ce().min(1),encodedBytes:Lt().int().nonnegative(),pcmBytes:Lt().int().nonnegative(),chunks:Lt().int().nonnegative()}),qe({type:Se("partial"),attemptId:Ce().min(1),text:Ce()}),qe({type:Se("final"),attemptId:Ce().min(1),text:Ce()}),qe({type:Se("closed"),attemptId:Ce().min(1),code:Lt().int().optional(),reason:Ce().optional()}),qe({type:Se("error"),attemptId:Ce().min(1),error:Ce().optional(),errorCode:Ce().optional()})]);function OP(e){return/^\/compact(?:\s|$)/.test(e.trimStart())}const Jee=/((?:authorization|api[_-]?key|token|password|secret)\s*[:=]\s*)(?:bearer\s+)?[^\s'"]+/giu,ete=/(--(?:api-key|token|password|secret)(?:=|\s+))[^\s'"]+/giu;function Pa(e){return typeof e=="string"?e:""}function Ku(e,t=140){const n=e.replace(/\s+/gu," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Gu(e){return e.replace(Jee,"$1[redacted]").replace(ete,"$1[redacted]")}function Tc(e){return Pa(e.file_path)||Pa(e.path)||Pa(e.notebook_path)}function tte(e,t){switch(e){case"Bash":{const n=Ku(Gu(Pa(t.command)));return n?`运行命令:${n}`:"运行命令"}case"BashBatch":{const n=Array.isArray(t.commands)?t.commands.filter(r=>typeof r=="string"):[];return n.length>0?`批量运行命令:${n.length} 条`:"批量运行命令"}case"ProcessWait":return"等待命令完成";case"ProcessInput":{const n=Ku(Gu(Pa(t.input)),80);return n?`发送终端输入:${n}`:"发送终端输入"}case"Read":{const n=Tc(t);return n?`读取文件:${n}`:"读取文件"}case"Write":{const n=Tc(t);return n?`写入文件:${n}`:"写入文件"}case"Edit":case"MultiEdit":{const n=Tc(t);return n?`编辑文件:${n}`:"编辑文件"}case"LS":{const n=Tc(t);return n?`列出目录:${n}`:"列出目录"}case"Grep":{const n=Ku(Gu(Pa(t.pattern)),80),r=Tc(t);return n&&r?`搜索:${n} in ${r}`:n?`搜索:${n}`:"搜索文本"}case"Glob":{const n=Ku(Gu(Pa(t.pattern)),80);return n?`查找文件:${n}`:"查找文件"}case"WebFetch":{const n=Ku(Gu(Pa(t.url)),100);return n?`读取网页:${n}`:"读取网页"}case"WebSearch":{const n=Ku(Gu(Pa(t.query)),100);return n?`网页搜索:${n}`:"网页搜索"}case"ViewImage":{const n=Tc(t);return n?`查看图片:${n}`:"查看图片"}case"ViewImageBatch":{const n=Array.isArray(t.paths)?t.paths.filter(r=>typeof r=="string"):[];return n.length>0?`批量查看图片:${n.length} 张`:"批量查看图片"}case"Web":return"访问网页";case"ToolScript":return"执行工具编排";case"TodoWrite":return"更新任务列表";case"Patch":{const n=Tc(t);if(n)return`应用补丁:${n}`;const r=Array.isArray(t.paths)?t.paths.filter(i=>typeof i=="string"):[];return r.length===1?`应用补丁:${r[0]}`:r.length>1?`应用补丁:${r[0]} 等 ${r.length} 个文件`:"应用补丁"}default:return`使用工具:${e}`}}const nte={NOT_REGISTERED:"NOT_REGISTERED",NOT_BOUND:"NOT_BOUND",PROXY_OFFLINE:"PROXY_OFFLINE",INVALID_MESSAGE:"INVALID_MESSAGE",STALE_BINDING:"STALE_BINDING",UNSUPPORTED:"UNSUPPORTED",INVALID_RANGE:"INVALID_RANGE"},Rr={INVALID_PATH:"INVALID_PATH",PATH_NOT_FOUND:"PATH_NOT_FOUND",PATH_NOT_DIRECTORY:"PATH_NOT_DIRECTORY",PATH_ACCESS_DENIED:"PATH_ACCESS_DENIED",PROXY_OFFLINE:"PROXY_OFFLINE",PROXY_NOT_FOUND:"PROXY_NOT_FOUND",PROXY_ONLINE:"PROXY_ONLINE",SESSION_NOT_FOUND:"SESSION_NOT_FOUND",SESSION_ALREADY_ACTIVE:"SESSION_ALREADY_ACTIVE",PROVIDER_UNSUPPORTED:"PROVIDER_UNSUPPORTED",APPROVAL_POLICY_UNSUPPORTED:"APPROVAL_POLICY_UNSUPPORTED",WORKER_START_FAILED:"WORKER_START_FAILED",PROCESS_START_FAILED:"PROCESS_START_FAILED",STREAM_CAPACITY_EXCEEDED:"STREAM_CAPACITY_EXCEEDED",CONTROL_LEASE_INVALID:"CONTROL_LEASE_INVALID",OPERATION_CONFLICT:"OPERATION_CONFLICT",RATE_LIMITED:"RATE_LIMITED",UNKNOWN:"UNKNOWN"},$l=1,rte=qe({proxyId:we,name:Ce().optional(),version:Ce().min(1).max(64),online:Ln(),sessions:ur(Ce())}),ite=qe({clientId:we,proxyId:we.optional(),connectedAt:Lt().int().nonnegative(),current:Ln().optional(),userAgent:Ce().optional(),platform:Ce().optional(),maxTouchPoints:Lt().int().nonnegative().optional(),browserName:Ce().min(1),osName:Ce().min(1),deviceKind:rn(["desktop","tablet","phone","unknown"]),remoteAddress:Ce().optional()}),Tx=qe({available:Ln(),command:Ce().optional(),error:Ce().optional(),suggestions:ur(Ce()).optional()}),xj=qe({claude:Tx,codex:Tx,kimi:Tx}),Sj=qe({name:Ce(),isDir:Ln()}),LP=qe({path:Ce(),entries:ur(Sj)}),DP=qe({name:Ce(),description:Ce(),argumentHint:Ce().optional(),source:Ce()}),ste=qe({id:Ce(),title:Ce(),projectDir:Ce(),updatedAt:Lt(),provider:rn(na),preferredMode:rn(QJ).optional()}),BP={timestamp:Lt().optional(),cursor:Ce().optional()},ote=Dn("role",[qe({role:rn(["user","assistant","system"]),text:Ce(),...BP}),qe({role:Se("activity"),text:Ce(),toolId:we,toolName:Ce(),parameters:Ud(Ce(),Ba()).optional(),status:rn(["running","done","error"]),...BP})]),ir={requestId:we.optional()},Dt={requestId:we},EC=rn(Object.values(Rr)),Jr={error:Ce().optional(),errorCode:EC.optional()},Bi={error:Ce().min(1),errorCode:EC},zP=rn(["inline","download"]),jP=rn(["clipboard_image","file"]);function xt(e,t,n){return{type:e,directions:new Set(Array.isArray(n)?n:n?[n]:[]),schema:qe({type:Se(e),...t??{}})}}function Yn(e,t,n){return{type:e,directions:new Set(Array.isArray(n)?n:n?[n]:[]),schema:qe({type:Se(e),...t}).strict()}}function Cr(e,t,n){return{type:e,directions:new Set(Array.isArray(n)?n:n?[n]:[]),schema:t}}const ate=Dn("success",[qe({type:Se("proxy_select_response"),...ir,success:Se(!0),proxyId:we,bindingId:we}).strict(),qe({type:Se("proxy_select_response"),...ir,success:Se(!1),...Jr}).strict()]),lte=Dn("status",[qe({type:Se("client_register_response"),protocolVersion:Se($l),status:Se("restored"),proxyId:we,bindingId:we}).strict(),qe({type:Se("client_register_response"),protocolVersion:Se($l),status:Se("proxy_offline"),proxyId:we,bindingId:we}).strict(),qe({type:Se("client_register_response"),protocolVersion:Se($l),status:Se("new")}).strict()]),cte=Dn("accepted",[qe({type:Se("preview_create_response"),...Dt,scope:on,operationId:we,accepted:Se(!0),previewId:we}).strict(),qe({type:Se("preview_create_response"),...Dt,scope:on,operationId:we,accepted:Se(!1),...Bi}).strict()]),ute=Dn("accepted",[qe({type:Se("device_preview_create_response"),...Dt,scope:on,operationId:we,accepted:Se(!0),previewId:we}).strict(),qe({type:Se("device_preview_create_response"),...Dt,scope:on,operationId:we,accepted:Se(!1),...Bi}).strict()]),dte=Dn("success",[qe({type:Se("preview_capability_response"),...Dt,scope:on,success:Se(!0),capability:Tee}).strict(),qe({type:Se("preview_capability_response"),...Dt,scope:on,success:Se(!1),...Bi}).strict()]),fte=Dn("success",[qe({type:Se("device_preview_capability_response"),...Dt,scope:on,success:Se(!0),capability:Bee}).strict(),qe({type:Se("device_preview_capability_response"),...Dt,scope:on,success:Se(!1),...Bi}).strict()]),hte=qe({type:Se("proxy_info_request"),...ir}).strict(),pte=qe({type:Se("proxy_info"),...ir,homePath:Ce(),agentCli:xj}).strict(),mte=Dn("success",[qe({type:Se("preview_static_inspect_response"),...Dt,scope:on,success:Se(!0),entryPath:Yc.optional(),htmlEntries:Mee}).strict(),qe({type:Se("preview_static_inspect_response"),...Dt,scope:on,success:Se(!1),...Bi}).strict()]),gte=Dn("success",[qe({type:Se("preview_rename_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!0)}).strict(),qe({type:Se("preview_rename_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!1),...Bi}).strict()]),vte=Dn("success",[qe({type:Se("preview_reconnect_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!0)}).strict(),qe({type:Se("preview_reconnect_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!1),...Bi}).strict()]),yte=Dn("success",[qe({type:Se("preview_close_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!0)}).strict(),qe({type:Se("preview_close_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!1),...Bi}).strict()]),bte=Dn("success",[qe({type:Se("device_preview_targets_response"),...Dt,scope:on,success:Se(!0),targets:ur(zee).max(1024)}).strict(),qe({type:Se("device_preview_targets_response"),...Dt,scope:on,success:Se(!1),...Bi}).strict()]),_te=Dn("success",[qe({type:Se("device_preview_rename_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!0)}).strict(),qe({type:Se("device_preview_rename_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!1),...Bi}).strict()]),wte=Dn("success",[qe({type:Se("device_preview_reconnect_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!0)}).strict(),qe({type:Se("device_preview_reconnect_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!1),...Bi}).strict()]),xte=Dn("success",[qe({type:Se("device_preview_close_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!0)}).strict(),qe({type:Se("device_preview_close_response"),...Dt,scope:on,operationId:we,previewId:we,success:Se(!1),...Bi}).strict()]),Ste=Dn("success",[qe({type:Se("device_preview_stream_url_response"),...Dt,scope:on,previewId:we,success:Se(!0),url:Ce().min(1).max(4096),leaseId:we,expiresAt:Lt().int().nonnegative(),controlMode:rn(["controller","view_only"])}).strict(),qe({type:Se("device_preview_stream_url_response"),...Dt,scope:on,previewId:we,success:Se(!1),...Bi}).strict()]),Ej={type:Se("device_preview_stream_start_response"),streamId:we,leaseId:we,previewId:we},Ete=qe({...Ej,success:Se(!0),format:Lee,width:Lt().int().positive().max(16384).optional(),height:Lt().int().positive().max(16384).optional()}).strict().superRefine((e,t)=>{e.width===void 0!=(e.height===void 0)&&t.addIssue({code:"custom",path:e.width===void 0?["width"]:["height"],message:"Device preview stream dimensions must include both width and height"})}),Cte=Dn("success",[Ete,qe({...Ej,success:Se(!1),...Bi}).strict()]),kte=qe({type:Se("device_preview_stream_complete"),streamId:we,leaseId:we,previewId:we,success:Se(!1),error:Ce().min(1)}).strict(),FP={type:Se("device_preview_stream_start"),streamId:we,leaseId:we,previewId:we},Tte=Dn("format",[qe({...FP,..._j.shape}).strict(),qe({...FP,...wj.shape}).strict()]),Rte=Dn("success",[qe({type:Se("device_preview_input_ack"),scope:on,leaseId:we,inputSeq:Lt().int().min(0).max(4294967295),success:Se(!0)}).strict(),qe({type:Se("device_preview_input_ack"),scope:on,leaseId:we,inputSeq:Lt().int().min(0).max(4294967295),success:Se(!1),...Bi}).strict()]),Ate=Dn("success",[qe({type:Se("device_preview_control_claim_response"),...Dt,scope:on,leaseId:we,success:Se(!0),controlMode:Se("controller")}).strict(),qe({type:Se("device_preview_control_claim_response"),...Dt,scope:on,leaseId:we,success:Se(!1),...Bi}).strict()]),Cj=rn(["default","auto","acceptEdits","plan","bypassPermissions","dontAsk"]),Nte=qe({type:Se("session_create"),...Dt,kind:Se("agent"),cwd:Ce(),name:Ce().optional(),provider:rn(na),mode:Se("json"),resumeSessionId:Ce().optional(),permissionMode:Cj.optional()}).strict(),Mte=qe({type:Se("session_create"),...Dt,kind:Se("agent"),cwd:Ce(),name:Ce().optional(),provider:rn(na),mode:Se("pty"),resumeSessionId:Ce().optional(),cols:Lt().int().positive().max(yC),rows:Lt().int().positive().max(bC),permissionMode:Cj.optional()}).strict(),Pte=qe({type:Se("session_create"),...Dt,kind:Se("terminal"),name:Ce().optional(),mode:Se("pty"),cols:Lt().int().positive().max(yC),rows:Lt().int().positive().max(bC)}).strict(),Ite=Dn("mode",[Nte,Dn("kind",[Mte,Pte])]),Rx={type:Se("session_create_response"),...Dt,success:Se(!0),sessionId:we,cwd:Ce(),lastActive:Lt(),name:Ce().optional(),nameLocked:Ln().optional()},Ote=Dn("mode",[qe({...Rx,kind:Se("agent"),mode:Se("json"),provider:rn(na)}).strict(),Dn("kind",[qe({...Rx,kind:Se("agent"),mode:Se("pty"),provider:rn(na),ptyOwner:rn(fj)}).strict(),qe({...Rx,kind:Se("terminal"),mode:Se("pty"),provider:Se("claude"),ptyOwner:Se("proxy-hosted")}).strict()])]),Lte=Dn("success",[Ote,qe({type:Se("session_create_response"),...Dt,success:Se(!1),...Bi,activeWriterPid:Lt().int().positive().optional()}).strict()]),CC=[Yn("proxy_register",{protocolVersion:Se($l),proxyId:we,name:Ce().optional(),proxyVersion:Ce().min(1).max(64)}),Yn("proxy_register_response",{protocolVersion:Se($l),status:rn(["new","reconnected"]),relayVersion:Ce().min(1).max(64),connectionId:we}),xt("proxy_list_request",ir),xt("proxy_list_response",{...ir,proxies:ur(rte)}),xt("proxy_remove",{...Dt,proxyId:we}),xt("proxy_remove_response",{...Dt,proxyId:we,success:Ln(),...Jr}),xt("relay_client_list_request",ir),xt("relay_client_list_response",{...ir,clients:ur(ite)}),xt("relay_client_kick",{...Dt,clientId:we}),xt("relay_client_kick_response",{...Dt,clientId:we,success:Ln(),...Jr}),xt("relay_client_kicked",{reason:Ce().optional()}),xt("remote_file_url_request",{...Dt,sessionId:we,path:Ce().min(1),disposition:zP}),xt("remote_file_url_response",{...Dt,...Jr,sessionId:we,path:Ce().optional(),success:Ln(),url:Ce().optional(),expiresAt:Lt().int().nonnegative().optional()}),xt("remote_file_metadata_request",{...Dt,sessionId:we,path:Ce().min(1)}),xt("remote_file_metadata_response",{...Dt,...Jr,sessionId:we,path:Ce().optional(),success:Ln(),mimeType:Ce().optional(),size:Lt().int().nonnegative().optional(),fileName:Ce().optional()}),xt("remote_file_stream_request",{streamId:we,sessionId:we,path:Ce().min(1),disposition:zP}),xt("remote_file_stream_response",{...Jr,streamId:we,sessionId:we,success:Ln(),path:Ce().optional(),mimeType:Ce().optional(),size:Lt().int().nonnegative().optional(),fileName:Ce().optional()}),xt("remote_file_stream_complete",{...Jr,streamId:we,success:Ln()}),xt("remote_file_stream_cancel",{streamId:we}),xt("remote_file_upload_url_request",{...Dt,sessionId:we,kind:jP,fileName:Ce().optional(),mimeType:Ce().min(1),size:Lt().int().nonnegative().optional()}),xt("remote_file_upload_url_response",{...Dt,...Jr,sessionId:we,success:Ln(),uploadUrl:Ce().optional(),expiresAt:Lt().int().nonnegative().optional()}),xt("remote_file_upload_stream_request",{uploadId:we,sessionId:we,kind:jP,fileName:Ce().optional(),mimeType:Ce().min(1),size:Lt().int().nonnegative().optional()}),xt("remote_file_upload_stream_complete",{uploadId:we}),xt("remote_file_upload_stream_cancel",{uploadId:we}),xt("remote_file_upload_stream_response",{...Jr,uploadId:we,sessionId:we,success:Ln(),path:Ce().optional()}),xt("proxy_select",{...ir,proxyId:we}),Cr("proxy_select_response",ate),xt("relay_error",{code:rn(Object.values(nte)),message:Ce(),requestId:we.optional()}),xt("voice_config_request",ir),xt("voice_config_response",{...ir,...Jr,config:EP.optional()}),xt("voice_config_update",{...ir,config:CP}),xt("voice_config_update_response",{...ir,...Jr,success:Ln(),config:EP.optional()}),xt("voice_config_test",{...ir,config:CP.optional()}),xt("voice_config_test_response",{...ir,...Jr,success:Ln(),audioBase64:Ce().optional(),audioSampleRate:Lt().int().positive().optional(),audioEncoding:Se("pcm_s16le").optional(),transcript:Ce().optional()}),xt("voice_capabilities_request",{...ir,region:rn(wC).optional()}),xt("voice_capabilities_response",{...ir,...Jr,capabilities:fee.optional()}),xt("latency_web_relay_ping",Dt),xt("latency_web_relay_pong",{...Dt,relayNow:Lt().optional()}),xt("latency_relay_proxy_request",Dt),xt("latency_relay_proxy_response",{...Dt,success:Ln(),rttMs:Lt().nonnegative().optional(),error:Ce().optional()}),xt("latency_relay_proxy_ping",{...Dt,relayNow:Lt().optional()}),xt("latency_relay_proxy_pong",{...Dt,proxyNow:Lt().optional()}),xt("latency_web_proxy_ping",Dt,"client_to_proxy"),xt("latency_web_proxy_pong",{...Dt,proxyNow:Lt().optional()},"proxy_to_client"),Yn("preview_capability_request",{...Dt,scope:on,refreshPath:Ln()},"client_to_proxy"),Cr("preview_capability_response",dte,"proxy_to_client"),Yn("preview_static_inspect_request",{...Dt,scope:on,path:Yc},"client_to_proxy"),Cr("preview_static_inspect_response",mte,"proxy_to_client"),Yn("preview_create_request",{...Dt,scope:on,operationId:we,source:Ree,tunnelProvider:gj,name:OS.optional()},"client_to_proxy"),Cr("preview_create_response",cte,"proxy_to_client"),Yn("preview_list_request",{...Dt,scope:on},"client_to_proxy"),Yn("preview_list_response",{...Dt,scope:on,epoch:we,revision:Lt().int().nonnegative(),previews:ur(Ex)},"proxy_to_client"),Yn("preview_rename_request",{...Dt,scope:on,operationId:we,previewId:we,name:OS},"client_to_proxy"),Cr("preview_rename_response",gte,"proxy_to_client"),Yn("preview_reconnect_request",{...Dt,scope:on,operationId:we,previewId:we},"client_to_proxy"),Cr("preview_reconnect_response",vte,"proxy_to_client"),Yn("preview_close_request",{...Dt,scope:on,operationId:we,previewId:we},"client_to_proxy"),Cr("preview_close_response",yte,"proxy_to_client"),Yn("preview_state_event",{epoch:we,revision:Lt().int().nonnegative(),preview:Ex}),Yn("preview_removed_event",{epoch:we,revision:Lt().int().nonnegative(),previewId:we}),Yn("preview_state_push",{scope:on,epoch:we,revision:Lt().int().nonnegative(),preview:Ex},"proxy_to_client"),Yn("preview_removed_push",{scope:on,epoch:we,revision:Lt().int().nonnegative(),previewId:we},"proxy_to_client"),Yn("device_preview_capability_request",{...Dt,scope:on,refreshPath:Ln()},"client_to_proxy"),Cr("device_preview_capability_response",fte,"proxy_to_client"),Yn("device_preview_targets_request",{...Dt,scope:on,refresh:Ln()},"client_to_proxy"),Cr("device_preview_targets_response",bte,"proxy_to_client"),Yn("device_preview_create_request",{...Dt,scope:on,operationId:we,targetId:we,name:BS.optional()},"client_to_proxy"),Cr("device_preview_create_response",ute,"proxy_to_client"),Yn("device_preview_list_request",{...Dt,scope:on},"client_to_proxy"),Yn("device_preview_list_response",{...Dt,scope:on,epoch:we,revision:Lt().int().nonnegative(),previews:ur(kx).max(1024)},"proxy_to_client"),Yn("device_preview_rename_request",{...Dt,scope:on,operationId:we,previewId:we,name:BS},"client_to_proxy"),Cr("device_preview_rename_response",_te,"proxy_to_client"),Yn("device_preview_reconnect_request",{...Dt,scope:on,operationId:we,previewId:we},"client_to_proxy"),Cr("device_preview_reconnect_response",wte,"proxy_to_client"),Yn("device_preview_close_request",{...Dt,scope:on,operationId:we,previewId:we},"client_to_proxy"),Cr("device_preview_close_response",xte,"proxy_to_client"),Yn("device_preview_state_event",{epoch:we,revision:Lt().int().nonnegative(),preview:kx}),Yn("device_preview_removed_event",{epoch:we,revision:Lt().int().nonnegative(),previewId:we}),Yn("device_preview_state_push",{scope:on,epoch:we,revision:Lt().int().nonnegative(),preview:kx},"proxy_to_client"),Yn("device_preview_removed_push",{scope:on,epoch:we,revision:Lt().int().nonnegative(),previewId:we},"proxy_to_client"),Yn("device_preview_stream_url_request",{...Dt,scope:on,previewId:we,profile:jee}),Cr("device_preview_stream_url_response",Ste),Cr("device_preview_stream_start",Tte),Cr("device_preview_stream_start_response",Cte),Yn("device_preview_stream_stop",{streamId:we,reason:$ee}),Cr("device_preview_stream_complete",kte),Yn("device_preview_input",{scope:on,leaseId:we,inputSeq:Lt().int().min(0).max(4294967295),input:Vee},"client_to_proxy"),Cr("device_preview_input_ack",Rte,"proxy_to_client"),Yn("device_preview_input_revoke",{leaseId:we,reason:Se("control_taken_over")}),Yn("device_preview_control_claim_request",{...Dt,scope:on,leaseId:we}),Cr("device_preview_control_claim_response",Ate),Yn("device_preview_control_revoked_push",{scope:on,leaseId:we,reason:rn(["taken_over","stream_closed","proxy_offline","lease_expired"])}),Yn("client_register",{protocolVersion:Se($l),clientId:we,userAgent:Ce().optional(),platform:Ce().optional(),maxTouchPoints:Lt().int().nonnegative().optional(),browserName:Ce().min(1),osName:Ce().min(1),deviceKind:rn(["desktop","tablet","phone","unknown"])}),Cr("client_register_response",lte),xt("proxy_offline",{proxyId:we}),xt("proxy_removed",{proxyId:we}),xt("proxy_disconnect",{proxyId:we}),xt("proxy_online",{proxyId:we}),Yn("dir_list_request",{...ir,path:Ce(),includeHidden:Ln()},"client_to_proxy"),xt("dir_list_response",{...ir,...Jr,entries:ur(Sj),path:Ce(),includeHidden:Ln()},"proxy_to_client"),xt("dir_create_request",{...ir,path:Ce()},"client_to_proxy"),xt("dir_create_response",{...ir,...Jr,path:Ce(),success:Ln()},"proxy_to_client"),xt("command_list_push",{sessionId:we,commands:ur(DP)},"proxy_to_client"),xt("file_tree_push",{groups:ur(LP)},"proxy_to_client"),Yn("session_list_request",{},"client_to_proxy"),xt("permission_mode_change",{mode:rn(["default","auto_accept","plan"]),sessionId:we.optional()},"client_to_proxy"),xt("session_history_request",Dt,"client_to_proxy"),xt("session_history_response",{...Dt,...Jr,success:Ln(),sessions:ur(ste)},"proxy_to_client"),xt("pty_state",{sessionId:we,payload:iee},"proxy_to_client"),xt("agent_status",{sessionId:we,payload:SP},"proxy_to_client"),xt("terminal_title",{sessionId:we,title:Ce()},"proxy_to_client"),xt("terminal_resize",{sessionId:we,cols:Lt().int().positive(),rows:Lt().int().positive(),outputSeq:Lt().int().nonnegative()},"proxy_to_client"),xt("terminal_resize_request",{sessionId:we,cols:Lt().int().positive(),rows:Lt().int().positive()},"client_to_proxy"),Yn("session_terminate",{sessionId:we},"client_to_proxy"),xt("session_rename",{...ir,sessionId:we,name:Ce()},"client_to_proxy"),xt("session_rename_response",{...ir,sessionId:we,success:Ln(),name:Ce().optional(),...Jr},"proxy_to_client"),xt("session_worker_abort",{sessionId:we},"client_to_proxy"),xt("turn_result",{sessionId:we,success:Ln(),isError:Ln(),result:Ce().optional()},"proxy_to_client"),xt("remote_input_raw",{sessionId:we,data:Ce(),traceId:we.optional()},"client_to_proxy"),Cr("proxy_info_request",hte,"client_to_proxy"),Cr("proxy_info",pte,"proxy_to_client"),xt("agent_cli_config_update",{...ir,provider:rn(na),path:Ce().min(1)},"client_to_proxy"),xt("agent_cli_config_update_response",{...ir,provider:rn(na),agentCli:xj.optional(),...Jr},"proxy_to_client"),Cr("session_create",Ite,"client_to_proxy"),Cr("session_create_response",Lte,"proxy_to_client"),xt("session_runtime_error",{sessionId:we,error:Ce(),errorCode:EC,activeWriterPid:Lt().int().positive().optional()},"proxy_to_client"),xt("session_messages_request",{...ir,sessionId:we,limit:Lt().int().min(1).max(200).optional(),before:Ce().optional()},"client_to_proxy"),xt("session_resources_request",{...Dt,sessionId:we},"client_to_proxy"),xt("session_resources_response",{...Dt,...Jr,sessionId:we,commands:ur(DP),groups:ur(LP)},"proxy_to_client"),xt("agent_status_request",{...ir,sessionId:we.optional()},"client_to_proxy"),xt("agent_status_response",{...ir,statuses:ur(qe({sessionId:we,payload:SP}))},"proxy_to_client"),xt("permission_request_delivered",{sessionId:we,requestId:we},"client_to_proxy"),xt("tool_approve",{sessionId:we,payload:GJ},"client_to_proxy"),xt("tool_deny",{sessionId:we,payload:XJ},"client_to_proxy"),xt("permission_decision_result",{sessionId:we,requestId:we,outcome:rn(["allow","deny"]),delivered:Ln(),message:Ce().optional()},"proxy_to_client"),xt("pending_approvals_push",{sessionId:we,approvals:ur(qe({requestId:we,toolName:Ce(),input:Ud(Ce(),Ba()),options:ur(dj).optional()}))},"proxy_to_client"),xt("voice_summary_request",{...ir,sessionId:we,messageId:we,text:Ce().min(1),reason:gee},"client_to_proxy"),xt("voice_summary_response",{...ir,...Jr,sessionId:we,messageId:we,success:Ln(),summary:Ce().min(1).optional()},"proxy_to_client"),xt("session_history_messages",{...ir,sessionId:we,before:Ce().optional(),messages:ur(ote),hasMore:Ln().optional(),nextBefore:Ce().optional()},"proxy_to_client"),xt("session_sync",{sessions:ur(hj({id:Ce(),cwd:Ce(),name:Ce().optional(),nameLocked:Ln().optional(),state:rn(_C)}))}),xt("session_subscribe",{sessionId:we,requestId:we},"client_to_proxy"),xt("session_snapshot",{sessionId:we,cols:Lt().int().positive(),rows:Lt().int().positive(),data:Ce(),outputSeq:Lt().int().nonnegative(),requestId:we},"proxy_to_client")],Dte=CC.map(e=>e.schema),Bte=Dn("type",Dte);new Set(CC.filter(e=>e.directions.has("proxy_to_client")).map(e=>e.type));new Set(CC.filter(e=>e.directions.has("client_to_proxy")).map(e=>e.type));const zte=3e4,jte=5e3,kC=zte+jte,yh={CLIENT_KICKED:4401,CLIENT_PROTOCOL_REJECTED:4402,DEVICE_STREAM_PROTOCOL_REJECTED:4403,DEVICE_STREAM_BINDING_REJECTED:4404,PROXY_PROTOCOL_REJECTED:4405},Wd={PAGE_OUTDATED:"page_outdated",SERVICE_OUTDATED:"service_outdated",PROTOCOL_MISMATCH:"protocol_mismatch"},bh=1,qg=4;function Fte(e){if(e.length<bh+qg)return null;const t=e[0];if(t===0||e.length<bh+t+qg)return null;const n=new TextDecoder().decode(e.subarray(bh,bh+t)),r=bh+t,i=new DataView(e.buffer,e.byteOffset+r,qg).getUint32(0,!0),s=e.subarray(r+qg);return{sessionId:n,outputSeq:i,data:s}}const zS=4,vy=2*1024*1024,$te=1,Hte=1,Ute=1,kj=2,Dv=4,Tj=$te+Hte+Ute,Wte=Tj+Dv,qte=Wte+zS,Vte=0,Yte=1,Ax=1,Nx=2,Yh=qte+kj;function Kte(e){return(e&-4)!==0||(e&(Ax|Nx))===(Ax|Nx)?null:{configuration:(e&Ax)!==0,keyframe:(e&Nx)!==0}}const _h=8;function Gte(e){if(e.length<Yh||e[0]!==Vte||e[1]!==Yte)return null;const t=Kte(e[2]);if(!t)return null;const n=new DataView(e.buffer,e.byteOffset+Tj,Dv+zS+kj),r=n.getUint32(0,!0);return r===0||r>vy?null:{annexBLength:r,packetSequence:n.getUint32(Dv,!0),...t,durationMs:n.getUint16(Dv+zS,!0)}}const Xte=132,Zte=32635;function Qte(e){let t=e;const n=t<0?128:0;t<0&&(t=-t),t=Math.min(t,Zte)+Xte;let r=7;for(let s=16384;r>0&&(t&s)===0;s>>=1)r-=1;const i=t>>r+3&15;return~(n|r<<4|i)&255}function Jte(e){const t=Math.floor(e.byteLength/2),n=new Uint8Array(t),r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(let i=0;i<t;i+=1)n[i]=Qte(r.getInt16(i*2,!0));return n}function ene(e){const t=new Set,n=Object.entries(e);for(const[i,s]of n)s.length===0&&t.add(i);let r=!0;for(;r;){r=!1;for(const[i,s]of n)t.has(i)||s.length>0&&s.every(o=>t.has(o))&&(t.add(i),r=!0)}return t}function $P(e){let t=e.initial;const n=ene(e.transitions),r=i=>{var l,u;const s=e.transitions[t];if(!(s!=null&&s.includes(i)))return(l=e.onRejected)==null||l.call(e,t,i,n.has(t)),!1;const o=t;return t=i,(u=e.onTransition)==null||u.call(e,o,i),!0};return{current:()=>t,is:i=>t===i,isIn:i=>i.includes(t),canTransitionTo:i=>{var s;return((s=e.transitions[t])==null?void 0:s.includes(i))??!1},transitionTo:i=>{if(!r(i))throw new Error(`Invalid FSM transition: ${t} -> ${i}`)},tryTransitionTo:r,isInAbsorbingState:()=>n.has(t)}}function TC(e,t){return!e||!t?null:`${encodeURIComponent(e)}:${encodeURIComponent(t)}`}function tne(e,t){return e.endsWith(`:${encodeURIComponent(t)}`)}function nne(){const e=Si("session",wn.ptyAutoYesSessions);if(!e)return{};try{const t=JSON.parse(e);return!t||typeof t!="object"||Array.isArray(t)?{}:Object.fromEntries(Object.entries(t).filter(n=>n[1]===!0))}catch{return{}}}function Vg(e){if(Object.entries(e).filter(([,n])=>n).length===0){Fd("session",wn.ptyAutoYesSessions);return}Tr("session",wn.ptyAutoYesSessions,JSON.stringify(e))}const Gt=$a()(Ha((e,t)=>({sessions:[],sessionListLoaded:!1,loadingProxyName:null,historySessions:[],historyLoadStatus:"idle",historyLoadGeneration:0,ptyTitles:{},ptyStateBySessionId:{},agentStatusBySessionId:{},ptyAutoYesBySessionKey:nne(),codexActiveWriterConflict:null,setSessions:n=>e(r=>{const i=new Set(n.map(s=>s.sessionId));return{sessions:n,sessionListLoaded:!0,loadingProxyName:null,agentStatusBySessionId:Object.fromEntries(Object.entries(r.agentStatusBySessionId).filter(([s])=>i.has(s))),ptyStateBySessionId:Object.fromEntries(Object.entries(r.ptyStateBySessionId).filter(([s])=>i.has(s))),ptyTitles:Object.fromEntries(Object.entries(r.ptyTitles).filter(([s])=>i.has(s)))}}),addSession:n=>e(r=>r.sessions.some(i=>i.sessionId===n.sessionId)?r:{sessions:[...r.sessions,n]}),removeSession:n=>e(r=>{const i=Object.fromEntries(Object.entries(r.ptyAutoYesBySessionKey).filter(([s])=>!tne(s,n)));return Vg(i),{sessions:r.sessions.filter(s=>s.sessionId!==n),agentStatusBySessionId:Object.fromEntries(Object.entries(r.agentStatusBySessionId).filter(([s])=>s!==n)),ptyStateBySessionId:Object.fromEntries(Object.entries(r.ptyStateBySessionId).filter(([s])=>s!==n)),ptyTitles:Object.fromEntries(Object.entries(r.ptyTitles).filter(([s])=>s!==n)),ptyAutoYesBySessionKey:i}}),updateSessionState:(n,r,i)=>e(s=>({sessions:s.sessions.map(o=>o.sessionId===n?{...o,state:r,...i!==void 0?{lastActive:i}:{}}:o)})),setAgentStatus:(n,r)=>e(i=>{const s=i.agentStatusBySessionId[n];return s&&s.seq>r.seq?i:{agentStatusBySessionId:{...i.agentStatusBySessionId,[n]:r}}}),setPtyState:(n,r)=>e(i=>{const s=i.ptyStateBySessionId[n];return s&&s.seq>r.seq?i:{ptyStateBySessionId:{...i.ptyStateBySessionId,[n]:r}}}),updateSessionName:(n,r)=>e(i=>({sessions:i.sessions.map(s=>s.sessionId===n?{...s,name:r}:s)})),renameSession:(n,r)=>e(i=>({sessions:i.sessions.map(s=>s.sessionId===n?{...s,name:r,nameLocked:!0}:s)})),setPtyTitle:(n,r)=>e(i=>({ptyTitles:{...i.ptyTitles,[n]:r}})),setPtyAutoYes:(n,r)=>e(i=>{const s={...i.ptyAutoYesBySessionKey};return r?s[n]=!0:delete s[n],Vg(s),{ptyAutoYesBySessionKey:s}}),setHistorySessions:n=>e(r=>({historySessions:n,historyLoadStatus:"loaded",historyLoadGeneration:r.historyLoadGeneration+1})),beginHistoryLoad:()=>{const n=t().historyLoadGeneration+1;return e({historyLoadStatus:"loading",historyLoadGeneration:n}),n},resolveHistoryLoad:(n,r)=>t().historyLoadGeneration!==n?!1:(e({historySessions:r,historyLoadStatus:"loaded"}),!0),rejectHistoryLoad:n=>t().historyLoadGeneration!==n?!1:(e({historyLoadStatus:"error"}),!0),cancelHistoryLoad:n=>t().historyLoadGeneration!==n?!1:(e({historyLoadStatus:"idle"}),!0),prepareForProxySwitch:n=>e(r=>({sessions:[],sessionListLoaded:!1,loadingProxyName:n,historySessions:[],historyLoadStatus:"idle",historyLoadGeneration:r.historyLoadGeneration+1,ptyTitles:{},ptyStateBySessionId:{},agentStatusBySessionId:{},codexActiveWriterConflict:null})),revokeProxyAuthorizations:n=>e(r=>{const i=`${encodeURIComponent(n)}:`,s=Object.fromEntries(Object.entries(r.ptyAutoYesBySessionKey).filter(([o])=>!o.startsWith(i)));return Vg(s),{ptyAutoYesBySessionKey:s}}),clearForProxyRemoval:n=>e(r=>{const i=`${encodeURIComponent(n)}:`,s=Object.fromEntries(Object.entries(r.ptyAutoYesBySessionKey).filter(([o])=>!o.startsWith(i)));return Vg(s),{sessions:[],sessionListLoaded:!1,loadingProxyName:null,historySessions:[],historyLoadStatus:"idle",historyLoadGeneration:r.historyLoadGeneration+1,ptyTitles:{},ptyStateBySessionId:{},agentStatusBySessionId:{},ptyAutoYesBySessionKey:s,codexActiveWriterConflict:null}}),setCodexActiveWriterConflict:n=>e({codexActiveWriterConflict:n})}),{name:"session-store"}));function eb(e,t){if(!e||/[\0\r\n]/.test(e))return null;const n=t?eb(t):null;let r,i,s;const o=/^([a-z]):[\\/]/i.exec(e),l=/^(?:\\\\|\/\/)([^\\/]+)[\\/]([^\\/]+)(?:[\\/]|$)/.exec(e);if(o)r=`${o[1].toUpperCase()}:\\`,i="\\",s=e.slice(o[0].length);else if(l&&!(e.startsWith("//")&&(n==null?void 0:n.separator)==="/")){if([l[1],l[2]].some(d=>d==="."||d===".."))return null;r=`\\\\${l[1]}\\${l[2]}\\`,i="\\",s=e.slice(l[0].length)}else if(e.startsWith("/"))r=(n==null?void 0:n.separator)==="\\"?n.root:"/",i=(n==null?void 0:n.separator)??"/",s=e;else return null;const u=[];for(const d of s.split(i==="\\"?/[\\/]/:/\//))!d||d==="."||(d===".."?u.pop():u.push(d));return{root:r,separator:i,parts:u}}function Hl(e,t){const n=eb(e,t);return n?n.root+n.parts.join(n.separator):""}function qd(e,t){var n;return((n=eb(e,t))==null?void 0:n.separator)??"/"}function wo(e,t=e){if(!e)return e;const n=qd(Hl(e,t)||t),r=n==="\\"?e.replaceAll("/","\\"):e;return r.endsWith(n)?r:`${r}${n}`}function RC(e,t){const n=eb(e,t);return n?n.root+n.parts.slice(0,-1).join(n.separator):""}function AC(e,t){const n=Hl(t,e);if(n)return n;if(/^[a-z]:/i.test(t)||t.startsWith("\\"))return"";const r=Hl(e);return r?Hl(`${wo(r)}${t}`):""}function HP(e,t){const n=Hl(e.trim()),r=t.trim();if(!n||!r||/^[a-z]:/i.test(r)||/^[\\/]/.test(r))return null;const i=qd(n)==="\\",s=r.replace(i?/[\\/]+$/:/\/+$/,"");return s.split(i?/[\\/]/:/\//).some(l=>!l||l==="."||l==="..")?null:AC(n,s)||null}const Li=$a()(Ha((e,t)=>({tree:new Map,treeWithHidden:new Map,cwd:"",homePath:"",agentCli:null,setDirEntries:(n,r,i=!1)=>{const s=Hl(n)||n;if(i){const l=new Map(t().treeWithHidden);l.set(s,r),e({treeWithHidden:l});return}const o=new Map(t().tree);o.set(s,r),e({tree:o})},setCwd:n=>e({cwd:n}),setHomePath:n=>e({homePath:n}),setAgentCli:n=>e({agentCli:n}),clearTree:()=>e({tree:new Map,treeWithHidden:new Map,cwd:""}),prepareForProxySwitch:()=>e({tree:new Map,treeWithHidden:new Map,cwd:"",homePath:"",agentCli:null})}),{name:"file-store"}));function rne(e){if(e.includes("Edg/")||e.includes("EdgiOS/"))return"Edge";if(e.includes("CriOS/")||e.includes("Chrome/"))return"Chrome";if(e.includes("FxiOS/")||e.includes("Firefox/"))return"Firefox";if(e.includes("OPiOS/"))return"Opera";if(e.includes("DuckDuckGo/"))return"DuckDuckGo";if(e.includes("Version/")&&e.includes("Safari/"))return"Safari"}function ine({userAgent:e="",platform:t,maxTouchPoints:n=0}){return t==="MacIntel"&&n>1&&(e.includes("Mac OS X")||e.includes("Macintosh"))}function sne(e){const t=e.userAgent??"";if(ine(e))return"iPad";if(t.includes("iPhone"))return"iPhone";if(t.includes("iPad"))return"iPad";if(t.includes("Mac OS X")||t.includes("Macintosh"))return"macOS";if(t.includes("Windows"))return"Windows";if(t.includes("Android"))return"Android"}function one(e){return e==="iPad"?"tablet":e==="iPhone"||e==="Android"?"phone":e==="macOS"||e==="Windows"?"desktop":"unknown"}function Rj(e){const t=e.browserName??(e.userAgent?rne(e.userAgent):void 0)??"浏览器",n=e.osName??sne(e)??"未知系统";return{...e,browserName:t,osName:n,deviceKind:e.deviceKind??one(n)}}function rf(){const e=typeof navigator>"u"?null:navigator;return Rj({...e!=null&&e.userAgent?{userAgent:e.userAgent}:{},...e!=null&&e.platform?{platform:e.platform}:{},...typeof(e==null?void 0:e.maxTouchPoints)=="number"?{maxTouchPoints:e.maxTouchPoints}:{}})}function ane(e){return`${e.browserName} · ${e.osName}`}function lne(e,t=$l){return e>t?Wd.PAGE_OUTDATED:e<t?Wd.SERVICE_OUTDATED:null}function Aj(e){return Object.values(Wd).some(t=>t===e)}const cne=1e4,une=5e3,Mx=15e3,dne=2e3,fne=1e4;class hne{constructor(t={}){je(this,"ws",null);je(this,"url","");je(this,"transportOpen",!1);je(this,"protocolReady",!1);je(this,"closed",!1);je(this,"reconnectTimer",null);je(this,"readyTimeoutTimer",null);je(this,"reconnectAttempt",0);je(this,"admissionSent",!1);je(this,"messageHandlers",new Set);je(this,"binarySubscribers",new Map);je(this,"statusHandlers",new Set);je(this,"pendingQueue",[]);je(this,"wakeListenersAttached",!1);je(this,"backgroundedAt",null);je(this,"connectionProbe",null);je(this,"connectionProbeSeq",0);je(this,"foregroundWatchdogTimer",null);je(this,"lastInboundAt",0);je(this,"probeConnectionLiveness");je(this,"visibilityListener",()=>{if(document.visibilityState==="hidden"){this.markBackgrounded();return}document.visibilityState==="visible"&&this.resumeFromBackground()});je(this,"onlineListener",()=>this.wakeReconnect(!0));je(this,"blurListener",()=>this.markBackgrounded());je(this,"focusListener",()=>{document.visibilityState!=="hidden"&&this.resumeFromBackground()});je(this,"pageHideListener",()=>this.markBackgrounded());je(this,"pageShowListener",()=>this.resumeFromBackground());const n=rf().deviceKind;this.probeConnectionLiveness=t.probeConnectionAfterBackground??(n==="phone"||n==="tablet")}markBackgrounded(){this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.backgroundedAt??(this.backgroundedAt=Date.now())}resumeFromBackground(){const t=this.backgroundedAt;this.backgroundedAt=null;const n=t!==null&&Date.now()-t>=une;if(this.probeConnectionLiveness&&n){this.probeConnection();return}this.wakeReconnect(),this.ensureForegroundWatchdog()}cancelConnectionProbe(t){const n=this.connectionProbe;!n||t&&n.socket!==t||(clearTimeout(n.timeout),this.connectionProbe=null)}cancelForegroundWatchdog(){this.foregroundWatchdogTimer&&(clearTimeout(this.foregroundWatchdogTimer),this.foregroundWatchdogTimer=null)}canRunForegroundWatchdog(){return this.probeConnectionLiveness&&!this.closed&&this.backgroundedAt===null&&(typeof document>"u"||document.visibilityState!=="hidden")}armForegroundWatchdog(t=Mx){this.cancelForegroundWatchdog(),!(!this.canRunForegroundWatchdog()||this.connectionProbe)&&(this.foregroundWatchdogTimer=setTimeout(()=>{this.foregroundWatchdogTimer=null,this.runForegroundWatchdog()},Math.max(0,t)))}ensureForegroundWatchdog(){this.foregroundWatchdogTimer||this.connectionProbe||this.armForegroundWatchdog()}runForegroundWatchdog(){if(!this.canRunForegroundWatchdog())return;const t=this.ws;if(!t||!this.transportOpen||!this.protocolReady||t.readyState!==WebSocket.OPEN){this.wakeReconnect(!0);return}const n=Date.now()-this.lastInboundAt;if(n<Mx){this.armForegroundWatchdog(Mx-n);return}this.probeConnection()}probeConnection(){if(this.closed)return;const t=this.ws;if(!this.transportOpen||!this.protocolReady||!t||t.readyState!==WebSocket.OPEN){this.wakeReconnect(!0);return}this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.connectionProbeSeq+=1;const n=`connection-liveness-${Date.now().toString(36)}-${this.connectionProbeSeq.toString(36)}`,r=setTimeout(()=>{const i=this.connectionProbe;!i||i.socket!==t||i.requestId!==n||(this.connectionProbe=null,!(this.ws!==t||this.closed)&&this.wakeReconnect(!0))},dne);this.connectionProbe={socket:t,requestId:n,timeout:r};try{t.send(JSON.stringify({type:"latency_web_relay_ping",requestId:n}))}catch{this.cancelConnectionProbe(t),this.ws===t&&!this.closed&&this.wakeReconnect(!0)}}consumeConnectionProbePong(t,n){const r=this.connectionProbe;if(!r||r.socket!==t)return!1;let i;try{i=JSON.parse(n)}catch{return!1}return i.type!=="latency_web_relay_pong"||i.requestId!==r.requestId?!1:(this.cancelConnectionProbe(t),!0)}noteInbound(t){this.ws===t&&(this.lastInboundAt=Date.now(),this.cancelConnectionProbe(t),this.ensureForegroundWatchdog())}cancelReconnectTimer(){this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}cancelReadyTimeout(){this.readyTimeoutTimer&&(clearTimeout(this.readyTimeoutTimer),this.readyTimeoutTimer=null)}armReadyTimeout(t){this.cancelReadyTimeout(),this.readyTimeoutTimer=setTimeout(()=>{if(this.readyTimeoutTimer=null,!(this.closed||this.ws!==t||this.protocolReady)){this.cancelConnectionProbe(t),this.cancelForegroundWatchdog(),this.ws=null,this.transportOpen=!1,this.protocolReady=!1,this.admissionSent=!1;try{t.close()}catch{}this.statusHandlers.forEach(n=>n(!1,{willReconnect:!0,transportOpen:!1,protocolReady:!1})),this.scheduleReconnect()}},fne)}connect(t){this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.cancelReadyTimeout(),this.ws&&(this.ws.close(),this.ws=null),this.cancelReconnectTimer(),this.transportOpen=!1,this.protocolReady=!1,this.admissionSent=!1,this.url=t,this.closed=!1,this.attachWakeListeners(),this.doConnect()}attachWakeListeners(){this.wakeListenersAttached||typeof window>"u"||(this.wakeListenersAttached=!0,document.addEventListener("visibilitychange",this.visibilityListener),window.addEventListener("online",this.onlineListener),window.addEventListener("blur",this.blurListener),window.addEventListener("focus",this.focusListener),window.addEventListener("pagehide",this.pageHideListener),window.addEventListener("pageshow",this.pageShowListener))}detachWakeListeners(){!this.wakeListenersAttached||typeof window>"u"||(this.wakeListenersAttached=!1,document.removeEventListener("visibilitychange",this.visibilityListener),window.removeEventListener("online",this.onlineListener),window.removeEventListener("blur",this.blurListener),window.removeEventListener("focus",this.focusListener),window.removeEventListener("pagehide",this.pageHideListener),window.removeEventListener("pageshow",this.pageShowListener))}wakeReconnect(t=!1){if(this.closed||!t&&this.transportOpen||!t&&this.ws&&this.ws.readyState===WebSocket.CONNECTING)return;this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.cancelReadyTimeout(),this.cancelReconnectTimer();const n=this.ws,r=this.transportOpen;if(this.ws=null,this.transportOpen=!1,this.protocolReady=!1,this.admissionSent=!1,r&&this.statusHandlers.forEach(i=>i(!1,{willReconnect:!0,transportOpen:!1,protocolReady:!1})),n)try{n.close()}catch{}this.doConnect()}send(t,n={}){if(!this.protocolReady){if(n.queueWhenDisconnected&&!this.closed){if(this.pendingQueue.length>=cne){const r=this.pendingQueue.shift();console.warn("WebSocket queue overflow: dropping oldest pending message",r==null?void 0:r.slice(0,200))}this.pendingQueue.push(t)}return!this.ws&&!n.queueWhenDisconnected&&console.warn("WebSocket send dropped: no socket"),!1}return this.ws?(this.doSend(t),!0):(console.warn("WebSocket send dropped: no socket"),!1)}sendAdmission(t){return!this.ws||!this.transportOpen||this.protocolReady||this.admissionSent||this.ws.readyState!==WebSocket.OPEN?!1:(this.admissionSent=!0,this.doSend(t),!0)}close(){var t;this.closed=!0,this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.cancelReadyTimeout(),this.cancelReconnectTimer(),(t=this.ws)==null||t.close(),this.ws=null,this.transportOpen=!1,this.protocolReady=!1,this.admissionSent=!1,this.pendingQueue.length=0,this.backgroundedAt=null,this.detachWakeListeners()}onMessage(t){return this.messageHandlers.add(t),()=>this.messageHandlers.delete(t)}onStatusChange(t){return this.statusHandlers.add(t),()=>this.statusHandlers.delete(t)}isConnected(){return this.protocolReady}markProtocolReady(){!this.transportOpen||this.protocolReady||!this.ws||this.ws.readyState!==WebSocket.OPEN||(this.protocolReady=!0,this.reconnectAttempt=0,this.cancelReadyTimeout(),this.statusHandlers.forEach(t=>t(!0,{willReconnect:!1,transportOpen:!0,protocolReady:!0})),this.flushPendingQueue())}failPermanently(t){if(this.closed&&!this.ws&&!this.transportOpen)return;this.closed=!0,this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.cancelReadyTimeout(),this.cancelReconnectTimer(),this.backgroundedAt=null,this.detachWakeListeners(),this.pendingQueue.length=0;const n=this.ws,r=n!==null||this.transportOpen;this.ws=null,this.transportOpen=!1,this.protocolReady=!1,this.admissionSent=!1;try{n==null||n.close(yh.CLIENT_PROTOCOL_REJECTED,t)}catch{}r&&this.statusHandlers.forEach(i=>i(!1,{willReconnect:!1,transportOpen:!1,protocolReady:!1,closeCode:yh.CLIENT_PROTOCOL_REJECTED,disconnectReason:t}))}subscribeBinary(t,n){let r=this.binarySubscribers.get(t);return r||(r=new Set,this.binarySubscribers.set(t,r)),r.add(n),()=>{r.delete(n),r.size===0&&this.binarySubscribers.delete(t)}}doConnect(){const t=new WebSocket(this.url);t.binaryType="arraybuffer",this.ws=t,this.transportOpen=!1,this.protocolReady=!1,this.admissionSent=!1,this.armReadyTimeout(t),this.armForegroundWatchdog(),t.addEventListener("open",()=>{this.ws===t&&(this.transportOpen=!0,this.protocolReady=!1,this.lastInboundAt=Date.now(),this.armForegroundWatchdog(),this.statusHandlers.forEach(n=>n(!1,{willReconnect:!1,transportOpen:!0,protocolReady:!1})))}),t.addEventListener("message",n=>{if(this.ws===t)if(n.data instanceof ArrayBuffer){if(!this.protocolReady)return;this.noteInbound(t),this.dispatchBinary(new Uint8Array(n.data))}else{const r=n.data,i=this.consumeConnectionProbePong(t,r);if(this.noteInbound(t),i)return;this.messageHandlers.forEach(s=>s(r))}}),t.addEventListener("close",n=>{if(this.ws!==t)return;this.cancelConnectionProbe(t),this.cancelForegroundWatchdog(),this.cancelReadyTimeout(),(n.code===yh.CLIENT_KICKED||n.code===yh.CLIENT_PROTOCOL_REJECTED)&&(this.closed=!0,this.cancelReconnectTimer(),this.detachWakeListeners(),this.pendingQueue.length=0),this.transportOpen=!1,this.protocolReady=!1,this.admissionSent=!1,this.ws=null;const r=!this.closed,i=n.code===yh.CLIENT_PROTOCOL_REJECTED?Aj(n.reason)?n.reason:Wd.PROTOCOL_MISMATCH:void 0;this.statusHandlers.forEach(s=>s(!1,{willReconnect:r,transportOpen:!1,protocolReady:!1,...n.code?{closeCode:n.code}:{},...i?{disconnectReason:i}:{}})),r&&this.scheduleReconnect()}),t.addEventListener("error",()=>{})}scheduleReconnect(){if(this.closed||this.reconnectTimer)return;const t=Math.min(1e3*Math.pow(2,this.reconnectAttempt),3e4),n=Math.random()*t;this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!this.closed&&this.doConnect()},n)}dispatchBinary(t){const n=Fte(t);if(!n)return;const r=this.binarySubscribers.get(n.sessionId);r&&r.forEach(i=>i(n.data,n.outputSeq))}doSend(t){var n;(n=this.ws)==null||n.send(t)}flushPendingQueue(){const t=this.pendingQueue.splice(0);for(const n of t)this.doSend(n)}}const pne=24,mne=48,gne=1,vne=4,yne=8,bne=8,_ne=32;function UP(e,t,n){return Math.min(n,Math.max(t,e))}function wne({viewportWidth:e,viewportHeight:t,sidebarWidth:n=0,safeAreaTop:r=0,safeAreaBottom:i=0,cellWidth:s,cellHeight:o}){if(e<=0||t<=0||s<=0||o<=0)return{cols:Lv,rows:IS};const l=Math.max(0,e-Math.max(0,n)-pne),u=Math.floor(l/s),f=u<Lv?_ne:bne,p=mne+gne+vne+yne+f+Math.max(0,r)+Math.max(0,i),y=Math.max(0,t-p),g=Math.floor(y/o);return{cols:UP(u,Lv,yC),rows:UP(g,IS,bC)}}function xne(){if(typeof document>"u"||!document.body)return{top:0,bottom:0};const e=document.createElement("div");Object.assign(e.style,{position:"fixed",visibility:"hidden",pointerEvents:"none",paddingTop:"env(safe-area-inset-top)",paddingBottom:"env(safe-area-inset-bottom)"}),document.body.append(e);const t=getComputedStyle(e),n={top:Number.parseFloat(t.paddingTop)||0,bottom:Number.parseFloat(t.paddingBottom)||0};return e.remove(),n}function Sne(e){const t={width:e*.5,height:e*1.25};if(typeof document>"u"||!document.body)return t;const n=document.createElement("span");n.textContent="W",Object.assign(n.style,{position:"fixed",left:"-9999px",top:"0",visibility:"hidden",whiteSpace:"pre",fontFamily:Az,fontSize:`${e}px`,fontWeight:"normal",fontStyle:"normal",fontVariant:"normal",letterSpacing:"0",lineHeight:"normal"}),document.body.append(n);const r=n.getBoundingClientRect();return n.remove(),{width:r.width>0?r.width:t.width,height:r.height>0?r.height:t.height}}function Ene(){if(typeof document>"u")return 0;const e=document.querySelector('[data-slot="sidebar"], [data-slot="sidebar-rail"]');if(!e)return 0;const t=e.getBoundingClientRect();return t.width>0&&t.height>0?t.width:0}function Cne(){const e=window.visualViewport,t=document.querySelector('[data-slot="app-shell"]'),n=t==null?void 0:t.getBoundingClientRect();return{width:Math.max(window.innerWidth,(e==null?void 0:e.width)??0,(n==null?void 0:n.width)??0),height:Math.max(window.innerHeight,(e==null?void 0:e.height)??0,(n==null?void 0:n.height)??0)}}function kne(e=jd){if(typeof window>"u")return{cols:Lv,rows:IS};const t=Cne(),n=xne(),r=Sne(e);return wne({viewportWidth:t.width,viewportHeight:t.height,sidebarWidth:Ene(),safeAreaTop:n.top,safeAreaBottom:n.bottom,cellWidth:r.width,cellHeight:r.height})}function Tne(e,t){if(e.length===0)throw new TypeError("PreviewScope proxyId must not be empty");if(t.length===0)throw new TypeError("PreviewScope bindingId must not be empty");return Object.freeze({proxyId:e,bindingId:t})}function tn(e,t){return e===t||e.proxyId===t.proxyId&&e.bindingId===t.bindingId}const On=1e4,Rne=2e4,Px=3e3,NC=200;function Ane(e){if(!e||typeof e!="object"||!("type"in e))return"(missing)";const t=e.type;return typeof t=="string"?t.slice(0,NC):"(invalid)"}function WP(e){return e.slice(0,2).map(t=>`${t.path.map(String).join(".")||"<root>"}:${t.code}`).join(",").slice(0,NC)}function Nne(e){let t;try{t=JSON.parse(e)}catch{return console.warn("RelayClient: invalid inbound JSON dropped",{length:e.length,preview:e.slice(0,NC)}),null}const n=cee.safeParse(t);if(n.success)return n.data;const r=Bte.safeParse(t);return r.success?r.data:(console.warn("RelayClient: malformed inbound message dropped",{type:Ane(t),envelope:WP(n.error.issues),control:WP(r.error.issues)}),null)}function Mne(e){try{const t=JSON.parse(e);return t!==null&&typeof t=="object"&&t.type==="client_register_response"}catch{return!1}}let qP=0;function kn(e){return qP+=1,`${e}-${Date.now().toString(36)}-${qP.toString(36)}`}class Pne{constructor(t,n){je(this,"ws");je(this,"clientId");je(this,"boundProxyId",null);je(this,"previewScope",null);je(this,"messageHandlers",new Set);je(this,"pendingMessages",[]);je(this,"devicePreviewInputSequence",0);je(this,"registered",!1);this.ws=t,this.clientId=n,this.ws.onMessage(r=>{const i=Nne(r);if(!i){(!this.registered||Mne(r))&&this.ws.failPermanently(Wd.PROTOCOL_MISMATCH);return}if(i.type==="client_register_response")this.registered=!0,i.status==="restored"||i.status==="proxy_offline"?(this.boundProxyId=i.proxyId,this.previewScope=Object.freeze({proxyId:i.proxyId,bindingId:i.bindingId})):(this.boundProxyId=null,this.previewScope=null),this.ws.markProtocolReady();else if(!this.registered){this.ws.failPermanently(Wd.PROTOCOL_MISMATCH);return}if(this.messageHandlers.size===0){this.pendingMessages.push(i);return}this.dispatch(i)})}dispatch(t){this.messageHandlers.forEach(n=>{try{n(t)}catch(r){console.warn("RelayClient: message handler error:",t.type,r)}})}register(){this.registered=!1,this.boundProxyId=null,this.previewScope=null;const t=rf();this.ws.sendAdmission(JSON.stringify({type:"client_register",protocolVersion:$l,clientId:this.clientId,...t}))}listProxies(){this.ws.send(JSON.stringify({type:"proxy_list_request"}))}requestProxyList(t=On){const n=kn("proxy-list");return this.waitForMessage(r=>r.type==="proxy_list_response"&&r.requestId===n,()=>this.ws.send(JSON.stringify({type:"proxy_list_request",requestId:n})),"请求开发机列表超时",t,n).then(r=>r.proxies)}removeOfflineProxy(t,n=On){const r=kn("proxy-remove");return this.waitForMessage(i=>i.type==="proxy_remove_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"proxy_remove",requestId:r,proxyId:t})),"移除开发机超时",n,r).then(i=>(i.success&&this.clearBoundProxy(t),{proxyId:i.proxyId,success:i.success,error:i.error,errorCode:i.errorCode}))}requestRelayClients(t=On){const n=kn("relay-clients");return this.waitForMessage(r=>r.type==="relay_client_list_response"&&r.requestId===n,()=>this.ws.send(JSON.stringify({type:"relay_client_list_request",requestId:n})),"读取客户端列表超时",t,n).then(r=>r.clients)}kickRelayClient(t,n=On){const r=kn("relay-client-kick");return this.waitForMessage(i=>i.type==="relay_client_kick_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"relay_client_kick",requestId:r,clientId:t})),"断开客户端超时",n,r).then(i=>({clientId:i.clientId,success:i.success,error:i.error,errorCode:i.errorCode}))}selectProxy(t,n=On){const r=kn("proxy-select");return this.waitForMessage(i=>i.type==="proxy_select_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"proxy_select",requestId:r,proxyId:t})),"连接开发机超时",n,r).then(i=>i.success?(this.boundProxyId=i.proxyId,this.previewScope=Object.freeze({proxyId:i.proxyId,bindingId:i.bindingId}),{success:!0,proxyId:i.proxyId,bindingId:i.bindingId}):{success:!1,error:i.error,errorCode:i.errorCode})}createDirectory(t,n=On){const r=kn("dir-create");return this.waitForMessage(i=>i.type==="dir_create_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"dir_create_request",requestId:r,path:t})),"创建目录超时",n,r).then(i=>({success:i.success,path:i.path,error:i.error,errorCode:i.errorCode}))}requestDirectoryList(t,n={}){const r=kn("dir-list"),i=n.includeHidden??!1;return this.waitForMessage(s=>s.type==="dir_list_response"&&s.requestId===r,()=>this.ws.send(JSON.stringify({type:"dir_list_request",requestId:r,path:t,includeHidden:i})),"读取目录超时",n.timeoutMs??On,r).then(s=>({path:s.path,entries:s.entries,includeHidden:s.includeHidden,error:s.error,errorCode:s.errorCode}))}uploadClipboardImage(t,n){return this.uploadRemoteFile(t,n,"clipboard_image")}requestRemoteFileUrl(t,n,r,i=On){const s=kn("remote-file-url");return this.waitForMessage(o=>o.type==="remote_file_url_response"&&o.requestId===s&&o.sessionId===t,()=>this.ws.send(JSON.stringify({type:"remote_file_url_request",requestId:s,sessionId:t,path:n,disposition:r})),"读取文件地址超时",i,s).then(o=>({sessionId:o.sessionId,success:o.success,path:o.path,url:o.url,expiresAt:o.expiresAt,error:o.error,errorCode:o.errorCode}))}uploadFile(t,n){return this.uploadRemoteFile(t,n,"file")}requestRemoteFileUploadUrl(t,n,r,i=On){const s=kn("remote-file-upload-url");return this.waitForMessage(o=>o.type==="remote_file_upload_url_response"&&o.requestId===s&&o.sessionId===t,()=>this.ws.send(JSON.stringify({type:"remote_file_upload_url_request",requestId:s,sessionId:t,kind:r,fileName:n.name||"upload",mimeType:n.type||"application/octet-stream",size:n.size})),"创建上传地址超时",i,s)}async uploadRemoteFile(t,n,r){const i=await this.requestRemoteFileUploadUrl(t,n,r);if(!i.success||!i.uploadUrl)return{sessionId:i.sessionId,success:!1,error:i.error??"创建上传地址失败",errorCode:i.errorCode};const s=await fetch(i.uploadUrl,{method:"PUT",headers:{"Content-Type":n.type||"application/octet-stream"},body:n}),o=await s.json().catch(()=>({}));return s.ok?{sessionId:o.sessionId??t,success:o.success,path:o.path,error:o.error,errorCode:o.errorCode}:{sessionId:t,success:!1,error:o.error??"上传失败",errorCode:o.errorCode}}requestProxyInfo(t=On){const n=kn("proxy-info");return this.waitForMessage(r=>r.type==="proxy_info"&&r.requestId===n,()=>this.ws.send(JSON.stringify({type:"proxy_info_request",requestId:n})),"读取开发机信息超时",t,n).then(r=>({homePath:r.homePath,agentCli:r.agentCli}))}requestWebPreviewCapability(t,n=!1,r={}){const i=kn("preview-capability");return this.waitForMessage(s=>s.type==="preview_capability_response"&&s.requestId===i&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"preview_capability_request",requestId:i,refreshPath:n}),"检查网页预览支持情况超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{success:!0,capability:s.capability}:{success:!1,error:s.error,errorCode:s.errorCode})}sendPreviewRequest(t,n){const r=this.previewScope;if(!r||r.proxyId!==t.proxyId||r.bindingId!==t.bindingId)throw new Error("预览上下文已失效,请重新选择开发机");return this.ws.send(JSON.stringify({...n,scope:t}))}inspectStaticWebPreview(t,n,r={}){const i=kn("preview-static-inspect");return this.waitForMessage(s=>s.type==="preview_static_inspect_response"&&s.requestId===i&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"preview_static_inspect_request",requestId:i,path:n}),"检查本地网页超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{success:!0,entryPath:s.entryPath,htmlEntries:s.htmlEntries}:{success:!1,error:s.error,errorCode:s.errorCode})}createWebPreview(t,n,r){const i=kn("preview-create"),s=r.tunnelProvider,o=r.operationId,l=r.timeoutMs??On;return this.waitForMessage(u=>u.type==="preview_create_response"&&u.requestId===i&&u.operationId===o&&tn(u.scope,t),()=>this.sendPreviewRequest(t,{type:"preview_create_request",requestId:i,operationId:o,source:n,tunnelProvider:s,name:r.name}),"创建网页预览超时",l,i,r.signal).then(u=>u.accepted?{operationId:u.operationId,accepted:!0,previewId:u.previewId}:{operationId:u.operationId,accepted:!1,error:u.error,errorCode:u.errorCode})}requestWebPreviewList(t,n={}){const r=kn("preview-list");return this.waitForMessage(i=>i.type==="preview_list_response"&&i.requestId===r&&tn(i.scope,t),()=>this.sendPreviewRequest(t,{type:"preview_list_request",requestId:r}),"读取网页预览列表超时",n.timeoutMs??On,r,n.signal).then(i=>({epoch:i.epoch,revision:i.revision,previews:i.previews}))}renameWebPreview(t,n,r,i){const s=kn("preview-rename");return this.waitForMessage(o=>o.type==="preview_rename_response"&&o.requestId===s&&o.operationId===i.operationId&&o.previewId===n&&tn(o.scope,t),()=>this.sendPreviewRequest(t,{type:"preview_rename_request",requestId:s,operationId:i.operationId,previewId:n,name:r}),"重命名网页预览超时",i.timeoutMs??On,s,i.signal).then(o=>o.success?{operationId:o.operationId,previewId:o.previewId,success:!0}:{operationId:o.operationId,previewId:o.previewId,success:!1,error:o.error,errorCode:o.errorCode})}reconnectWebPreview(t,n,r){const i=kn("preview-reconnect");return this.waitForMessage(s=>s.type==="preview_reconnect_response"&&s.requestId===i&&s.operationId===r.operationId&&s.previewId===n&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"preview_reconnect_request",requestId:i,operationId:r.operationId,previewId:n}),"重新连接网页预览超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{operationId:s.operationId,previewId:s.previewId,success:!0}:{operationId:s.operationId,previewId:s.previewId,success:!1,error:s.error,errorCode:s.errorCode})}closeWebPreview(t,n,r){const i=kn("preview-close");return this.waitForMessage(s=>s.type==="preview_close_response"&&s.requestId===i&&s.operationId===r.operationId&&s.previewId===n&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"preview_close_request",requestId:i,operationId:r.operationId,previewId:n}),"关闭网页预览超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{operationId:s.operationId,previewId:s.previewId,success:!0}:{operationId:s.operationId,previewId:s.previewId,success:!1,error:s.error,errorCode:s.errorCode})}requestDevicePreviewCapability(t,n=!1,r={}){const i=kn("device-preview-capability");return this.waitForMessage(s=>s.type==="device_preview_capability_response"&&s.requestId===i&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_capability_request",requestId:i,refreshPath:n}),"检查模拟器支持情况超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{success:!0,capability:s.capability}:{success:!1,error:s.error,errorCode:s.errorCode})}requestDevicePreviewTargets(t,n=!1,r={}){const i=kn("device-preview-targets");return this.waitForMessage(s=>s.type==="device_preview_targets_response"&&s.requestId===i&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_targets_request",requestId:i,refresh:n}),"读取模拟器列表超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{success:!0,targets:s.targets}:{success:!1,error:s.error,errorCode:s.errorCode})}createDevicePreview(t,n,r){const i=kn("device-preview-create"),s=r.operationId;return this.waitForMessage(o=>o.type==="device_preview_create_response"&&o.requestId===i&&o.operationId===s&&tn(o.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_create_request",requestId:i,operationId:s,targetId:n,name:r.name}),"创建模拟器预览超时",r.timeoutMs??On,i,r.signal).then(o=>o.accepted?{operationId:o.operationId,accepted:!0,previewId:o.previewId}:{operationId:o.operationId,accepted:!1,error:o.error,errorCode:o.errorCode})}requestDevicePreviewList(t,n={}){const r=kn("device-preview-list");return this.waitForMessage(i=>i.type==="device_preview_list_response"&&i.requestId===r&&tn(i.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_list_request",requestId:r}),"读取模拟器预览列表超时",n.timeoutMs??On,r,n.signal).then(i=>({epoch:i.epoch,revision:i.revision,previews:i.previews}))}renameDevicePreview(t,n,r,i){const s=kn("device-preview-rename");return this.waitForMessage(o=>o.type==="device_preview_rename_response"&&o.requestId===s&&o.operationId===i.operationId&&o.previewId===n&&tn(o.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_rename_request",requestId:s,operationId:i.operationId,previewId:n,name:r}),"重命名模拟器预览超时",i.timeoutMs??On,s,i.signal).then(o=>o.success?{operationId:o.operationId,previewId:o.previewId,success:!0}:{operationId:o.operationId,previewId:o.previewId,success:!1,error:o.error,errorCode:o.errorCode})}reconnectDevicePreview(t,n,r){const i=kn("device-preview-reconnect");return this.waitForMessage(s=>s.type==="device_preview_reconnect_response"&&s.requestId===i&&s.operationId===r.operationId&&s.previewId===n&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_reconnect_request",requestId:i,operationId:r.operationId,previewId:n}),"重新连接模拟器预览超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{operationId:s.operationId,previewId:s.previewId,success:!0}:{operationId:s.operationId,previewId:s.previewId,success:!1,error:s.error,errorCode:s.errorCode})}closeDevicePreview(t,n,r){const i=kn("device-preview-close");return this.waitForMessage(s=>s.type==="device_preview_close_response"&&s.requestId===i&&s.operationId===r.operationId&&s.previewId===n&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_close_request",requestId:i,operationId:r.operationId,previewId:n}),"关闭模拟器预览超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{operationId:s.operationId,previewId:s.previewId,success:!0}:{operationId:s.operationId,previewId:s.previewId,success:!1,error:s.error,errorCode:s.errorCode})}requestDevicePreviewStream(t,n,r,i){const s=kn("device-preview-stream");return this.waitForMessage(o=>o.type==="device_preview_stream_url_response"&&o.requestId===s&&o.previewId===n&&tn(o.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_stream_url_request",requestId:s,previewId:n,profile:r}),"打开模拟器画面超时",i.timeoutMs??On,s,i.signal).then(o=>o.success?{previewId:o.previewId,success:!0,url:o.url,leaseId:o.leaseId,expiresAt:o.expiresAt,controlMode:o.controlMode}:{previewId:o.previewId,success:!1,error:o.error,errorCode:o.errorCode})}sendDevicePreviewInput(t,n,r,i){this.devicePreviewInputSequence=this.devicePreviewInputSequence+1>>>0;const s=this.devicePreviewInputSequence;return this.waitForMessage(o=>o.type==="device_preview_input_ack"&&o.leaseId===n&&o.inputSeq===s&&tn(o.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_input",leaseId:n,inputSeq:s,input:r}),"模拟器操作超时",i.timeoutMs??On,void 0,i.signal).then(o=>o.success?{leaseId:o.leaseId,inputSeq:o.inputSeq,success:!0}:{leaseId:o.leaseId,inputSeq:o.inputSeq,success:!1,error:o.error,errorCode:o.errorCode})}claimDevicePreviewControl(t,n,r){const i=kn("device-preview-control");return this.waitForMessage(s=>s.type==="device_preview_control_claim_response"&&s.requestId===i&&s.leaseId===n&&tn(s.scope,t),()=>this.sendPreviewRequest(t,{type:"device_preview_control_claim_request",requestId:i,leaseId:n}),"获取模拟器控制权超时",r.timeoutMs??On,i,r.signal).then(s=>s.success?{success:!0,controlMode:s.controlMode}:{success:!1,error:s.error,errorCode:s.errorCode})}updateAgentCliPath(t,n,r=On){const i=kn("agent-cli-config");return this.waitForMessage(s=>s.type==="agent_cli_config_update_response"&&s.requestId===i,()=>this.ws.send(JSON.stringify({type:"agent_cli_config_update",requestId:i,provider:t,path:n})),"保存 Agent CLI 路径超时",r,i).then(s=>({provider:s.provider,agentCli:s.agentCli,error:s.error,errorCode:s.errorCode}))}requestVoiceConfig(t=On){const n=kn("voice-config");return this.waitForMessage(r=>r.type==="voice_config_response"&&r.requestId===n,()=>this.ws.send(JSON.stringify({type:"voice_config_request",requestId:n})),"读取语音设置超时",t,n).then(r=>({config:r.config,error:r.error,errorCode:r.errorCode}))}updateVoiceConfig(t,n=On){const r=kn("voice-config-update");return this.waitForMessage(i=>i.type==="voice_config_update_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"voice_config_update",requestId:r,config:t})),"保存语音设置超时",n,r).then(i=>({success:i.success,config:i.config,error:i.error,errorCode:i.errorCode}))}testVoiceConfig(t={},n=On){const r=kn("voice-config-test");return this.waitForMessage(i=>i.type==="voice_config_test_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"voice_config_test",requestId:r,config:t})),"测试语音配置超时",n,r).then(i=>({success:i.success,audioBase64:i.audioBase64,audioSampleRate:i.audioSampleRate,audioEncoding:i.audioEncoding,transcript:i.transcript,error:i.error,errorCode:i.errorCode}))}requestVoiceCapabilities(t={},n=On){const r=kn("voice-capabilities");return this.waitForMessage(i=>i.type==="voice_capabilities_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"voice_capabilities_request",requestId:r,...t.region?{region:t.region}:{}})),"读取语音能力列表超时",n,r).then(i=>({capabilities:i.capabilities,error:i.error,errorCode:i.errorCode}))}requestVoiceSummary(t,n,r,i,s=Rne){const o=kn("voice-summary");return this.waitForMessage(l=>l.type==="voice_summary_response"&&l.requestId===o&&l.sessionId===t&&l.messageId===n,()=>this.ws.send(JSON.stringify({type:"voice_summary_request",requestId:o,sessionId:t,messageId:n,text:r,reason:i})),"生成语音摘要超时",s,o).then(l=>({sessionId:l.sessionId,messageId:l.messageId,success:l.success,summary:l.summary,error:l.error,errorCode:l.errorCode}))}measureWebRelayLatency(t=Px){const n=kn("latency-web-relay"),r=performance.now();return this.waitForMessage(i=>i.type==="latency_web_relay_pong"&&i.requestId===n,()=>this.ws.send(JSON.stringify({type:"latency_web_relay_ping",requestId:n})),"Web 到 Relay 服务器测速超时",t,n).then(()=>({success:!0,rttMs:performance.now()-r}))}measureRelayProxyLatency(t=Px){const n=kn("latency-relay-proxy");return this.waitForMessage(r=>r.type==="latency_relay_proxy_response"&&r.requestId===n,()=>this.ws.send(JSON.stringify({type:"latency_relay_proxy_request",requestId:n})),"Relay 服务器到开发机测速超时",t,n).then(r=>({success:r.success,rttMs:r.rttMs,error:r.error}))}measureWebProxyLatency(t=Px){const n=kn("latency-web-proxy"),r=performance.now();return this.waitForMessage(i=>i.type==="latency_web_proxy_pong"&&i.requestId===n,()=>this.ws.send(JSON.stringify({type:"latency_web_proxy_ping",requestId:n})),"Web 到开发机测速超时",t,n).then(()=>({success:!0,rttMs:performance.now()-r}))}requestSessionHistory(t=On){const n=kn("session-history");return this.waitForMessage(r=>r.type==="session_history_response"&&r.requestId===n,()=>this.ws.send(JSON.stringify({type:"session_history_request",requestId:n})),"读取历史会话超时",t,n).then(r=>{if(!r.success)throw new Error(r.error??"读取历史会话失败");return r.sessions})}requestSessionMessages(t,n=On){return this.requestSessionMessagesPage(t,{},n).then(r=>r.messages)}requestSessionMessagesPage(t,n={},r=On){const i=kn("session-messages");return this.waitForMessage(s=>s.type==="session_history_messages"&&s.requestId===i&&s.sessionId===t,()=>this.ws.send(JSON.stringify({type:"session_messages_request",requestId:i,sessionId:t,...n.limit!==void 0?{limit:n.limit}:{},...n.before!==void 0?{before:n.before}:{}})),"读取会话消息超时",r,i).then(s=>({messages:s.messages,hasMore:s.hasMore??!1,...s.nextBefore!==void 0?{nextBefore:s.nextBefore}:{},...s.before!==void 0?{before:s.before}:{}}))}requestAgentStatuses(t,n=On){const r=kn("agent-status");return this.waitForMessage(i=>i.type==="agent_status_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"agent_status_request",requestId:r,...t?{sessionId:t}:{}})),"读取 Agent 状态超时",n,r).then(i=>i.statuses)}requestSessionResources(t,n=On){const r=kn("session-resources");return this.waitForMessage(i=>i.type==="session_resources_response"&&i.requestId===r&&i.sessionId===t,()=>this.ws.send(JSON.stringify({type:"session_resources_request",requestId:r,sessionId:t})),"读取会话资源超时",n,r).then(i=>({sessionId:i.sessionId,commands:i.commands,groups:i.groups,error:i.error,errorCode:i.errorCode}))}createSession(t,n=kC){const r=kn("session-create"),i=t.mode==="pty"?kne(Ie.getState().ptyFontSize):void 0;return this.waitForMessage(s=>s.type==="session_create_response"&&s.requestId===r,()=>this.ws.send(JSON.stringify({type:"session_create",requestId:r,...i,...t})),"创建超时,请检查开发机连接后重试",n)}renameSession(t,n,r=On){const i=kn("session-rename");return this.waitForMessage(s=>s.type==="session_rename_response"&&s.requestId===i&&s.sessionId===t,()=>this.ws.send(JSON.stringify({type:"session_rename",requestId:i,sessionId:t,name:n})),"重命名超时,请检查开发机连接后重试",r).then(s=>({sessionId:s.sessionId,success:s.success,name:s.name,error:s.error,errorCode:s.errorCode}))}sendEnvelope(t){return this.ws.send(JSON.stringify(t))}sendControl(t){return this.ws.send(JSON.stringify(t))}waitForMessage(t,n,r,i,s,o){return new Promise((l,u)=>{let d=!1,f=null,p=null,y=null;const g=()=>{f==null||f(),p==null||p(),o==null||o.removeEventListener("abort",w),y&&clearTimeout(y)},_=x=>{d||(d=!0,g(),x())},w=()=>{const x=new Error("请求已取消");x.name="AbortError",_(()=>u(x))};if(o!=null&&o.aborted){w();return}o==null||o.addEventListener("abort",w,{once:!0}),f=this.onMessage(x=>{if(t(x)){_(()=>l(x));return}if(s&&x.type==="relay_error"&&x.requestId===s){const S=x.message??"relay error";_(()=>u(new Error(`Relay 服务器拒绝请求: ${S}`)))}}),p=this.ws.onStatusChange((x,S)=>{x||(S==null?void 0:S.transportOpen)===!0||_(()=>u(new Error("连接已断开")))}),y=setTimeout(()=>{_(()=>u(new Error(r)))},i);try{n()===!1&&_(()=>u(new Error("连接已断开")))}catch(x){_(()=>u(x instanceof Error?x:new Error(String(x))))}})}getBoundProxyId(){return this.boundProxyId}getPreviewScope(){return this.previewScope}clearBoundProxy(t){(!t||this.boundProxyId===t)&&(this.boundProxyId=null,this.previewScope=null)}onMessage(t){if(this.messageHandlers.add(t),this.pendingMessages.length>0){const n=this.pendingMessages;this.pendingMessages=[];for(const r of n)this.dispatch(r)}return()=>{this.messageHandlers.delete(t)}}}var cu=uB();const Nj=Vp(cu);function Ine(e){if(typeof document>"u")return;let t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",t.appendChild(n),n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e))}const One=e=>{switch(e){case"success":return Bne;case"info":return jne;case"warning":return zne;case"error":return Fne;default:return null}},Lne=Array(12).fill(0),Dne=({visible:e,className:t})=>ct.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},ct.createElement("div",{className:"sonner-spinner"},Lne.map((n,r)=>ct.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),Bne=ct.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ct.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),zne=ct.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},ct.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),jne=ct.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ct.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),Fne=ct.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},ct.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),$ne=ct.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},ct.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),ct.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),Hne=()=>{const[e,t]=ct.useState(document.hidden);return ct.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let jS=1;class Une{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{const n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;const{message:r,...i}=t,s=typeof(t==null?void 0:t.id)=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:jS++,o=this.toasts.find(u=>u.id===s),l=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(s)&&this.dismissedToasts.delete(s),o?this.toasts=this.toasts.map(u=>u.id===s?(this.publish({...u,...t,id:s,title:r}),{...u,...t,id:s,dismissible:l,title:r}):u):this.addToast({title:r,...i,dismissible:l,id:s}),s},this.dismiss=t=>(t?(this.dismissedToasts.add(t),requestAnimationFrame(()=>this.subscribers.forEach(n=>n({id:t,dismiss:!0})))):this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));const i=Promise.resolve(t instanceof Function?t():t);let s=r!==void 0,o;const l=i.then(async d=>{if(o=["resolve",d],ct.isValidElement(d))s=!1,this.create({id:r,type:"default",message:d});else if(qne(d)&&!d.ok){s=!1;const p=typeof n.error=="function"?await n.error(`HTTP error! status: ${d.status}`):n.error,y=typeof n.description=="function"?await n.description(`HTTP error! status: ${d.status}`):n.description,_=typeof p=="object"&&!ct.isValidElement(p)?p:{message:p};this.create({id:r,type:"error",description:y,..._})}else if(d instanceof Error){s=!1;const p=typeof n.error=="function"?await n.error(d):n.error,y=typeof n.description=="function"?await n.description(d):n.description,_=typeof p=="object"&&!ct.isValidElement(p)?p:{message:p};this.create({id:r,type:"error",description:y,..._})}else if(n.success!==void 0){s=!1;const p=typeof n.success=="function"?await n.success(d):n.success,y=typeof n.description=="function"?await n.description(d):n.description,_=typeof p=="object"&&!ct.isValidElement(p)?p:{message:p};this.create({id:r,type:"success",description:y,..._})}}).catch(async d=>{if(o=["reject",d],n.error!==void 0){s=!1;const f=typeof n.error=="function"?await n.error(d):n.error,p=typeof n.description=="function"?await n.description(d):n.description,g=typeof f=="object"&&!ct.isValidElement(f)?f:{message:f};this.create({id:r,type:"error",description:p,...g})}}).finally(()=>{s&&(this.dismiss(r),r=void 0),n.finally==null||n.finally.call(n)}),u=()=>new Promise((d,f)=>l.then(()=>o[0]==="reject"?f(o[1]):d(o[1])).catch(f));return typeof r!="string"&&typeof r!="number"?{unwrap:u}:Object.assign(r,{unwrap:u})},this.custom=(t,n)=>{const r=(n==null?void 0:n.id)||jS++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}}const ys=new Une,Wne=(e,t)=>{const n=(t==null?void 0:t.id)||jS++;return ys.addToast({title:e,...t,id:n}),n},qne=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",Vne=Wne,Yne=()=>ys.toasts,Kne=()=>ys.getActiveToasts(),We=Object.assign(Vne,{success:ys.success,info:ys.info,warning:ys.warning,error:ys.error,custom:ys.custom,message:ys.message,promise:ys.promise,dismiss:ys.dismiss,loading:ys.loading},{getHistory:Yne,getToasts:Kne});Ine("[data-sonner-toaster][dir=ltr],html[dir=ltr]{--toast-icon-margin-start:-3px;--toast-icon-margin-end:4px;--toast-svg-margin-start:-1px;--toast-svg-margin-end:0px;--toast-button-margin-start:auto;--toast-button-margin-end:0;--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)}[data-sonner-toaster][dir=rtl],html[dir=rtl]{--toast-icon-margin-start:4px;--toast-icon-margin-end:-3px;--toast-svg-margin-start:0px;--toast-svg-margin-end:-1px;--toast-button-margin-start:0;--toast-button-margin-end:auto;--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)}[data-sonner-toaster]{position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:0;z-index:999999999;transition:transform .4s ease}@media (hover:none) and (pointer:coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}[data-sonner-toaster][data-x-position=right]{right:var(--offset-right)}[data-sonner-toaster][data-x-position=left]{left:var(--offset-left)}[data-sonner-toaster][data-x-position=center]{left:50%;transform:translateX(-50%)}[data-sonner-toaster][data-y-position=top]{top:var(--offset-top)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--offset-bottom)}[data-sonner-toast]{--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:0;overflow-wrap:anywhere}[data-sonner-toast][data-styled=true]{padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px rgba(0,0,0,.1);width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}[data-sonner-toast]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-y-position=top]{top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))}[data-sonner-toast][data-y-position=bottom]{bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))}[data-sonner-toast][data-styled=true] [data-description]{font-weight:400;line-height:1.4;color:#3f3f3f}[data-rich-colors=true][data-sonner-toast][data-styled=true] [data-description]{color:inherit}[data-sonner-toaster][data-sonner-theme=dark] [data-description]{color:#e8e8e8}[data-sonner-toast][data-styled=true] [data-title]{font-weight:500;line-height:1.5;color:inherit}[data-sonner-toast][data-styled=true] [data-icon]{display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}[data-sonner-toast][data-promise=true] [data-icon]>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}[data-sonner-toast][data-styled=true] [data-icon]>*{flex-shrink:0}[data-sonner-toast][data-styled=true] [data-icon] svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}[data-sonner-toast][data-styled=true] [data-content]{display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:0;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}[data-sonner-toast][data-styled=true] [data-button]:focus-visible{box-shadow:0 0 0 2px rgba(0,0,0,.4)}[data-sonner-toast][data-styled=true] [data-button]:first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}[data-sonner-toast][data-styled=true] [data-cancel]{color:var(--normal-text);background:rgba(0,0,0,.08)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-styled=true] [data-cancel]{background:rgba(255,255,255,.3)}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast][data-styled=true] [data-close-button]:focus-visible{box-shadow:0 4px 12px rgba(0,0,0,.1),0 0 0 2px rgba(0,0,0,.2)}[data-sonner-toast][data-styled=true] [data-disabled=true]{cursor:not-allowed}[data-sonner-toast][data-styled=true]:hover [data-close-button]:hover{background:var(--gray2);border-color:var(--gray5)}[data-sonner-toast][data-swiping=true]::before{content:'';position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}[data-sonner-toast][data-y-position=top][data-swiping=true]::before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]::before{top:50%;transform:scaleY(3) translateY(-50%)}[data-sonner-toast][data-swiping=false][data-removed=true]::before{content:'';position:absolute;inset:0;transform:scaleY(2)}[data-sonner-toast][data-expanded=true]::after{content:'';position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}[data-sonner-toast][data-mounted=true]{--y:translateY(0);opacity:1}[data-sonner-toast][data-expanded=false][data-front=false]{--scale:var(--toasts-before) * 0.05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}[data-sonner-toast]>*{transition:opacity .4s}[data-sonner-toast][data-x-position=right]{right:0}[data-sonner-toast][data-x-position=left]{left:0}[data-sonner-toast][data-expanded=false][data-front=false][data-styled=true]>*{opacity:0}[data-sonner-toast][data-visible=false]{opacity:0;pointer-events:none}[data-sonner-toast][data-mounted=true][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}[data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]{--y:translateY(calc(var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]{--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}[data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]{--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s}[data-sonner-toast][data-removed=true][data-front=false]::before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y,0)) translateX(var(--swipe-amount-x,0));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{from{transform:var(--y) translateX(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translateX(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{from{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width:600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-sonner-theme=light]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 87%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 93%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 84%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)}[data-sonner-toaster][data-sonner-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)}[data-sonner-toaster][data-sonner-theme=dark]{--normal-bg:#000;--normal-bg-hover:hsl(0, 0%, 12%);--normal-border:hsl(0, 0%, 20%);--normal-border-hover:hsl(0, 0%, 25%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 43%, 17%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 9%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-sonner-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size:16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:first-child{animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}100%{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}100%{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}100%{opacity:.15}}@media (prefers-reduced-motion){.sonner-loading-bar,[data-sonner-toast],[data-sonner-toast]>*{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}");function Yg(e){return e.label!==void 0}const Gne=3,Xne="24px",Zne="16px",VP=4e3,Qne=356,Jne=14,ere=45,tre=200;function Lo(...e){return e.filter(Boolean).join(" ")}function nre(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const rre=e=>{var t,n,r,i,s,o,l,u,d;const{invert:f,toast:p,unstyled:y,interacting:g,setHeights:_,visibleToasts:w,heights:x,index:S,toasts:k,expanded:T,removeToast:N,defaultRichColors:P,closeButton:R,style:M,cancelButtonStyle:L,actionButtonStyle:X,className:U="",descriptionClassName:V="",duration:j,position:A,gap:D,expandByDefault:O,classNames:I,icons:B,closeButtonAriaLabel:F="Close toast"}=e,[Y,z]=ct.useState(null),[q,K]=ct.useState(null),[$,re]=ct.useState(!1),[Q,G]=ct.useState(!1),[Z,ae]=ct.useState(!1),[le,me]=ct.useState(!1),[ke,$e]=ct.useState(!1),[he,He]=ct.useState(0),[Nt,ye]=ct.useState(0),Ze=ct.useRef(p.duration||j||VP),Oe=ct.useRef(null),ze=ct.useRef(null),et=S===0,Ct=S+1<=w,tt=p.type,Le=p.dismissible!==!1,it=p.className||"",dt=p.descriptionClassName||"",be=ct.useMemo(()=>x.findIndex(W=>W.toastId===p.id)||0,[x,p.id]),Ve=ct.useMemo(()=>{var W;return(W=p.closeButton)!=null?W:R},[p.closeButton,R]),ft=ct.useMemo(()=>p.duration||j||VP,[p.duration,j]),St=ct.useRef(0),wt=ct.useRef(0),fn=ct.useRef(0),Xt=ct.useRef(null),[Jt,xn]=A.split("-"),mn=ct.useMemo(()=>x.reduce((W,ie,J)=>J>=be?W:W+ie.height,0),[x,be]),yt=Hne(),Zt=p.invert||f,zt=tt==="loading";wt.current=ct.useMemo(()=>be*D+mn,[be,mn]),ct.useEffect(()=>{Ze.current=ft},[ft]),ct.useEffect(()=>{re(!0)},[]),ct.useEffect(()=>{const W=ze.current;if(W){const ie=W.getBoundingClientRect().height;return ye(ie),_(J=>[{toastId:p.id,height:ie,position:p.position},...J]),()=>_(J=>J.filter(ce=>ce.toastId!==p.id))}},[_,p.id]),ct.useLayoutEffect(()=>{if(!$)return;const W=ze.current,ie=W.style.height;W.style.height="auto";const J=W.getBoundingClientRect().height;W.style.height=ie,ye(J),_(ce=>ce.find(te=>te.toastId===p.id)?ce.map(te=>te.toastId===p.id?{...te,height:J}:te):[{toastId:p.id,height:J,position:p.position},...ce])},[$,p.title,p.description,_,p.id,p.jsx,p.action,p.cancel]);const yn=ct.useCallback(()=>{G(!0),He(wt.current),_(W=>W.filter(ie=>ie.toastId!==p.id)),setTimeout(()=>{N(p)},tre)},[p,N,_,wt]);ct.useEffect(()=>{if(p.promise&&tt==="loading"||p.duration===1/0||p.type==="loading")return;let W;return T||g||yt?(()=>{if(fn.current<St.current){const ce=new Date().getTime()-St.current;Ze.current=Ze.current-ce}fn.current=new Date().getTime()})():(()=>{Ze.current!==1/0&&(St.current=new Date().getTime(),W=setTimeout(()=>{p.onAutoClose==null||p.onAutoClose.call(p,p),yn()},Ze.current))})(),()=>clearTimeout(W)},[T,g,p,tt,yt,yn]),ct.useEffect(()=>{p.delete&&(yn(),p.onDismiss==null||p.onDismiss.call(p,p))},[yn,p.delete]);function $n(){var W;if(B!=null&&B.loading){var ie;return ct.createElement("div",{className:Lo(I==null?void 0:I.loader,p==null||(ie=p.classNames)==null?void 0:ie.loader,"sonner-loader"),"data-visible":tt==="loading"},B.loading)}return ct.createElement(Dne,{className:Lo(I==null?void 0:I.loader,p==null||(W=p.classNames)==null?void 0:W.loader),visible:tt==="loading"})}const Zn=p.icon||(B==null?void 0:B[tt])||One(tt);var Jn,gn;return ct.createElement("li",{tabIndex:0,ref:ze,className:Lo(U,it,I==null?void 0:I.toast,p==null||(t=p.classNames)==null?void 0:t.toast,I==null?void 0:I.default,I==null?void 0:I[tt],p==null||(n=p.classNames)==null?void 0:n[tt]),"data-sonner-toast":"","data-rich-colors":(Jn=p.richColors)!=null?Jn:P,"data-styled":!(p.jsx||p.unstyled||y),"data-mounted":$,"data-promise":!!p.promise,"data-swiped":ke,"data-removed":Q,"data-visible":Ct,"data-y-position":Jt,"data-x-position":xn,"data-index":S,"data-front":et,"data-swiping":Z,"data-dismissible":Le,"data-type":tt,"data-invert":Zt,"data-swipe-out":le,"data-swipe-direction":q,"data-expanded":!!(T||O&&$),"data-testid":p.testId,style:{"--index":S,"--toasts-before":S,"--z-index":k.length-S,"--offset":`${Q?he:wt.current}px`,"--initial-height":O?"auto":`${Nt}px`,...M,...p.style},onDragEnd:()=>{ae(!1),z(null),Xt.current=null},onPointerDown:W=>{W.button!==2&&(zt||!Le||(Oe.current=new Date,He(wt.current),W.target.setPointerCapture(W.pointerId),W.target.tagName!=="BUTTON"&&(ae(!0),Xt.current={x:W.clientX,y:W.clientY})))},onPointerUp:()=>{var W,ie,J;if(le||!Le)return;Xt.current=null;const ce=Number(((W=ze.current)==null?void 0:W.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Te=Number(((ie=ze.current)==null?void 0:ie.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),te=new Date().getTime()-((J=Oe.current)==null?void 0:J.getTime()),se=Y==="x"?ce:Te,ue=Math.abs(se)/te;if(Math.abs(se)>=ere||ue>.11){He(wt.current),p.onDismiss==null||p.onDismiss.call(p,p),K(Y==="x"?ce>0?"right":"left":Te>0?"down":"up"),yn(),me(!0);return}else{var ge,ee;(ge=ze.current)==null||ge.style.setProperty("--swipe-amount-x","0px"),(ee=ze.current)==null||ee.style.setProperty("--swipe-amount-y","0px")}$e(!1),ae(!1),z(null)},onPointerMove:W=>{var ie,J,ce;if(!Xt.current||!Le||((ie=window.getSelection())==null?void 0:ie.toString().length)>0)return;const te=W.clientY-Xt.current.y,se=W.clientX-Xt.current.x;var ue;const ge=(ue=e.swipeDirections)!=null?ue:nre(A);!Y&&(Math.abs(se)>1||Math.abs(te)>1)&&z(Math.abs(se)>Math.abs(te)?"x":"y");let ee={x:0,y:0};const oe=de=>1/(1.5+Math.abs(de)/20);if(Y==="y"){if(ge.includes("top")||ge.includes("bottom"))if(ge.includes("top")&&te<0||ge.includes("bottom")&&te>0)ee.y=te;else{const de=te*oe(te);ee.y=Math.abs(de)<Math.abs(te)?de:te}}else if(Y==="x"&&(ge.includes("left")||ge.includes("right")))if(ge.includes("left")&&se<0||ge.includes("right")&&se>0)ee.x=se;else{const de=se*oe(se);ee.x=Math.abs(de)<Math.abs(se)?de:se}(Math.abs(ee.x)>0||Math.abs(ee.y)>0)&&$e(!0),(J=ze.current)==null||J.style.setProperty("--swipe-amount-x",`${ee.x}px`),(ce=ze.current)==null||ce.style.setProperty("--swipe-amount-y",`${ee.y}px`)}},Ve&&!p.jsx&&tt!=="loading"?ct.createElement("button",{"aria-label":F,"data-disabled":zt,"data-close-button":!0,onClick:zt||!Le?()=>{}:()=>{yn(),p.onDismiss==null||p.onDismiss.call(p,p)},className:Lo(I==null?void 0:I.closeButton,p==null||(r=p.classNames)==null?void 0:r.closeButton)},(gn=B==null?void 0:B.close)!=null?gn:$ne):null,(tt||p.icon||p.promise)&&p.icon!==null&&((B==null?void 0:B[tt])!==null||p.icon)?ct.createElement("div",{"data-icon":"",className:Lo(I==null?void 0:I.icon,p==null||(i=p.classNames)==null?void 0:i.icon)},p.promise||p.type==="loading"&&!p.icon?p.icon||$n():null,p.type!=="loading"?Zn:null):null,ct.createElement("div",{"data-content":"",className:Lo(I==null?void 0:I.content,p==null||(s=p.classNames)==null?void 0:s.content)},ct.createElement("div",{"data-title":"",className:Lo(I==null?void 0:I.title,p==null||(o=p.classNames)==null?void 0:o.title)},p.jsx?p.jsx:typeof p.title=="function"?p.title():p.title),p.description?ct.createElement("div",{"data-description":"",className:Lo(V,dt,I==null?void 0:I.description,p==null||(l=p.classNames)==null?void 0:l.description)},typeof p.description=="function"?p.description():p.description):null),ct.isValidElement(p.cancel)?p.cancel:p.cancel&&Yg(p.cancel)?ct.createElement("button",{"data-button":!0,"data-cancel":!0,style:p.cancelButtonStyle||L,onClick:W=>{Yg(p.cancel)&&Le&&(p.cancel.onClick==null||p.cancel.onClick.call(p.cancel,W),yn())},className:Lo(I==null?void 0:I.cancelButton,p==null||(u=p.classNames)==null?void 0:u.cancelButton)},p.cancel.label):null,ct.isValidElement(p.action)?p.action:p.action&&Yg(p.action)?ct.createElement("button",{"data-button":!0,"data-action":!0,style:p.actionButtonStyle||X,onClick:W=>{Yg(p.action)&&(p.action.onClick==null||p.action.onClick.call(p.action,W),!W.defaultPrevented&&yn())},className:Lo(I==null?void 0:I.actionButton,p==null||(d=p.classNames)==null?void 0:d.actionButton)},p.action.label):null)};function YP(){if(typeof window>"u"||typeof document>"u")return"ltr";const e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function ire(e,t){const n={};return[e,t].forEach((r,i)=>{const s=i===1,o=s?"--mobile-offset":"--offset",l=s?Zne:Xne;function u(d){["top","right","bottom","left"].forEach(f=>{n[`${o}-${f}`]=typeof d=="number"?`${d}px`:d})}typeof r=="number"||typeof r=="string"?u(r):typeof r=="object"?["top","right","bottom","left"].forEach(d=>{r[d]===void 0?n[`${o}-${d}`]=l:n[`${o}-${d}`]=typeof r[d]=="number"?`${r[d]}px`:r[d]}):u(l)}),n}const sre=ct.forwardRef(function(t,n){const{id:r,invert:i,position:s="bottom-right",hotkey:o=["altKey","KeyT"],expand:l,closeButton:u,className:d,offset:f,mobileOffset:p,theme:y="light",richColors:g,duration:_,style:w,visibleToasts:x=Gne,toastOptions:S,dir:k=YP(),gap:T=Jne,icons:N,containerAriaLabel:P="Notifications"}=t,[R,M]=ct.useState([]),L=ct.useMemo(()=>r?R.filter($=>$.toasterId===r):R.filter($=>!$.toasterId),[R,r]),X=ct.useMemo(()=>Array.from(new Set([s].concat(L.filter($=>$.position).map($=>$.position)))),[L,s]),[U,V]=ct.useState([]),[j,A]=ct.useState(!1),[D,O]=ct.useState(!1),[I,B]=ct.useState(y!=="system"?y:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),F=ct.useRef(null),Y=o.join("+").replace(/Key/g,"").replace(/Digit/g,""),z=ct.useRef(null),q=ct.useRef(!1),K=ct.useCallback($=>{M(re=>{var Q;return(Q=re.find(G=>G.id===$.id))!=null&&Q.delete||ys.dismiss($.id),re.filter(({id:G})=>G!==$.id)})},[]);return ct.useEffect(()=>ys.subscribe($=>{if($.dismiss){requestAnimationFrame(()=>{M(re=>re.map(Q=>Q.id===$.id?{...Q,delete:!0}:Q))});return}setTimeout(()=>{Nj.flushSync(()=>{M(re=>{const Q=re.findIndex(G=>G.id===$.id);return Q!==-1?[...re.slice(0,Q),{...re[Q],...$},...re.slice(Q+1)]:[$,...re]})})})}),[R]),ct.useEffect(()=>{if(y!=="system"){B(y);return}if(y==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?B("dark"):B("light")),typeof window>"u")return;const $=window.matchMedia("(prefers-color-scheme: dark)");try{$.addEventListener("change",({matches:re})=>{B(re?"dark":"light")})}catch{$.addListener(({matches:Q})=>{try{B(Q?"dark":"light")}catch(G){console.error(G)}})}},[y]),ct.useEffect(()=>{R.length<=1&&A(!1)},[R]),ct.useEffect(()=>{const $=re=>{var Q;if(o.every(ae=>re[ae]||re.code===ae)){var Z;A(!0),(Z=F.current)==null||Z.focus()}re.code==="Escape"&&(document.activeElement===F.current||(Q=F.current)!=null&&Q.contains(document.activeElement))&&A(!1)};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[o]),ct.useEffect(()=>{if(F.current)return()=>{z.current&&(z.current.focus({preventScroll:!0}),z.current=null,q.current=!1)}},[F.current]),ct.createElement("section",{ref:n,"aria-label":`${P} ${Y}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},X.map(($,re)=>{var Q;const[G,Z]=$.split("-");return L.length?ct.createElement("ol",{key:$,dir:k==="auto"?YP():k,tabIndex:-1,ref:F,className:d,"data-sonner-toaster":!0,"data-sonner-theme":I,"data-y-position":G,"data-x-position":Z,style:{"--front-toast-height":`${((Q=U[0])==null?void 0:Q.height)||0}px`,"--width":`${Qne}px`,"--gap":`${T}px`,...w,...ire(f,p)},onBlur:ae=>{q.current&&!ae.currentTarget.contains(ae.relatedTarget)&&(q.current=!1,z.current&&(z.current.focus({preventScroll:!0}),z.current=null))},onFocus:ae=>{ae.target instanceof HTMLElement&&ae.target.dataset.dismissible==="false"||q.current||(q.current=!0,z.current=ae.relatedTarget)},onMouseEnter:()=>A(!0),onMouseMove:()=>A(!0),onMouseLeave:()=>{D||A(!1)},onDragEnd:()=>A(!1),onPointerDown:ae=>{ae.target instanceof HTMLElement&&ae.target.dataset.dismissible==="false"||O(!0)},onPointerUp:()=>O(!1)},L.filter(ae=>!ae.position&&re===0||ae.position===$).map((ae,le)=>{var me,ke;return ct.createElement(rre,{key:ae.id,icons:N,index:le,toast:ae,defaultRichColors:g,duration:(me=S==null?void 0:S.duration)!=null?me:_,className:S==null?void 0:S.className,descriptionClassName:S==null?void 0:S.descriptionClassName,invert:i,visibleToasts:x,closeButton:(ke=S==null?void 0:S.closeButton)!=null?ke:u,interacting:D,position:$,style:S==null?void 0:S.style,unstyled:S==null?void 0:S.unstyled,classNames:S==null?void 0:S.classNames,cancelButtonStyle:S==null?void 0:S.cancelButtonStyle,actionButtonStyle:S==null?void 0:S.actionButtonStyle,closeButtonAriaLabel:S==null?void 0:S.closeButtonAriaLabel,removeToast:K,toasts:L.filter($e=>$e.position==ae.position),heights:U.filter($e=>$e.position==ae.position),setHeights:V,expandByDefault:l,gap:T,expanded:j,swipeDirections:t.swipeDirections})})):null}))});function ore(){const e=Ie(t=>t.themePreference);return m.jsx(sre,{theme:e==="auto"?"system":e,position:"top-center",toastOptions:{classNames:{toast:"bg-card text-foreground border border-border",success:"border-l-4 !border-l-[var(--color-status-success)]",error:"border-l-4 !border-l-[var(--color-status-error)]",warning:"border-l-4 !border-l-[var(--color-status-warning)]",info:"border-l-4 !border-l-[var(--color-status-working)]"}}})}function FS(e){return"error"in e}async function $S(e,t){let n=t.proxyId;if(n&&e.getBoundProxyId()===n)return{proxyId:n};if(!n&&t.sessionId){let i;try{i=await e.requestProxyList()}catch(o){return{error:o instanceof Error?o.message:String(o),code:Rr.UNKNOWN}}const s=i.find(o=>{var l;return(l=o.sessions)==null?void 0:l.includes(t.sessionId)});if(!s)return{error:`Session ${t.sessionId} not found on any proxy`,code:Rr.SESSION_NOT_FOUND};n=s.proxyId}if(!n)return{error:"No proxy specified",code:Rr.UNKNOWN};let r;try{r=await e.selectProxy(n)}catch(i){return{error:i instanceof Error?i.message:String(i),code:Rr.UNKNOWN}}return r.success?{proxyId:n}:{error:r.error||"Proxy select failed",code:r.errorCode??Rr.UNKNOWN}}function are(e){const t=Array.from(e,n=>n.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}function tb(e,t=globalThis.crypto??null){if(typeof(t==null?void 0:t.randomUUID)=="function")try{return`${e}-${t.randomUUID()}`}catch{}if(typeof(t==null?void 0:t.getRandomValues)=="function")try{const n=new Uint8Array(16);return t.getRandomValues(n),n[6]=n[6]&15|64,n[8]=n[8]&63|128,`${e}-${are(n)}`}catch{}throw new Error("当前浏览器无法生成预览操作标识")}function nb(e){return Object.freeze({operations:Object.freeze(e.slice())})}function lre(e){if(e.operationId.length===0)throw new TypeError("Preview pending operationId must not be empty");if(e.fingerprint.length===0)throw new TypeError("Preview pending fingerprint must not be empty");if(e.kind!=="create"&&e.previewId.length===0)throw new TypeError("Preview pending previewId must not be empty");if(e.previewKind!=="web"&&e.previewKind!=="device")throw new TypeError("Preview pending previewKind must be web or device");if(!Number.isFinite(e.startedAt))throw new TypeError("Preview pending startedAt must be finite")}function cre(e,t){return e.kind!==t.kind||e.previewKind!==t.previewKind||e.fingerprint!==t.fingerprint?!1:e.kind==="create"||t.kind==="create"?e.kind===t.kind:e.previewId===t.previewId}function KP(){return nb([])}function Mj(e,t,n){return e.operations.find(r=>r.operationId===n&&tn(r.scope,t))}function ure(e,t,n){return e.operations.filter(r=>r.previewKind===n&&tn(r.scope,t))}function Pj(e,t,n,r){return e.operations.filter(i=>i.kind!=="create"&&i.previewKind===n&&i.previewId===r&&tn(i.scope,t))}function dre(e,t){lre(t);const n=Mj(e,t.scope,t.operationId);if(n)return cre(n,t)?{status:"ignored",reason:"duplicate",registry:e,operation:n}:{status:"conflict",reason:"operation-id-conflict",registry:e,existing:n};const r=Object.freeze({...t});return{status:"applied",registry:nb([...e.operations,r]),operation:r}}function fre(e,t,n){const r=e.operations.findIndex(s=>s.operationId===n&&tn(s.scope,t));if(r<0)return{status:"ignored",reason:"not-found",registry:e};const i=e.operations[r];return{status:"applied",registry:nb([...e.operations.slice(0,r),...e.operations.slice(r+1)]),operation:i}}function hre(e,t){const n=e.operations.filter(r=>!tn(r.scope,t));return n.length===e.operations.length?e:nb(n)}function pre(e){return Object.freeze(e.slice())}function Ij(e,t){if(e.length===0)throw new TypeError("Preview epoch must not be empty");if(!Number.isSafeInteger(t)||t<0)throw new TypeError("Preview revision must be a non-negative safe integer")}function mre(e){const t=new Set;for(const n of e){if(n.previewId.length===0)throw new TypeError("Preview id must not be empty");if(t.has(n.previewId))throw new TypeError(`Duplicate preview id in snapshot: ${n.previewId}`);t.add(n.previewId)}}function HS(e,t,n,r){return Object.freeze({scope:e,syncStatus:"synchronized",epoch:t,revision:n,previews:pre(r)})}function US(e,t){return Object.freeze({scope:e.scope,syncStatus:"needs-resync",epoch:e.epoch,revision:e.revision,previews:e.previews,resyncCause:Object.freeze(t)})}function gre(e,t){const n=e.findIndex(r=>r.previewId===t.previewId);return n<0?[...e,t]:e.map((r,i)=>i===n?t:r)}function vre(e,t){if(Ij(t.epoch,t.revision),mre(t.previews),!tn(e.scope,t.scope))return{status:"ignored",reason:"scope-mismatch",state:e};if(e.syncStatus==="needs-resync"){const n=e.resyncCause;return t.epoch===n.observedEpoch&&t.revision<n.observedRevision?{status:"needs-resync",reason:"resync-pending",state:e}:{status:"applied",reason:e.epoch!==t.epoch?"epoch-replaced":"snapshot",state:HS(e.scope,t.epoch,t.revision,t.previews)}}if(e.syncStatus==="synchronized"&&e.epoch===t.epoch){if(t.revision<e.revision)return{status:"ignored",reason:"stale-revision",state:e};if(t.revision===e.revision)return{status:"ignored",reason:"duplicate-revision",state:e}}return{status:"applied",reason:e.syncStatus==="synchronized"&&e.epoch!==t.epoch?"epoch-replaced":"snapshot",state:HS(e.scope,t.epoch,t.revision,t.previews)}}function yre(e,t){const n=e.resyncCause,r=n.observedEpoch===t.epoch?Math.max(n.observedRevision,t.revision):t.revision;return n.observedEpoch===t.epoch&&n.observedRevision===r?e:US(e,{reason:n.observedEpoch===t.epoch?n.reason:"unknown-epoch",observedEpoch:t.epoch,observedRevision:r})}function bre(e,t){if(Ij(t.epoch,t.revision),t.kind==="state"&&t.preview.previewId.length===0)throw new TypeError("Preview id must not be empty");if(t.kind==="removed"&&t.previewId.length===0)throw new TypeError("Preview id must not be empty");if(!tn(e.scope,t.scope))return{status:"ignored",reason:"scope-mismatch",state:e};if(e.syncStatus==="needs-resync")return{status:"needs-resync",reason:"resync-pending",state:yre(e,t)};if(e.syncStatus==="awaiting-snapshot"||e.epoch!==t.epoch)return{status:"needs-resync",reason:"unknown-epoch",state:US(e,{reason:"unknown-epoch",observedEpoch:t.epoch,observedRevision:t.revision})};if(t.revision<e.revision)return{status:"ignored",reason:"stale-revision",state:e};if(t.revision===e.revision)return{status:"ignored",reason:"duplicate-revision",state:e};if(t.revision!==e.revision+1)return{status:"needs-resync",reason:"revision-gap",state:US(e,{reason:"revision-gap",observedEpoch:t.epoch,observedRevision:t.revision})};const n=t.kind==="state"?gre(e.previews,t.preview):e.previews.filter(r=>r.previewId!==t.previewId);return{status:"applied",reason:"event",state:HS(e.scope,e.epoch,t.revision,n)}}function Oj(e){return Object.freeze({scope:e,syncStatus:"awaiting-snapshot",epoch:null,revision:-1,previews:Object.freeze([])})}function Lj(e,t){return t.kind==="snapshot"?vre(e,t):bre(e,t)}const Ix={authoritative:null,targets:[],capability:null,capabilityStatus:"idle",capabilityError:null,targetsStatus:"idle",targetsError:null,listLoaded:!1};function Ox(e,t,n){const r=t().authoritative;if(!r)return null;const i=Lj(r,n),s=n.kind==="snapshot"&&tn(r.scope,n.scope);return(i.state!==r||s&&!t().listLoaded)&&e({authoritative:i.state,...s?{listLoaded:!0}:{}}),i}const Dj=e=>{var t;return((t=e.authoritative)==null?void 0:t.previews)??[]},gr=$a()(Ha((e,t)=>({...Ix,activateScope:n=>e({...Ix,authoritative:Oj(n)}),replaceSnapshot:(n,r)=>Ox(e,t,{kind:"snapshot",scope:n,epoch:r.epoch,revision:r.revision,previews:r.previews}),applyPreviewState:(n,r,i,s)=>Ox(e,t,{kind:"state",scope:n,epoch:i,revision:s,preview:r}),applyPreviewRemoved:(n,r,i,s)=>Ox(e,t,{kind:"removed",scope:n,epoch:i,revision:s,previewId:r}),setCapabilityLoading:n=>{var i;const r=(i=t().authoritative)==null?void 0:i.scope;!r||!tn(r,n)||e({capabilityStatus:"loading",capabilityError:null})},setCapability:(n,r)=>{var s;const i=(s=t().authoritative)==null?void 0:s.scope;!i||!tn(i,n)||e({capability:r,capabilityStatus:"loaded",capabilityError:null})},setCapabilityError:(n,r)=>{var s;const i=(s=t().authoritative)==null?void 0:s.scope;!i||!tn(i,n)||e({capabilityStatus:"error",capabilityError:r})},setTargetsLoading:n=>{var i;const r=(i=t().authoritative)==null?void 0:i.scope;!r||!tn(r,n)||e({targetsStatus:"loading",targetsError:null})},setTargets:(n,r)=>{var s;const i=(s=t().authoritative)==null?void 0:s.scope;!i||!tn(i,n)||e({targets:r,targetsStatus:"loaded",targetsError:null})},setTargetsError:(n,r)=>{var s;const i=(s=t().authoritative)==null?void 0:s.scope;!i||!tn(i,n)||e({targetsStatus:"error",targetsError:r})},markListLoading:n=>{var i;const r=(i=t().authoritative)==null?void 0:i.scope;!r||!tn(r,n)||e({listLoaded:!1})},clear:()=>e({...Ix})}),{name:"device-preview-store"})),qo=$a()(Ha((e,t)=>({registry:KP(),begin:n=>{const r=dre(t().registry,n);return r.registry!==t().registry&&e({registry:r.registry}),r},finish:(n,r)=>{const i=fre(t().registry,n,r);i.registry!==t().registry&&e({registry:i.registry})},clearScope:n=>{const r=hre(t().registry,n);r!==t().registry&&e({registry:r})},clear:()=>e({registry:KP()})}),{name:"preview-operation-store"}));function _re(e,t,n,r,i){return t?e.registry.operations.some(s=>s.kind!=="create"&&s.previewKind===n&&s.previewId===r&&tn(s.scope,t)&&s.kind===i):!1}const Lx={authoritative:null,listLoaded:!1,capability:null,capabilityStatus:"idle",capabilityError:null};function Dx(e,t,n){const r=t().authoritative;if(!r)return null;const i=Lj(r,n),s=n.kind==="snapshot"&&tn(r.scope,n.scope);return(i.state!==r||s&&!t().listLoaded)&&e({authoritative:i.state,...s?{listLoaded:!0}:{}}),i}const GP=e=>{var t;return((t=e.authoritative)==null?void 0:t.previews)??[]},Kr=$a()(Ha((e,t)=>({...Lx,activateScope:n=>e({...Lx,authoritative:Oj(n)}),replaceSnapshot:(n,r)=>Dx(e,t,{kind:"snapshot",scope:n,epoch:r.epoch,revision:r.revision,previews:r.previews}),applyPreviewState:(n,r,i,s)=>Dx(e,t,{kind:"state",scope:n,epoch:i,revision:s,preview:r}),applyPreviewRemoved:(n,r,i,s)=>Dx(e,t,{kind:"removed",scope:n,epoch:i,revision:s,previewId:r}),setCapabilityLoading:n=>{var i;const r=(i=t().authoritative)==null?void 0:i.scope;!r||!tn(r,n)||e({capabilityStatus:"loading",capabilityError:null})},setCapability:(n,r)=>{var s;const i=(s=t().authoritative)==null?void 0:s.scope;!i||!tn(i,n)||e({capability:r,capabilityStatus:"loaded",capabilityError:null})},setCapabilityError:(n,r)=>{var s;const i=(s=t().authoritative)==null?void 0:s.scope;!i||!tn(i,n)||e({capabilityStatus:"error",capabilityError:r})},markListLoading:n=>{var i;const r=(i=t().authoritative)==null?void 0:i.scope;!r||!tn(r,n)||e({listLoaded:!1})},clear:()=>e({...Lx})}),{name:"preview-store"})),XP=100,ZP=5e3;class Bx extends Error{constructor(n){super("预览上下文已失效,请重新选择开发机");je(this,"scope");this.name="PreviewScopeInactiveError",this.scope=n}}class QP extends Error{constructor(n,r,i){super(n==="web"?"网页预览已创建,但暂时无法确认状态,请重试":"模拟器预览已创建,但暂时无法确认状态,请重试");je(this,"previewKind");je(this,"previewId");je(this,"confirmationCause");this.name="PreviewCreateConfirmationError",this.previewKind=n,this.previewId=r,this.confirmationCause=i}}class Kg extends Error{constructor(n,r,i,s="resource-busy"){super(s==="operation-id-conflict"?"operationId 已用于不同的预览操作":r==="create"?n==="web"?"已有网页预览正在创建":"已有模拟器预览正在创建":n==="web"?"该网页预览正在处理中":"该模拟器预览正在处理中");je(this,"previewKind");je(this,"operationKind");je(this,"previewId");je(this,"reason");this.name="PreviewOperationConflictError",this.previewKind=n,this.operationKind=r,this.previewId=i,this.reason=s}}function wre(e,t){t instanceof Error&&t.name==="AbortError"||console.error(`[preview-controller] ${e} failed`,t)}function zx(e){return e instanceof Error?e.message:String(e)}function Bj(e){return e===void 0?null:e.trim()}function xre(e,t,n){const r=e.kind==="local"?[e.kind,e.url]:[e.kind,e.path,e.entryPath];return JSON.stringify([r,t,Bj(n)])}function Sre(e,t){return JSON.stringify([e,Bj(t)])}function JP(e){return JSON.stringify([e.trim()])}function e2(e,t){return e.previewKind===t.previewKind&&e.kind===t.kind&&e.previewId===t.previewId&&e.fingerprint===t.fingerprint}class Ere{constructor(t={}){je(this,"createOperationId");je(this,"now");je(this,"reportBackgroundError");je(this,"active",null);je(this,"webSnapshotFlight",null);je(this,"deviceSnapshotFlight",null);je(this,"webSnapshotSequence",0);je(this,"deviceSnapshotSequence",0);je(this,"webResyncRequested",!1);je(this,"deviceResyncRequested",!1);je(this,"webResyncAfterSequence",null);je(this,"deviceResyncAfterSequence",null);je(this,"webResyncRetryKey",null);je(this,"deviceResyncRetryKey",null);je(this,"webResyncRetryTimer",null);je(this,"deviceResyncRetryTimer",null);je(this,"webResyncRetryAttempt",0);je(this,"deviceResyncRetryAttempt",0);je(this,"operationFlights",new Map);this.createOperationId=t.createOperationId??tb,this.now=t.now??Date.now,this.reportBackgroundError=t.reportBackgroundError??wre}activate(t,n){var s;const r=t.getPreviewScope();if(!r||!tn(r,n))throw new Bx(n);if(((s=this.active)==null?void 0:s.relay)===t&&tn(this.active.scope,n))return;this.releaseActiveBinding();const i=Tne(n.proxyId,n.bindingId);this.active={relay:t,scope:i,abortController:new AbortController},this.resetTransientState(),Kr.getState().activateScope(i),gr.getState().activateScope(i)}deactivate(t,n){const r=this.active;return!r||r.relay!==t||!tn(r.scope,n)?!1:(this.releaseActiveBinding(),Kr.getState().clear(),gr.getState().clear(),!0)}dispose(){this.active&&this.releaseActiveBinding(),this.resetTransientState(),this.operationFlights.clear(),qo.getState().clear(),Kr.getState().clear(),gr.getState().clear()}getActiveScope(){return this.active&&this.isCurrent(this.active)?this.active.scope:null}isActive(t,n){const r=this.active;return r!==null&&r.relay===t&&tn(r.scope,n)&&this.isCurrent(r)}syncWebSnapshot(t){return this.startWebSnapshot(this.requireActive(t))}syncDeviceSnapshot(t){return this.startDeviceSnapshot(this.requireActive(t))}applyWebPreviewState(t,n,r,i,s){const o=this.currentForMessage(t,n);if(!o)return null;const u=Kr.getState().applyPreviewState(o.scope,r,i,s);return this.afterWebEvent(o,u),u}applyWebPreviewRemoved(t,n,r,i,s){const o=this.currentForMessage(t,n);if(!o)return null;const u=Kr.getState().applyPreviewRemoved(o.scope,r,i,s);return this.afterWebEvent(o,u),u}applyDevicePreviewState(t,n,r,i,s){const o=this.currentForMessage(t,n);if(!o)return null;const u=gr.getState().applyPreviewState(o.scope,r,i,s);return this.afterDeviceEvent(o,u),u}applyDevicePreviewRemoved(t,n,r,i,s){const o=this.currentForMessage(t,n);if(!o)return null;const u=gr.getState().applyPreviewRemoved(o.scope,r,i,s);return this.afterDeviceEvent(o,u),u}handleMessage(t,n){switch(n.type){case"preview_state_push":return this.applyWebPreviewState(t,n.scope,n.preview,n.epoch,n.revision)!==null;case"preview_removed_push":return this.applyWebPreviewRemoved(t,n.scope,n.previewId,n.epoch,n.revision)!==null;case"device_preview_state_push":return this.applyDevicePreviewState(t,n.scope,n.preview,n.epoch,n.revision)!==null;case"device_preview_removed_push":return this.applyDevicePreviewRemoved(t,n.scope,n.previewId,n.epoch,n.revision)!==null;default:return!1}}async inspectStaticWebPreview(t,n,r={}){const i=this.requireActive(t),s=this.querySignal(i,r.signal),o=await i.relay.inspectStaticWebPreview(i.scope,n,{timeoutMs:r.timeoutMs,signal:s});return s.throwIfAborted(),this.isCurrent(i)?o:null}async requestWebPreviewCapability(t,n=!1,r={}){var o;const i=this.requireActive(t),s=this.querySignal(i,r.signal);Kr.getState().setCapabilityLoading(i.scope);try{const l=await i.relay.requestWebPreviewCapability(i.scope,n,{timeoutMs:r.timeoutMs,signal:s});return s.throwIfAborted(),this.isCurrent(i)?(l.success?Kr.getState().setCapability(i.scope,l.capability):Kr.getState().setCapabilityError(i.scope,l.error),l):null}catch(l){throw this.isCurrent(i)&&!((o=r.signal)!=null&&o.aborted)&&Kr.getState().setCapabilityError(i.scope,zx(l)),l}}async requestDevicePreviewCapability(t,n=!1,r={}){var o;const i=this.requireActive(t),s=this.querySignal(i,r.signal);gr.getState().setCapabilityLoading(i.scope);try{const l=await i.relay.requestDevicePreviewCapability(i.scope,n,{timeoutMs:r.timeoutMs,signal:s});return s.throwIfAborted(),this.isCurrent(i)?(l.success?gr.getState().setCapability(i.scope,l.capability):gr.getState().setCapabilityError(i.scope,l.error),l):null}catch(l){throw this.isCurrent(i)&&!((o=r.signal)!=null&&o.aborted)&&gr.getState().setCapabilityError(i.scope,zx(l)),l}}async requestDevicePreviewTargets(t,n=!1,r={}){var o;const i=this.requireActive(t),s=this.querySignal(i,r.signal);gr.getState().setTargetsLoading(i.scope);try{const l=await i.relay.requestDevicePreviewTargets(i.scope,n,{timeoutMs:r.timeoutMs,signal:s});return s.throwIfAborted(),this.isCurrent(i)?(l.success?gr.getState().setTargets(i.scope,l.targets):gr.getState().setTargetsError(i.scope,l.error),l):null}catch(l){throw this.isCurrent(i)&&!((o=r.signal)!=null&&o.aborted)&&gr.getState().setTargetsError(i.scope,zx(l)),l}}async requestDevicePreviewStream(t,n,r,i={}){const s=this.requireActive(t),o=this.querySignal(s,i.signal),l=await s.relay.requestDevicePreviewStream(s.scope,n,r,{timeoutMs:i.timeoutMs,signal:o});return o.throwIfAborted(),this.isCurrent(s)?Object.freeze({...l,scope:s.scope,signal:o}):null}async sendDevicePreviewInput(t,n,r={}){const i=this.requireActive(t.scope),s=r.signal?AbortSignal.any([t.signal,r.signal]):t.signal,o=this.querySignal(i,s);o.throwIfAborted();const l=await i.relay.sendDevicePreviewInput(i.scope,t.leaseId,n,{timeoutMs:r.timeoutMs,signal:o});return o.throwIfAborted(),this.isCurrent(i)?l:null}async claimDevicePreviewControl(t,n={}){const r=this.requireActive(t.scope),i=n.signal?AbortSignal.any([t.signal,n.signal]):t.signal,s=this.querySignal(r,i);s.throwIfAborted();const o=await r.relay.claimDevicePreviewControl(r.scope,t.leaseId,{timeoutMs:n.timeoutMs,signal:s});return s.throwIfAborted(),this.isCurrent(r)?o:null}createWebPreview(t,n,r){const i=r.operationId??this.createOperationId("web-preview-create");return this.runCreateOperation(t,"web",i,xre(n,r.tunnelProvider,r.name),r.timeoutMs,s=>s.relay.createWebPreview(s.scope,n,{tunnelProvider:r.tunnelProvider,name:r.name,operationId:i,timeoutMs:r.timeoutMs,signal:s.abortController.signal}))}renameWebPreview(t,n,r,i={}){const s=i.operationId??this.createOperationId("web-preview-rename");return this.runMutationOperation(t,"web","rename",n,s,JP(r),o=>o.relay.renameWebPreview(o.scope,n,r,{operationId:s,timeoutMs:i.timeoutMs,signal:o.abortController.signal}))}reconnectWebPreview(t,n,r={}){const i=r.operationId??this.createOperationId("web-preview-reconnect");return this.runMutationOperation(t,"web","reconnect",n,i,"[]",s=>s.relay.reconnectWebPreview(s.scope,n,{operationId:i,timeoutMs:r.timeoutMs,signal:s.abortController.signal}))}closeWebPreview(t,n,r={}){const i=r.operationId??this.createOperationId("web-preview-close");return this.runMutationOperation(t,"web","close",n,i,"[]",s=>s.relay.closeWebPreview(s.scope,n,{operationId:i,timeoutMs:r.timeoutMs,signal:s.abortController.signal}))}createDevicePreview(t,n,r={}){const i=r.operationId??this.createOperationId("device-preview-create");return this.runCreateOperation(t,"device",i,Sre(n,r.name),r.timeoutMs,s=>s.relay.createDevicePreview(s.scope,n,{name:r.name,operationId:i,timeoutMs:r.timeoutMs,signal:s.abortController.signal}))}renameDevicePreview(t,n,r,i={}){const s=i.operationId??this.createOperationId("device-preview-rename");return this.runMutationOperation(t,"device","rename",n,s,JP(r),o=>o.relay.renameDevicePreview(o.scope,n,r,{operationId:s,timeoutMs:i.timeoutMs,signal:o.abortController.signal}))}reconnectDevicePreview(t,n,r={}){const i=r.operationId??this.createOperationId("device-preview-reconnect");return this.runMutationOperation(t,"device","reconnect",n,i,"[]",s=>s.relay.reconnectDevicePreview(s.scope,n,{operationId:i,timeoutMs:r.timeoutMs,signal:s.abortController.signal}))}closeDevicePreview(t,n,r={}){const i=r.operationId??this.createOperationId("device-preview-close");return this.runMutationOperation(t,"device","close",n,i,"[]",s=>s.relay.closeDevicePreview(s.scope,n,{operationId:i,timeoutMs:r.timeoutMs,signal:s.abortController.signal}))}requireActive(t){const n=this.active;if(!n||!tn(n.scope,t)||!this.isCurrent(n))throw new Bx(t);return n}querySignal(t,n){return n?AbortSignal.any([t.abortController.signal,n]):t.abortController.signal}currentForMessage(t,n){const r=this.active;return r&&r.relay===t&&tn(r.scope,n)&&this.isCurrent(r)?r:null}isCurrent(t){if(this.active!==t||t.abortController.signal.aborted)return!1;const n=t.relay.getPreviewScope();return n!==null&&tn(n,t.scope)}releaseActiveBinding(){const t=this.active;t&&(this.active=null,t.abortController.abort(),qo.getState().clearScope(t.scope),this.resetTransientState())}resetTransientState(){this.webResyncRetryTimer!==null&&clearTimeout(this.webResyncRetryTimer),this.deviceResyncRetryTimer!==null&&clearTimeout(this.deviceResyncRetryTimer),this.webSnapshotFlight=null,this.deviceSnapshotFlight=null,this.webResyncRequested=!1,this.deviceResyncRequested=!1,this.webResyncAfterSequence=null,this.deviceResyncAfterSequence=null,this.webResyncRetryKey=null,this.deviceResyncRetryKey=null,this.webResyncRetryTimer=null,this.deviceResyncRetryTimer=null,this.webResyncRetryAttempt=0,this.deviceResyncRetryAttempt=0}startWebSnapshot(t,n){const r=this.webSnapshotFlight;if((r==null?void 0:r.activation)===t)return r.promise;Kr.getState().markListLoading(t.scope);const i=++this.webSnapshotSequence,s=t.relay.requestWebPreviewList(t.scope,{signal:t.abortController.signal,timeoutMs:n}).then(l=>{if(t.abortController.signal.throwIfAborted(),!this.isCurrent(t))return null;const u=Kr.getState(),d=u.authoritative;return this.webResyncAfterSequence!==null&&i<=this.webResyncAfterSequence&&(d==null?void 0:d.syncStatus)==="needs-resync"&&tn(d.scope,t.scope)?{status:"needs-resync",reason:"resync-pending",state:d}:u.replaceSnapshot(t.scope,l)}),o={activation:t,sequence:i,promise:s};return this.webSnapshotFlight=o,s.then(()=>this.finishWebSnapshot(o),()=>this.finishWebSnapshot(o)),s}finishWebSnapshot(t){this.webSnapshotFlight===t&&(this.webSnapshotFlight=null,this.webResyncRequested&&this.drainWebResync(t.activation))}startDeviceSnapshot(t,n){const r=this.deviceSnapshotFlight;if((r==null?void 0:r.activation)===t)return r.promise;gr.getState().markListLoading(t.scope);const i=++this.deviceSnapshotSequence,s=t.relay.requestDevicePreviewList(t.scope,{signal:t.abortController.signal,timeoutMs:n}).then(l=>{if(t.abortController.signal.throwIfAborted(),!this.isCurrent(t))return null;const u=gr.getState(),d=u.authoritative;return this.deviceResyncAfterSequence!==null&&i<=this.deviceResyncAfterSequence&&(d==null?void 0:d.syncStatus)==="needs-resync"&&tn(d.scope,t.scope)?{status:"needs-resync",reason:"resync-pending",state:d}:u.replaceSnapshot(t.scope,l)}),o={activation:t,sequence:i,promise:s};return this.deviceSnapshotFlight=o,s.then(()=>this.finishDeviceSnapshot(o),()=>this.finishDeviceSnapshot(o)),s}finishDeviceSnapshot(t){this.deviceSnapshotFlight===t&&(this.deviceSnapshotFlight=null,this.deviceResyncRequested&&this.drainDeviceResync(t.activation))}afterWebEvent(t,n){(n==null?void 0:n.status)==="needs-resync"&&this.requestWebResync(t)}afterDeviceEvent(t,n){(n==null?void 0:n.status)==="needs-resync"&&this.requestDeviceResync(t)}requestWebResync(t){this.isCurrent(t)&&(this.webResyncRetryTimer!==null&&(clearTimeout(this.webResyncRetryTimer),this.webResyncRetryTimer=null),this.webResyncRequested=!0,this.webResyncAfterSequence=Math.max(this.webResyncAfterSequence??-1,this.webSnapshotSequence),queueMicrotask(()=>this.drainWebResync(t)))}drainWebResync(t){var o;if(!this.isCurrent(t)||!this.webResyncRequested||this.webSnapshotFlight)return;const n=this.webResyncAfterSequence,r=n!==null&&this.webSnapshotSequence<=n;if(((o=Kr.getState().authoritative)==null?void 0:o.syncStatus)!=="needs-resync"&&!r){this.webResyncRequested=!1,this.webResyncAfterSequence=null,this.webResyncRetryKey=null,this.webResyncRetryAttempt=0;return}this.webResyncRequested=!1;const i=this.startWebSnapshot(t),s=this.webSnapshotSequence;i.then(l=>{if(!this.isCurrent(t))return;if((l==null?void 0:l.status)!=="needs-resync"){this.webResyncAfterSequence!==null&&this.webResyncAfterSequence<s&&(this.webResyncAfterSequence=null),this.webResyncRetryKey=null,this.webResyncRetryAttempt=0;return}const u=l.state.resyncCause,d=`${u.observedEpoch}\0${u.observedRevision}`,f=this.webResyncRetryKey===d;this.webResyncRetryKey=d,this.webResyncAfterSequence=Math.max(this.webResyncAfterSequence??-1,s),!this.webSnapshotFlight&&(f?this.scheduleWebResyncRetry(t):this.requestWebResync(t))},l=>{this.isCurrent(t)&&(this.webResyncAfterSequence=Math.max(this.webResyncAfterSequence??-1,s),this.reportBackgroundError("web-resync",l),this.scheduleWebResyncRetry(t))})}scheduleWebResyncRetry(t){if(!this.isCurrent(t)||this.webResyncRetryTimer!==null)return;const n=Math.min(XP*2**this.webResyncRetryAttempt,ZP);this.webResyncRetryAttempt+=1,this.webResyncRetryTimer=setTimeout(()=>{this.webResyncRetryTimer=null,this.requestWebResync(t)},n)}requestDeviceResync(t){this.isCurrent(t)&&(this.deviceResyncRetryTimer!==null&&(clearTimeout(this.deviceResyncRetryTimer),this.deviceResyncRetryTimer=null),this.deviceResyncRequested=!0,this.deviceResyncAfterSequence=Math.max(this.deviceResyncAfterSequence??-1,this.deviceSnapshotSequence),queueMicrotask(()=>this.drainDeviceResync(t)))}drainDeviceResync(t){var o;if(!this.isCurrent(t)||!this.deviceResyncRequested||this.deviceSnapshotFlight)return;const n=this.deviceResyncAfterSequence,r=n!==null&&this.deviceSnapshotSequence<=n;if(((o=gr.getState().authoritative)==null?void 0:o.syncStatus)!=="needs-resync"&&!r){this.deviceResyncRequested=!1,this.deviceResyncAfterSequence=null,this.deviceResyncRetryKey=null,this.deviceResyncRetryAttempt=0;return}this.deviceResyncRequested=!1;const i=this.startDeviceSnapshot(t),s=this.deviceSnapshotSequence;i.then(l=>{if(!this.isCurrent(t))return;if((l==null?void 0:l.status)!=="needs-resync"){this.deviceResyncAfterSequence!==null&&this.deviceResyncAfterSequence<s&&(this.deviceResyncAfterSequence=null),this.deviceResyncRetryKey=null,this.deviceResyncRetryAttempt=0;return}const u=l.state.resyncCause,d=`${u.observedEpoch}\0${u.observedRevision}`,f=this.deviceResyncRetryKey===d;this.deviceResyncRetryKey=d,this.deviceResyncAfterSequence=Math.max(this.deviceResyncAfterSequence??-1,s),!this.deviceSnapshotFlight&&(f?this.scheduleDeviceResyncRetry(t):this.requestDeviceResync(t))},l=>{this.isCurrent(t)&&(this.deviceResyncAfterSequence=Math.max(this.deviceResyncAfterSequence??-1,s),this.reportBackgroundError("device-resync",l),this.scheduleDeviceResyncRetry(t))})}scheduleDeviceResyncRetry(t){if(!this.isCurrent(t)||this.deviceResyncRetryTimer!==null)return;const n=Math.min(XP*2**this.deviceResyncRetryAttempt,ZP);this.deviceResyncRetryAttempt+=1,this.deviceResyncRetryTimer=setTimeout(()=>{this.deviceResyncRetryTimer=null,this.requestDeviceResync(t)},n)}operationKey(t,n){return`${t.proxyId}\0${t.bindingId}\0${n}`}runCreateOperation(t,n,r,i,s,o){return this.trackOperation(t,n,"create",void 0,r,i,l=>this.executeCreateOperation(l,n,r,s,o))}runMutationOperation(t,n,r,i,s,o,l){return this.trackOperation(t,n,r,i,s,o,u=>this.executeMutationOperation(u,n,s,l))}trackOperation(t,n,r,i,s,o,l){let u;try{u=this.requireActive(t)}catch(T){return Promise.reject(T)}const d={kind:r,previewKind:n,operationId:s,fingerprint:o,scope:u.scope,...r==="create"?{}:{previewId:i},startedAt:this.now()},f={previewKind:n,kind:r,...i===void 0?{}:{previewId:i},fingerprint:o},p=this.operationKey(u.scope,s),y=this.operationFlights.get(p);if(y)return e2(y,f)?y.promise:Promise.reject(new Kg(n,r,i,"operation-id-conflict"));const g=qo.getState(),_=Mj(g.registry,u.scope,s);if(_)return Promise.reject(new Kg(n,r,i,e2(_,f)?"resource-busy":"operation-id-conflict"));if(r==="create"?ure(g.registry,u.scope,n).some(T=>T.kind==="create"):Pj(g.registry,u.scope,n,i).length>0)return Promise.reject(new Kg(n,r,i));const x=g.begin(d);if(x.status!=="applied")return Promise.reject(new Kg(n,r,i,x.status==="conflict"?"operation-id-conflict":"resource-busy"));const k=l(u).finally(()=>this.operationFlights.delete(p));return this.operationFlights.set(p,{...f,promise:k}),k}async executeMutationOperation(t,n,r,i){let s;try{s=await i(t),t.abortController.signal.throwIfAborted()}catch(o){throw qo.getState().finish(t.scope,r),this.reconcileAfterOperation(t,n),o}return qo.getState().finish(t.scope,r),this.reconcileAfterOperation(t,n),s}async executeCreateOperation(t,n,r,i,s){let o;try{o=await s(t),this.assertCurrentBinding(t)}catch(l){throw qo.getState().finish(t.scope,r),this.reconcileAfterOperation(t,n,i),l}if(!o.accepted)return qo.getState().finish(t.scope,r),o;try{return await this.confirmCreatedPreview(t,n,o.previewId,i),o}catch(l){throw this.reconcileAfterOperation(t,n,i),l}finally{qo.getState().finish(t.scope,r)}}async confirmCreatedPreview(t,n,r,i){if(this.assertCurrentBinding(t),this.hasAuthoritativePreview(t,n,r))return;let s;try{s=n==="web"?await this.ensureWebSnapshotAfterCurrentFlight(t,i):await this.ensureDeviceSnapshotAfterCurrentFlight(t,i)}catch(o){throw this.assertCurrentBinding(t),new QP(n,r,o)}if(this.assertCurrentBinding(t),!this.hasAuthoritativePreview(t,n,r))throw(s==null?void 0:s.status)==="needs-resync"&&(n==="web"?this.requestWebResync(t):this.requestDeviceResync(t)),new QP(n,r)}assertCurrentBinding(t){if(t.abortController.signal.throwIfAborted(),!this.isCurrent(t))throw new Bx(t.scope)}hasAuthoritativePreview(t,n,r){const i=n==="web"?Kr.getState().authoritative:gr.getState().authoritative;return i!==null&&tn(i.scope,t.scope)&&i.previews.some(s=>s.previewId===r)}async reconcileAfterOperation(t,n,r){if(this.isCurrent(t))try{const i=n==="web"?await this.ensureWebSnapshotAfterCurrentFlight(t,r):await this.ensureDeviceSnapshotAfterCurrentFlight(t,r);(i==null?void 0:i.status)==="needs-resync"&&(n==="web"?this.requestWebResync(t):this.requestDeviceResync(t))}catch(i){this.reportBackgroundError(n==="web"?"web-reconciliation":"device-reconciliation",i)}}async ensureWebSnapshotAfterCurrentFlight(t,n){const r=this.webSnapshotSequence+1;for(;this.isCurrent(t);){const i=this.webSnapshotFlight;if(!i)return this.startWebSnapshot(t,n);if(i.sequence>=r)return i.promise;try{await i.promise}catch{}}return null}async ensureDeviceSnapshotAfterCurrentFlight(t,n){const r=this.deviceSnapshotSequence+1;for(;this.isCurrent(t);){const i=this.deviceSnapshotFlight;if(!i)return this.startDeviceSnapshot(t,n);if(i.sequence>=r)return i.promise;try{await i.promise}catch{}}return null}}const Tt=new Ere;async function MC(e,t){const n=Ie.getState().selectedProxyId;if(!n)return{status:"skipped"};const r=Gt.getState().beginHistoryLoad();try{const i=t===void 0?await e.requestSessionHistory():await e.requestSessionHistory(t);return Ie.getState().selectedProxyId!==n?(Gt.getState().cancelHistoryLoad(r),{status:"stale"}):Gt.getState().resolveHistoryLoad(r,i)?{status:"loaded",sessions:i}:{status:"stale"}}catch(i){return Ie.getState().selectedProxyId!==n?(Gt.getState().cancelHistoryLoad(r),{status:"stale"}):Gt.getState().rejectHistoryLoad(r)?{status:"failed",error:i}:{status:"stale"}}}function t2(e){return typeof e=="string"?e:""}function yy(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function WS(e){switch(e){case"add":return"新增";case"delete":return"删除";case"update":return"更新";default:return"变更"}}function jx(e,t){const n=yy(t);return n?{title:e,content:n}:null}function Cre(e,t){return e?t?`${e}
526
526
  ${t}`:e:t}function Fx(e,t,n){const r=yy(t),i=yy(n);return!r&&!i?null:{kind:"diff",title:e,content:Cre(r,i),oldContent:r,newContent:i}}function kre(e){const t=e.replace(/\r\n?/gu,`
527
527
  `).split(`
528
528
  `);t.at(-1)===""&&t.pop();const n=[],r=[];let i=!1,s=!1;for(const o of t){if(o.startsWith("@@")){i=!0;continue}if(!i||o.startsWith("\\ No newline"))continue;const l=o[0],u=o.slice(1);l===" "?(n.push(u),r.push(u),s=!0):l==="-"?(n.push(u),s=!0):l==="+"&&(r.push(u),s=!0)}return s?{oldContent:n.join(`
@@ -577,7 +577,7 @@ ${s}`,l=zj(`${WS(r.kind)}:${r.path}`,o,r.kind);n.push(l.kind==="diff"?{...l,co
577
577
 
578
578
  If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
579
579
 
580
- For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return b.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},Coe="DialogDescriptionWarning",koe=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${C5(Coe).contentName}}.`;return b.useEffect(()=>{var s;const i=(s=e.current)==null?void 0:s.getAttribute("aria-describedby");t&&i&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},UC=d5,Toe=h5,WC=m5,qC=g5,VC=v5,k5=b5,T5=w5,db=S5;function Roe(e){const t=b.useRef({value:e,previous:e});return b.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}function Aoe(e){const[t,n]=b.useState(void 0);return Vi(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const s=i[0];let o,l;if("borderBoxSize"in s){const u=s.borderBoxSize,d=Array.isArray(u)?u[0]:u;o=d.inlineSize,l=d.blockSize}else o=e.offsetWidth,l=e.offsetHeight;n({width:o,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const Noe=["top","right","bottom","left"],Yl=Math.min,Ds=Math.max,wy=Math.round,tv=Math.floor,Jo=e=>({x:e,y:e}),Moe={left:"right",right:"left",bottom:"top",top:"bottom"};function ZS(e,t,n){return Ds(e,Yl(t,n))}function ja(e,t){return typeof e=="function"?e(t):e}function Fa(e){return e.split("-")[0]}function af(e){return e.split("-")[1]}function YC(e){return e==="x"?"y":"x"}function KC(e){return e==="y"?"height":"width"}function Zo(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function GC(e){return YC(Zo(e))}function Poe(e,t,n){n===void 0&&(n=!1);const r=af(e),i=GC(e),s=KC(i);let o=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(o=xy(o)),[o,xy(o)]}function Ioe(e){const t=xy(e);return[QS(e),t,QS(t)]}function QS(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const T2=["left","right"],R2=["right","left"],Ooe=["top","bottom"],Loe=["bottom","top"];function Doe(e,t,n){switch(e){case"top":case"bottom":return n?t?R2:T2:t?T2:R2;case"left":case"right":return t?Ooe:Loe;default:return[]}}function Boe(e,t,n,r){const i=af(e);let s=Doe(Fa(e),n==="start",r);return i&&(s=s.map(o=>o+"-"+i),t&&(s=s.concat(s.map(QS)))),s}function xy(e){const t=Fa(e);return Moe[t]+e.slice(t.length)}function zoe(e){return{top:0,right:0,bottom:0,left:0,...e}}function R5(e){return typeof e!="number"?zoe(e):{top:e,right:e,bottom:e,left:e}}function Sy(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function A2(e,t,n){let{reference:r,floating:i}=e;const s=Zo(t),o=GC(t),l=KC(o),u=Fa(t),d=s==="y",f=r.x+r.width/2-i.width/2,p=r.y+r.height/2-i.height/2,y=r[l]/2-i[l]/2;let g;switch(u){case"top":g={x:f,y:r.y-i.height};break;case"bottom":g={x:f,y:r.y+r.height};break;case"right":g={x:r.x+r.width,y:p};break;case"left":g={x:r.x-i.width,y:p};break;default:g={x:r.x,y:r.y}}switch(af(t)){case"start":g[o]-=y*(n&&d?-1:1);break;case"end":g[o]+=y*(n&&d?-1:1);break}return g}async function joe(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:s,rects:o,elements:l,strategy:u}=e,{boundary:d="clippingAncestors",rootBoundary:f="viewport",elementContext:p="floating",altBoundary:y=!1,padding:g=0}=ja(t,e),_=R5(g),x=l[y?p==="floating"?"reference":"floating":p],S=Sy(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(x)))==null||n?x:x.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(l.floating)),boundary:d,rootBoundary:f,strategy:u})),k=p==="floating"?{x:r,y:i,width:o.floating.width,height:o.floating.height}:o.reference,T=await(s.getOffsetParent==null?void 0:s.getOffsetParent(l.floating)),N=await(s.isElement==null?void 0:s.isElement(T))?await(s.getScale==null?void 0:s.getScale(T))||{x:1,y:1}:{x:1,y:1},P=Sy(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:k,offsetParent:T,strategy:u}):k);return{top:(S.top-P.top+_.top)/N.y,bottom:(P.bottom-S.bottom+_.bottom)/N.y,left:(S.left-P.left+_.left)/N.x,right:(P.right-S.right+_.right)/N.x}}const Foe=50,$oe=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:s=[],platform:o}=n,l=o.detectOverflow?o:{...o,detectOverflow:joe},u=await(o.isRTL==null?void 0:o.isRTL(t));let d=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:f,y:p}=A2(d,r,u),y=r,g=0;const _={};for(let w=0;w<s.length;w++){const x=s[w];if(!x)continue;const{name:S,fn:k}=x,{x:T,y:N,data:P,reset:R}=await k({x:f,y:p,initialPlacement:r,placement:y,strategy:i,middlewareData:_,rects:d,platform:l,elements:{reference:e,floating:t}});f=T??f,p=N??p,_[S]={..._[S],...P},R&&g<Foe&&(g++,typeof R=="object"&&(R.placement&&(y=R.placement),R.rects&&(d=R.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:i}):R.rects),{x:f,y:p}=A2(d,y,u)),w=-1)}return{x:f,y:p,placement:y,strategy:i,middlewareData:_}},Hoe=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:s,platform:o,elements:l,middlewareData:u}=t,{element:d,padding:f=0}=ja(e,t)||{};if(d==null)return{};const p=R5(f),y={x:n,y:r},g=GC(i),_=KC(g),w=await o.getDimensions(d),x=g==="y",S=x?"top":"left",k=x?"bottom":"right",T=x?"clientHeight":"clientWidth",N=s.reference[_]+s.reference[g]-y[g]-s.floating[_],P=y[g]-s.reference[g],R=await(o.getOffsetParent==null?void 0:o.getOffsetParent(d));let M=R?R[T]:0;(!M||!await(o.isElement==null?void 0:o.isElement(R)))&&(M=l.floating[T]||s.floating[_]);const L=N/2-P/2,X=M/2-w[_]/2-1,U=Yl(p[S],X),V=Yl(p[k],X),j=U,A=M-w[_]-V,D=M/2-w[_]/2+L,O=ZS(j,D,A),I=!u.arrow&&af(i)!=null&&D!==O&&s.reference[_]/2-(D<j?U:V)-w[_]/2<0,B=I?D<j?D-j:D-A:0;return{[g]:y[g]+B,data:{[g]:O,centerOffset:D-O-B,...I&&{alignmentOffset:B}},reset:I}}}),Uoe=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:s,rects:o,initialPlacement:l,platform:u,elements:d}=t,{mainAxis:f=!0,crossAxis:p=!0,fallbackPlacements:y,fallbackStrategy:g="bestFit",fallbackAxisSideDirection:_="none",flipAlignment:w=!0,...x}=ja(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const S=Fa(i),k=Zo(l),T=Fa(l)===l,N=await(u.isRTL==null?void 0:u.isRTL(d.floating)),P=y||(T||!w?[xy(l)]:Ioe(l)),R=_!=="none";!y&&R&&P.push(...Boe(l,w,_,N));const M=[l,...P],L=await u.detectOverflow(t,x),X=[];let U=((r=s.flip)==null?void 0:r.overflows)||[];if(f&&X.push(L[S]),p){const D=Poe(i,o,N);X.push(L[D[0]],L[D[1]])}if(U=[...U,{placement:i,overflows:X}],!X.every(D=>D<=0)){var V,j;const D=(((V=s.flip)==null?void 0:V.index)||0)+1,O=M[D];if(O&&(!(p==="alignment"?k!==Zo(O):!1)||U.every(F=>Zo(F.placement)===k?F.overflows[0]>0:!0)))return{data:{index:D,overflows:U},reset:{placement:O}};let I=(j=U.filter(B=>B.overflows[0]<=0).sort((B,F)=>B.overflows[1]-F.overflows[1])[0])==null?void 0:j.placement;if(!I)switch(g){case"bestFit":{var A;const B=(A=U.filter(F=>{if(R){const Y=Zo(F.placement);return Y===k||Y==="y"}return!0}).map(F=>[F.placement,F.overflows.filter(Y=>Y>0).reduce((Y,z)=>Y+z,0)]).sort((F,Y)=>F[1]-Y[1])[0])==null?void 0:A[0];B&&(I=B);break}case"initialPlacement":I=l;break}if(i!==I)return{reset:{placement:I}}}return{}}}};function N2(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function M2(e){return Noe.some(t=>e[t]>=0)}const Woe=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...s}=ja(e,t);switch(i){case"referenceHidden":{const o=await r.detectOverflow(t,{...s,elementContext:"reference"}),l=N2(o,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:M2(l)}}}case"escaped":{const o=await r.detectOverflow(t,{...s,altBoundary:!0}),l=N2(o,n.floating);return{data:{escapedOffsets:l,escaped:M2(l)}}}default:return{}}}}},A5=new Set(["left","top"]);async function qoe(e,t){const{placement:n,platform:r,elements:i}=e,s=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=Fa(n),l=af(n),u=Zo(n)==="y",d=A5.has(o)?-1:1,f=s&&u?-1:1,p=ja(t,e);let{mainAxis:y,crossAxis:g,alignmentAxis:_}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return l&&typeof _=="number"&&(g=l==="end"?_*-1:_),u?{x:g*f,y:y*d}:{x:y*d,y:g*f}}const Voe=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:s,placement:o,middlewareData:l}=t,u=await qoe(t,e);return o===((n=l.offset)==null?void 0:n.placement)&&(r=l.arrow)!=null&&r.alignmentOffset?{}:{x:i+u.x,y:s+u.y,data:{...u,placement:o}}}}},Yoe=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:s}=t,{mainAxis:o=!0,crossAxis:l=!1,limiter:u={fn:S=>{let{x:k,y:T}=S;return{x:k,y:T}}},...d}=ja(e,t),f={x:n,y:r},p=await s.detectOverflow(t,d),y=Zo(Fa(i)),g=YC(y);let _=f[g],w=f[y];if(o){const S=g==="y"?"top":"left",k=g==="y"?"bottom":"right",T=_+p[S],N=_-p[k];_=ZS(T,_,N)}if(l){const S=y==="y"?"top":"left",k=y==="y"?"bottom":"right",T=w+p[S],N=w-p[k];w=ZS(T,w,N)}const x=u.fn({...t,[g]:_,[y]:w});return{...x,data:{x:x.x-n,y:x.y-r,enabled:{[g]:o,[y]:l}}}}}},Koe=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:i,rects:s,middlewareData:o}=t,{offset:l=0,mainAxis:u=!0,crossAxis:d=!0}=ja(e,t),f={x:n,y:r},p=Zo(i),y=YC(p);let g=f[y],_=f[p];const w=ja(l,t),x=typeof w=="number"?{mainAxis:w,crossAxis:0}:{mainAxis:0,crossAxis:0,...w};if(u){const T=y==="y"?"height":"width",N=s.reference[y]-s.floating[T]+x.mainAxis,P=s.reference[y]+s.reference[T]-x.mainAxis;g<N?g=N:g>P&&(g=P)}if(d){var S,k;const T=y==="y"?"width":"height",N=A5.has(Fa(i)),P=s.reference[p]-s.floating[T]+(N&&((S=o.offset)==null?void 0:S[p])||0)+(N?0:x.crossAxis),R=s.reference[p]+s.reference[T]+(N?0:((k=o.offset)==null?void 0:k[p])||0)-(N?x.crossAxis:0);_<P?_=P:_>R&&(_=R)}return{[y]:g,[p]:_}}}},Goe=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:i,rects:s,platform:o,elements:l}=t,{apply:u=()=>{},...d}=ja(e,t),f=await o.detectOverflow(t,d),p=Fa(i),y=af(i),g=Zo(i)==="y",{width:_,height:w}=s.floating;let x,S;p==="top"||p==="bottom"?(x=p,S=y===(await(o.isRTL==null?void 0:o.isRTL(l.floating))?"start":"end")?"left":"right"):(S=p,x=y==="end"?"top":"bottom");const k=w-f.top-f.bottom,T=_-f.left-f.right,N=Yl(w-f[x],k),P=Yl(_-f[S],T),R=!t.middlewareData.shift;let M=N,L=P;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(L=T),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(M=k),R&&!y){const U=Ds(f.left,0),V=Ds(f.right,0),j=Ds(f.top,0),A=Ds(f.bottom,0);g?L=_-2*(U!==0||V!==0?U+V:Ds(f.left,f.right)):M=w-2*(j!==0||A!==0?j+A:Ds(f.top,f.bottom))}await u({...t,availableWidth:L,availableHeight:M});const X=await o.getDimensions(l.floating);return _!==X.width||w!==X.height?{reset:{rects:!0}}:{}}}};function fb(){return typeof window<"u"}function lf(e){return N5(e)?(e.nodeName||"").toLowerCase():"#document"}function zs(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function oa(e){var t;return(t=(N5(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function N5(e){return fb()?e instanceof Node||e instanceof zs(e).Node:!1}function ko(e){return fb()?e instanceof Element||e instanceof zs(e).Element:!1}function Wa(e){return fb()?e instanceof HTMLElement||e instanceof zs(e).HTMLElement:!1}function P2(e){return!fb()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof zs(e).ShadowRoot}function im(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=To(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function Xoe(e){return/^(table|td|th)$/.test(lf(e))}function hb(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const Zoe=/transform|translate|scale|rotate|perspective|filter/,Qoe=/paint|layout|strict|content/,Rc=e=>!!e&&e!=="none";let Zx;function XC(e){const t=ko(e)?To(e):e;return Rc(t.transform)||Rc(t.translate)||Rc(t.scale)||Rc(t.rotate)||Rc(t.perspective)||!ZC()&&(Rc(t.backdropFilter)||Rc(t.filter))||Zoe.test(t.willChange||"")||Qoe.test(t.contain||"")}function Joe(e){let t=Kl(e);for(;Wa(t)&&!Kd(t);){if(XC(t))return t;if(hb(t))return null;t=Kl(t)}return null}function ZC(){return Zx==null&&(Zx=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Zx}function Kd(e){return/^(html|body|#document)$/.test(lf(e))}function To(e){return zs(e).getComputedStyle(e)}function pb(e){return ko(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Kl(e){if(lf(e)==="html")return e;const t=e.assignedSlot||e.parentNode||P2(e)&&e.host||oa(e);return P2(t)?t.host:t}function M5(e){const t=Kl(e);return Kd(t)?e.ownerDocument?e.ownerDocument.body:e.body:Wa(t)&&im(t)?t:M5(t)}function Np(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=M5(e),s=i===((r=e.ownerDocument)==null?void 0:r.body),o=zs(i);if(s){const l=JS(o);return t.concat(o,o.visualViewport||[],im(i)?i:[],l&&n?Np(l):[])}else return t.concat(i,Np(i,[],n))}function JS(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function P5(e){const t=To(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Wa(e),s=i?e.offsetWidth:n,o=i?e.offsetHeight:r,l=wy(n)!==s||wy(r)!==o;return l&&(n=s,r=o),{width:n,height:r,$:l}}function QC(e){return ko(e)?e:e.contextElement}function Od(e){const t=QC(e);if(!Wa(t))return Jo(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:s}=P5(t);let o=(s?wy(n.width):n.width)/r,l=(s?wy(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!l||!Number.isFinite(l))&&(l=1),{x:o,y:l}}const eae=Jo(0);function I5(e){const t=zs(e);return!ZC()||!t.visualViewport?eae:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function tae(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==zs(e)?!1:t}function Xc(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),s=QC(e);let o=Jo(1);t&&(r?ko(r)&&(o=Od(r)):o=Od(e));const l=tae(s,n,r)?I5(s):Jo(0);let u=(i.left+l.x)/o.x,d=(i.top+l.y)/o.y,f=i.width/o.x,p=i.height/o.y;if(s){const y=zs(s),g=r&&ko(r)?zs(r):r;let _=y,w=JS(_);for(;w&&r&&g!==_;){const x=Od(w),S=w.getBoundingClientRect(),k=To(w),T=S.left+(w.clientLeft+parseFloat(k.paddingLeft))*x.x,N=S.top+(w.clientTop+parseFloat(k.paddingTop))*x.y;u*=x.x,d*=x.y,f*=x.x,p*=x.y,u+=T,d+=N,_=zs(w),w=JS(_)}}return Sy({width:f,height:p,x:u,y:d})}function mb(e,t){const n=pb(e).scrollLeft;return t?t.left+n:Xc(oa(e)).left+n}function O5(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-mb(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function nae(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const s=i==="fixed",o=oa(r),l=t?hb(t.floating):!1;if(r===o||l&&s)return n;let u={scrollLeft:0,scrollTop:0},d=Jo(1);const f=Jo(0),p=Wa(r);if((p||!p&&!s)&&((lf(r)!=="body"||im(o))&&(u=pb(r)),p)){const g=Xc(r);d=Od(r),f.x=g.x+r.clientLeft,f.y=g.y+r.clientTop}const y=o&&!p&&!s?O5(o,u):Jo(0);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-u.scrollLeft*d.x+f.x+y.x,y:n.y*d.y-u.scrollTop*d.y+f.y+y.y}}function rae(e){return Array.from(e.getClientRects())}function iae(e){const t=oa(e),n=pb(e),r=e.ownerDocument.body,i=Ds(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Ds(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let o=-n.scrollLeft+mb(e);const l=-n.scrollTop;return To(r).direction==="rtl"&&(o+=Ds(t.clientWidth,r.clientWidth)-i),{width:i,height:s,x:o,y:l}}const I2=25;function sae(e,t){const n=zs(e),r=oa(e),i=n.visualViewport;let s=r.clientWidth,o=r.clientHeight,l=0,u=0;if(i){s=i.width,o=i.height;const f=ZC();(!f||f&&t==="fixed")&&(l=i.offsetLeft,u=i.offsetTop)}const d=mb(r);if(d<=0){const f=r.ownerDocument,p=f.body,y=getComputedStyle(p),g=f.compatMode==="CSS1Compat"&&parseFloat(y.marginLeft)+parseFloat(y.marginRight)||0,_=Math.abs(r.clientWidth-p.clientWidth-g);_<=I2&&(s-=_)}else d<=I2&&(s+=d);return{width:s,height:o,x:l,y:u}}function oae(e,t){const n=Xc(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,s=Wa(e)?Od(e):Jo(1),o=e.clientWidth*s.x,l=e.clientHeight*s.y,u=i*s.x,d=r*s.y;return{width:o,height:l,x:u,y:d}}function O2(e,t,n){let r;if(t==="viewport")r=sae(e,n);else if(t==="document")r=iae(oa(e));else if(ko(t))r=oae(t,n);else{const i=I5(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Sy(r)}function L5(e,t){const n=Kl(e);return n===t||!ko(n)||Kd(n)?!1:To(n).position==="fixed"||L5(n,t)}function aae(e,t){const n=t.get(e);if(n)return n;let r=Np(e,[],!1).filter(l=>ko(l)&&lf(l)!=="body"),i=null;const s=To(e).position==="fixed";let o=s?Kl(e):e;for(;ko(o)&&!Kd(o);){const l=To(o),u=XC(o);!u&&l.position==="fixed"&&(i=null),(s?!u&&!i:!u&&l.position==="static"&&!!i&&(i.position==="absolute"||i.position==="fixed")||im(o)&&!u&&L5(e,o))?r=r.filter(f=>f!==o):i=l,o=Kl(o)}return t.set(e,r),r}function lae(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[...n==="clippingAncestors"?hb(t)?[]:aae(t,this._c):[].concat(n),r],l=O2(t,o[0],i);let u=l.top,d=l.right,f=l.bottom,p=l.left;for(let y=1;y<o.length;y++){const g=O2(t,o[y],i);u=Ds(g.top,u),d=Yl(g.right,d),f=Yl(g.bottom,f),p=Ds(g.left,p)}return{width:d-p,height:f-u,x:p,y:u}}function cae(e){const{width:t,height:n}=P5(e);return{width:t,height:n}}function uae(e,t,n){const r=Wa(t),i=oa(t),s=n==="fixed",o=Xc(e,!0,s,t);let l={scrollLeft:0,scrollTop:0};const u=Jo(0);function d(){u.x=mb(i)}if(r||!r&&!s)if((lf(t)!=="body"||im(i))&&(l=pb(t)),r){const g=Xc(t,!0,s,t);u.x=g.x+t.clientLeft,u.y=g.y+t.clientTop}else i&&d();s&&!r&&i&&d();const f=i&&!r&&!s?O5(i,l):Jo(0),p=o.left+l.scrollLeft-u.x-f.x,y=o.top+l.scrollTop-u.y-f.y;return{x:p,y,width:o.width,height:o.height}}function Qx(e){return To(e).position==="static"}function L2(e,t){if(!Wa(e)||To(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return oa(e)===n&&(n=n.ownerDocument.body),n}function D5(e,t){const n=zs(e);if(hb(e))return n;if(!Wa(e)){let i=Kl(e);for(;i&&!Kd(i);){if(ko(i)&&!Qx(i))return i;i=Kl(i)}return n}let r=L2(e,t);for(;r&&Xoe(r)&&Qx(r);)r=L2(r,t);return r&&Kd(r)&&Qx(r)&&!XC(r)?n:r||Joe(e)||n}const dae=async function(e){const t=this.getOffsetParent||D5,n=this.getDimensions,r=await n(e.floating);return{reference:uae(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function fae(e){return To(e).direction==="rtl"}const hae={convertOffsetParentRelativeRectToViewportRelativeRect:nae,getDocumentElement:oa,getClippingRect:lae,getOffsetParent:D5,getElementRects:dae,getClientRects:rae,getDimensions:cae,getScale:Od,isElement:ko,isRTL:fae};function B5(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function pae(e,t){let n=null,r;const i=oa(e);function s(){var l;clearTimeout(r),(l=n)==null||l.disconnect(),n=null}function o(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),s();const d=e.getBoundingClientRect(),{left:f,top:p,width:y,height:g}=d;if(l||t(),!y||!g)return;const _=tv(p),w=tv(i.clientWidth-(f+y)),x=tv(i.clientHeight-(p+g)),S=tv(f),T={rootMargin:-_+"px "+-w+"px "+-x+"px "+-S+"px",threshold:Ds(0,Yl(1,u))||1};let N=!0;function P(R){const M=R[0].intersectionRatio;if(M!==u){if(!N)return o();M?o(!1,M):r=setTimeout(()=>{o(!1,1e-7)},1e3)}M===1&&!B5(d,e.getBoundingClientRect())&&o(),N=!1}try{n=new IntersectionObserver(P,{...T,root:i.ownerDocument})}catch{n=new IntersectionObserver(P,T)}n.observe(e)}return o(!0),s}function mae(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:s=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,d=QC(e),f=i||s?[...d?Np(d):[],...t?Np(t):[]]:[];f.forEach(S=>{i&&S.addEventListener("scroll",n,{passive:!0}),s&&S.addEventListener("resize",n)});const p=d&&l?pae(d,n):null;let y=-1,g=null;o&&(g=new ResizeObserver(S=>{let[k]=S;k&&k.target===d&&g&&t&&(g.unobserve(t),cancelAnimationFrame(y),y=requestAnimationFrame(()=>{var T;(T=g)==null||T.observe(t)})),n()}),d&&!u&&g.observe(d),t&&g.observe(t));let _,w=u?Xc(e):null;u&&x();function x(){const S=Xc(e);w&&!B5(w,S)&&n(),w=S,_=requestAnimationFrame(x)}return n(),()=>{var S;f.forEach(k=>{i&&k.removeEventListener("scroll",n),s&&k.removeEventListener("resize",n)}),p==null||p(),(S=g)==null||S.disconnect(),g=null,u&&cancelAnimationFrame(_)}}const gae=Voe,vae=Yoe,yae=Uoe,bae=Goe,_ae=Woe,D2=Hoe,wae=Koe,xae=(e,t,n)=>{const r=new Map,i={platform:hae,...n},s={...i.platform,_c:r};return $oe(e,t,{...i,platform:s})};var Sae=typeof document<"u",Eae=function(){},Hv=Sae?b.useLayoutEffect:Eae;function Ey(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Ey(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const s=i[r];if(!(s==="_owner"&&e.$$typeof)&&!Ey(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function z5(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function B2(e,t){const n=z5(e);return Math.round(t*n)/n}function Jx(e){const t=b.useRef(e);return Hv(()=>{t.current=e}),t}function Cae(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:s,floating:o}={},transform:l=!0,whileElementsMounted:u,open:d}=e,[f,p]=b.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[y,g]=b.useState(r);Ey(y,r)||g(r);const[_,w]=b.useState(null),[x,S]=b.useState(null),k=b.useCallback(F=>{F!==R.current&&(R.current=F,w(F))},[]),T=b.useCallback(F=>{F!==M.current&&(M.current=F,S(F))},[]),N=s||_,P=o||x,R=b.useRef(null),M=b.useRef(null),L=b.useRef(f),X=u!=null,U=Jx(u),V=Jx(i),j=Jx(d),A=b.useCallback(()=>{if(!R.current||!M.current)return;const F={placement:t,strategy:n,middleware:y};V.current&&(F.platform=V.current),xae(R.current,M.current,F).then(Y=>{const z={...Y,isPositioned:j.current!==!1};D.current&&!Ey(L.current,z)&&(L.current=z,cu.flushSync(()=>{p(z)}))})},[y,t,n,V,j]);Hv(()=>{d===!1&&L.current.isPositioned&&(L.current.isPositioned=!1,p(F=>({...F,isPositioned:!1})))},[d]);const D=b.useRef(!1);Hv(()=>(D.current=!0,()=>{D.current=!1}),[]),Hv(()=>{if(N&&(R.current=N),P&&(M.current=P),N&&P){if(U.current)return U.current(N,P,A);A()}},[N,P,A,U,X]);const O=b.useMemo(()=>({reference:R,floating:M,setReference:k,setFloating:T}),[k,T]),I=b.useMemo(()=>({reference:N,floating:P}),[N,P]),B=b.useMemo(()=>{const F={position:n,left:0,top:0};if(!I.floating)return F;const Y=B2(I.floating,f.x),z=B2(I.floating,f.y);return l?{...F,transform:"translate("+Y+"px, "+z+"px)",...z5(I.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:Y,top:z}},[n,l,I.floating,f.x,f.y]);return b.useMemo(()=>({...f,update:A,refs:O,elements:I,floatingStyles:B}),[f,A,O,I,B])}const kae=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?D2({element:r.current,padding:i}).fn(n):{}:r?D2({element:r,padding:i}).fn(n):{}}}},Tae=(e,t)=>{const n=gae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Rae=(e,t)=>{const n=vae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Aae=(e,t)=>({fn:wae(e).fn,options:[e,t]}),Nae=(e,t)=>{const n=yae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Mae=(e,t)=>{const n=bae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Pae=(e,t)=>{const n=_ae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Iae=(e,t)=>{const n=kae(e);return{name:n.name,fn:n.fn,options:[e,t]}};var Oae="Arrow",j5=b.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...s}=e;return m.jsx(bn.svg,{...s,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:m.jsx("polygon",{points:"0,0 30,0 15,10"})})});j5.displayName=Oae;var Lae=j5,JC="Popper",[F5,nc]=Ua(JC),[Dae,$5]=F5(JC),H5=e=>{const{__scopePopper:t,children:n}=e,[r,i]=b.useState(null);return m.jsx(Dae,{scope:t,anchor:r,onAnchorChange:i,children:n})};H5.displayName=JC;var U5="PopperAnchor",W5=b.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,s=$5(U5,n),o=b.useRef(null),l=sr(t,o),u=b.useRef(null);return b.useEffect(()=>{const d=u.current;u.current=(r==null?void 0:r.current)||o.current,d!==u.current&&s.onAnchorChange(u.current)}),r?null:m.jsx(bn.div,{...i,ref:l})});W5.displayName=U5;var ek="PopperContent",[Bae,zae]=F5(ek),q5=b.forwardRef((e,t)=>{var Z,ae,le,me,ke,$e;const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:s="center",alignOffset:o=0,arrowPadding:l=0,avoidCollisions:u=!0,collisionBoundary:d=[],collisionPadding:f=0,sticky:p="partial",hideWhenDetached:y=!1,updatePositionStrategy:g="optimized",onPlaced:_,...w}=e,x=$5(ek,n),[S,k]=b.useState(null),T=sr(t,he=>k(he)),[N,P]=b.useState(null),R=Aoe(N),M=(R==null?void 0:R.width)??0,L=(R==null?void 0:R.height)??0,X=r+(s!=="center"?"-"+s:""),U=typeof f=="number"?f:{top:0,right:0,bottom:0,left:0,...f},V=Array.isArray(d)?d:[d],j=V.length>0,A={padding:U,boundary:V.filter(Fae),altBoundary:j},{refs:D,floatingStyles:O,placement:I,isPositioned:B,middlewareData:F}=Cae({strategy:"fixed",placement:X,whileElementsMounted:(...he)=>mae(...he,{animationFrame:g==="always"}),elements:{reference:x.anchor},middleware:[Tae({mainAxis:i+L,alignmentAxis:o}),u&&Rae({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?Aae():void 0,...A}),u&&Nae({...A}),Mae({...A,apply:({elements:he,rects:He,availableWidth:Nt,availableHeight:ye})=>{const{width:Ze,height:Oe}=He.reference,ze=he.floating.style;ze.setProperty("--radix-popper-available-width",`${Nt}px`),ze.setProperty("--radix-popper-available-height",`${ye}px`),ze.setProperty("--radix-popper-anchor-width",`${Ze}px`),ze.setProperty("--radix-popper-anchor-height",`${Oe}px`)}}),N&&Iae({element:N,padding:l}),$ae({arrowWidth:M,arrowHeight:L}),y&&Pae({strategy:"referenceHidden",...A})]}),[Y,z]=K5(I),q=ra(_);Vi(()=>{B&&(q==null||q())},[B,q]);const K=(Z=F.arrow)==null?void 0:Z.x,$=(ae=F.arrow)==null?void 0:ae.y,re=((le=F.arrow)==null?void 0:le.centerOffset)!==0,[Q,G]=b.useState();return Vi(()=>{S&&G(window.getComputedStyle(S).zIndex)},[S]),m.jsx("div",{ref:D.setFloating,"data-radix-popper-content-wrapper":"",style:{...O,transform:B?O.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Q,"--radix-popper-transform-origin":[(me=F.transformOrigin)==null?void 0:me.x,(ke=F.transformOrigin)==null?void 0:ke.y].join(" "),...(($e=F.hide)==null?void 0:$e.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:m.jsx(Bae,{scope:n,placedSide:Y,onArrowChange:P,arrowX:K,arrowY:$,shouldHideArrow:re,children:m.jsx(bn.div,{"data-side":Y,"data-align":z,...w,ref:T,style:{...w.style,animation:B?void 0:"none"}})})})});q5.displayName=ek;var V5="PopperArrow",jae={top:"bottom",right:"left",bottom:"top",left:"right"},Y5=b.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,s=zae(V5,r),o=jae[s.placedSide];return m.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[o]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:m.jsx(Lae,{...i,ref:n,style:{...i.style,display:"block"}})})});Y5.displayName=V5;function Fae(e){return e!==null}var $ae=e=>({name:"transformOrigin",options:e,fn(t){var x,S,k;const{placement:n,rects:r,middlewareData:i}=t,o=((x=i.arrow)==null?void 0:x.centerOffset)!==0,l=o?0:e.arrowWidth,u=o?0:e.arrowHeight,[d,f]=K5(n),p={start:"0%",center:"50%",end:"100%"}[f],y=(((S=i.arrow)==null?void 0:S.x)??0)+l/2,g=(((k=i.arrow)==null?void 0:k.y)??0)+u/2;let _="",w="";return d==="bottom"?(_=o?p:`${y}px`,w=`${-u}px`):d==="top"?(_=o?p:`${y}px`,w=`${r.floating.height+u}px`):d==="right"?(_=`${-u}px`,w=o?p:`${g}px`):d==="left"&&(_=`${r.floating.width+u}px`,w=o?p:`${g}px`),{data:{x:_,y:w}}}});function K5(e){const[t,n="center"]=e.split("-");return[t,n]}var gb=H5,sm=W5,vb=q5,yb=Y5,e0="rovingFocusGroup.onEntryFocus",Hae={bubbles:!1,cancelable:!0},om="RovingFocusGroup",[e1,G5,Uae]=zC(om),[Wae,X5]=Ua(om,[Uae]),[qae,Vae]=Wae(om),Z5=b.forwardRef((e,t)=>m.jsx(e1.Provider,{scope:e.__scopeRovingFocusGroup,children:m.jsx(e1.Slot,{scope:e.__scopeRovingFocusGroup,children:m.jsx(Yae,{...e,ref:t})})}));Z5.displayName=om;var Yae=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:s,currentTabStopId:o,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:d,preventScrollOnEntryFocus:f=!1,...p}=e,y=b.useRef(null),g=sr(t,y),_=jC(s),[w,x]=Kc({prop:o,defaultProp:l??null,onChange:u,caller:om}),[S,k]=b.useState(!1),T=ra(d),N=G5(n),P=b.useRef(!1),[R,M]=b.useState(0);return b.useEffect(()=>{const L=y.current;if(L)return L.addEventListener(e0,T),()=>L.removeEventListener(e0,T)},[T]),m.jsx(qae,{scope:n,orientation:r,dir:_,loop:i,currentTabStopId:w,onItemFocus:b.useCallback(L=>x(L),[x]),onItemShiftTab:b.useCallback(()=>k(!0),[]),onFocusableItemAdd:b.useCallback(()=>M(L=>L+1),[]),onFocusableItemRemove:b.useCallback(()=>M(L=>L-1),[]),children:m.jsx(bn.div,{tabIndex:S||R===0?-1:0,"data-orientation":r,...p,ref:g,style:{outline:"none",...e.style},onMouseDown:$t(e.onMouseDown,()=>{P.current=!0}),onFocus:$t(e.onFocus,L=>{const X=!P.current;if(L.target===L.currentTarget&&X&&!S){const U=new CustomEvent(e0,Hae);if(L.currentTarget.dispatchEvent(U),!U.defaultPrevented){const V=N().filter(I=>I.focusable),j=V.find(I=>I.active),A=V.find(I=>I.id===w),O=[j,A,...V].filter(Boolean).map(I=>I.ref.current);e3(O,f)}}P.current=!1}),onBlur:$t(e.onBlur,()=>k(!1))})})}),Q5="RovingFocusGroupItem",J5=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:s,children:o,...l}=e,u=Di(),d=s||u,f=Vae(Q5,n),p=f.currentTabStopId===d,y=G5(n),{onFocusableItemAdd:g,onFocusableItemRemove:_,currentTabStopId:w}=f;return b.useEffect(()=>{if(r)return g(),()=>_()},[r,g,_]),m.jsx(e1.ItemSlot,{scope:n,id:d,focusable:r,active:i,children:m.jsx(bn.span,{tabIndex:p?0:-1,"data-orientation":f.orientation,...l,ref:t,onMouseDown:$t(e.onMouseDown,x=>{r?f.onItemFocus(d):x.preventDefault()}),onFocus:$t(e.onFocus,()=>f.onItemFocus(d)),onKeyDown:$t(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){f.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const S=Xae(x,f.orientation,f.dir);if(S!==void 0){if(x.metaKey||x.ctrlKey||x.altKey||x.shiftKey)return;x.preventDefault();let T=y().filter(N=>N.focusable).map(N=>N.ref.current);if(S==="last")T.reverse();else if(S==="prev"||S==="next"){S==="prev"&&T.reverse();const N=T.indexOf(x.currentTarget);T=f.loop?Zae(T,N+1):T.slice(N+1)}setTimeout(()=>e3(T))}}),children:typeof o=="function"?o({isCurrentTabStop:p,hasTabStop:w!=null}):o})})});J5.displayName=Q5;var Kae={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Gae(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Xae(e,t,n){const r=Gae(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Kae[r]}function e3(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Zae(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Qae=Z5,Jae=J5,t1=["Enter"," "],ele=["ArrowDown","PageUp","Home"],t3=["ArrowUp","PageDown","End"],tle=[...ele,...t3],nle={ltr:[...t1,"ArrowRight"],rtl:[...t1,"ArrowLeft"]},rle={ltr:["ArrowLeft"],rtl:["ArrowRight"]},am="Menu",[Mp,ile,sle]=zC(am),[uu,n3]=Ua(am,[sle,nc,X5]),bb=nc(),r3=X5(),[ole,du]=uu(am),[ale,lm]=uu(am),i3=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:s,modal:o=!0}=e,l=bb(t),[u,d]=b.useState(null),f=b.useRef(!1),p=ra(s),y=jC(i);return b.useEffect(()=>{const g=()=>{f.current=!0,document.addEventListener("pointerdown",_,{capture:!0,once:!0}),document.addEventListener("pointermove",_,{capture:!0,once:!0})},_=()=>f.current=!1;return document.addEventListener("keydown",g,{capture:!0}),()=>{document.removeEventListener("keydown",g,{capture:!0}),document.removeEventListener("pointerdown",_,{capture:!0}),document.removeEventListener("pointermove",_,{capture:!0})}},[]),m.jsx(gb,{...l,children:m.jsx(ole,{scope:t,open:n,onOpenChange:p,content:u,onContentChange:d,children:m.jsx(ale,{scope:t,onClose:b.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:f,dir:y,modal:o,children:r})})})};i3.displayName=am;var lle="MenuAnchor",tk=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=bb(n);return m.jsx(sm,{...i,...r,ref:t})});tk.displayName=lle;var nk="MenuPortal",[cle,s3]=uu(nk,{forceMount:void 0}),o3=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,s=du(nk,t);return m.jsx(cle,{scope:t,forceMount:n,children:m.jsx(ho,{present:n||s.open,children:m.jsx(of,{asChild:!0,container:i,children:r})})})};o3.displayName=nk;var oo="MenuContent",[ule,rk]=uu(oo),a3=b.forwardRef((e,t)=>{const n=s3(oo,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,s=du(oo,e.__scopeMenu),o=lm(oo,e.__scopeMenu);return m.jsx(Mp.Provider,{scope:e.__scopeMenu,children:m.jsx(ho,{present:r||s.open,children:m.jsx(Mp.Slot,{scope:e.__scopeMenu,children:o.modal?m.jsx(dle,{...i,ref:t}):m.jsx(fle,{...i,ref:t})})})})}),dle=b.forwardRef((e,t)=>{const n=du(oo,e.__scopeMenu),r=b.useRef(null),i=sr(t,r);return b.useEffect(()=>{const s=r.current;if(s)return cb(s)},[]),m.jsx(ik,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:$t(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),fle=b.forwardRef((e,t)=>{const n=du(oo,e.__scopeMenu);return m.jsx(ik,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),hle=Vl("MenuContent.ScrollLock"),ik=b.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:s,onCloseAutoFocus:o,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:f,onFocusOutside:p,onInteractOutside:y,onDismiss:g,disableOutsideScroll:_,...w}=e,x=du(oo,n),S=lm(oo,n),k=bb(n),T=r3(n),N=ile(n),[P,R]=b.useState(null),M=b.useRef(null),L=sr(t,M,x.onContentChange),X=b.useRef(0),U=b.useRef(""),V=b.useRef(0),j=b.useRef(null),A=b.useRef("right"),D=b.useRef(0),O=_?rm:b.Fragment,I=_?{as:hle,allowPinchZoom:!0}:void 0,B=Y=>{var Z,ae;const z=U.current+Y,q=N().filter(le=>!le.disabled),K=document.activeElement,$=(Z=q.find(le=>le.ref.current===K))==null?void 0:Z.textValue,re=q.map(le=>le.textValue),Q=Cle(re,z,$),G=(ae=q.find(le=>le.textValue===Q))==null?void 0:ae.ref.current;(function le(me){U.current=me,window.clearTimeout(X.current),me!==""&&(X.current=window.setTimeout(()=>le(""),1e3))})(z),G&&setTimeout(()=>G.focus())};b.useEffect(()=>()=>window.clearTimeout(X.current),[]),ab();const F=b.useCallback(Y=>{var q,K;return A.current===((q=j.current)==null?void 0:q.side)&&Tle(Y,(K=j.current)==null?void 0:K.area)},[]);return m.jsx(ule,{scope:n,searchRef:U,onItemEnter:b.useCallback(Y=>{F(Y)&&Y.preventDefault()},[F]),onItemLeave:b.useCallback(Y=>{var z;F(Y)||((z=M.current)==null||z.focus(),R(null))},[F]),onTriggerLeave:b.useCallback(Y=>{F(Y)&&Y.preventDefault()},[F]),pointerGraceTimerRef:V,onPointerGraceIntentChange:b.useCallback(Y=>{j.current=Y},[]),children:m.jsx(O,{...I,children:m.jsx(nm,{asChild:!0,trapped:i,onMountAutoFocus:$t(s,Y=>{var z;Y.preventDefault(),(z=M.current)==null||z.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:m.jsx(sf,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:f,onFocusOutside:p,onInteractOutside:y,onDismiss:g,children:m.jsx(Qae,{asChild:!0,...T,dir:S.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:R,onEntryFocus:$t(u,Y=>{S.isUsingKeyboardRef.current||Y.preventDefault()}),preventScrollOnEntryFocus:!0,children:m.jsx(vb,{role:"menu","aria-orientation":"vertical","data-state":S3(x.open),"data-radix-menu-content":"",dir:S.dir,...k,...w,ref:L,style:{outline:"none",...w.style},onKeyDown:$t(w.onKeyDown,Y=>{const q=Y.target.closest("[data-radix-menu-content]")===Y.currentTarget,K=Y.ctrlKey||Y.altKey||Y.metaKey,$=Y.key.length===1;q&&(Y.key==="Tab"&&Y.preventDefault(),!K&&$&&B(Y.key));const re=M.current;if(Y.target!==re||!tle.includes(Y.key))return;Y.preventDefault();const G=N().filter(Z=>!Z.disabled).map(Z=>Z.ref.current);t3.includes(Y.key)&&G.reverse(),Sle(G)}),onBlur:$t(e.onBlur,Y=>{Y.currentTarget.contains(Y.target)||(window.clearTimeout(X.current),U.current="")}),onPointerMove:$t(e.onPointerMove,Pp(Y=>{const z=Y.target,q=D.current!==Y.clientX;if(Y.currentTarget.contains(z)&&q){const K=Y.clientX>D.current?"right":"left";A.current=K,D.current=Y.clientX}}))})})})})})})});a3.displayName=oo;var ple="MenuGroup",sk=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return m.jsx(bn.div,{role:"group",...r,ref:t})});sk.displayName=ple;var mle="MenuLabel",l3=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return m.jsx(bn.div,{...r,ref:t})});l3.displayName=mle;var Cy="MenuItem",z2="menu.itemSelect",_b=b.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,s=b.useRef(null),o=lm(Cy,e.__scopeMenu),l=rk(Cy,e.__scopeMenu),u=sr(t,s),d=b.useRef(!1),f=()=>{const p=s.current;if(!n&&p){const y=new CustomEvent(z2,{bubbles:!0,cancelable:!0});p.addEventListener(z2,g=>r==null?void 0:r(g),{once:!0}),Gj(p,y),y.defaultPrevented?d.current=!1:o.onClose()}};return m.jsx(c3,{...i,ref:u,disabled:n,onClick:$t(e.onClick,f),onPointerDown:p=>{var y;(y=e.onPointerDown)==null||y.call(e,p),d.current=!0},onPointerUp:$t(e.onPointerUp,p=>{var y;d.current||(y=p.currentTarget)==null||y.click()}),onKeyDown:$t(e.onKeyDown,p=>{const y=l.searchRef.current!=="";n||y&&p.key===" "||t1.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});_b.displayName=Cy;var c3=b.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...s}=e,o=rk(Cy,n),l=r3(n),u=b.useRef(null),d=sr(t,u),[f,p]=b.useState(!1),[y,g]=b.useState("");return b.useEffect(()=>{const _=u.current;_&&g((_.textContent??"").trim())},[s.children]),m.jsx(Mp.ItemSlot,{scope:n,disabled:r,textValue:i??y,children:m.jsx(Jae,{asChild:!0,...l,focusable:!r,children:m.jsx(bn.div,{role:"menuitem","data-highlighted":f?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:d,onPointerMove:$t(e.onPointerMove,Pp(_=>{r?o.onItemLeave(_):(o.onItemEnter(_),_.defaultPrevented||_.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:$t(e.onPointerLeave,Pp(_=>o.onItemLeave(_))),onFocus:$t(e.onFocus,()=>p(!0)),onBlur:$t(e.onBlur,()=>p(!1))})})})}),gle="MenuCheckboxItem",u3=b.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return m.jsx(m3,{scope:e.__scopeMenu,checked:n,children:m.jsx(_b,{role:"menuitemcheckbox","aria-checked":ky(n)?"mixed":n,...i,ref:t,"data-state":ak(n),onSelect:$t(i.onSelect,()=>r==null?void 0:r(ky(n)?!0:!n),{checkForDefaultPrevented:!1})})})});u3.displayName=gle;var d3="MenuRadioGroup",[vle,yle]=uu(d3,{value:void 0,onValueChange:()=>{}}),f3=b.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,s=ra(r);return m.jsx(vle,{scope:e.__scopeMenu,value:n,onValueChange:s,children:m.jsx(sk,{...i,ref:t})})});f3.displayName=d3;var h3="MenuRadioItem",p3=b.forwardRef((e,t)=>{const{value:n,...r}=e,i=yle(h3,e.__scopeMenu),s=n===i.value;return m.jsx(m3,{scope:e.__scopeMenu,checked:s,children:m.jsx(_b,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":ak(s),onSelect:$t(r.onSelect,()=>{var o;return(o=i.onValueChange)==null?void 0:o.call(i,n)},{checkForDefaultPrevented:!1})})})});p3.displayName=h3;var ok="MenuItemIndicator",[m3,ble]=uu(ok,{checked:!1}),g3=b.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,s=ble(ok,n);return m.jsx(ho,{present:r||ky(s.checked)||s.checked===!0,children:m.jsx(bn.span,{...i,ref:t,"data-state":ak(s.checked)})})});g3.displayName=ok;var _le="MenuSeparator",v3=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return m.jsx(bn.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});v3.displayName=_le;var wle="MenuArrow",y3=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=bb(n);return m.jsx(yb,{...i,...r,ref:t})});y3.displayName=wle;var xle="MenuSub",[tLe,b3]=uu(xle),Xh="MenuSubTrigger",_3=b.forwardRef((e,t)=>{const n=du(Xh,e.__scopeMenu),r=lm(Xh,e.__scopeMenu),i=b3(Xh,e.__scopeMenu),s=rk(Xh,e.__scopeMenu),o=b.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=s,d={__scopeMenu:e.__scopeMenu},f=b.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);return b.useEffect(()=>f,[f]),b.useEffect(()=>{const p=l.current;return()=>{window.clearTimeout(p),u(null)}},[l,u]),m.jsx(tk,{asChild:!0,...d,children:m.jsx(c3,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":i.contentId,"data-state":S3(n.open),...e,ref:za(t,i.onTriggerChange),onClick:p=>{var y;(y=e.onClick)==null||y.call(e,p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:$t(e.onPointerMove,Pp(p=>{s.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!o.current&&(s.onPointerGraceIntentChange(null),o.current=window.setTimeout(()=>{n.onOpenChange(!0),f()},100))})),onPointerLeave:$t(e.onPointerLeave,Pp(p=>{var g,_;f();const y=(g=n.content)==null?void 0:g.getBoundingClientRect();if(y){const w=(_=n.content)==null?void 0:_.dataset.side,x=w==="right",S=x?-5:5,k=y[x?"left":"right"],T=y[x?"right":"left"];s.onPointerGraceIntentChange({area:[{x:p.clientX+S,y:p.clientY},{x:k,y:y.top},{x:T,y:y.top},{x:T,y:y.bottom},{x:k,y:y.bottom}],side:w}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(p),p.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:$t(e.onKeyDown,p=>{var g;const y=s.searchRef.current!=="";e.disabled||y&&p.key===" "||nle[r.dir].includes(p.key)&&(n.onOpenChange(!0),(g=n.content)==null||g.focus(),p.preventDefault())})})})});_3.displayName=Xh;var w3="MenuSubContent",x3=b.forwardRef((e,t)=>{const n=s3(oo,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,s=du(oo,e.__scopeMenu),o=lm(oo,e.__scopeMenu),l=b3(w3,e.__scopeMenu),u=b.useRef(null),d=sr(t,u);return m.jsx(Mp.Provider,{scope:e.__scopeMenu,children:m.jsx(ho,{present:r||s.open,children:m.jsx(Mp.Slot,{scope:e.__scopeMenu,children:m.jsx(ik,{id:l.contentId,"aria-labelledby":l.triggerId,...i,ref:d,align:"start",side:o.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:f=>{var p;o.isUsingKeyboardRef.current&&((p=u.current)==null||p.focus()),f.preventDefault()},onCloseAutoFocus:f=>f.preventDefault(),onFocusOutside:$t(e.onFocusOutside,f=>{f.target!==l.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:$t(e.onEscapeKeyDown,f=>{o.onClose(),f.preventDefault()}),onKeyDown:$t(e.onKeyDown,f=>{var g;const p=f.currentTarget.contains(f.target),y=rle[o.dir].includes(f.key);p&&y&&(s.onOpenChange(!1),(g=l.trigger)==null||g.focus(),f.preventDefault())})})})})})});x3.displayName=w3;function S3(e){return e?"open":"closed"}function ky(e){return e==="indeterminate"}function ak(e){return ky(e)?"indeterminate":e?"checked":"unchecked"}function Sle(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Ele(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function Cle(e,t,n){const i=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let o=Ele(e,Math.max(s,0));i.length===1&&(o=o.filter(d=>d!==n));const u=o.find(d=>d.toLowerCase().startsWith(i.toLowerCase()));return u!==n?u:void 0}function kle(e,t){const{x:n,y:r}=e;let i=!1;for(let s=0,o=t.length-1;s<t.length;o=s++){const l=t[s],u=t[o],d=l.x,f=l.y,p=u.x,y=u.y;f>r!=y>r&&n<(p-d)*(r-f)/(y-f)+d&&(i=!i)}return i}function Tle(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return kle(n,t)}function Pp(e){return t=>t.pointerType==="mouse"?e(t):void 0}var Rle=i3,Ale=tk,Nle=o3,Mle=a3,Ple=sk,Ile=l3,Ole=_b,Lle=u3,Dle=f3,Ble=p3,zle=g3,jle=v3,Fle=y3,$le=_3,Hle=x3,wb="DropdownMenu",[Ule]=Ua(wb,[n3]),is=n3(),[Wle,E3]=Ule(wb),C3=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:s,onOpenChange:o,modal:l=!0}=e,u=is(t),d=b.useRef(null),[f,p]=Kc({prop:i,defaultProp:s??!1,onChange:o,caller:wb});return m.jsx(Wle,{scope:t,triggerId:Di(),triggerRef:d,contentId:Di(),open:f,onOpenChange:p,onOpenToggle:b.useCallback(()=>p(y=>!y),[p]),modal:l,children:m.jsx(Rle,{...u,open:f,onOpenChange:p,dir:r,modal:l,children:n})})};C3.displayName=wb;var k3="DropdownMenuTrigger",T3=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,s=E3(k3,n),o=is(n);return m.jsx(Ale,{asChild:!0,...o,children:m.jsx(bn.button,{type:"button",id:s.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":s.open?s.contentId:void 0,"data-state":s.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:za(t,s.triggerRef),onPointerDown:$t(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(s.onOpenToggle(),s.open||l.preventDefault())}),onKeyDown:$t(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&s.onOpenToggle(),l.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});T3.displayName=k3;var qle="DropdownMenuPortal",R3=e=>{const{__scopeDropdownMenu:t,...n}=e,r=is(t);return m.jsx(Nle,{...r,...n})};R3.displayName=qle;var A3="DropdownMenuContent",N3=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=E3(A3,n),s=is(n),o=b.useRef(!1);return m.jsx(Mle,{id:i.contentId,"aria-labelledby":i.triggerId,...s,...r,ref:t,onCloseAutoFocus:$t(e.onCloseAutoFocus,l=>{var u;o.current||(u=i.triggerRef.current)==null||u.focus(),o.current=!1,l.preventDefault()}),onInteractOutside:$t(e.onInteractOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,f=u.button===2||d;(!i.modal||f)&&(o.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});N3.displayName=A3;var Vle="DropdownMenuGroup",Yle=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(Ple,{...i,...r,ref:t})});Yle.displayName=Vle;var Kle="DropdownMenuLabel",M3=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(Ile,{...i,...r,ref:t})});M3.displayName=Kle;var Gle="DropdownMenuItem",P3=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(Ole,{...i,...r,ref:t})});P3.displayName=Gle;var Xle="DropdownMenuCheckboxItem",I3=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(Lle,{...i,...r,ref:t})});I3.displayName=Xle;var Zle="DropdownMenuRadioGroup",Qle=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(Dle,{...i,...r,ref:t})});Qle.displayName=Zle;var Jle="DropdownMenuRadioItem",ece=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(Ble,{...i,...r,ref:t})});ece.displayName=Jle;var tce="DropdownMenuItemIndicator",O3=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(zle,{...i,...r,ref:t})});O3.displayName=tce;var nce="DropdownMenuSeparator",L3=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(jle,{...i,...r,ref:t})});L3.displayName=nce;var rce="DropdownMenuArrow",ice=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(Fle,{...i,...r,ref:t})});ice.displayName=rce;var sce="DropdownMenuSubTrigger",oce=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx($le,{...i,...r,ref:t})});oce.displayName=sce;var ace="DropdownMenuSubContent",lce=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(Hle,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});lce.displayName=ace;var cce=C3,uce=T3,dce=R3,fce=N3,hce=M3,pce=P3,mce=I3,gce=O3,vce=L3;function j2(e,[t,n]){return Math.min(n,Math.max(t,e))}var xb="Popover",[D3]=Ua(xb,[nc]),cm=nc(),[yce,rc]=D3(xb),B3=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:s,modal:o=!1}=e,l=cm(t),u=b.useRef(null),[d,f]=b.useState(!1),[p,y]=Kc({prop:r,defaultProp:i??!1,onChange:s,caller:xb});return m.jsx(gb,{...l,children:m.jsx(yce,{scope:t,contentId:Di(),triggerRef:u,open:p,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(g=>!g),[y]),hasCustomAnchor:d,onCustomAnchorAdd:b.useCallback(()=>f(!0),[]),onCustomAnchorRemove:b.useCallback(()=>f(!1),[]),modal:o,children:n})})};B3.displayName=xb;var z3="PopoverAnchor",bce=b.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=rc(z3,n),s=cm(n),{onCustomAnchorAdd:o,onCustomAnchorRemove:l}=i;return b.useEffect(()=>(o(),()=>l()),[o,l]),m.jsx(sm,{...s,...r,ref:t})});bce.displayName=z3;var j3="PopoverTrigger",F3=b.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=rc(j3,n),s=cm(n),o=sr(t,i.triggerRef),l=m.jsx(bn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":q3(i.open),...r,ref:o,onClick:$t(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?l:m.jsx(sm,{asChild:!0,...s,children:l})});F3.displayName=j3;var lk="PopoverPortal",[_ce,wce]=D3(lk,{forceMount:void 0}),$3=e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,s=rc(lk,t);return m.jsx(_ce,{scope:t,forceMount:n,children:m.jsx(ho,{present:n||s.open,children:m.jsx(of,{asChild:!0,container:i,children:r})})})};$3.displayName=lk;var Gd="PopoverContent",H3=b.forwardRef((e,t)=>{const n=wce(Gd,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,s=rc(Gd,e.__scopePopover);return m.jsx(ho,{present:r||s.open,children:s.modal?m.jsx(Sce,{...i,ref:t}):m.jsx(Ece,{...i,ref:t})})});H3.displayName=Gd;var xce=Vl("PopoverContent.RemoveScroll"),Sce=b.forwardRef((e,t)=>{const n=rc(Gd,e.__scopePopover),r=b.useRef(null),i=sr(t,r),s=b.useRef(!1);return b.useEffect(()=>{const o=r.current;if(o)return cb(o)},[]),m.jsx(rm,{as:xce,allowPinchZoom:!0,children:m.jsx(U3,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:$t(e.onCloseAutoFocus,o=>{var l;o.preventDefault(),s.current||(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:$t(e.onPointerDownOutside,o=>{const l=o.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,d=l.button===2||u;s.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:$t(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1})})})}),Ece=b.forwardRef((e,t)=>{const n=rc(Gd,e.__scopePopover),r=b.useRef(!1),i=b.useRef(!1);return m.jsx(U3,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var o,l;(o=e.onCloseAutoFocus)==null||o.call(e,s),s.defaultPrevented||(r.current||(l=n.triggerRef.current)==null||l.focus(),s.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:s=>{var u,d;(u=e.onInteractOutside)==null||u.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const o=s.target;((d=n.triggerRef.current)==null?void 0:d.contains(o))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&i.current&&s.preventDefault()}})}),U3=b.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:o,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,...p}=e,y=rc(Gd,n),g=cm(n);return ab(),m.jsx(nm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:s,children:m.jsx(sf,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:f,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onDismiss:()=>y.onOpenChange(!1),children:m.jsx(vb,{"data-state":q3(y.open),role:"dialog",id:y.contentId,...g,...p,ref:t,style:{...p.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),W3="PopoverClose",Cce=b.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=rc(W3,n);return m.jsx(bn.button,{type:"button",...r,ref:t,onClick:$t(e.onClick,()=>i.onOpenChange(!1))})});Cce.displayName=W3;var kce="PopoverArrow",Tce=b.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=cm(n);return m.jsx(yb,{...i,...r,ref:t})});Tce.displayName=kce;function q3(e){return e?"open":"closed"}var Rce=B3,Ace=F3,Nce=$3,Mce=H3,Pce=[" ","Enter","ArrowUp","ArrowDown"],Ice=[" ","Enter"],Zc="Select",[Sb,Eb,Oce]=zC(Zc),[cf]=Ua(Zc,[Oce,nc]),Cb=nc(),[Lce,ic]=cf(Zc),[Dce,Bce]=cf(Zc),V3=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:i,onOpenChange:s,value:o,defaultValue:l,onValueChange:u,dir:d,name:f,autoComplete:p,disabled:y,required:g,form:_}=e,w=Cb(t),[x,S]=b.useState(null),[k,T]=b.useState(null),[N,P]=b.useState(!1),R=jC(d),[M,L]=Kc({prop:r,defaultProp:i??!1,onChange:s,caller:Zc}),[X,U]=Kc({prop:o,defaultProp:l,onChange:u,caller:Zc}),V=b.useRef(null),j=x?_||!!x.closest("form"):!0,[A,D]=b.useState(new Set),O=Array.from(A).map(I=>I.props.value).join(";");return m.jsx(gb,{...w,children:m.jsxs(Lce,{required:g,scope:t,trigger:x,onTriggerChange:S,valueNode:k,onValueNodeChange:T,valueNodeHasChildren:N,onValueNodeHasChildrenChange:P,contentId:Di(),value:X,onValueChange:U,open:M,onOpenChange:L,dir:R,triggerPointerDownPosRef:V,disabled:y,children:[m.jsx(Sb.Provider,{scope:t,children:m.jsx(Dce,{scope:e.__scopeSelect,onNativeOptionAdd:b.useCallback(I=>{D(B=>new Set(B).add(I))},[]),onNativeOptionRemove:b.useCallback(I=>{D(B=>{const F=new Set(B);return F.delete(I),F})},[]),children:n})}),j?m.jsxs(p4,{"aria-hidden":!0,required:g,tabIndex:-1,name:f,autoComplete:p,value:X,onChange:I=>U(I.target.value),disabled:y,form:_,children:[X===void 0?m.jsx("option",{value:""}):null,Array.from(A)]},O):null]})})};V3.displayName=Zc;var Y3="SelectTrigger",K3=b.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...i}=e,s=Cb(n),o=ic(Y3,n),l=o.disabled||r,u=sr(t,o.onTriggerChange),d=Eb(n),f=b.useRef("touch"),[p,y,g]=g4(w=>{const x=d().filter(T=>!T.disabled),S=x.find(T=>T.value===o.value),k=v4(x,w,S);k!==void 0&&o.onValueChange(k.value)}),_=w=>{l||(o.onOpenChange(!0),g()),w&&(o.triggerPointerDownPosRef.current={x:Math.round(w.pageX),y:Math.round(w.pageY)})};return m.jsx(sm,{asChild:!0,...s,children:m.jsx(bn.button,{type:"button",role:"combobox","aria-controls":o.contentId,"aria-expanded":o.open,"aria-required":o.required,"aria-autocomplete":"none",dir:o.dir,"data-state":o.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":m4(o.value)?"":void 0,...i,ref:u,onClick:$t(i.onClick,w=>{w.currentTarget.focus(),f.current!=="mouse"&&_(w)}),onPointerDown:$t(i.onPointerDown,w=>{f.current=w.pointerType;const x=w.target;x.hasPointerCapture(w.pointerId)&&x.releasePointerCapture(w.pointerId),w.button===0&&w.ctrlKey===!1&&w.pointerType==="mouse"&&(_(w),w.preventDefault())}),onKeyDown:$t(i.onKeyDown,w=>{const x=p.current!=="";!(w.ctrlKey||w.altKey||w.metaKey)&&w.key.length===1&&y(w.key),!(x&&w.key===" ")&&Pce.includes(w.key)&&(_(),w.preventDefault())})})})});K3.displayName=Y3;var G3="SelectValue",X3=b.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:i,children:s,placeholder:o="",...l}=e,u=ic(G3,n),{onValueNodeHasChildrenChange:d}=u,f=s!==void 0,p=sr(t,u.onValueNodeChange);return Vi(()=>{d(f)},[d,f]),m.jsx(bn.span,{...l,ref:p,style:{pointerEvents:"none"},children:m4(u.value)?m.jsx(m.Fragment,{children:o}):s})});X3.displayName=G3;var zce="SelectIcon",Z3=b.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...i}=e;return m.jsx(bn.span,{"aria-hidden":!0,...i,ref:t,children:r||"▼"})});Z3.displayName=zce;var jce="SelectPortal",Q3=e=>m.jsx(of,{asChild:!0,...e});Q3.displayName=jce;var Qc="SelectContent",J3=b.forwardRef((e,t)=>{const n=ic(Qc,e.__scopeSelect),[r,i]=b.useState();if(Vi(()=>{i(new DocumentFragment)},[]),!n.open){const s=r;return s?cu.createPortal(m.jsx(e4,{scope:e.__scopeSelect,children:m.jsx(Sb.Slot,{scope:e.__scopeSelect,children:m.jsx("div",{children:e.children})})}),s):null}return m.jsx(t4,{...e,ref:t})});J3.displayName=Qc;var _o=10,[e4,sc]=cf(Qc),Fce="SelectContentImpl",$ce=Vl("SelectContent.RemoveScroll"),t4=b.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:s,onPointerDownOutside:o,side:l,sideOffset:u,align:d,alignOffset:f,arrowPadding:p,collisionBoundary:y,collisionPadding:g,sticky:_,hideWhenDetached:w,avoidCollisions:x,...S}=e,k=ic(Qc,n),[T,N]=b.useState(null),[P,R]=b.useState(null),M=sr(t,Z=>N(Z)),[L,X]=b.useState(null),[U,V]=b.useState(null),j=Eb(n),[A,D]=b.useState(!1),O=b.useRef(!1);b.useEffect(()=>{if(T)return cb(T)},[T]),ab();const I=b.useCallback(Z=>{const[ae,...le]=j().map($e=>$e.ref.current),[me]=le.slice(-1),ke=document.activeElement;for(const $e of Z)if($e===ke||($e==null||$e.scrollIntoView({block:"nearest"}),$e===ae&&P&&(P.scrollTop=0),$e===me&&P&&(P.scrollTop=P.scrollHeight),$e==null||$e.focus(),document.activeElement!==ke))return},[j,P]),B=b.useCallback(()=>I([L,T]),[I,L,T]);b.useEffect(()=>{A&&B()},[A,B]);const{onOpenChange:F,triggerPointerDownPosRef:Y}=k;b.useEffect(()=>{if(T){let Z={x:0,y:0};const ae=me=>{var ke,$e;Z={x:Math.abs(Math.round(me.pageX)-(((ke=Y.current)==null?void 0:ke.x)??0)),y:Math.abs(Math.round(me.pageY)-((($e=Y.current)==null?void 0:$e.y)??0))}},le=me=>{Z.x<=10&&Z.y<=10?me.preventDefault():T.contains(me.target)||F(!1),document.removeEventListener("pointermove",ae),Y.current=null};return Y.current!==null&&(document.addEventListener("pointermove",ae),document.addEventListener("pointerup",le,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ae),document.removeEventListener("pointerup",le,{capture:!0})}}},[T,F,Y]),b.useEffect(()=>{const Z=()=>F(!1);return window.addEventListener("blur",Z),window.addEventListener("resize",Z),()=>{window.removeEventListener("blur",Z),window.removeEventListener("resize",Z)}},[F]);const[z,q]=g4(Z=>{const ae=j().filter(ke=>!ke.disabled),le=ae.find(ke=>ke.ref.current===document.activeElement),me=v4(ae,Z,le);me&&setTimeout(()=>me.ref.current.focus())}),K=b.useCallback((Z,ae,le)=>{const me=!O.current&&!le;(k.value!==void 0&&k.value===ae||me)&&(X(Z),me&&(O.current=!0))},[k.value]),$=b.useCallback(()=>T==null?void 0:T.focus(),[T]),re=b.useCallback((Z,ae,le)=>{const me=!O.current&&!le;(k.value!==void 0&&k.value===ae||me)&&V(Z)},[k.value]),Q=r==="popper"?n1:n4,G=Q===n1?{side:l,sideOffset:u,align:d,alignOffset:f,arrowPadding:p,collisionBoundary:y,collisionPadding:g,sticky:_,hideWhenDetached:w,avoidCollisions:x}:{};return m.jsx(e4,{scope:n,content:T,viewport:P,onViewportChange:R,itemRefCallback:K,selectedItem:L,onItemLeave:$,itemTextRefCallback:re,focusSelectedItem:B,selectedItemText:U,position:r,isPositioned:A,searchRef:z,children:m.jsx(rm,{as:$ce,allowPinchZoom:!0,children:m.jsx(nm,{asChild:!0,trapped:k.open,onMountAutoFocus:Z=>{Z.preventDefault()},onUnmountAutoFocus:$t(i,Z=>{var ae;(ae=k.trigger)==null||ae.focus({preventScroll:!0}),Z.preventDefault()}),children:m.jsx(sf,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:Z=>Z.preventDefault(),onDismiss:()=>k.onOpenChange(!1),children:m.jsx(Q,{role:"listbox",id:k.contentId,"data-state":k.open?"open":"closed",dir:k.dir,onContextMenu:Z=>Z.preventDefault(),...S,...G,onPlaced:()=>D(!0),ref:M,style:{display:"flex",flexDirection:"column",outline:"none",...S.style},onKeyDown:$t(S.onKeyDown,Z=>{const ae=Z.ctrlKey||Z.altKey||Z.metaKey;if(Z.key==="Tab"&&Z.preventDefault(),!ae&&Z.key.length===1&&q(Z.key),["ArrowUp","ArrowDown","Home","End"].includes(Z.key)){let me=j().filter(ke=>!ke.disabled).map(ke=>ke.ref.current);if(["ArrowUp","End"].includes(Z.key)&&(me=me.slice().reverse()),["ArrowUp","ArrowDown"].includes(Z.key)){const ke=Z.target,$e=me.indexOf(ke);me=me.slice($e+1)}setTimeout(()=>I(me)),Z.preventDefault()}})})})})})})});t4.displayName=Fce;var Hce="SelectItemAlignedPosition",n4=b.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...i}=e,s=ic(Qc,n),o=sc(Qc,n),[l,u]=b.useState(null),[d,f]=b.useState(null),p=sr(t,M=>f(M)),y=Eb(n),g=b.useRef(!1),_=b.useRef(!0),{viewport:w,selectedItem:x,selectedItemText:S,focusSelectedItem:k}=o,T=b.useCallback(()=>{if(s.trigger&&s.valueNode&&l&&d&&w&&x&&S){const M=s.trigger.getBoundingClientRect(),L=d.getBoundingClientRect(),X=s.valueNode.getBoundingClientRect(),U=S.getBoundingClientRect();if(s.dir!=="rtl"){const ke=U.left-L.left,$e=X.left-ke,he=M.left-$e,He=M.width+he,Nt=Math.max(He,L.width),ye=window.innerWidth-_o,Ze=j2($e,[_o,Math.max(_o,ye-Nt)]);l.style.minWidth=He+"px",l.style.left=Ze+"px"}else{const ke=L.right-U.right,$e=window.innerWidth-X.right-ke,he=window.innerWidth-M.right-$e,He=M.width+he,Nt=Math.max(He,L.width),ye=window.innerWidth-_o,Ze=j2($e,[_o,Math.max(_o,ye-Nt)]);l.style.minWidth=He+"px",l.style.right=Ze+"px"}const V=y(),j=window.innerHeight-_o*2,A=w.scrollHeight,D=window.getComputedStyle(d),O=parseInt(D.borderTopWidth,10),I=parseInt(D.paddingTop,10),B=parseInt(D.borderBottomWidth,10),F=parseInt(D.paddingBottom,10),Y=O+I+A+F+B,z=Math.min(x.offsetHeight*5,Y),q=window.getComputedStyle(w),K=parseInt(q.paddingTop,10),$=parseInt(q.paddingBottom,10),re=M.top+M.height/2-_o,Q=j-re,G=x.offsetHeight/2,Z=x.offsetTop+G,ae=O+I+Z,le=Y-ae;if(ae<=re){const ke=V.length>0&&x===V[V.length-1].ref.current;l.style.bottom="0px";const $e=d.clientHeight-w.offsetTop-w.offsetHeight,he=Math.max(Q,G+(ke?$:0)+$e+B),He=ae+he;l.style.height=He+"px"}else{const ke=V.length>0&&x===V[0].ref.current;l.style.top="0px";const he=Math.max(re,O+w.offsetTop+(ke?K:0)+G)+le;l.style.height=he+"px",w.scrollTop=ae-re+w.offsetTop}l.style.margin=`${_o}px 0`,l.style.minHeight=z+"px",l.style.maxHeight=j+"px",r==null||r(),requestAnimationFrame(()=>g.current=!0)}},[y,s.trigger,s.valueNode,l,d,w,x,S,s.dir,r]);Vi(()=>T(),[T]);const[N,P]=b.useState();Vi(()=>{d&&P(window.getComputedStyle(d).zIndex)},[d]);const R=b.useCallback(M=>{M&&_.current===!0&&(T(),k==null||k(),_.current=!1)},[T,k]);return m.jsx(Wce,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:g,onScrollButtonChange:R,children:m.jsx("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:N},children:m.jsx(bn.div,{...i,ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})});n4.displayName=Hce;var Uce="SelectPopperPosition",n1=b.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:i=_o,...s}=e,o=Cb(n);return m.jsx(vb,{...o,...s,ref:t,align:r,collisionPadding:i,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});n1.displayName=Uce;var[Wce,ck]=cf(Qc,{}),r1="SelectViewport",r4=b.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...i}=e,s=sc(r1,n),o=ck(r1,n),l=sr(t,s.onViewportChange),u=b.useRef(0);return m.jsxs(m.Fragment,{children:[m.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),m.jsx(Sb.Slot,{scope:n,children:m.jsx(bn.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:l,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:$t(i.onScroll,d=>{const f=d.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:y}=o;if(y!=null&&y.current&&p){const g=Math.abs(u.current-f.scrollTop);if(g>0){const _=window.innerHeight-_o*2,w=parseFloat(p.style.minHeight),x=parseFloat(p.style.height),S=Math.max(w,x);if(S<_){const k=S+g,T=Math.min(_,k),N=k-T;p.style.height=T+"px",p.style.bottom==="0px"&&(f.scrollTop=N>0?N:0,p.style.justifyContent="flex-end")}}}u.current=f.scrollTop})})})]})});r4.displayName=r1;var i4="SelectGroup",[qce,Vce]=cf(i4),Yce=b.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,i=Di();return m.jsx(qce,{scope:n,id:i,children:m.jsx(bn.div,{role:"group","aria-labelledby":i,...r,ref:t})})});Yce.displayName=i4;var s4="SelectLabel",Kce=b.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,i=Vce(s4,n);return m.jsx(bn.div,{id:i.id,...r,ref:t})});Kce.displayName=s4;var Ty="SelectItem",[Gce,o4]=cf(Ty),a4=b.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:i=!1,textValue:s,...o}=e,l=ic(Ty,n),u=sc(Ty,n),d=l.value===r,[f,p]=b.useState(s??""),[y,g]=b.useState(!1),_=sr(t,k=>{var T;return(T=u.itemRefCallback)==null?void 0:T.call(u,k,r,i)}),w=Di(),x=b.useRef("touch"),S=()=>{i||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return m.jsx(Gce,{scope:n,value:r,disabled:i,textId:w,isSelected:d,onItemTextChange:b.useCallback(k=>{p(T=>T||((k==null?void 0:k.textContent)??"").trim())},[]),children:m.jsx(Sb.ItemSlot,{scope:n,value:r,disabled:i,textValue:f,children:m.jsx(bn.div,{role:"option","aria-labelledby":w,"data-highlighted":y?"":void 0,"aria-selected":d&&y,"data-state":d?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...o,ref:_,onFocus:$t(o.onFocus,()=>g(!0)),onBlur:$t(o.onBlur,()=>g(!1)),onClick:$t(o.onClick,()=>{x.current!=="mouse"&&S()}),onPointerUp:$t(o.onPointerUp,()=>{x.current==="mouse"&&S()}),onPointerDown:$t(o.onPointerDown,k=>{x.current=k.pointerType}),onPointerMove:$t(o.onPointerMove,k=>{var T;x.current=k.pointerType,i?(T=u.onItemLeave)==null||T.call(u):x.current==="mouse"&&k.currentTarget.focus({preventScroll:!0})}),onPointerLeave:$t(o.onPointerLeave,k=>{var T;k.currentTarget===document.activeElement&&((T=u.onItemLeave)==null||T.call(u))}),onKeyDown:$t(o.onKeyDown,k=>{var N;((N=u.searchRef)==null?void 0:N.current)!==""&&k.key===" "||(Ice.includes(k.key)&&S(),k.key===" "&&k.preventDefault())})})})})});a4.displayName=Ty;var Zh="SelectItemText",l4=b.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:i,...s}=e,o=ic(Zh,n),l=sc(Zh,n),u=o4(Zh,n),d=Bce(Zh,n),[f,p]=b.useState(null),y=sr(t,S=>p(S),u.onItemTextChange,S=>{var k;return(k=l.itemTextRefCallback)==null?void 0:k.call(l,S,u.value,u.disabled)}),g=f==null?void 0:f.textContent,_=b.useMemo(()=>m.jsx("option",{value:u.value,disabled:u.disabled,children:g},u.value),[u.disabled,u.value,g]),{onNativeOptionAdd:w,onNativeOptionRemove:x}=d;return Vi(()=>(w(_),()=>x(_)),[w,x,_]),m.jsxs(m.Fragment,{children:[m.jsx(bn.span,{id:u.textId,...s,ref:y}),u.isSelected&&o.valueNode&&!o.valueNodeHasChildren?cu.createPortal(s.children,o.valueNode):null]})});l4.displayName=Zh;var c4="SelectItemIndicator",u4=b.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return o4(c4,n).isSelected?m.jsx(bn.span,{"aria-hidden":!0,...r,ref:t}):null});u4.displayName=c4;var i1="SelectScrollUpButton",d4=b.forwardRef((e,t)=>{const n=sc(i1,e.__scopeSelect),r=ck(i1,e.__scopeSelect),[i,s]=b.useState(!1),o=sr(t,r.onScrollButtonChange);return Vi(()=>{if(n.viewport&&n.isPositioned){let l=function(){const d=u.scrollTop>0;s(d)};const u=n.viewport;return l(),u.addEventListener("scroll",l),()=>u.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),i?m.jsx(h4,{...e,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}}):null});d4.displayName=i1;var s1="SelectScrollDownButton",f4=b.forwardRef((e,t)=>{const n=sc(s1,e.__scopeSelect),r=ck(s1,e.__scopeSelect),[i,s]=b.useState(!1),o=sr(t,r.onScrollButtonChange);return Vi(()=>{if(n.viewport&&n.isPositioned){let l=function(){const d=u.scrollHeight-u.clientHeight,f=Math.ceil(u.scrollTop)<d;s(f)};const u=n.viewport;return l(),u.addEventListener("scroll",l),()=>u.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),i?m.jsx(h4,{...e,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}}):null});f4.displayName=s1;var h4=b.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...i}=e,s=sc("SelectScrollButton",n),o=b.useRef(null),l=Eb(n),u=b.useCallback(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return b.useEffect(()=>()=>u(),[u]),Vi(()=>{var f;const d=l().find(p=>p.ref.current===document.activeElement);(f=d==null?void 0:d.ref.current)==null||f.scrollIntoView({block:"nearest"})},[l]),m.jsx(bn.div,{"aria-hidden":!0,...i,ref:t,style:{flexShrink:0,...i.style},onPointerDown:$t(i.onPointerDown,()=>{o.current===null&&(o.current=window.setInterval(r,50))}),onPointerMove:$t(i.onPointerMove,()=>{var d;(d=s.onItemLeave)==null||d.call(s),o.current===null&&(o.current=window.setInterval(r,50))}),onPointerLeave:$t(i.onPointerLeave,()=>{u()})})}),Xce="SelectSeparator",Zce=b.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return m.jsx(bn.div,{"aria-hidden":!0,...r,ref:t})});Zce.displayName=Xce;var o1="SelectArrow",Qce=b.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,i=Cb(n),s=ic(o1,n),o=sc(o1,n);return s.open&&o.position==="popper"?m.jsx(yb,{...i,...r,ref:t}):null});Qce.displayName=o1;var Jce="SelectBubbleInput",p4=b.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const i=b.useRef(null),s=sr(r,i),o=Roe(t);return b.useEffect(()=>{const l=i.current;if(!l)return;const u=window.HTMLSelectElement.prototype,f=Object.getOwnPropertyDescriptor(u,"value").set;if(o!==t&&f){const p=new Event("change",{bubbles:!0});f.call(l,t),l.dispatchEvent(p)}},[o,t]),m.jsx(bn.select,{...n,style:{...Xj,...n.style},ref:s,defaultValue:t})});p4.displayName=Jce;function m4(e){return e===""||e===void 0}function g4(e){const t=ra(e),n=b.useRef(""),r=b.useRef(0),i=b.useCallback(o=>{const l=n.current+o;t(l),(function u(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>u(""),1e3))})(l)},[t]),s=b.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return b.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,i,s]}function v4(e,t,n){const i=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let o=eue(e,Math.max(s,0));i.length===1&&(o=o.filter(d=>d!==n));const u=o.find(d=>d.textValue.toLowerCase().startsWith(i.toLowerCase()));return u!==n?u:void 0}function eue(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var tue=V3,nue=K3,rue=X3,iue=Z3,sue=Q3,oue=J3,aue=r4,lue=a4,cue=l4,uue=u4,due=d4,fue=f4,[kb]=Ua("Tooltip",[nc]),Tb=nc(),y4="TooltipProvider",hue=700,a1="tooltip.open",[pue,uk]=kb(y4),b4=e=>{const{__scopeTooltip:t,delayDuration:n=hue,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:s}=e,o=b.useRef(!0),l=b.useRef(!1),u=b.useRef(0);return b.useEffect(()=>{const d=u.current;return()=>window.clearTimeout(d)},[]),m.jsx(pue,{scope:t,isOpenDelayedRef:o,delayDuration:n,onOpen:b.useCallback(()=>{window.clearTimeout(u.current),o.current=!1},[]),onClose:b.useCallback(()=>{window.clearTimeout(u.current),u.current=window.setTimeout(()=>o.current=!0,r)},[r]),isPointerInTransitRef:l,onPointerInTransitChange:b.useCallback(d=>{l.current=d},[]),disableHoverableContent:i,children:s})};b4.displayName=y4;var Ip="Tooltip",[mue,um]=kb(Ip),_4=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:s,disableHoverableContent:o,delayDuration:l}=e,u=uk(Ip,e.__scopeTooltip),d=Tb(t),[f,p]=b.useState(null),y=Di(),g=b.useRef(0),_=o??u.disableHoverableContent,w=l??u.delayDuration,x=b.useRef(!1),[S,k]=Kc({prop:r,defaultProp:i??!1,onChange:M=>{M?(u.onOpen(),document.dispatchEvent(new CustomEvent(a1))):u.onClose(),s==null||s(M)},caller:Ip}),T=b.useMemo(()=>S?x.current?"delayed-open":"instant-open":"closed",[S]),N=b.useCallback(()=>{window.clearTimeout(g.current),g.current=0,x.current=!1,k(!0)},[k]),P=b.useCallback(()=>{window.clearTimeout(g.current),g.current=0,k(!1)},[k]),R=b.useCallback(()=>{window.clearTimeout(g.current),g.current=window.setTimeout(()=>{x.current=!0,k(!0),g.current=0},w)},[w,k]);return b.useEffect(()=>()=>{g.current&&(window.clearTimeout(g.current),g.current=0)},[]),m.jsx(gb,{...d,children:m.jsx(mue,{scope:t,contentId:y,open:S,stateAttribute:T,trigger:f,onTriggerChange:p,onTriggerEnter:b.useCallback(()=>{u.isOpenDelayedRef.current?R():N()},[u.isOpenDelayedRef,R,N]),onTriggerLeave:b.useCallback(()=>{_?P():(window.clearTimeout(g.current),g.current=0)},[P,_]),onOpen:N,onClose:P,disableHoverableContent:_,children:n})})};_4.displayName=Ip;var l1="TooltipTrigger",w4=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=um(l1,n),s=uk(l1,n),o=Tb(n),l=b.useRef(null),u=sr(t,l,i.onTriggerChange),d=b.useRef(!1),f=b.useRef(!1),p=b.useCallback(()=>d.current=!1,[]);return b.useEffect(()=>()=>document.removeEventListener("pointerup",p),[p]),m.jsx(sm,{asChild:!0,...o,children:m.jsx(bn.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:u,onPointerMove:$t(e.onPointerMove,y=>{y.pointerType!=="touch"&&!f.current&&!s.isPointerInTransitRef.current&&(i.onTriggerEnter(),f.current=!0)}),onPointerLeave:$t(e.onPointerLeave,()=>{i.onTriggerLeave(),f.current=!1}),onPointerDown:$t(e.onPointerDown,()=>{i.open&&i.onClose(),d.current=!0,document.addEventListener("pointerup",p,{once:!0})}),onFocus:$t(e.onFocus,()=>{d.current||i.onOpen()}),onBlur:$t(e.onBlur,i.onClose),onClick:$t(e.onClick,i.onClose)})})});w4.displayName=l1;var dk="TooltipPortal",[gue,vue]=kb(dk,{forceMount:void 0}),x4=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,s=um(dk,t);return m.jsx(gue,{scope:t,forceMount:n,children:m.jsx(ho,{present:n||s.open,children:m.jsx(of,{asChild:!0,container:i,children:r})})})};x4.displayName=dk;var Xd="TooltipContent",S4=b.forwardRef((e,t)=>{const n=vue(Xd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...s}=e,o=um(Xd,e.__scopeTooltip);return m.jsx(ho,{present:r||o.open,children:o.disableHoverableContent?m.jsx(E4,{side:i,...s,ref:t}):m.jsx(yue,{side:i,...s,ref:t})})}),yue=b.forwardRef((e,t)=>{const n=um(Xd,e.__scopeTooltip),r=uk(Xd,e.__scopeTooltip),i=b.useRef(null),s=sr(t,i),[o,l]=b.useState(null),{trigger:u,onClose:d}=n,f=i.current,{onPointerInTransitChange:p}=r,y=b.useCallback(()=>{l(null),p(!1)},[p]),g=b.useCallback((_,w)=>{const x=_.currentTarget,S={x:_.clientX,y:_.clientY},k=xue(S,x.getBoundingClientRect()),T=Sue(S,k),N=Eue(w.getBoundingClientRect()),P=kue([...T,...N]);l(P),p(!0)},[p]);return b.useEffect(()=>()=>y(),[y]),b.useEffect(()=>{if(u&&f){const _=x=>g(x,f),w=x=>g(x,u);return u.addEventListener("pointerleave",_),f.addEventListener("pointerleave",w),()=>{u.removeEventListener("pointerleave",_),f.removeEventListener("pointerleave",w)}}},[u,f,g,y]),b.useEffect(()=>{if(o){const _=w=>{const x=w.target,S={x:w.clientX,y:w.clientY},k=(u==null?void 0:u.contains(x))||(f==null?void 0:f.contains(x)),T=!Cue(S,o);k?y():T&&(y(),d())};return document.addEventListener("pointermove",_),()=>document.removeEventListener("pointermove",_)}},[u,f,o,d,y]),m.jsx(E4,{...e,ref:s})}),[bue,_ue]=kb(Ip,{isInside:!1}),wue=ese("TooltipContent"),E4=b.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:s,onPointerDownOutside:o,...l}=e,u=um(Xd,n),d=Tb(n),{onClose:f}=u;return b.useEffect(()=>(document.addEventListener(a1,f),()=>document.removeEventListener(a1,f)),[f]),b.useEffect(()=>{if(u.trigger){const p=y=>{const g=y.target;g!=null&&g.contains(u.trigger)&&f()};return window.addEventListener("scroll",p,{capture:!0}),()=>window.removeEventListener("scroll",p,{capture:!0})}},[u.trigger,f]),m.jsx(sf,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:p=>p.preventDefault(),onDismiss:f,children:m.jsxs(vb,{"data-state":u.stateAttribute,...d,...l,ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[m.jsx(wue,{children:r}),m.jsx(bue,{scope:n,isInside:!0,children:m.jsx(Qj,{id:u.contentId,role:"tooltip",children:i||r})})]})})});S4.displayName=Xd;var C4="TooltipArrow",k4=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=Tb(n);return _ue(C4,n).isInside?null:m.jsx(yb,{...i,...r,ref:t})});k4.displayName=C4;function xue(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),s=Math.abs(t.left-e.x);switch(Math.min(n,r,i,s)){case s:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Sue(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function Eue(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function Cue(e,t){const{x:n,y:r}=e;let i=!1;for(let s=0,o=t.length-1;s<t.length;o=s++){const l=t[s],u=t[o],d=l.x,f=l.y,p=u.x,y=u.y;f>r!=y>r&&n<(p-d)*(r-f)/(y-f)+d&&(i=!i)}return i}function kue(e){const t=e.slice();return t.sort((n,r)=>n.x<r.x?-1:n.x>r.x?1:n.y<r.y?-1:n.y>r.y?1:0),Tue(t)}function Tue(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const i=e[r];for(;t.length>=2;){const s=t[t.length-1],o=t[t.length-2];if((s.x-o.x)*(i.y-o.y)>=(s.y-o.y)*(i.x-o.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const s=n[n.length-1],o=n[n.length-2];if((s.x-o.x)*(i.y-o.y)>=(s.y-o.y)*(i.x-o.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var Rue=b4,Aue=_4,Nue=w4,Mue=x4,Pue=S4,Iue=k4;const T4=b.createContext(!1);function Oue({blocked:e,children:t}){return m.jsx(T4.Provider,{value:e,children:t})}function dm(){return b.useContext(T4)}function Rb({...e}){return m.jsx(Rce,{"data-slot":"popover",...e})}function Ab({...e}){return m.jsx(Ace,{"data-slot":"popover-trigger",...e})}function Nb({className:e,align:t="center",sideOffset:n=4,inert:r,"aria-disabled":i,...s}){const o=dm();return m.jsx(Nce,{children:m.jsx(Mce,{"data-slot":"popover-content",align:t,sideOffset:n,className:Ye("z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-hidden data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),inert:o||r?!0:void 0,"aria-disabled":o?!0:i,"data-relay-interaction-blocked":o?"true":void 0,...s})})}const F2=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,$2=uz,Lue=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return $2(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:i,defaultVariants:s}=t,o=Object.keys(i).map(d=>{const f=n==null?void 0:n[d],p=s==null?void 0:s[d];if(f===null)return null;const y=F2(f)||F2(p);return i[d][y]}),l=n&&Object.entries(n).reduce((d,f)=>{let[p,y]=f;return y===void 0||(d[p]=y),d},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,f)=>{let{class:p,className:y,...g}=f;return Object.entries(g).every(_=>{let[w,x]=_;return Array.isArray(x)?x.includes({...s,...l}[w]):{...s,...l}[w]===x})?[...d,p,y]:d},[]);return $2(e,o,u,n==null?void 0:n.class,n==null?void 0:n.className)},Due=Lue("inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-normal whitespace-nowrap transition-[color,background-color,border-color,box-shadow,opacity] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/75 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function gt({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const s=r?Qie:"button";return m.jsx(s,{"data-slot":"button","data-variant":t,"data-size":n,className:Ye(Due({variant:t,size:n,className:e})),...i})}function uf({...e}){return m.jsx(cce,{"data-slot":"dropdown-menu",...e})}function df({...e}){return m.jsx(uce,{"data-slot":"dropdown-menu-trigger",...e})}function ff({className:e,sideOffset:t=4,inert:n,"aria-disabled":r,...i}){const s=dm();return m.jsx(dce,{children:m.jsx(fce,{"data-slot":"dropdown-menu-content",sideOffset:t,className:Ye("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),inert:s||n?!0:void 0,"aria-disabled":s?!0:r,"data-relay-interaction-blocked":s?"true":void 0,...i})})}function ni({className:e,inset:t,variant:n="default",...r}){return m.jsx(pce,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:Ye("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function t0({className:e,children:t,checked:n,...r}){return m.jsxs(mce,{"data-slot":"dropdown-menu-checkbox-item",className:Ye("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),checked:n,...r,children:[m.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:m.jsx(gce,{children:m.jsx(Co,{className:"size-4"})})}),t]})}function nv({className:e,inset:t,...n}){return m.jsx(hce,{"data-slot":"dropdown-menu-label","data-inset":t,className:Ye("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...n})}function Ld({className:e,...t}){return m.jsx(vce,{"data-slot":"dropdown-menu-separator",className:Ye("-mx-1 my-1 h-px bg-border",e),...t})}const Bue={"no-proxy":{heading:"还没有连接开发机",body:"在开发机上启动 DEV Anywhere,本页会显示可连接的开发机"},"client-token-missing":{heading:"需要 client token",body:"Relay 已启用客户端访问控制,请在设置中填写"},"client-token-invalid":{heading:"client token 无效",body:"client token 无效或已过期,请在设置中更新"},"no-session":{heading:"没有选中的会话",body:""},"no-messages":{heading:"开始对话",body:""}};function Uc({variant:e,action:t}){const{heading:n,body:r}=Bue[e];return e==="no-messages"?m.jsx("div",{className:"flex h-full w-full items-center justify-center animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:m.jsx("p",{className:"text-sm text-muted-foreground",children:n})}):m.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-6 px-6 text-center animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[m.jsx("h2",{className:"text-2xl font-semibold",children:n}),r&&m.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:r}),t&&m.jsx("div",{children:t})]})}const zue={online:"bg-[var(--color-status-success)]",offline:"bg-[var(--muted-foreground)]",connecting:"bg-[var(--color-status-working)] animate-pulse"},jue={online:"开发机在线",offline:"开发机离线",connecting:"正在连接开发机"};function c1({status:e,className:t}){return m.jsx("span",{className:Ye("inline-block w-2 h-2 rounded-full shrink-0",zue[e],t),role:"status","aria-label":jue[e]})}function ss({...e}){return m.jsx(UC,{"data-slot":"dialog",...e})}function Fue({...e}){return m.jsx(WC,{"data-slot":"dialog-portal",...e})}function $ue({...e}){return m.jsx(db,{"data-slot":"dialog-close",...e})}function Hue({className:e,...t}){return m.jsx(qC,{"data-slot":"dialog-overlay",className:Ye("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function os({className:e,children:t,showCloseButton:n=!0,focusSurfaceOnOpen:r=!1,onOpenAutoFocus:i,inert:s,"aria-disabled":o,...l}){const u=dm();return m.jsxs(Fue,{"data-slot":"dialog-portal",children:[m.jsx(Hue,{}),m.jsxs(VC,{"data-slot":"dialog-content",className:Ye("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),onOpenAutoFocus:d=>{i==null||i(d),!(!r||d.defaultPrevented)&&(d.preventDefault(),d.currentTarget.focus({preventScroll:!0}))},inert:u||s?!0:void 0,"aria-disabled":u?!0:o,"data-relay-interaction-blocked":u?"true":void 0,...l,children:[t,n&&m.jsxs(db,{"data-slot":"dialog-close",className:"absolute top-2 right-2 flex size-11 items-center justify-center rounded-md opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[m.jsx(ou,{}),m.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function as({className:e,...t}){return m.jsx("div",{"data-slot":"dialog-header",className:Ye("flex flex-col gap-2 text-center sm:text-left",e),...t})}function Fs({className:e,showCloseButton:t=!1,children:n,...r}){return m.jsxs("div",{"data-slot":"dialog-footer",className:Ye("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end max-sm:[&_button]:min-h-11",e),...r,children:[n,t&&m.jsx(db,{asChild:!0,children:m.jsx(gt,{variant:"outline",children:"Close"})})]})}function Yi({className:e,...t}){return m.jsx(k5,{"data-slot":"dialog-title",className:Ye("text-lg leading-none font-semibold",e),...t})}function _s({className:e,...t}){return m.jsx(T5,{"data-slot":"dialog-description",className:Ye("text-sm text-muted-foreground",e),...t})}function Uue(e){return`“${(e==null?void 0:e.name)??(e==null?void 0:e.proxyId)??"这台开发机"}”只会从当前 Relay 的开发机列表中移除。不会删除机器上的文件或会话,也不会阻止它再次连接;以后重新运行时,它会重新出现在列表中。`}function Wue({open:e,target:t,removing:n,onOpenChange:r,onConfirm:i}){return m.jsx(ss,{open:e,onOpenChange:s=>{n||r(s)},children:m.jsxs(os,{"data-slot":"proxy-removal-dialog",showCloseButton:!n,onEscapeKeyDown:s=>{n&&s.preventDefault()},onPointerDownOutside:s=>{n&&s.preventDefault()},children:[m.jsxs(as,{children:[m.jsx(Yi,{children:"移除离线开发机?"}),m.jsx(_s,{children:Uue(t)})]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"ghost",disabled:n,onClick:()=>r(!1),children:"取消"}),m.jsxs(gt,{type:"button",variant:"destructive",disabled:n||!t,"aria-busy":n||void 0,onClick:i,"data-slot":"proxy-removal-confirm",children:[n&&m.jsx(ii,{className:"size-4 animate-spin","aria-hidden":"true"}),n?"正在移除":"移除"]})]})]})})}const Uv=80,que=8,Vue=1.2;function H2(e){return Math.max(0,Math.min(Uv,e))}function Yue({proxyId:e,name:t,selected:n,revealed:r,disabled:i=!1,onRevealedChange:s,onRemove:o}){const l=t??e,u=b.useRef(null),d=b.useRef(!1),[f,p]=b.useState(null),y=f??(r?Uv:0),g=f!==null;function _(k){var T,N;if(!(i||k.pointerType!=="touch"&&k.pointerType!=="pen")&&!k.target.closest("button")){u.current={pointerId:k.pointerId,startX:k.clientX,startY:k.clientY,startOffset:r?Uv:0,axis:"pending"};try{(N=(T=k.currentTarget).setPointerCapture)==null||N.call(T,k.pointerId)}catch{}}}function w(k){const T=u.current;if(!T||T.pointerId!==k.pointerId)return;const N=k.clientX-T.startX,P=k.clientY-T.startY;if(T.axis==="pending"){if(Math.hypot(N,P)<que)return;T.axis=Math.abs(N)>Math.abs(P)*Vue?"horizontal":"vertical"}T.axis!=="vertical"&&(k.preventDefault(),p(H2(T.startOffset-N)))}function x(k,T=!1){var R,M;const N=u.current;if(!N||N.pointerId!==k.pointerId)return;u.current=null;try{(M=(R=k.currentTarget).releasePointerCapture)==null||M.call(R,k.pointerId)}catch{}if(N.axis!=="horizontal"||T){p(null);return}k.preventDefault();const P=f??H2(N.startOffset-(k.clientX-N.startX));p(null),s(P>=Uv/2),d.current=!0,window.setTimeout(()=>{d.current=!1},0)}function S(k){if(d.current){d.current=!1,k.preventDefault();return}r&&s(!1)}return m.jsxs("li",{className:"relative h-11 overflow-hidden rounded-md border border-border bg-card","data-slot":"proxy-item","data-swipeable":"true","data-proxy-id":e,"data-online":"false","data-revealed":r||void 0,children:[m.jsxs("div",{className:"relative z-10 flex h-full w-full touch-pan-y select-none items-center gap-3 bg-card px-3 text-left text-muted-foreground transition-transform duration-200 ease-out motion-reduce:transition-none",style:{transform:`translateX(-${y}px)`,transitionDuration:g?"0ms":void 0},title:"这台开发机离线。向左滑动可移除。","data-slot":"proxy-swipe-foreground","data-offset":y,onPointerDown:_,onPointerMove:w,onPointerUp:k=>x(k),onPointerCancel:k=>x(k,!0),onClick:S,children:[m.jsx(c1,{status:"offline"}),m.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-normal",children:l}),n&&m.jsx(Co,{className:"size-4 shrink-0 text-primary","aria-label":"已选"}),m.jsx("span",{className:"shrink-0 text-xs",children:"离线"})]}),m.jsx("button",{type:"button",className:`absolute inset-y-0 right-0 z-0 flex w-20 items-center justify-center bg-destructive text-sm font-medium text-white outline-none transition-colors hover:bg-destructive/90 focus-visible:z-20 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset disabled:pointer-events-none disabled:opacity-50 ${r?"":"pointer-events-none"}`,tabIndex:r?0:-1,disabled:i,"aria-label":`移除 ${l}`,"aria-hidden":r?void 0:!0,"data-slot":"proxy-mobile-remove",onClick:o,children:"移除"})]})}function R4({layout:e,variant:t="default"}){const n=Ie(M=>M.proxies),r=Ie(M=>M.proxyListLoaded),i=Ie(M=>M.relayClientAuthIssue),s=Ie(M=>M.selectedProxyId),o=Ie(M=>M.proxySwitchTarget),l=rs(),u=ws(),[d,f]=b.useState(!1),[p,y]=b.useState(null),[g,_]=b.useState(null),[w,x]=b.useState(null);async function S(M,L){if(o)return;const X=Ft;if(!X){We.error("请先连接开发机");return}const U=L??M,V=s!==null&&s!==M;Ie.getState().setProxySwitchTarget({proxyId:M,name:U});try{const j=await X.selectProxy(M);if(!j.success){We.error(`无法连接 ${U}:${j.error??"未知错误"}`);return}const A=X.getPreviewScope();if(!A||A.proxyId!==M||A.bindingId!==j.bindingId)throw Tt.dispose(),X.clearBoundProxy(),new Error("开发机绑定状态无效,请重试");Tt.activate(X,A),Tt.syncWebSnapshot(A).catch(D=>{D instanceof Error&&D.name==="AbortError"||console.error("[proxy-switcher] web preview snapshot failed",D)}),Tt.syncDeviceSnapshot(A).catch(D=>{D instanceof Error&&D.name==="AbortError"||console.error("[proxy-switcher] device preview snapshot failed",D)}),V&&(Gt.getState().prepareForProxySwitch(U),Li.getState().prepareForProxySwitch()),Tr("local",wn.proxyId,M),Ie.getState().setProxy(M,L??null),Ie.getState().setProxyOnline(!0),Ie.getState().transitionToPhase("session_browsing"),X.sendControl({type:"session_list_request"}),X.requestProxyInfo().then(D=>{if(Ie.getState().selectedProxyId!==M||!Tt.isActive(X,A))return;const O=Li.getState();O.setHomePath(D.homePath),O.setAgentCli(D.agentCli)}).catch(D=>{Tt.isActive(X,A)&&console.error("[proxy-switcher] post-bind proxy info fetch failed",D)}),X.requestAgentStatuses().then(D=>{if(Ie.getState().selectedProxyId!==M||!Tt.isActive(X,A))return;const O=Gt.getState();for(const I of D)O.setAgentStatus(I.sessionId,I.payload)}).catch(D=>{Tt.isActive(X,A)&&console.error("[proxy-switcher] post-bind data fetch failed",D)}),MC(X).then(D=>{D.status==="failed"&&console.error("[proxy-switcher] post-bind data fetch failed",D.error)}),f(!1),(e==="page"||l.pathname.startsWith("/chat/")||l.pathname.startsWith("/preview/device/"))&&u("/sessions")}catch(j){const A=j instanceof Error?j.message:"未知错误";We.error(`无法连接 ${U}:${A}`)}finally{Ie.getState().setProxySwitchTarget(null)}}function k(M){M.online||w||(y(null),_({proxyId:M.proxyId,...M.name?{name:M.name}:{}}))}async function T(){const M=g;if(!M||w)return;const L=Ft;if(!L){We.error("Relay 连接不可用,请稍后重试");return}const X=Ie.getState().proxies.find(U=>U.proxyId===M.proxyId);if(!X){if(!Ie.getState().proxyListLoaded){We.info("正在重新连接 Relay,请稍后再试");return}fp(M.proxyId,L)&&u("/"),We.info("这台开发机已经不在列表中"),_(null);return}if(X.online){We.warning("这台开发机已重新上线,未移除"),_(null);return}x(M.proxyId),$re(M.proxyId);try{const U=await L.removeOfflineProxy(M.proxyId);if(U.success){Cd(M.proxyId),fp(M.proxyId,L)&&u("/"),We.success(`已移除 ${M.name??M.proxyId}`),_(null);return}if(U.errorCode===Rr.PROXY_ONLINE){Cd(M.proxyId),We.warning("这台开发机已重新上线,未移除"),_(null),L.listProxies();return}if(U.errorCode===Rr.PROXY_NOT_FOUND){Cd(M.proxyId),fp(M.proxyId,L)&&u("/"),We.info("这台开发机已经不在列表中"),_(null),L.listProxies();return}Cd(M.proxyId),We.error(U.error??"无法移除开发机,请重试")}catch(U){We.error(U instanceof Error?U.message:"无法移除开发机,请重试"),L.listProxies()}finally{x(null)}}const N=m.jsx(Wue,{open:g!==null,target:g,removing:w!==null,onOpenChange:M=>{M||_(null)},onConfirm:()=>void T()});if(e==="page")return i==="missing_client_token"?m.jsx(Uc,{variant:"client-token-missing"}):i==="invalid_client_token"?m.jsx(Uc,{variant:"client-token-invalid"}):r?n.length===0?m.jsx(Uc,{variant:"no-proxy"}):m.jsxs(m.Fragment,{children:[m.jsxs("div",{className:"flex h-full flex-col gap-3 overflow-auto p-4",children:[m.jsx("h3",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"开发机"}),m.jsx("ul",{role:"list",className:"flex flex-col gap-2",children:n.map(M=>{const L=(o==null?void 0:o.proxyId)===M.proxyId,X=o!==null;return M.online?m.jsx("li",{children:m.jsxs("button",{type:"button","data-slot":"proxy-item","data-proxy-id":M.proxyId,"data-online":"true","data-selecting":L||void 0,disabled:X||w!==null,"aria-busy":L||void 0,onClick:()=>S(M.proxyId,M.name),className:Ye("flex h-11 min-h-[44px] w-full items-center gap-3 rounded-md border bg-card px-3 text-left transition-colors disabled:cursor-not-allowed disabled:hover:bg-card",L?"border-primary/40 bg-accent text-accent-foreground":"border-border hover:bg-accent",X&&!L||w!==null?"opacity-50":""),"aria-pressed":s===M.proxyId,children:[m.jsx(c1,{status:"online"}),m.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-normal",children:M.name??M.proxyId}),L?m.jsxs(m.Fragment,{children:[m.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:"正在连接"}),m.jsx(ii,{className:"size-4 shrink-0 animate-spin text-primary","aria-hidden":!0})]}):s===M.proxyId?m.jsx(Co,{className:"size-4 shrink-0 text-primary","aria-label":"已选"}):null]})},M.proxyId):m.jsx(Yue,{proxyId:M.proxyId,name:M.name,selected:s===M.proxyId,revealed:p===M.proxyId,disabled:X||w!==null,onRevealedChange:U=>y(U?M.proxyId:null),onRemove:()=>k(M)},M.proxyId)})})]}),N]}):m.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 text-muted-foreground animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[m.jsx(ii,{className:"h-5 w-5 animate-spin","aria-hidden":!0}),m.jsx("p",{className:"text-sm",children:"连接中..."})]});const P=n.find(M=>M.proxyId===s),R=(P==null?void 0:P.name)??(P==null?void 0:P.proxyId)??"未选择开发机";return m.jsxs(m.Fragment,{children:[m.jsxs(Rb,{open:d,onOpenChange:f,children:[m.jsx(Ab,{asChild:!0,children:m.jsxs("button",{type:"button","data-slot":"proxy-switcher-trigger",className:Ye("group transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",t==="sidebarChrome"?"inline-flex min-h-9 min-w-0 max-w-full items-center justify-start gap-1.5 rounded-md text-left text-foreground hover:text-primary":"flex h-10 w-full items-center gap-2 rounded-md border border-border bg-background px-4 hover:bg-accent"),"aria-label":`当前连接:${R}`,children:[t==="default"&&m.jsx("span",{className:"h-4 w-4 shrink-0","aria-hidden":!0}),m.jsx("span",{className:Ye("truncate",t==="sidebarChrome"?"min-w-0 text-base font-semibold leading-none":"flex-1 text-center text-sm font-normal"),children:R}),m.jsx(Ql,{className:"h-4 w-4 text-muted-foreground shrink-0 transition-transform group-data-[state=open]:rotate-180","aria-hidden":!0})]})}),m.jsx(Nb,{align:"start",className:"w-[260px] p-1",children:n.length===0?m.jsx("div",{className:"text-xs text-muted-foreground p-2",children:"暂无可连接开发机"}):m.jsx("ul",{role:"list",className:"flex flex-col",children:n.map(M=>{const L=(o==null?void 0:o.proxyId)===M.proxyId,X=o!==null;return m.jsxs("li",{className:"group flex min-w-0 items-center rounded-md",children:[m.jsxs("button",{type:"button","data-slot":"proxy-item","data-proxy-id":M.proxyId,"data-online":M.online,"data-selecting":L||void 0,disabled:!M.online||X,"aria-busy":L||void 0,onClick:()=>S(M.proxyId,M.name),className:Ye("flex h-9 min-w-0 flex-1 items-center gap-2 rounded-md px-2 text-left transition-colors disabled:cursor-not-allowed disabled:hover:bg-transparent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",L?"bg-accent text-accent-foreground":"hover:bg-accent",X&&!L?"opacity-50":"",M.online?"":"opacity-50"),"aria-pressed":s===M.proxyId,title:M.online?void 0:"这台开发机离线",children:[m.jsx(c1,{status:M.online?"online":"offline"}),m.jsx("span",{className:"text-sm font-normal flex-1 truncate min-w-0",children:M.name??M.proxyId}),L?m.jsx(ii,{className:"h-4 w-4 animate-spin text-primary shrink-0","aria-label":"正在连接"}):s===M.proxyId?m.jsx(Co,{className:"h-4 w-4 text-primary shrink-0","aria-label":"已选"}):null,!M.online&&!L&&m.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:"离线"})]}),!M.online&&m.jsxs(uf,{children:[m.jsx(df,{asChild:!0,children:m.jsx(gt,{type:"button",variant:"ghost",size:"icon-xs",className:"mr-1 size-8 text-muted-foreground opacity-60 hover:opacity-100 focus-visible:opacity-100",disabled:X||w!==null,"aria-label":`${M.name??M.proxyId} 操作`,"data-slot":"proxy-row-menu-trigger",children:m.jsx(Ky,{"aria-hidden":"true"})})}),m.jsx(ff,{align:"end","data-slot":"proxy-row-menu",children:m.jsxs(ni,{variant:"destructive","data-slot":"proxy-row-remove-item",onSelect:U=>{U.stopPropagation(),k(M)},children:[m.jsx(az,{"aria-hidden":"true"}),"移除开发机"]})})]})]},M.proxyId)})})})]}),N]})}function Kue({delayDuration:e=0,...t}){return m.jsx(Rue,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function hf({...e}){return m.jsx(Aue,{"data-slot":"tooltip",...e})}function pf({...e}){return m.jsx(Nue,{"data-slot":"tooltip-trigger",...e})}function mf({className:e,sideOffset:t=0,children:n,hideArrow:r=!1,...i}){return m.jsx(Mue,{children:m.jsxs(Pue,{"data-slot":"tooltip-content",sideOffset:t,className:Ye("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...i,children:[n,!r&&m.jsx(Iue,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}function fu({...e}){return m.jsx(UC,{"data-slot":"sheet",...e})}function Gue({...e}){return m.jsx(Toe,{"data-slot":"sheet-trigger",...e})}function Xue({...e}){return m.jsx(WC,{"data-slot":"sheet-portal",...e})}function Zue({className:e,...t}){return m.jsx(qC,{"data-slot":"sheet-overlay",className:Ye("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function hu({className:e,overlayClassName:t,children:n,side:r="right",showCloseButton:i=!0,focusSurfaceOnOpen:s=!1,onOpenAutoFocus:o,inert:l,"aria-disabled":u,...d}){const f=dm();return m.jsxs(Xue,{children:[m.jsx(Zue,{className:t}),m.jsxs(VC,{"data-slot":"sheet-content",className:Ye("fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500",r==="right"&&"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",r==="left"&&"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",r==="top"&&"inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",r==="bottom"&&"inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",e),onOpenAutoFocus:p=>{o==null||o(p),!(!s||p.defaultPrevented)&&(p.preventDefault(),p.currentTarget.focus({preventScroll:!0}))},inert:f||l?!0:void 0,"aria-disabled":f?!0:u,"data-relay-interaction-blocked":f?"true":void 0,...d,children:[n,i&&m.jsxs(db,{"data-slot":"sheet-close",className:"absolute top-2 right-2 flex size-11 items-center justify-center rounded-md opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:pointer-events-none data-[state=open]:bg-secondary",children:[m.jsx(ou,{className:"size-4"}),m.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function gf({className:e,...t}){return m.jsx("div",{"data-slot":"sheet-header",className:Ye("flex flex-col gap-1.5 p-4",e),...t})}function pu({className:e,...t}){return m.jsx(k5,{"data-slot":"sheet-title",className:Ye("font-semibold text-foreground",e),...t})}function Mb({className:e,...t}){return m.jsx(T5,{"data-slot":"sheet-description",className:Ye("text-sm text-muted-foreground",e),...t})}const Que={claude:"Claude Code",codex:"Codex",kimi:"Kimi Code"},U2=["claude","codex","kimi"];function Pb(e){return Que[e]}function A4(e,t){return U2.indexOf(e)-U2.indexOf(t)}function Op(e){return e.provider}const u1=60*1e3,d1=60*u1,Jue=24*d1;function N4(e,t=Date.now()){const n=t-e;if(n<u1)return"刚刚";if(n<d1)return`${Math.floor(n/u1)} 分钟前`;if(n<Jue)return`${Math.floor(n/d1)} 小时前`;const r=new Date(e),i=r.getMonth()+1,s=r.getDate(),o=String(r.getHours()).padStart(2,"0"),l=String(r.getMinutes()).padStart(2,"0");return`${i} 月 ${s} 日 ${o}:${l}`}const W2={idle:{dot:"bg-[var(--color-status-success)]",text:"text-[var(--color-status-success)]",label:"空闲"},working:{dot:"bg-[var(--color-status-working)] animate-pulse",text:"text-[var(--color-status-working)]",label:"工作中"},compacting:{dot:"bg-[var(--color-status-compacting)] animate-pulse",text:"text-[var(--color-status-compacting)]",label:"压缩中"},waiting_approval:{dot:"bg-[var(--color-status-warning)]",text:"text-[var(--color-status-warning)]",label:"等待审批"},error:{dot:"bg-[var(--color-status-error)]",text:"text-[var(--color-status-error)]",label:"出错"},terminated:{dot:"bg-muted-foreground",text:"text-muted-foreground",label:"已终止"}};function f1(e){return e.kind!=="terminal"?W2[e.state]:e.state==="terminated"?W2.terminated:e.state==="error"?{dot:"bg-[var(--color-status-error)]",text:"text-[var(--color-status-error)]",label:"已断开"}:{dot:"bg-[var(--color-status-success)]",text:"text-[var(--color-status-success)]",label:"运行中"}}function ede({session:e}){const t=f1(e);return m.jsx("span",{className:Ye("inline-block size-2 rounded-full shrink-0",t.dot),"aria-label":`会话状态:${t.label}`,role:"status"})}function tde({mode:e}){if(e!=="pty"&&e!=="json")return null;const t=e==="json"?"聊天视图":"终端视图",n=e==="json"?sC:aC;return m.jsx("span",{className:"inline-flex h-5 w-4 shrink-0 items-center justify-center text-muted-foreground",role:"img","aria-label":t,title:t,"data-slot":"session-mode-icon","data-mode":e,children:m.jsx(n,{className:"size-3.5","aria-hidden":"true"})})}function nde({session:e,selected:t,now:n,onClick:r,onRename:i,onTerminate:s}){const o=e.lastActive,l=e.cwd,u=sb(e.name),d=LC(e),f=e.nameLocked&&e.name?e.name:d||(u==="New Session"?e.sessionId.slice(0,8):u),p=N4(o,n),y=e.mode==="pty"&&e.ptyOwner==="local-terminal",g=e.kind==="terminal"?"终止终端":y?"断开远程连接":"终止会话";return m.jsxs("li",{className:Ye("relative flex items-center gap-2 px-4 py-2 w-full min-w-0 transition-colors","min-h-[44px]","hover:bg-accent",t&&"dev-sidebar-active-row"),"data-slot":"session-row","data-session-id":e.sessionId,"data-selected":t,children:[t&&m.jsx("span",{className:"dev-sidebar-active-indicator absolute left-0 top-0 bottom-0 w-[2px]","aria-hidden":"true"}),m.jsxs("button",{type:"button","data-slot":"session-row-select",onClick:r,className:"flex min-h-11 flex-col justify-center gap-1 flex-1 min-w-0 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-sm md:min-h-0","aria-pressed":t,children:[m.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[m.jsx(ede,{session:e}),m.jsx("span",{className:"text-sm font-normal truncate flex-1",title:l,children:f})]}),m.jsxs("span",{className:"flex items-center gap-1.5 text-xs leading-5 h-5",children:[m.jsx(tde,{mode:e.mode}),m.jsx("span",{className:"text-muted-foreground/60 shrink-0","aria-hidden":"true",children:"·"}),e.kind!=="terminal"&&m.jsxs(m.Fragment,{children:[m.jsx("span",{className:"font-mono text-muted-foreground shrink-0",children:Pb(e.provider)}),m.jsx("span",{className:"text-muted-foreground/60 shrink-0","aria-hidden":"true",children:"·"})]}),m.jsx("span",{className:Ye("shrink-0",f1(e).text),children:f1(e).label}),p&&m.jsxs(m.Fragment,{children:[m.jsx("span",{className:"text-muted-foreground/60 shrink-0","aria-hidden":"true",children:"·"}),m.jsx("span",{className:"text-muted-foreground shrink-0 tabular-nums",children:p})]})]})]}),(i||s)&&m.jsxs(uf,{children:[m.jsx(df,{asChild:!0,children:m.jsx(gt,{variant:"ghost",size:"icon-xs",className:"size-11 md:size-6","aria-label":"会话操作","data-slot":"session-row-menu-trigger",onClick:_=>_.stopPropagation(),children:m.jsx(Ky,{"aria-hidden":"true"})})}),m.jsxs(ff,{align:"end","data-slot":"session-row-menu",children:[i&&m.jsx(ni,{"data-slot":"session-row-rename-item",onSelect:_=>{_.stopPropagation(),i()},children:"重命名"}),s&&m.jsx(ni,{variant:"destructive","data-slot":"session-row-terminate-item",onSelect:_=>{_.stopPropagation(),s()},children:g})]})]})]})}function co(e){const[t,n]=b.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(e).matches);return b.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia(e),i=s=>n(s.matches);return n(r.matches),r.addEventListener("change",i),()=>r.removeEventListener("change",i)},[e]),t}function rde({session:e,now:t,disabled:n,loading:r,onClick:i,modeTag:s}){const o=m.jsx(ide,{title:e.title,modeTag:s}),l=m.jsx("span",{className:"text-xs text-muted-foreground tabular-nums",children:N4(e.updatedAt,t)}),u=m.jsxs("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[o,l]});return m.jsx("li",{"data-slot":"history-row","data-session-id":e.id,"data-loading":r?"true":void 0,className:"group w-full flex items-stretch",children:m.jsxs("button",{type:"button",onClick:i,disabled:n,"data-slot":"history-row-primary",className:Ye("min-w-0 flex-1 flex items-start gap-2 pl-10 pr-4 py-2 min-h-[50px]","text-left transition-colors outline-none","hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50 disabled:cursor-wait disabled:hover:bg-transparent"),"aria-label":`恢复会话:${e.title}`,children:[u,m.jsx(W7,{className:Ye("mt-0.5 size-3.5 shrink-0 text-muted-foreground transition-opacity",r?"animate-pulse opacity-100":"opacity-0 group-hover:opacity-100 group-focus-visible:opacity-100"),"aria-hidden":"true"})]})})}function ide({title:e,modeTag:t}){return m.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[m.jsx("span",{className:"text-sm font-normal truncate min-w-0",title:e,children:e}),t&&m.jsx(sde,{mode:t})]})}function sde({mode:e}){const t=e==="json"?"聊天视图":"终端视图",n=e==="json"?sC:aC;return m.jsx("span",{"data-slot":"history-mode-tag","data-mode":e,role:"img","aria-label":t,title:t,className:Ye("inline-flex size-5 shrink-0 items-center justify-center rounded border","border-border bg-muted/50 text-muted-foreground"),children:m.jsx(n,{className:"size-3","aria-hidden":"true"})})}function M4({providerLabel:e}){return m.jsx("div",{className:"grid min-w-0 gap-4","data-slot":"bypass-permission-warning",role:"alert",children:m.jsxs("div",{className:"flex min-w-0 items-start gap-3 text-sm",children:[m.jsx(LY,{className:"mt-0.5 size-5 shrink-0 text-destructive","aria-hidden":"true"}),m.jsxs("div",{className:"grid min-w-0 gap-2",children:[m.jsxs("p",{className:"font-medium text-foreground",children:[e," 将不再请求工具审批。"]}),m.jsx("p",{className:"text-muted-foreground",children:"Agent 可以直接执行命令、修改或删除文件,并可能绕过部分沙箱保护。"})]})]})})}function ode({now:e}){const t=Gt(V=>V.historySessions),n=Gt(V=>V.historyLoadStatus),[r,i]=b.useState(null),[s,o]=b.useState(null),[l,u]=b.useState("json"),[d,f]=b.useState("default"),[p,y]=b.useState(!1),[g,_]=b.useState(new Set),[w,x]=b.useState(new Set),S=ws(),k=b.useMemo(()=>{const V=new Map;for(const j of t){const A=Op(j);let D=V.get(A);D||(D=new Map,V.set(A,D));const O=P4(j.projectDir),I=D.get(O);I?I.sessions.push(j):D.set(O,{dir:O,sessions:[j]})}return Array.from(V.entries()).sort(([j],[A])=>A4(j,A)).map(([j,A])=>({provider:j,sessions:Array.from(A.values()).flatMap(D=>D.sessions),projects:Array.from(A.values()).map(D=>({dir:D.dir,shortDir:sb(D.dir),sessions:D.sessions}))}))},[t]);function T(V){o(V),u(ade(V)),f(lde(V))}async function N(V,j,A){if(r)return;const D=Ft;if(!D){We.error("请先连接开发机");return}i(V.id);const O=Op(V);try{const I=await D.createSession({kind:"agent",cwd:V.projectDir,mode:j,provider:O,resumeSessionId:V.id,...A?{permissionMode:A}:{}});if(!I.success){if(I.errorCode===Rr.SESSION_ALREADY_ACTIVE){Gt.getState().setCodexActiveWriterConflict({...I.activeWriterPid?{activeWriterPid:I.activeWriterPid}:{}}),o(null);return}We.error(`恢复失败:${I.error}`);return}if(I.kind!=="agent"){We.error("恢复失败:开发机返回了错误的会话类型");return}const B={sessionId:I.sessionId,kind:"agent",...I.name!==void 0?{name:I.name}:{},...I.nameLocked!==void 0?{nameLocked:I.nameLocked}:{},state:"idle",cwd:I.cwd,lastActive:I.lastActive,provider:I.provider},F=I.mode==="pty"?{...B,mode:"pty",ptyOwner:I.ptyOwner}:{...B,mode:"json"};Gt.getState().addSession(F),S(`/chat/${I.sessionId}?mode=${I.mode}`),o(null)}catch(I){We.error(`恢复失败:${I instanceof Error?I.message:String(I)}`)}finally{i(null)}}function P(){const V=Ft;!V||Gt.getState().historyLoadStatus==="loading"||MC(V).then(j=>{j.status==="failed"&&We.error(j.error instanceof Error?j.error.message:String(j.error))})}function R(V,j){const A=q2(V,j);x(D=>{const O=new Set(D);return O.has(A)?O.delete(A):O.add(A),O})}function M(V){_(j=>{const A=new Set(j);return A.has(V)?A.delete(V):A.add(V),A})}const L=t.length>0,X=n==="loading",U=s?I4():[];return m.jsxs("div",{"data-slot":"history-list",className:"flex flex-col",children:[m.jsxs("div",{className:"flex min-h-11 w-full items-center gap-1.5 px-4 py-1.5 md:min-h-[36px]",children:[m.jsxs("button",{type:"button",onClick:()=>L&&y(V=>!V),disabled:!L,"aria-expanded":L?p:void 0,"data-slot":"history-section-header","data-expanded":p,className:Ye("flex min-w-0 flex-1 items-center gap-1.5 rounded-md py-0.5 text-left","transition-colors outline-none","hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring","disabled:cursor-default disabled:hover:text-inherit"),children:[m.jsxs("h3",{className:"min-w-0 text-sm font-semibold text-foreground",children:["全部会话",L?m.jsxs("span",{className:"ml-1 text-muted-foreground/70 font-normal",children:["· ",t.length]}):null]}),L?m.jsx(dp,{className:Ye("size-3.5 shrink-0 text-muted-foreground/80 transition-transform",p&&"rotate-90"),"aria-hidden":"true"}):null]}),m.jsx(gt,{type:"button",variant:"ghost",size:"icon-sm","aria-label":"刷新全部会话","aria-busy":X,title:X?"正在加载":"刷新",onClick:P,disabled:X,"data-slot":"history-refresh",className:"size-11 md:size-8",children:m.jsx(em,{className:Ye("size-3.5",X&&"animate-spin motion-reduce:animate-none"),"aria-hidden":"true"})})]}),!L&&X&&m.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 text-sm text-muted-foreground/80","data-slot":"history-loading",role:"status","aria-live":"polite",children:[m.jsx(ii,{className:"size-3.5 shrink-0 animate-spin motion-reduce:animate-none","aria-hidden":"true"}),m.jsx("span",{children:"正在加载会话记录..."})]}),!L&&n==="idle"&&m.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/80","data-slot":"history-idle",role:"status",children:"会话记录尚未加载"}),!L&&n==="error"&&m.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/80","data-slot":"history-error",role:"status",children:"会话记录加载失败,请点击刷新重试"}),L&&n==="error"&&m.jsx("div",{className:"px-4 pb-2 text-xs text-muted-foreground/80","data-slot":"history-stale",role:"status",children:"刷新失败,当前显示上次加载的结果"}),!L&&n==="loaded"&&m.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/70","data-slot":"history-empty",children:"暂无会话记录"}),L&&p&&m.jsx("ul",{role:"list",className:"flex flex-col",children:k.map(V=>{const j=g.has(V.provider);return m.jsxs("li",{children:[m.jsxs("button",{type:"button",onClick:()=>M(V.provider),"aria-expanded":!j,"data-slot":"history-provider-header","data-expanded":!j,className:Ye("w-full flex items-center gap-2 px-4 pt-2 pb-1 min-h-[32px]","text-xs text-muted-foreground text-left transition-colors outline-none","hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"),children:[m.jsx("span",{className:"font-mono",children:Pb(V.provider)}),m.jsx("span",{className:"h-px flex-1 bg-border/70","aria-hidden":"true"}),m.jsx("span",{className:"tabular-nums",children:V.sessions.length}),m.jsx(dp,{className:Ye("size-3.5 shrink-0 text-muted-foreground/80 transition-transform",!j&&"rotate-90"),"aria-hidden":"true"})]}),!j&&m.jsx("ul",{role:"list",className:"flex flex-col",children:V.projects.map(A=>{const D=q2(V.provider,A.dir),O=w.has(D);return m.jsxs("li",{children:[m.jsxs("button",{type:"button",onClick:()=>R(V.provider,A.dir),"aria-expanded":O,"data-slot":"history-group-header","data-expanded":O,className:Ye("w-full flex items-center gap-1.5 pl-6 pr-4 py-2 min-h-[36px]","text-left transition-colors outline-none","hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"),children:[m.jsx("span",{className:"text-sm font-mono truncate flex-1 min-w-0",title:A.dir,children:A.shortDir}),m.jsx("span",{className:"text-xs text-muted-foreground/80 tabular-nums shrink-0",children:A.sessions.length}),m.jsx(dp,{className:Ye("size-3.5 shrink-0 text-muted-foreground/80 transition-transform",O&&"rotate-90"),"aria-hidden":"true"})]}),O&&m.jsx("ul",{role:"list",className:"flex flex-col",children:A.sessions.map(I=>m.jsx(rde,{session:I,now:e,disabled:r!==null,loading:r===I.id,onClick:()=>T(I),modeTag:I.preferredMode},I.id))})]},D)})})]},V.provider)})}),m.jsx(cde,{session:s,open:s!==null,modes:U,mode:l,permissionMode:d,submitting:r!==null,onOpenChange:V=>{V||o(null)},onModeChange:u,onPermissionModeChange:f,onConfirm:()=>{s&&N(s,l,d)}})]})}function q2(e,t){return`${e}:${P4(t)}`}function P4(e){const t=e.trim();return!t||t==="/"?t||"/":t.replace(/\/+$/,"")||"/"}function I4(){return["json","pty"]}function ade(e){const t=I4();return e.preferredMode&&t.includes(e.preferredMode)?e.preferredMode:t[0]??"json"}function lde(e){return Op(e)==="codex"?"auto":"default"}function cde({session:e,open:t,modes:n,mode:r,permissionMode:i,submitting:s,onOpenChange:o,onModeChange:l,onPermissionModeChange:u,onConfirm:d}){const[f,p]=b.useState(!1),y=i==="bypassPermissions",g=co("(min-width: 768px)"),_=e?Op(e):null,w=_==="codex",x=_==="kimi";b.useEffect(()=>{t||p(!1)},[t]);const S=f?m.jsx(M4,{providerLabel:e?Pb(Op(e)):"Agent"}):m.jsxs("div",{className:"grid min-w-0 gap-4",children:[m.jsxs("div",{className:"grid min-w-0 gap-2",children:[m.jsx("span",{className:"text-sm font-medium",children:"模式"}),m.jsxs("div",{role:"radiogroup","aria-label":"恢复模式",className:"grid min-w-0 grid-cols-2 gap-2",children:[n.includes("json")&&m.jsx(V2,{checked:r==="json",label:"聊天",icon:m.jsx(sC,{className:"size-4","aria-hidden":"true"}),disabled:s,onClick:()=>l("json")}),n.includes("pty")&&m.jsx(V2,{checked:r==="pty",label:"终端",icon:m.jsx(aC,{className:"size-4","aria-hidden":"true"}),disabled:s,onClick:()=>l("pty")})]})]}),m.jsxs("div",{className:"grid min-w-0 gap-2",children:[m.jsx("span",{className:"text-sm font-medium",children:"权限模式"}),m.jsxs("div",{role:"radiogroup","aria-label":"权限模式",className:"grid min-w-0 gap-2",children:[!w&&m.jsx(rv,{checked:i==="default",label:x?"手工审批":"严格审批",description:x?"工具调用会在 Web 中请求确认。":"所有需要权限的操作都要确认。",disabled:s,onClick:()=>u("default")}),m.jsx(rv,{checked:i==="auto",label:w?"按需审批":x?"自动审批":"自动判定",description:w?"Codex 在需要时请求确认。":x?"Kimi Code 使用原生 yolo 模式自动审批。":"交给 Agent CLI 的原生策略判断。",disabled:s,onClick:()=>u("auto")}),x&&m.jsx(rv,{checked:i==="plan",label:"只读规划",description:"Kimi Code 使用只读规划模式。",disabled:s,onClick:()=>u("plan")}),m.jsx(rv,{checked:i==="bypassPermissions",label:x?"全自动":"跳过全部审批",description:x?"危险模式,Kimi Code 将全自动执行。":"危险模式,会跳过工具审批和部分沙箱保护。",destructive:!0,disabled:s,onClick:()=>u("bypassPermissions")})]})]})]}),k=m.jsxs(m.Fragment,{children:[m.jsx(gt,{type:"button",variant:"ghost",disabled:s,onClick:()=>{f?p(!1):o(!1)},children:f?"返回":"取消"}),m.jsx(gt,{type:"button",variant:f?"destructive":"default",disabled:s,onClick:()=>{if(y&&!f){p(!0);return}d()},"data-slot":f?"bypass-permission-confirm":void 0,children:s?"恢复中...":f?"确认":"恢复"})]});return g?m.jsx(ss,{open:t,onOpenChange:o,children:m.jsxs(os,{focusSurfaceOnOpen:!0,className:"min-w-0 sm:max-w-md","data-slot":"history-restore-dialog",children:[m.jsxs(as,{className:"min-w-0",children:[m.jsx(Yi,{children:f?"跳过全部审批?":"恢复会话"}),m.jsx(_s,{className:"min-w-0 truncate pr-10 sm:pr-0",title:e==null?void 0:e.title,children:(e==null?void 0:e.title)??""})]}),S,m.jsx(Fs,{children:k})]})}):m.jsx(fu,{open:t,onOpenChange:o,children:m.jsxs(hu,{side:"bottom",focusSurfaceOnOpen:!0,className:"inset-x-2 w-auto max-h-[calc(100dvh-0.75rem)] min-w-0 overflow-hidden rounded-t-xl border bg-background p-0","data-slot":"history-restore-dialog",children:[m.jsxs(gf,{className:"min-w-0 shrink-0 px-4 pb-2 pt-4 text-left",children:[m.jsx(pu,{children:f?"跳过全部审批?":"恢复会话"}),m.jsx(Mb,{className:"min-w-0 truncate pr-10",title:e==null?void 0:e.title,children:(e==null?void 0:e.title)??""})]}),m.jsx("div",{className:"min-h-0 overflow-y-auto px-4 pb-3","data-slot":"history-restore-body",children:S}),m.jsx("div",{className:"shrink-0 border-t border-border/70 bg-background px-4 pb-[max(theme(spacing.4),env(safe-area-inset-bottom))] pt-3","data-slot":"history-restore-footer",children:m.jsx("div",{className:"flex flex-col-reverse gap-2 [&_button]:min-h-11 [&_button]:w-full",children:k})})]})})}function V2({checked:e,label:t,icon:n,disabled:r,onClick:i}){return m.jsxs("button",{type:"button",role:"radio","aria-label":t,"aria-checked":e,disabled:r,onClick:i,className:Ye("grid min-h-11 w-full min-w-0 max-w-full grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-2 rounded-md border px-3 text-sm outline-none transition-colors md:h-10 md:min-h-0","focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-wait disabled:opacity-60",e?"border-primary text-foreground":"border-border text-muted-foreground hover:bg-accent/60 hover:text-foreground"),children:[n,m.jsx("span",{className:"min-w-0 text-center",children:t}),m.jsx(Co,{className:Ye("size-3.5 justify-self-end transition-opacity",e?"opacity-100":"opacity-0"),"aria-hidden":"true"})]})}function rv({checked:e,label:t,description:n,destructive:r,disabled:i,onClick:s}){return m.jsxs("button",{type:"button",role:"radio","aria-label":t,"aria-checked":e,disabled:i,onClick:s,className:Ye("grid w-full min-w-0 max-w-full grid-cols-[auto_minmax(0,1fr)_auto] items-start gap-3 rounded-md border p-3 text-left outline-none transition-colors","focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-wait disabled:opacity-60",e?r?"border-destructive/70":"border-primary":"border-border hover:bg-accent/60"),children:[m.jsx("span",{className:Ye("mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-full border",e?r?"border-destructive":"border-primary":"border-muted-foreground/50"),"aria-hidden":"true",children:e&&m.jsx("span",{className:Ye("size-2 rounded-full",r?"bg-destructive":"bg-primary")})}),m.jsxs("span",{className:"grid min-w-0 gap-1",children:[m.jsx("span",{className:Ye("text-sm font-medium",r?"text-destructive":"text-foreground"),children:t}),m.jsx("span",{className:"min-w-0 break-words text-xs leading-5 text-muted-foreground",children:n})]}),e&&m.jsx(Co,{className:Ye("mt-0.5 size-4 shrink-0",r?"text-destructive":"text-primary"),"aria-hidden":"true"})]})}function Ib({...e}){return m.jsx(tue,{"data-slot":"select",...e})}function Ob({...e}){return m.jsx(rue,{"data-slot":"select-value",...e})}function Lb({className:e,size:t="default",children:n,...r}){return m.jsxs(nue,{"data-slot":"select-trigger","data-size":t,className:Ye("flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/75 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...r,children:[n,m.jsx(iue,{asChild:!0,children:m.jsx(Ql,{className:"size-4 opacity-50"})})]})}function Db({className:e,children:t,position:n="item-aligned",align:r="center",inert:i,"aria-disabled":s,...o}){const l=dm();return m.jsx(sue,{children:m.jsxs(oue,{"data-slot":"select-content",className:Ye("relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,align:r,inert:l||i?!0:void 0,"aria-disabled":l?!0:s,"data-relay-interaction-blocked":l?"true":void 0,...o,children:[m.jsx(ude,{}),m.jsx(aue,{className:Ye("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:t}),m.jsx(dde,{})]})})}function Bb({className:e,children:t,...n}){return m.jsxs(lue,{"data-slot":"select-item",className:Ye("relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...n,children:[m.jsx("span",{"data-slot":"select-item-indicator",className:"absolute right-2 flex size-3.5 items-center justify-center",children:m.jsx(uue,{children:m.jsx(Co,{className:"size-4"})})}),m.jsx(cue,{children:t})]})}function ude({className:e,...t}){return m.jsx(due,{"data-slot":"select-scroll-up-button",className:Ye("flex cursor-default items-center justify-center py-1",e),...t,children:m.jsx(rC,{className:"size-4"})})}function dde({className:e,...t}){return m.jsx(fue,{"data-slot":"select-scroll-down-button",className:Ye("flex cursor-default items-center justify-center py-1",e),...t,children:m.jsx(Ql,{className:"size-4"})})}function fde(e,t,n){var u;if(t==="insert"){const d=e.split("@").pop()??"",f=qd((n==null?void 0:n.baseCwd)??d)==="\\",p=Math.max(d.lastIndexOf("/"),f?d.lastIndexOf("\\"):-1);return{currentPath:p>=0?d.slice(0,p+1):f?".\\":"./",query:d.slice(p+1).toLowerCase()}}const r=Hl((n==null?void 0:n.baseCwd)??"");if(!e)return{currentPath:wo(r),query:""};const i=AC(r,e);if(!i)return{currentPath:"",query:""};const s=RC(i),o=qd(i);return e.endsWith("/")||o==="\\"&&e.endsWith("\\")||i===s||i===r||((u=n==null?void 0:n.knownDirs)==null?void 0:u.has(i))?{currentPath:wo(i),query:""}:{currentPath:wo(s),query:i.slice(i.lastIndexOf(o)+1).toLowerCase()}}function n0(e,t){return AC(e,t)}const O4=b.forwardRef(function({filter:t,onSelect:n,onNavigate:r,onSelectCurrentDirectory:i,onCreateDirectory:s,mode:o="insert",placement:l="floating",dirsOnly:u=!1,fileExtensions:d,includeHidden:f=!1,autoHighlightFirst:p=!0,title:y},g){const _=Li(he=>f?he.treeWithHidden:he.tree),w=Li(he=>he.cwd),x=Li(he=>he.homePath),S=o==="insert"?w:x||w,k=b.useMemo(()=>new Set(_.keys()),[_]),T=b.useMemo(()=>fde(t,o,{baseCwd:S,knownDirs:k}),[t,o,S,k]),N=T.currentPath,P=b.useMemo(()=>n0(S,N),[S,N]),R=T.query,M=b.useRef(new Map),[L,X]=b.useState(!1),[U,V]=b.useState(""),[j,A]=b.useState(!1),[D,O]=b.useState(null),[I,B]=b.useState(0);b.useEffect(()=>{if(!P)return;const he=`${f?"hidden":"default"}\0${P}`;if(_.has(P))return;const He=Ft;if(!He)return;let Nt=!1;O(Ze=>(Ze==null?void 0:Ze.path)===P?null:Ze);let ye=M.current.get(he);if(!ye){ye=He.requestDirectoryList(P,{includeHidden:f}),M.current.set(he,ye);const Ze=()=>{M.current.get(he)===ye&&M.current.delete(he)};ye.then(Ze,Ze)}return ye.then(Ze=>{if(!Nt){if(Ze.error!==void 0||Ze.errorCode!==void 0){O({path:P,message:Ze.error||"读取失败"});return}Li.getState().setDirEntries(Ze.path,Ze.entries,Ze.includeHidden)}},Ze=>{Nt||O({path:P,message:Ze instanceof Error?Ze.message:"读取失败"})}),()=>{Nt=!0}},[P,f,_,I]);const F=(D==null?void 0:D.path)===P?D:null,Y=!_.has(P)&&!F,z=b.useMemo(()=>d==null?void 0:d.map(he=>he.startsWith(".")?he.toLowerCase():`.${he.toLowerCase()}`),[d]),q=b.useMemo(()=>{let he=_.get(P)??[];return u?he=he.filter(He=>He.isDir):z!=null&&z.length&&(he=he.filter(He=>He.isDir||z.some(Nt=>He.name.toLowerCase().endsWith(Nt)))),R&&(he=he.filter(He=>He.name.toLowerCase().includes(R))),he},[_,P,R,u,z]),[K,$]=b.useState(p?0:-1);b.useEffect(()=>$(p?0:-1),[p,N,R]),b.useEffect(()=>{X(!1),V("")},[P]),b.useEffect(()=>{K>=q.length&&q.length>0&&$(q.length-1)},[q.length,K]);const re=b.useRef(null),Q=b.useRef(!1);b.useEffect(()=>{var He;if(!Q.current)return;Q.current=!1;const he=(He=re.current)==null?void 0:He.querySelector(`[data-entry-index="${K}"]`);he==null||he.scrollIntoView({block:"nearest"})},[K]);const G=b.useCallback(he=>{const He=qd(S),Nt=`${wo(N,S)}${he.name}${he.isDir?He:""}`;if(o==="insert")return Nt.replace(He==="\\"?/^\.[\\/]/:/^\.\//,"");const ye=n0(S,Nt);return he.isDir?wo(ye):ye},[S,N,o]),Z=b.useCallback(he=>{const He=n0(S,he);if(!He)return;const Nt=wo(He);if(o==="select"){r(Nt);return}n(Nt)},[S,o,r,n]),ae=b.useCallback(he=>{const He=G(he);if(he.isDir){Z(He);return}n(He)},[G,Z,n]);async function le(){const he=HP(P,U);if(!(!he||!s)){A(!0);try{const He=await s(he);if(!He)return;if(V(""),X(!1),i){i(wo(He));return}Z(He)}finally{A(!1)}}}b.useImperativeHandle(g,()=>({handleKey(he){return q.length===0?!1:he.key==="ArrowDown"?(Q.current=!0,$(He=>Math.min(q.length-1,He+1)),!0):he.key==="ArrowUp"?(Q.current=!0,$(He=>Math.max(0,He-1)),!0):he.key==="Enter"&&K>=0&&!he.nativeEvent.isComposing?(ae(q[K]),!0):!1}}),[q,K,ae]);const me=b.useMemo(()=>RC(P),[P]),ke=l==="inline"?"relative w-full bg-popover border border-border rounded-md overflow-hidden":o==="insert"?"absolute bottom-full left-0 right-0 z-50 mb-2 bg-popover border border-border rounded-md shadow-lg overflow-hidden":"absolute left-0 right-0 top-full z-50 mt-2 bg-popover border border-border rounded-md shadow-lg overflow-hidden",$e=l==="inline"?"max-h-[min(11rem,30dvh)] overflow-y-auto overscroll-contain":o==="select"?"max-h-44 overflow-y-auto overscroll-contain":"max-h-60 overflow-y-auto overscroll-contain";return m.jsxs("div",{className:ke,"data-slot":"file-path-picker","data-mode":o,"data-placement":l,children:[o==="select"?m.jsxs("div",{className:"border-b border-border/70 px-3 py-2",children:[m.jsxs("div",{className:"min-w-0",children:[y?m.jsx("p",{className:"mb-2 truncate text-xs text-muted-foreground","data-slot":"file-path-picker-title",children:y}):null,m.jsx("p",{className:"truncate font-mono text-xs text-foreground","data-slot":"file-path-picker-current-directory",title:P,children:P||"正在读取路径"})]}),m.jsxs("div",{className:"mt-1 flex items-center justify-between gap-2",role:"toolbar","aria-label":"路径操作","data-slot":"file-path-picker-actions",children:[m.jsx("button",{type:"button","data-slot":"file-path-picker-parent",className:"inline-flex min-h-11 min-w-11 items-center justify-start px-0 text-xs font-medium text-primary hover:underline focus-visible:underline focus-visible:outline-none disabled:cursor-not-allowed disabled:text-muted-foreground disabled:no-underline md:min-h-8 md:min-w-0",disabled:!P||P===me,onClick:()=>Z(me),children:"上一级"}),i||s?m.jsxs("span",{className:"flex shrink-0 items-center gap-4",children:[s?m.jsx("button",{type:"button","data-slot":"file-path-picker-create-directory-toggle",className:"inline-flex min-h-11 min-w-11 items-center justify-center px-0 text-xs font-medium text-primary hover:underline focus-visible:underline focus-visible:outline-none disabled:cursor-not-allowed disabled:text-muted-foreground disabled:no-underline md:min-h-8 md:min-w-0",disabled:!P||j,onClick:()=>X(he=>!he),children:"新建目录"}):null,i?m.jsx("button",{type:"button","data-slot":"select-current-directory",className:"inline-flex min-h-11 min-w-11 items-center justify-center px-0 text-xs font-medium text-primary hover:underline focus-visible:underline focus-visible:outline-none disabled:cursor-not-allowed disabled:text-muted-foreground disabled:no-underline md:min-h-8 md:min-w-0",disabled:!P,onClick:()=>i(wo(P)),children:"选定"}):null]}):null]}),L?m.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[m.jsx("input",{type:"text","data-slot":"file-path-picker-create-directory-name",value:U,onChange:he=>V(he.target.value),onKeyDown:he=>{he.key==="Enter"&&!he.nativeEvent.isComposing&&(he.preventDefault(),le()),he.key==="Escape"&&(X(!1),V(""))},placeholder:"目录名称",className:"min-h-11 min-w-0 flex-1 rounded-md border border-border bg-input px-2 text-base outline-none focus-visible:ring-2 focus-visible:ring-ring md:h-8 md:min-h-0 md:text-sm",autoComplete:"off",autoCorrect:"off",spellCheck:!1}),m.jsx("button",{type:"button","data-slot":"file-path-picker-create-directory-submit",className:"min-h-11 rounded-md bg-primary px-3 text-sm text-primary-foreground disabled:cursor-not-allowed disabled:opacity-50 md:h-8 md:min-h-0",disabled:!HP(P,U)||j,onClick:()=>void le(),children:j?"创建中...":"创建目录"})]}):null]}):null,m.jsx("div",{className:$e,"data-slot":"file-path-picker-entries",children:F?m.jsxs("div",{"data-slot":"file-path-picker-error",className:"flex items-center justify-between gap-3 px-3 py-2",role:"alert",children:[m.jsx("span",{className:"min-w-0 text-xs text-destructive",title:F.message,children:"无法读取这个文件夹"}),m.jsx("button",{type:"button","data-slot":"file-path-picker-retry",className:"shrink-0 rounded px-2 py-1 text-xs text-primary hover:bg-primary/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>B(he=>he+1),children:"重试"})]}):q.length===0?m.jsx("div",{className:"px-3 py-2 text-xs text-muted-foreground",children:Y?"加载中...":"没有匹配的路径"}):m.jsx("ul",{ref:re,role:"list",className:"flex flex-col",children:q.map((he,He)=>m.jsx("li",{children:m.jsx("button",{type:"button",onClick:()=>ae(he),onMouseEnter:()=>$(He),className:Ye("w-full flex min-h-11 items-center gap-2 px-3 py-2 text-sm text-left transition-colors md:h-9 md:min-h-0 md:py-0",He===K&&"bg-[color-mix(in_srgb,var(--primary)_15%,transparent)]",he.isDir&&"font-semibold"),"data-slot":"file-entry","data-entry-type":he.isDir?"dir":"file","data-entry-name":he.name,"data-entry-index":He,children:m.jsxs("span",{className:"font-mono text-[13px]",children:[he.name,he.isDir?"/":""]})})},he.name))})})]})});function Y2(e,t,n){const r=Wv(e,t);return r?n==="file"?wo(RC(r)):r:t}function Wv(e,t){const n=Hl(e,t);return n?e.endsWith("/")||qd(n)==="\\"&&e.endsWith("\\")?wo(n):n:""}function fk({value:e,onValueChange:t,selectionKind:n,fileExtensions:r,includeHidden:i=!1,onCreateDirectory:s,disabled:o=!1,placeholder:l="选择路径",label:u,labelActions:d,id:f,name:p,required:y,autoFocus:g,"aria-describedby":_,"aria-invalid":w,"data-slot":x,className:S,onKeyDown:k}){const T=b.useId(),N=f??`remote-path-${T}`,P=`${N}-label`,R=Li(Q=>Q.homePath),M=co("(pointer: coarse), (hover: none)"),L=rf().deviceKind,X=M||L==="phone"||L==="tablet",[U,V]=b.useState(!1),[j,A]=b.useState(()=>Y2(e,R,n)),[D,O]=b.useState(e),I=b.useRef(null),B=b.useRef(null);b.useEffect(()=>{U||D===e||O(e)},[D,U,e]),b.useEffect(()=>{if(!U)return;function Q(G){const Z=I.current,ae=G.target;Z&&(G.composedPath().includes(Z)||ae instanceof Node&&Z.contains(ae))||(V(!1),O(e))}return document.addEventListener("click",Q),()=>document.removeEventListener("click",Q)},[U,e]),b.useEffect(()=>{o&&(V(!1),O(e))},[o,e]);const F=n!=="file";function Y(){if(o)return;const Q=Y2(e,R,n);A(Q),O(e),V(!0)}function z(){V(!1),O(e)}function q(Q){const G=Wv(Q,R);G&&(A(G),O(G),t(G),V(!1))}function K(Q){const G=Wv(Q,R);G&&A(G)}function $(Q){var G;if(U&&((G=B.current)!=null&&G.handleKey(Q))){Q.preventDefault();return}if(Q.key==="Escape"&&U){Q.preventDefault(),z();return}k==null||k(Q)}const re=U?m.jsx("div",{className:Ye(X&&"mt-2"),"data-slot":"remote-path-browser",children:m.jsx(O4,{ref:B,mode:"select",placement:X?"inline":"floating",filter:j,dirsOnly:n==="directory",fileExtensions:r,includeHidden:i,autoHighlightFirst:!X,title:l,onNavigate:K,onSelect:q,onSelectCurrentDirectory:F?q:void 0,onCreateDirectory:s})}):null;return m.jsxs("div",{className:Ye("flex min-w-0 flex-col gap-1",S),children:[m.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[m.jsx("span",{id:P,className:"min-w-0 text-sm",children:u}),d?m.jsx("div",{className:"flex shrink-0 items-center gap-4",children:d}):null]}),m.jsx("div",{ref:I,className:"relative min-w-0",onBlur:Q=>{if(!U||X)return;const G=Q.relatedTarget;G instanceof Node&&Q.currentTarget.contains(G)||window.setTimeout(()=>{var Z;(Z=I.current)!=null&&Z.contains(document.activeElement)||z()},0)},children:X?m.jsxs(m.Fragment,{children:[m.jsxs("button",{id:N,type:"button","aria-labelledby":P,"aria-describedby":_,"aria-invalid":w,"aria-expanded":U,"aria-controls":`${N}-browser`,disabled:o,"data-slot":x,"data-path-control":"button",onClick:()=>{U?z():Y()},className:"flex min-h-11 w-full min-w-0 items-center gap-2 rounded-md border border-border bg-input px-3 text-left text-base outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60",children:[m.jsx(DV,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),m.jsx("span",{className:Ye("min-w-0 flex-1 truncate font-mono",e?"text-foreground":"text-muted-foreground"),title:e||void 0,children:e||l})]}),p?m.jsx("input",{type:"hidden",name:p,value:e,required:y}):null,m.jsx("div",{id:`${N}-browser`,children:re})]}):m.jsxs(m.Fragment,{children:[m.jsx("input",{id:N,type:"text","aria-labelledby":P,"aria-describedby":_,"aria-invalid":w,name:p,required:y,autoFocus:g,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:o,value:D,"data-slot":x,"data-path-control":"input",onFocus:Y,onChange:Q=>{const G=Q.target.value,Z=Wv(G,R);O(G),A(Z||R),t(Z||G),V(!0)},onKeyDown:$,placeholder:l,className:"min-h-11 min-w-0 w-full rounded-md border border-border bg-input px-3 font-mono text-base outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60 md:h-9 md:min-h-0 md:text-sm"}),re]})})]})}const K2="工作目录不存在或不可访问:",hde=[{value:"default",label:"严格审批"},{value:"auto",label:"自动判定"},{value:"acceptEdits",label:"自动接受编辑"},{value:"plan",label:"只读规划"},{value:"bypassPermissions",label:"跳过全部审批"}],L4=[{value:"auto",label:"按需审批"},{value:"bypassPermissions",label:"跳过全部审批"}],D4=[{value:"default",label:"手工审批"},{value:"auto",label:"自动审批"},{value:"plan",label:"只读规划"},{value:"bypassPermissions",label:"全自动"}],Lp={claude:"Claude Code",codex:"Codex",kimi:"Kimi Code"};function pde(e,t){return t!==Rr.PATH_NOT_FOUND||!e.startsWith(K2)?null:e.slice(K2.length).trim()||null}function B4(e,t){if(!t)return{label:"检测中",disabled:!0};const n=t[e];return n.available?{label:"可用",disabled:!1,title:n.command}:{label:"未找到",disabled:!0,title:n.error}}function mde(e,t){return e==="codex"?L4.some(n=>n.value===t)?t:"auto":e==="kimi"?D4.some(n=>n.value===t)?t:"default":t}async function gde({relay:e,agentCli:t,form:n,timeoutMs:r=kC}){var d,f;const i=n.cwd.trim();if(!i)return{type:"validation_error",message:"请输入工作目录"};if(!e)return{type:"relay_missing",message:"请先连接开发机"};if(B4(n.provider,t).disabled){const p=(d=t==null?void 0:t[n.provider])==null?void 0:d.error;return{type:"provider_unavailable",message:p?`${Lp[n.provider]} 不可用:${p}`:`${Lp[n.provider]} 暂不可用`}}const o=n.mode,l=n.provider,u=n.name.trim();try{const p=await e.createSession({kind:"agent",cwd:i,name:u||void 0,mode:o,provider:l,permissionMode:n.permissionMode},r);if(!p.success){const w=pde(p.error,p.errorCode);return w?{type:"missing_cwd",path:w,message:"找不到这个工作目录"}:{type:"create_error",message:`创建失败:${p.error}`}}if(p.kind!=="agent")return{type:"create_error",message:"创建失败:开发机返回了错误的会话类型"};const y=((f=p.name)==null?void 0:f.trim())||void 0,g={sessionId:p.sessionId,kind:"agent",name:y,...p.nameLocked!==void 0?{nameLocked:p.nameLocked}:{},state:"idle",cwd:p.cwd,lastActive:p.lastActive,provider:p.provider};return{type:"success",session:p.mode==="pty"?{...g,mode:"pty",ptyOwner:p.ptyOwner}:{...g,mode:"json"},route:`/chat/${p.sessionId}?mode=${p.mode}`}}catch(p){return{type:"exception",message:p instanceof Error?p.message:String(p)}}}async function vde({relay:e,timeoutMs:t=kC}){var n;if(!e)return{type:"relay_missing",message:"请先连接开发机"};try{const r=await e.createSession({kind:"terminal",mode:"pty"},t);return r.success?r.kind!=="terminal"?{type:"create_error",message:"创建终端失败:开发机返回了错误的会话类型"}:{type:"success",session:{sessionId:r.sessionId,kind:"terminal",name:((n=r.name)==null?void 0:n.trim())||void 0,...r.nameLocked!==void 0?{nameLocked:r.nameLocked}:{},state:"idle",cwd:r.cwd,lastActive:r.lastActive,mode:"pty",provider:r.provider,ptyOwner:r.ptyOwner},route:`/chat/${r.sessionId}?mode=pty`}:{type:"create_error",message:`创建终端失败:${r.error}`}}catch(r){return{type:"exception",message:r instanceof Error?r.message:String(r)}}}const yde=["claude","codex","kimi"];function bde({agentCli:e,provider:t,cliPathDraftProvider:n,cliPathDraft:r,savingCliPath:i,onProviderChange:s,onCliPathDraftChange:o,onDiscardCliPathDraft:l,onSaveCliPath:u}){const d=e==null?void 0:e[t],f=(d==null?void 0:d.command)??"",p=n===t,y=p?r:f,g=p&&r.trim()!==f;return m.jsxs("section",{"aria-label":"Agent CLI",className:"flex min-w-0 flex-col gap-2",children:[m.jsx("span",{className:"text-sm",children:"Agent CLI"}),m.jsxs(Ib,{value:t,disabled:i,onValueChange:_=>s(_),children:[m.jsx(Lb,{className:"min-h-11 w-full md:min-h-0","aria-label":"Agent CLI","data-slot":"agent-cli-provider-select",children:m.jsx(Ob,{})}),m.jsx(Db,{"data-slot":"agent-cli-provider-options",children:yde.map(_=>m.jsx(Bb,{value:_,className:"min-h-11 md:min-h-0",children:Lp[_]},_))})]}),m.jsxs("div",{className:"relative min-w-0","data-slot":"agent-cli-path-card",children:[m.jsx(fk,{id:`agent-cli-path-${t}`,"data-slot":"agent-cli-path",label:"CLI 路径",value:y,onValueChange:_=>o(t,_),selectionKind:"file",includeHidden:!0,disabled:i,placeholder:"选择 CLI 可执行文件",labelActions:g?m.jsxs("div",{className:"flex items-center gap-4","data-slot":"agent-cli-path-actions",children:[m.jsx("button",{type:"button",className:"inline-flex min-h-11 min-w-11 items-center justify-center px-0 text-xs font-medium text-muted-foreground hover:underline focus-visible:underline focus-visible:outline-none disabled:cursor-not-allowed disabled:no-underline md:min-h-8 md:min-w-0",onClick:l,disabled:i,children:"取消"}),m.jsx("button",{type:"button",className:"inline-flex min-h-11 min-w-11 items-center justify-center px-0 text-xs font-medium text-primary hover:underline focus-visible:underline focus-visible:outline-none disabled:cursor-not-allowed disabled:text-muted-foreground disabled:no-underline md:min-h-8 md:min-w-0",onClick:u,disabled:i||!r.trim(),children:i?"保存中...":"保存"})]}):void 0,onKeyDown:_=>{_.key==="Enter"&&g&&(_.preventDefault(),_.stopPropagation(),u()),_.key==="Escape"&&p&&(_.preventDefault(),_.stopPropagation(),l())}},t),d!=null&&d.error&&!g?m.jsx("p",{className:"mt-1 break-all text-xs text-destructive",children:d.error}):null]})]})}function Qh({open:e,onOpenChange:t}){var Z;const[n,r]=b.useState(""),[i,s]=b.useState(""),[o,l]=b.useState("claude"),[u,d]=b.useState("pty"),[f,p]=b.useState("default"),[y,g]=b.useState(!1),[_,w]=b.useState(!1),[x,S]=b.useState(null),[k,T]=b.useState(null),[N,P]=b.useState(""),[R,M]=b.useState(!1),L=b.useRef(e);L.current=e;const X=ws(),U=Li(ae=>ae.homePath),V=Li(ae=>ae.agentCli),j=co("(min-width: 768px)");b.useEffect(()=>{e&&!i&&U&&s(U)},[e,U,i]),b.useEffect(()=>{if(!e||U&&V)return;const ae=Ft==null?void 0:Ft.requestProxyInfo();ae&&ae.then(le=>{const me=Li.getState();me.setHomePath(le.homePath),me.setAgentCli(le.agentCli)}).catch(le=>{console.error("[create-session-dialog] requestProxyInfo failed",le)})},[e,U,V]);function A(){r(""),s(""),l("claude"),d("pty"),p("default"),g(!1),S(null),T(null),P(""),M(!1)}function D(){if(f==="bypassPermissions"){g(!0);return}q()}async function O(){await q(),L.current&&g(!1)}const I=o==="codex"?L4:o==="kimi"?D4:hde,B=B4(o,V),F=k===o&&N.trim()!==(((Z=V==null?void 0:V[o])==null?void 0:Z.command)??""),Y=_||R||B.disabled||F;function z(ae){const le=mde(ae,f);le!==f&&p(le)}async function q(ae){S(null),w(!0);try{const le=await gde({relay:Ft,agentCli:V,form:{cwd:ae??i,name:n,provider:o,permissionMode:f,mode:u}});if(le.type==="success"){if(Gt.getState().addSession(le.session),!L.current)return;t(!1),A(),X(le.route);return}if(le.type==="missing_cwd"&&S(le.path),We.error(le.message),le.type==="validation_error"||le.type==="relay_missing")return}finally{w(!1)}}async function K(ae){const le=Ft;if(!le)return We.error("请先连接开发机"),null;try{const me=await le.createDirectory(ae);return me.success?(S(null),We.success("目录已创建"),me.path):(We.error(`目录创建失败:${me.error??"未知错误"}`),null)}catch(me){return We.error(me instanceof Error?me.message:String(me)),null}}function $(ae,le){T(ae),P(le)}async function re(){if(!k)return;const ae=k,le=N.trim();if(!le){We.error("请选择 Agent CLI 可执行文件");return}const me=Ft;if(!me){We.error("请先连接开发机");return}M(!0);try{const ke=await me.updateAgentCliPath(ae,le);if(ke.error||!ke.agentCli){We.error(`路径保存失败:${ke.error??"未知错误"}`);return}Li.getState().setAgentCli(ke.agentCli),We.success(`${Lp[ae]} 路径已保存`),T(null),P("")}catch(ke){We.error(ke instanceof Error?ke.message:String(ke))}finally{M(!1)}}function Q(ae){d(ae),z(o)}const G=y?m.jsxs("div",{className:"grid min-w-0 gap-5","data-slot":"bypass-permission-confirmation",children:[m.jsx(M4,{providerLabel:Lp[o]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"ghost",className:"min-h-11 md:min-h-0",onClick:()=>g(!1),disabled:_,children:"返回"}),m.jsx(gt,{type:"button",variant:"destructive",className:"min-h-11 md:min-h-0",onClick:()=>void O(),disabled:_,"data-slot":"bypass-permission-confirm",children:_?"创建中...":"确认"})]})]}):m.jsxs("form",{className:"flex min-w-0 flex-col gap-4","data-slot":"create-session-form",autoComplete:"off",onSubmit:ae=>{ae.preventDefault(),D()},children:[m.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[m.jsx("span",{className:"text-sm",children:"名称(可选)"}),m.jsx("input",{type:"text",name:"dev-anywhere-session-name",autoComplete:"off",autoCorrect:"off",spellCheck:!1,value:n,onChange:ae=>r(ae.target.value),className:"min-h-11 min-w-0 rounded-md border border-border bg-input px-3 text-base outline-none focus-visible:ring-2 focus-visible:ring-ring md:h-9 md:min-h-0 md:text-sm",placeholder:"自动生成"})]}),m.jsx(fk,{id:"create-session-cwd",name:"dev-anywhere-session-cwd","data-slot":"create-session-cwd",label:"工作目录",value:i,selectionKind:"directory",placeholder:"选择工作目录",onCreateDirectory:K,onValueChange:ae=>{s(ae),S(null)}}),x?m.jsxs("section",{role:"status","aria-live":"polite",className:"rounded-md border border-primary/50 bg-primary/10 p-3",children:[m.jsx("p",{className:"text-sm font-medium",children:"工作目录不存在"}),m.jsx("p",{className:"mt-1 break-all font-mono text-xs text-muted-foreground",children:x})]}):null,m.jsxs("section",{"aria-label":"交互方式",className:"flex min-w-0 flex-col gap-2",children:[m.jsx("span",{className:"text-sm",children:"交互方式"}),m.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-2 sm:grid-cols-2",children:[m.jsxs("button",{type:"button","aria-pressed":u==="pty",onClick:()=>Q("pty"),className:Ye("flex min-h-14 min-w-0 flex-col items-start justify-center gap-1 rounded-md border px-3 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring",u==="pty"?"border-primary/70 bg-primary/10":"border-border bg-muted/20"),children:[m.jsx("span",{className:"text-sm font-medium",children:"终端模式"}),m.jsx("span",{className:"text-xs text-muted-foreground",children:"像本地终端一样操作"})]}),m.jsxs("button",{type:"button","aria-pressed":u==="json",onClick:()=>Q("json"),className:Ye("flex min-h-14 min-w-0 flex-col items-start justify-center gap-1 rounded-md border px-3 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring",u==="json"?"border-primary/70 bg-primary/10":"border-border bg-muted/20"),children:[m.jsx("span",{className:"text-sm font-medium",children:"聊天模式"}),m.jsx("span",{className:"text-xs text-muted-foreground",children:"气泡式对话,支持 Voice Pilot"})]})]})]}),m.jsx(bde,{agentCli:V,provider:o,cliPathDraftProvider:k,cliPathDraft:N,savingCliPath:R,onProviderChange:ae=>{l(ae),z(ae),T(null),P("")},onCliPathDraftChange:$,onDiscardCliPathDraft:()=>{T(null),P("")},onSaveCliPath:()=>void re()}),m.jsxs("label",{className:"flex min-w-0 flex-col gap-2",children:[m.jsx("span",{className:"text-sm",children:"权限模式"}),m.jsxs(Ib,{value:f,onValueChange:ae=>p(ae),children:[m.jsx(Lb,{className:"w-full",children:m.jsx(Ob,{})}),m.jsx(Db,{children:I.map(ae=>m.jsx(Bb,{value:ae.value,children:ae.label},ae.value))})]})]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"ghost",className:"min-h-11 md:min-h-0",onClick:()=>t(!1),disabled:_,children:"取消"}),m.jsx(gt,{type:"submit",className:"min-h-11 md:min-h-0",disabled:Y,children:_?"创建中...":"创建"})]})]});return j?m.jsx(ss,{open:e,onOpenChange:t,children:m.jsxs(os,{className:"!w-[calc(100vw-2rem)] !max-w-none max-h-[calc(100dvh-2rem)] overflow-y-auto sm:!w-[44rem]","data-slot":"create-session-dialog",focusSurfaceOnOpen:!0,children:[m.jsx(as,{children:m.jsx(Yi,{children:y?"跳过全部审批?":"新建会话"})}),G]})}):m.jsx(fu,{open:e,onOpenChange:t,children:m.jsxs(hu,{side:"bottom",className:"inset-x-2 max-h-[calc(100dvh-0.75rem)] w-auto overflow-x-hidden overflow-y-auto rounded-t-xl border bg-background px-4 pb-[max(theme(spacing.4),env(safe-area-inset-bottom))] pt-3","data-slot":"create-session-dialog",focusSurfaceOnOpen:!0,children:[m.jsx(gf,{className:"px-0 pb-1 pt-0 text-left",children:m.jsx(pu,{children:y?"跳过全部审批?":"新建会话"})}),G]})})}function Jh({open:e,sessionId:t,initialName:n,onOpenChange:r,onRename:i}){const s=b.useMemo(()=>(n==null?void 0:n.trim())??"",[n]),[o,l]=b.useState(s),[u,d]=b.useState(null),[f,p]=b.useState(!1);b.useEffect(()=>{e&&(l(s),d(null),p(!1))},[s,e]);async function y(g){g.preventDefault();const _=o.trim();if(!_){d("会话标题不能为空");return}if(t){p(!0);try{await i(t,_),r(!1)}catch(w){d(w instanceof Error?w.message:String(w))}finally{p(!1)}}}return m.jsx(ss,{open:e,onOpenChange:r,children:m.jsx(os,{className:"sm:max-w-md","data-slot":"session-rename-dialog",children:m.jsxs("form",{className:"grid gap-4",onSubmit:g=>void y(g),children:[m.jsxs(as,{children:[m.jsx(Yi,{children:"重命名会话"}),m.jsx(_s,{children:"自定义名称会显示在会话列表和顶部标题中。"})]}),m.jsxs("div",{className:"grid gap-2",children:[m.jsx("label",{htmlFor:"session-rename-title",className:"text-sm font-medium",children:"会话标题"}),m.jsx("input",{id:"session-rename-title",value:o,autoFocus:!0,maxLength:100,"aria-invalid":!!u,"aria-describedby":u?"session-rename-error":void 0,className:Ye("h-10 rounded-md border border-input bg-background px-3 text-sm shadow-xs outline-none transition-[border-color,box-shadow]","placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/75","disabled:cursor-not-allowed disabled:opacity-50",u&&"border-destructive focus-visible:ring-destructive/20"),disabled:f,onChange:g=>{l(g.target.value),u&&d(null)}}),u?m.jsx("p",{id:"session-rename-error",className:"text-sm text-destructive",children:u}):null]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"outline",onClick:()=>r(!1),children:"取消"}),m.jsx(gt,{type:"submit",disabled:f,children:"保存"})]})]})})})}function _de(e){return(e==null?void 0:e.kind)==="agent"&&e.mode==="pty"&&e.ptyOwner==="local-terminal"}function wde(e){return(e==null?void 0:e.kind)==="terminal"}function xde(e){return _de(e)?{title:"断开远程连接?",description:"这只会断开当前页面和本地终端的连接,本地终端里的 Claude Code/Codex/Kimi Code 会继续运行。重新接入前,页面不能继续查看或输入这个会话。",confirmLabel:"断开远程连接",destructive:!1}:wde(e)?{title:"终止终端?",description:"这会停止当前终端进程,并清理这个终端会话的运行状态。终止后不能继续输入,也无法恢复正在执行的命令。",confirmLabel:"终止终端",destructive:!0}:{title:"终止会话?",description:"这会停止当前 Agent 进程,并清理这个会话的运行状态。终止后不能继续输入,也无法恢复正在执行的任务。",confirmLabel:"终止会话",destructive:!0}}function iv({open:e,session:t,onOpenChange:n,onConfirm:r}){const i=xde(t);function s(){t&&(r(t),n(!1))}return m.jsx(ss,{open:e,onOpenChange:n,children:m.jsxs(os,{"data-slot":"session-termination-dialog",children:[m.jsxs(as,{children:[m.jsx(Yi,{children:i.title}),m.jsx(_s,{children:i.description})]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"ghost",onClick:()=>n(!1),children:"取消"}),m.jsx(gt,{type:"button",variant:i.destructive?"destructive":"default",onClick:s,"data-slot":"session-termination-confirm",children:i.confirmLabel})]})]})})}function z4(e){var t,n,r,i,s,o,l,u,d,f,p,y;return e.connected===!1||e.proxyOnline===!1?"disconnected":e.routeSessionEnded||((t=e.session)==null?void 0:t.state)==="terminated"?"terminated":((n=e.session)==null?void 0:n.state)==="error"?"error":e.hasPendingApproval||((r=e.session)==null?void 0:r.state)==="waiting_approval"?"waiting_approval":((i=e.session)==null?void 0:i.state)==="compacting"?"compacting":((s=e.session)==null?void 0:s.state)==="working"?"working":((o=e.session)==null?void 0:o.state)==="idle"?"idle":((l=e.agentStatus)==null?void 0:l.phase)==="waiting_permission"||((u=e.ptyState)==null?void 0:u.state)==="approval_wait"?"waiting_approval":((d=e.agentStatus)==null?void 0:d.phase)==="thinking"||((f=e.agentStatus)==null?void 0:f.phase)==="tool_use"||((p=e.agentStatus)==null?void 0:p.phase)==="outputting"||((y=e.ptyState)==null?void 0:y.state)==="working"?"working":"idle"}function Sde(e){if(e.session.state==="error")return"error";const t=z4(e);return t==="disconnected"?e.session.state:t}const Ede=new Set(["localhost","127.0.0.1","[::1]"]),h1={cloudflare:{label:"Cloudflare Tunnel",executable:"cloudflared",installUrl:"https://developers.cloudflare.com/tunnel/downloads/"},cpolar:{label:"Cpolar",executable:"cpolar"}};function Cde(){return Si("local",wn.webPreviewTunnelProvider)==="cpolar"?"cpolar":"cloudflare"}function j4(e,t){if(e)return t==="cloudflare"?e.cloudflared:e.cpolar}function r0(e,t){var n;return((n=j4(e,t))==null?void 0:n.available)===!0}function kde(e){const t=e.trim();if(!t)return"请输入本机网站地址";let n;try{n=new URL(t)}catch{return"请输入完整的 http:// 本机网站地址"}return n.protocol!=="http:"||!Ede.has(n.hostname)||n.username!==""||n.password!==""?"只支持 localhost、127.0.0.1 或 [::1] 的 http:// 地址":null}function xh(){return{status:"idle"}}function Tde({open:e,onOpenChange:t}){const[n,r]=b.useState(""),[i,s]=b.useState(Cde),[o,l]=b.useState("local"),[u,d]=b.useState(""),[f,p]=b.useState(""),[y,g]=b.useState(""),[_,w]=b.useState(xh),[x,S]=b.useState(!1),k=b.useRef(null),T=b.useRef(null),N=b.useRef(null),P=b.useRef(null),R=b.useRef(i);R.current=i;const M=b.useRef(e);M.current=e;const L=co("(min-width: 768px)"),X=Ie(G=>G.selectedProxyId),U=Kr(G=>G.capability),V=Kr(G=>G.capabilityStatus),j=Kr(G=>G.capabilityError),A=Kr(G=>{var Z;return((Z=G.authoritative)==null?void 0:Z.scope)??null}),D=A?`${A.proxyId}\0${A.bindingId}`:null,O=b.useCallback(G=>{R.current=G,s(G),Tr("local",wn.webPreviewTunnelProvider,G)},[]);function I(){var G,Z;r(""),l("local"),d(""),p(""),g(""),w(xh()),S(!1),(G=k.current)==null||G.abort(),k.current=null,(Z=T.current)==null||Z.abort(),T.current=null,N.current=null,P.current=null}const B=b.useCallback(async G=>{var le;(le=k.current)==null||le.abort();const Z=new AbortController;k.current=Z;const ae=Tt.getActiveScope();if(!(!ae||ae.proxyId!==X))try{const me=await Tt.requestWebPreviewCapability(ae,G,{signal:Z.signal});if(!me||Z.signal.aborted||!M.current||!me.success)return;const ke=R.current,$e=ke==="cloudflare"?"cpolar":"cloudflare";!r0(me.capability,ke)&&r0(me.capability,$e)&&O($e)}catch{}},[O,X]);function F(G){!G&&x||t(G)}b.useEffect(()=>{if(!e){I();return}return B(!1),()=>{var G;(G=k.current)==null||G.abort(),k.current=null}},[B,e,D]),b.useEffect(()=>{var le;if(!e||o!=="static")return;(le=T.current)==null||le.abort(),T.current=null;const G=f.trim();if(!G){w(xh()),g("");return}const Z=new AbortController;T.current=Z,w({status:"loading"}),g("");const ae=window.setTimeout(()=>{const me=Ft,ke=Tt.getActiveScope();if(!me||!ke||ke.proxyId!==X){w({status:"error",message:"请先连接开发机"});return}Tt.inspectStaticWebPreview(ke,G,{signal:Z.signal}).then($e=>{if(!$e||Z.signal.aborted||!M.current||!Tt.isActive(me,ke))return;if(!$e.success){w({status:"error",message:$e.error});return}const he=$e.htmlEntries;if(he.length===0&&!$e.entryPath){w({status:"error",message:"这里没有可以预览的网页"});return}const He={entryPath:$e.entryPath,htmlEntries:he};w({status:"ready",path:G,result:He}),g($e.entryPath??"")}).catch($e=>{Z.signal.aborted||!M.current||$e instanceof Error&&$e.name==="AbortError"||!Tt.isActive(me,ke)||w({status:"error",message:$e instanceof Error?$e.message:"检查网页失败"})})},300);return()=>{window.clearTimeout(ae),Z.abort(),T.current===Z&&(T.current=null)}},[e,D,X,o,f]);const Y=o==="local"?kde(u):null,z=o==="static"&&_.status==="ready"&&_.path===f.trim()&&!!(_.result.entryPath||y),q=V==="loaded"&&r0(U,i),$=x||!q||!(o==="local"?Y===null:z);async function re(){var me,ke,$e;if($)return;const G=Ft;if(!G){We.error("请先连接开发机");return}let Z;if(o==="local")Z={kind:"local",url:u.trim()};else{if(_.status!=="ready"||_.path!==f.trim())return;const he=_.result.entryPath??y;if(!he)return;Z={kind:"static",path:_.path,entryPath:he}}S(!0);const ae=Tt.getActiveScope();if(!ae){S(!1),We.error("请先连接开发机");return}let le=null;try{const he=n.trim(),He=JSON.stringify({proxyId:ae.proxyId,tunnelProvider:i,source:Z,name:he||void 0});((me=N.current)==null?void 0:me.sourceKey)!==He&&(N.current={sourceKey:He,operationId:tb(`preview-operation-${i}`)}),le=N.current.operationId,P.current=le;const Nt=await Tt.createWebPreview(ae,Z,{tunnelProvider:i,operationId:le,...he?{name:he}:{}});if(P.current!==le)return;if(!Nt.accepted){((ke=N.current)==null?void 0:ke.operationId)===le&&(N.current=null),We.error(Nt.error);return}if((($e=N.current)==null?void 0:$e.operationId)===le&&(N.current=null),!M.current||!Tt.isActive(G,ae))return;t(!1)}catch(he){if(!le||P.current!==le||!M.current||!Tt.isActive(G,ae))return;We.error(he instanceof Error?he.message:"无法创建网页预览")}finally{le&&P.current===le&&(P.current=null,M.current&&S(!1))}}const Q=m.jsxs("form",{className:"flex min-w-0 flex-col gap-4","data-slot":"create-web-preview-form",autoComplete:"off",onSubmit:G=>{G.preventDefault(),re()},children:[m.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[m.jsx("span",{className:"text-sm",children:"名称(可选)"}),m.jsx("input",{type:"text",name:"dev-anywhere-web-preview-name",value:n,maxLength:256,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:x,placeholder:"自动生成","data-slot":"web-preview-name",onChange:G=>{r(G.target.value)},className:"min-h-11 min-w-0 rounded-md border border-border bg-input px-3 text-base outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60 md:h-9 md:min-h-0 md:text-sm"})]}),m.jsxs("section",{className:"flex min-w-0 flex-col gap-1","data-slot":"web-preview-tunnel-provider-field","data-provider":i,children:[m.jsx("span",{className:"text-sm",children:"内网穿透服务"}),m.jsxs(Ib,{value:i,disabled:x,onValueChange:G=>O(G),children:[m.jsx(Lb,{"aria-label":"内网穿透服务","data-slot":"web-preview-tunnel-provider-select","data-provider":i,className:"min-h-11 w-full md:min-h-0",children:m.jsx(Ob,{})}),m.jsx(Db,{"data-slot":"web-preview-tunnel-provider-options",children:Object.keys(h1).map(G=>m.jsx(Bb,{value:G,"data-slot":"web-preview-tunnel-provider-option","data-provider":G,children:h1[G].label},G))})]})]}),m.jsx(Rde,{status:V,capability:U,provider:i,error:j,disabled:x,onRetry:()=>void B(!0)}),m.jsxs("section",{"aria-label":"网页来源",className:"flex min-w-0 flex-col gap-2",children:[m.jsx("span",{className:"text-sm",children:"网页来源"}),m.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-2 sm:grid-cols-2",children:[m.jsxs("button",{type:"button","data-slot":"web-preview-source-local",disabled:x,"aria-pressed":o==="local",onClick:()=>{var G;(G=T.current)==null||G.abort(),T.current=null,w(xh()),g(""),l("local")},className:Ye("flex min-h-16 min-w-0 flex-col items-start justify-center gap-1 rounded-md border px-3 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60",o==="local"?"border-primary/70 bg-primary/10":"border-border bg-muted/20"),children:[m.jsx("span",{className:"text-sm font-medium",children:"本机网站"}),m.jsx("span",{className:"text-xs text-muted-foreground",children:"输入 localhost 地址"})]}),m.jsxs("button",{type:"button","data-slot":"web-preview-source-static",disabled:x,"aria-pressed":o==="static",onClick:()=>{var G;(G=T.current)==null||G.abort(),T.current=null,w(xh()),g(""),l("static")},className:Ye("flex min-h-16 min-w-0 flex-col items-start justify-center gap-1 rounded-md border px-3 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60",o==="static"?"border-primary/70 bg-primary/10":"border-border bg-muted/20"),children:[m.jsx("span",{className:"text-sm font-medium",children:"网页文件"}),m.jsx("span",{className:"text-xs text-muted-foreground",children:"选择 HTML 网页文件或目录"})]})]})]}),o==="local"?m.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[m.jsx("span",{className:"text-sm",children:"本机网站地址"}),m.jsx("input",{type:"url","data-slot":"web-preview-local-url","aria-label":"本机网站地址",inputMode:"url",name:"dev-anywhere-preview-local-url",autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:x,value:u,onChange:G=>{d(G.target.value)},placeholder:"http://localhost:5173","aria-invalid":u.length>0&&Y!==null,className:"min-h-11 min-w-0 rounded-md border border-border bg-input px-3 font-mono text-base outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60 md:h-9 md:min-h-0 md:text-sm"}),u.length>0&&Y?m.jsx("span",{"data-slot":"web-preview-local-url-error",className:"text-xs text-destructive",role:"alert",children:Y}):null]}):m.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[m.jsx(fk,{id:"create-web-preview-path",name:"dev-anywhere-preview-static-path","data-slot":"web-preview-static-path",label:"网页位置",value:f,selectionKind:"file-or-directory",fileExtensions:[".html",".htm"],disabled:x,placeholder:"选择 HTML 网页文件或目录",onValueChange:p}),m.jsx(Ade,{inspection:_,selectedEntryPath:y,disabled:x,onEntryPathChange:G=>{g(G)}})]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"ghost","data-slot":"create-web-preview-cancel",className:"min-h-11 md:min-h-0",onClick:()=>F(!1),disabled:x,children:"取消"}),m.jsx(gt,{type:"submit",className:"min-h-11 md:min-h-0",disabled:$,"data-slot":"create-web-preview-submit",children:x?"正在创建...":"创建预览"})]})]});return L?m.jsx(ss,{open:e,onOpenChange:F,children:m.jsxs(os,{showCloseButton:!x,onEscapeKeyDown:G=>{x&&G.preventDefault()},onPointerDownOutside:G=>{x&&G.preventDefault()},className:"!w-[calc(100vw-2rem)] !max-w-none max-h-[calc(100dvh-2rem)] overflow-y-auto sm:!w-[40rem]","data-slot":"create-web-preview-dialog",focusSurfaceOnOpen:!0,children:[m.jsxs(as,{children:[m.jsx(Yi,{children:"新建网页预览"}),m.jsx(_s,{children:"输入本机网站地址,或选择 HTML 网页文件或目录。"})]}),Q]})}):m.jsx(fu,{open:e,onOpenChange:F,children:m.jsxs(hu,{side:"bottom",showCloseButton:!x,onEscapeKeyDown:G=>{x&&G.preventDefault()},onPointerDownOutside:G=>{x&&G.preventDefault()},className:"inset-x-2 max-h-[calc(100dvh-0.75rem)] w-auto overflow-x-hidden overflow-y-auto rounded-t-xl border bg-background px-4 pb-[max(theme(spacing.4),env(safe-area-inset-bottom))] pt-3","data-slot":"create-web-preview-dialog",focusSurfaceOnOpen:!0,children:[m.jsxs(gf,{className:"px-0 pb-1 pt-0 text-left",children:[m.jsx(pu,{children:"新建网页预览"}),m.jsx(Mb,{children:"输入本机网站地址,或选择 HTML 网页文件或目录。"})]}),Q]})})}function Rde({status:e,capability:t,provider:n,error:r,disabled:i,onRetry:s}){const o=h1[n];if(e==="loading"||e==="idle")return m.jsxs("div",{"data-slot":"web-preview-capability-status","data-status":"loading","data-provider":n,className:"flex items-center gap-2 rounded-md border border-border/70 bg-muted/20 px-3 py-2 text-sm text-muted-foreground",role:"status",children:[m.jsx(ii,{className:"size-4 animate-spin","aria-hidden":"true"}),"正在检测 ",o.label,"..."]});if(e==="error")return m.jsx("div",{"data-slot":"web-preview-capability-status","data-status":"error","data-provider":n,className:"rounded-md border border-destructive/45 bg-destructive/5 p-3",role:"alert",children:m.jsxs("div",{className:"flex items-start gap-2",children:[m.jsx(XB,{className:"mt-0.5 size-4 shrink-0 text-destructive","aria-hidden":"true"}),m.jsxs("div",{className:"min-w-0 flex-1",children:[m.jsxs("p",{className:"text-sm font-medium",children:["无法检测 ",o.label]}),r?m.jsx("p",{className:"mt-1 break-words text-xs text-muted-foreground",children:r}):null]}),m.jsx(G2,{onClick:s,disabled:i})]})});const l=j4(t,n);if(!(l!=null&&l.available)){const u=(l==null?void 0:l.suggestions)??[],d=`未找到 ${o.label}`,f=(l==null?void 0:l.error)&&l.error!==d;return m.jsx("div",{"data-slot":"web-preview-capability-status","data-status":"missing","data-provider":n,className:"rounded-md border border-[var(--color-status-warning)]/45 bg-[var(--color-status-warning)]/5 p-3",role:"alert",children:m.jsxs("div",{className:"flex items-start gap-2",children:[m.jsx(fV,{className:"mt-0.5 size-4 shrink-0 text-[var(--color-status-warning)]","aria-hidden":"true"}),m.jsxs("div",{className:"min-w-0 flex-1",children:[m.jsx("p",{className:"text-sm font-medium",children:d}),m.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["请先安装 ",o.executable,",并确保它在用户 Shell 的 PATH 中,然后重新检测。"]}),u.length>0?m.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:[m.jsx("span",{children:"检测到的位置:"}),m.jsx("ul",{className:"mt-1 space-y-1",children:u.map(p=>m.jsx("li",{"data-slot":n==="cloudflare"?"web-preview-cloudflared-suggestion":"web-preview-cpolar-suggestion","data-provider":n,"data-path":p,children:m.jsx("code",{className:"break-all rounded bg-muted px-1 py-0.5",children:p})},p))})]}):null,o.installUrl?m.jsx("a",{"data-slot":"web-preview-cloudflared-install-link","data-provider":n,href:o.installUrl,target:"_blank",rel:"noopener noreferrer",className:"mt-2 inline-block text-xs text-primary underline-offset-4 hover:underline",children:"查看官方安装说明"}):null,f?m.jsx("p",{className:"mt-1 break-words text-xs text-muted-foreground/80",children:l.error}):null]}),m.jsx(G2,{onClick:s,disabled:i})]})})}return m.jsxs("div",{"data-slot":"web-preview-capability-status","data-status":"ready","data-provider":n,className:"flex items-center gap-2 rounded-md border border-[var(--color-status-success)]/35 bg-[var(--color-status-success)]/5 px-3 py-2 text-sm",role:"status",children:[m.jsx(iV,{className:"size-4 text-[var(--color-status-success)]","aria-hidden":"true"}),m.jsxs("span",{children:[o.label," 已安装"]}),l.version?m.jsxs("span",{className:"truncate text-xs text-muted-foreground",children:["· ",l.version]}):null]})}function G2({onClick:e,disabled:t}){return m.jsxs(gt,{type:"button",variant:"outline",size:"sm","data-slot":"web-preview-capability-retry",className:"shrink-0",onClick:e,disabled:t,children:[m.jsx(em,{className:"size-3.5","aria-hidden":"true"}),"重新检测"]})}function Ade({inspection:e,selectedEntryPath:t,disabled:n,onEntryPathChange:r}){if(e.status==="idle")return null;if(e.status==="loading")return m.jsxs("span",{"data-slot":"web-preview-static-inspection","data-status":"loading",className:"flex items-center gap-2 text-xs text-muted-foreground",role:"status",children:[m.jsx(ii,{className:"size-3.5 animate-spin","aria-hidden":"true"}),"正在检查网页..."]});if(e.status==="error")return m.jsx("span",{"data-slot":"web-preview-static-inspection","data-status":"error",className:"text-xs text-destructive",role:"alert",children:e.message});if(!e.result.entryPath&&e.result.htmlEntries.length>1)return m.jsxs("label",{"data-slot":"web-preview-static-inspection","data-status":"choose-entry",className:"mt-1 flex min-w-0 flex-col gap-2",children:[m.jsx("span",{className:"text-sm",children:"这个文件夹里有多个网页,打开预览时先显示哪个?"}),m.jsxs(Ib,{value:t,onValueChange:r,disabled:n,children:[m.jsx(Lb,{"data-slot":"web-preview-entry-select",className:"w-full font-mono",children:m.jsx(Ob,{placeholder:"选择网页"})}),m.jsx(Db,{children:e.result.htmlEntries.map(o=>m.jsx(Bb,{value:o,"data-entry-path":o,children:o},o))})]})]});const s=e.result.entryPath;return s?m.jsxs("span",{"data-slot":"web-preview-static-inspection","data-status":"ready","data-entry-path":s,className:"truncate text-xs text-muted-foreground",title:s,children:["打开时显示:",m.jsx("span",{className:"font-mono",children:s})]}):null}const p1={ios:"iOS Simulator",android:"Android Emulator"};function Nde({open:e,platform:t,onOpenChange:n}){const r=ws(),i=co("(min-width: 768px)"),s=Ie(F=>F.selectedProxyId),o=gr(F=>F.capability),l=gr(F=>F.targets),u=gr(F=>F.targetsStatus),d=gr(F=>F.targetsError),f=gr(Dj),p=gr(F=>{var Y;return((Y=F.authoritative)==null?void 0:Y.scope)??null}),y=p?`${p.proxyId}\0${p.bindingId}`:null,[g,_]=b.useState(""),[w,x]=b.useState(null),[S,k]=b.useState(!1),T=b.useRef(null),N=b.useRef(e);N.current=e;const P=b.useRef(null),R=b.useRef(null),M=b.useMemo(()=>l.filter(F=>F.platform===t),[t,l]),L=b.useMemo(()=>new Set(f.map(F=>F.targetId)),[f]),X=b.useMemo(()=>M.filter(F=>!L.has(F.targetId)),[L,M]),U=X.find(F=>F.targetId===w),V=o==null?void 0:o[t],j=b.useCallback(async F=>{var K;(K=T.current)==null||K.abort();const Y=new AbortController;T.current=Y;const z=Ft,q=Tt.getActiveScope();if(!(!z||!q||q.proxyId!==s))try{const $=await Tt.requestDevicePreviewCapability(q,F,{signal:Y.signal});if(!$||Y.signal.aborted||!N.current||!$.success)return;await Tt.requestDevicePreviewTargets(q,!0,{signal:Y.signal})}catch{}},[s]);b.useEffect(()=>{var F;if(!e){(F=T.current)==null||F.abort(),T.current=null,_(""),x(null),k(!1),P.current=null,R.current=null;return}return j(!1),()=>{var Y;(Y=T.current)==null||Y.abort(),T.current=null}},[j,e,t,y]),b.useEffect(()=>{if(e){if(w&&!U){x(null);return}!w&&X.length===1&&x(X[0].targetId)}},[e,X,U,w]);async function A(){var K,$,re;const F=U;if(!F||S||(V==null?void 0:V.available)!==!0)return;const Y=Ft,z=Tt.getActiveScope();if(!Y||!z||z.proxyId!==s){We.error("请先连接开发机");return}k(!0);let q=null;try{const Q=g.trim(),G=((K=P.current)==null?void 0:K.proxyId)===z.proxyId&&P.current.targetId===F.targetId&&P.current.name===Q?P.current:{proxyId:z.proxyId,targetId:F.targetId,name:Q,operationId:tb("device-preview-operation")};P.current=G,q=G.operationId,R.current=q;const Z=await Tt.createDevicePreview(z,F.targetId,{operationId:G.operationId,...Q?{name:Q}:{}});if(R.current!==G.operationId)return;if(!Z.accepted){if((($=P.current)==null?void 0:$.operationId)===G.operationId&&(P.current=null),!N.current||!Tt.isActive(Y,z))return;We.error(Z.error);return}if(((re=P.current)==null?void 0:re.operationId)===G.operationId&&(P.current=null),!N.current||!Tt.isActive(Y,z))return;n(!1),r(`/preview/device/${Z.previewId}`)}catch(Q){if(!q||R.current!==q||!N.current||!Tt.isActive(Y,z))return;We.error(Q instanceof Error?Q.message:"无法创建模拟器预览")}finally{q&&R.current===q&&(R.current=null,N.current&&k(!1))}}function D(F){var Y;!F&&S||(F||((Y=T.current)==null||Y.abort(),T.current=null,P.current=null,R.current=null,_(""),x(null)),n(F))}const O=m.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-4",children:[m.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[m.jsx("span",{className:"text-sm",children:"名称(可选)"}),m.jsx("input",{type:"text",name:"dev-anywhere-device-preview-name",value:g,maxLength:256,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:S,placeholder:"自动生成","data-slot":"device-preview-name",onChange:F=>{_(F.target.value)},className:"min-h-11 min-w-0 rounded-md border border-border bg-input px-3 text-base outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60 md:h-9 md:min-h-0 md:text-sm"})]}),m.jsx(Mde,{platform:t,tool:V}),m.jsx("div",{className:"grid min-w-0 grid-cols-1 gap-2","data-slot":"device-preview-targets",children:u==="loading"?m.jsxs("div",{className:"flex min-h-28 items-center justify-center gap-2 text-sm text-muted-foreground",children:[m.jsx(ii,{className:"size-4 animate-spin","aria-hidden":"true"}),"正在查找已启动的模拟器..."]}):u==="error"?m.jsx(X2,{message:d??"无法读取模拟器列表"}):M.length===0?m.jsx(X2,{message:`没有已启动的 ${p1[t]}`}):M.map(F=>{const Y=F.targetId===w,z=L.has(F.targetId);return m.jsx(Pde,{target:F,selected:Y,disabled:z||S,alreadyOpen:z,onClick:()=>{x(F.targetId)}},F.targetId)})}),m.jsxs(Fs,{className:"gap-2 sm:gap-2",children:[m.jsxs(gt,{type:"button",variant:"outline",disabled:S||u==="loading",onClick:()=>void j(!0),"data-slot":"device-preview-refresh",children:[m.jsx(em,{className:"size-4","aria-hidden":"true"}),"重新检测"]}),m.jsx(gt,{type:"button",disabled:!U||S||(V==null?void 0:V.available)!==!0,onClick:()=>void A(),"data-slot":"create-device-preview-submit",children:S?"正在创建...":"创建预览"})]})]}),I=`新建 ${p1[t]} 预览`,B="选择开发机上已经启动的模拟器。";return i?m.jsx(ss,{open:e,onOpenChange:D,children:m.jsxs(os,{showCloseButton:!S,className:"sm:max-w-xl","data-slot":"create-device-preview-dialog","data-platform":t,focusSurfaceOnOpen:!0,children:[m.jsxs(as,{children:[m.jsx(Yi,{children:I}),m.jsx(_s,{children:B})]}),O]})}):m.jsx(fu,{open:e,onOpenChange:D,children:m.jsxs(hu,{side:"bottom",showCloseButton:!S,className:"inset-x-2 max-h-[calc(100dvh-0.75rem)] w-auto min-w-0 max-w-[calc(100%-1rem)] overflow-x-hidden overflow-y-auto rounded-t-xl border bg-background px-4 pb-[max(theme(spacing.4),env(safe-area-inset-bottom))] pt-3","data-slot":"create-device-preview-dialog","data-platform":t,focusSurfaceOnOpen:!0,children:[m.jsxs(gf,{className:"px-0 pb-1 pt-0 text-left",children:[m.jsx(pu,{children:I}),m.jsx(Mb,{children:B})]}),O]})})}function Mde({platform:e,tool:t}){if(!t||t.available)return null;const n=e==="android"&&!!t.command,r=e==="ios"?"Baguette":"adb",i=t.supported?e==="ios"&&t.version?"outdated":t.command?"unavailable":"missing":"unsupported",s=n?"Android 模拟器预览不可用":i==="unsupported"?`${p1[e]} 不可用`:i==="outdated"?`需要更新 ${r}`:i==="unavailable"?`${r} 暂时不可用`:`未找到 ${r}`,o=t.error??(e==="ios"?"需要先在开发机上安装 Baguette 0.1.96 或更高版本。":"需要先在开发机上安装 adb。"),l=o.trim()!==s.trim();return m.jsx("div",{className:"rounded-lg border border-amber-500/45 bg-amber-500/5 p-3 text-sm","data-slot":"device-preview-tool-status","data-status":i,children:m.jsxs("div",{className:"flex gap-2",children:[m.jsx(XB,{className:"mt-0.5 size-4 shrink-0 text-amber-600","aria-hidden":"true"}),m.jsxs("div",{className:"min-w-0",children:[m.jsx("p",{className:"font-medium",children:s}),l?m.jsx("p",{className:"mt-1 text-muted-foreground","data-slot":"device-preview-tool-description",children:o}):null,i!=="unsupported"&&!n?m.jsx("a",{href:e==="ios"?"https://github.com/tddworks/baguette#install":"https://developer.android.com/tools/releases/platform-tools",target:"_blank",rel:"noreferrer",className:"mt-1 inline-block text-primary underline underline-offset-4",children:"查看安装方法"}):null]})]})})}function X2({message:e}){return m.jsx("div",{className:"flex min-h-28 items-center justify-center rounded-lg border border-dashed px-4 text-center text-sm text-muted-foreground",children:e})}function Pde({target:e,selected:t,disabled:n,alreadyOpen:r,onClick:i}){const s=e.platform==="ios"?"iOS":"Android",o=`${e.model} · ${s} ${e.osVersion}`;return m.jsxs("button",{type:"button",className:Ye("flex min-h-16 w-full min-w-0 max-w-full items-center gap-3 overflow-hidden rounded-lg border px-3 py-2 text-left outline-none transition-colors",t?"border-primary bg-primary/5":"border-border hover:bg-accent",n&&"cursor-not-allowed opacity-55"),disabled:n,"aria-pressed":t,onClick:i,"data-slot":"device-preview-target","data-target-id":e.targetId,"data-already-open":r?"true":"false","data-interactive":e.interactive?"true":"false",children:[m.jsx(uy,{className:"size-5 shrink-0 text-muted-foreground","aria-hidden":"true"}),m.jsxs("span",{className:"min-w-0 flex-1",children:[m.jsx("span",{className:"block truncate text-sm font-medium",children:e.name}),m.jsx("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground","data-slot":"device-preview-target-device","data-device-model":e.model,"data-os-version":e.osVersion,children:o})]}),r?m.jsx("span",{className:"text-xs text-muted-foreground",children:"已在预览"}):t?m.jsx(Co,{className:"size-4 text-primary","aria-hidden":"true"}):null]})}function F4({open:e,onOpenChange:t}){const[n,r]=b.useState(()=>e?"chooser":"closed"),i=b.useRef(null),s=co("(min-width: 768px)");b.useLayoutEffect(()=>{if(e){n==="closed"&&r("chooser");return}n!=="closed"&&(i.current=n,r("closed"))},[e,n]);function o(){t(!1)}const l=m.jsxs("div",{className:"grid gap-2 pt-2","data-slot":"frontend-preview-options",children:[m.jsx(i0,{icon:m.jsx(JB,{className:"size-5","aria-hidden":"true"}),title:"网页",description:"通过临时链接访问或分享本机网页",slot:"frontend-preview-web",onClick:()=>r("web")}),m.jsx(i0,{icon:m.jsx(uy,{className:"size-5","aria-hidden":"true"}),title:"iOS Simulator",description:"查看和操控开发机上已启动的 iPhone 或 iPad 模拟器",slot:"frontend-preview-ios",onClick:()=>r("ios")}),m.jsx(i0,{icon:m.jsx(uy,{className:"size-5","aria-hidden":"true"}),title:"Android Emulator",description:"查看和操控开发机上已启动的 Android 模拟器",slot:"frontend-preview-android",onClick:()=>r("android")})]}),u=n==="closed"?i.current:n,d=e&&n!=="closed";switch(u){case"chooser":return s?m.jsx(ss,{open:d,onOpenChange:f=>!f&&o(),children:m.jsxs(os,{className:"sm:max-w-lg","data-slot":"create-frontend-preview-dialog",children:[m.jsxs(as,{children:[m.jsx(Yi,{children:"新建预览"}),m.jsx(_s,{children:"选择预览类型。"})]}),l]})},"chooser"):m.jsx(fu,{open:d,onOpenChange:f=>!f&&o(),children:m.jsxs(hu,{side:"bottom",className:"inset-x-2 w-auto rounded-t-xl border bg-background px-4 pb-[max(theme(spacing.4),env(safe-area-inset-bottom))] pt-3","data-slot":"create-frontend-preview-dialog",focusSurfaceOnOpen:!0,children:[m.jsxs(gf,{className:"px-0 pb-1 pt-0 text-left",children:[m.jsx(pu,{children:"新建预览"}),m.jsx(Mb,{children:"选择预览类型。"})]}),l]})},"chooser");case"web":return m.jsx(Tde,{open:d,onOpenChange:f=>!f&&o()},"web");case"ios":case"android":return m.jsx(Nde,{open:d,platform:u,onOpenChange:f=>!f&&o()},u);case null:return null}}function i0({icon:e,title:t,description:n,slot:r,onClick:i}){return m.jsxs(gt,{type:"button",variant:"outline",className:"h-auto min-h-[4.5rem] justify-start gap-3 px-4 py-3 text-left","data-slot":r,onClick:i,children:[m.jsx("span",{className:"text-muted-foreground",children:e}),m.jsxs("span",{className:"min-w-0",children:[m.jsx("span",{className:"block font-medium text-foreground",children:t}),m.jsx("span",{className:"mt-0.5 block whitespace-normal text-xs leading-5 text-muted-foreground",children:n})]})]})}function Ide({preview:e,closing:t,onOpenChange:n,onConfirm:r}){return m.jsx(ss,{open:e!==null,onOpenChange:n,children:m.jsxs(os,{"data-slot":"device-preview-close-dialog",children:[m.jsxs(as,{children:[m.jsx(Yi,{children:"停止预览?"}),m.jsx(_s,{children:"模拟器会继续在开发机上运行。"})]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"ghost",disabled:t,onClick:()=>n(!1),children:"取消"}),m.jsx(gt,{type:"button",variant:"destructive",disabled:!e||t,onClick:()=>e&&r(e),"data-slot":"device-preview-close-confirm",children:t?"正在停止...":"停止预览"})]})]})})}const Ode={ready:{dot:"bg-[var(--color-status-success)]",text:"text-[var(--color-status-success)]",label:"已连接"},disconnected:{dot:"bg-muted-foreground",text:"text-muted-foreground",label:"已断开"}};function Lde({preview:e,selected:t,pendingOperation:n,onRename:r,onReconnect:i,onClose:s}){const o=Ode[e.state],l=n==="reconnect"?{dot:"bg-[var(--color-status-working)] animate-pulse",text:"text-[var(--color-status-working)]",label:"正在重新连接",busy:!0}:n==="close"?{dot:"bg-muted-foreground animate-pulse",text:"text-muted-foreground",label:"正在停止",busy:!0}:o,u=e.state==="ready",d=e.state==="disconnected",f=e.platform==="ios"?"iOS":"Android",p=m.jsxs(m.Fragment,{children:[m.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[m.jsx("span",{className:Ye("inline-block size-2 shrink-0 rounded-full",l.dot),role:"status","aria-label":`预览状态:${l.label}`}),m.jsx("span",{className:"flex-1 truncate text-sm font-normal",title:e.name,children:e.name})]}),m.jsxs("span",{className:"flex h-5 min-w-0 items-center gap-1.5 text-xs leading-5",children:[m.jsx(uy,{className:"size-3.5 shrink-0 text-muted-foreground","aria-hidden":"true"}),m.jsxs("span",{className:"min-w-0 flex-1 truncate text-muted-foreground","data-slot":"device-preview-row-device","data-device-model":e.model,"data-os-version":e.osVersion,children:[e.model," · ",f," ",e.osVersion]}),m.jsx("span",{className:Ye("shrink-0",l.text),children:l.label})]})]});return m.jsxs("li",{className:Ye("relative flex min-h-[44px] w-full min-w-0 items-center gap-2 px-4 py-2 transition-colors hover:bg-accent",t&&"bg-accent"),"data-slot":"device-preview-row","data-preview-id":e.previewId,"data-preview-state":e.state,"data-preview-operation":n,children:[u?m.jsx(nC,{to:`/preview/device/${e.previewId}`,className:"flex min-h-11 min-w-0 flex-1 flex-col justify-center gap-1 rounded-sm text-left outline-none focus-visible:ring-2 focus-visible:ring-ring md:min-h-0","data-slot":"device-preview-row-open",children:p}):m.jsx("div",{className:"flex min-h-11 min-w-0 flex-1 flex-col justify-center gap-1 md:min-h-0",children:p}),m.jsxs(uf,{children:[m.jsx(df,{asChild:!0,children:m.jsx(gt,{variant:"ghost",size:"icon-xs",className:"size-11 md:size-6","aria-label":"模拟器预览操作",disabled:n!==void 0,"data-slot":"device-preview-row-menu-trigger",children:l.busy||n==="rename"?m.jsx(ii,{className:"animate-spin","aria-hidden":"true"}):m.jsx(Ky,{"aria-hidden":"true"})})}),m.jsxs(ff,{align:"end","data-slot":"device-preview-row-menu",children:[m.jsx(ni,{"data-slot":"device-preview-row-rename-item",onSelect:r,children:"重命名"}),d?m.jsx(ni,{"data-slot":"device-preview-row-reconnect-item",onSelect:i,children:"重新连接"}):null,m.jsx(Ld,{}),m.jsx(ni,{variant:"destructive","data-slot":"device-preview-row-close-item",onSelect:s,children:"停止预览"})]})]})]})}function Dde({preview:e,closing:t,onOpenChange:n,onConfirm:r}){return m.jsx(ss,{open:e!==null,onOpenChange:n,children:m.jsxs(os,{"data-slot":"preview-close-dialog",children:[m.jsxs(as,{children:[m.jsx(Yi,{children:"关闭预览?"}),m.jsx(_s,{children:"关闭后,当前预览链接将立即失效。"})]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"ghost",disabled:t,onClick:()=>n(!1),children:"取消"}),m.jsx(gt,{type:"button",variant:"destructive",disabled:!e||t,onClick:()=>e&&r(e),"data-slot":"preview-close-confirm",children:t?"正在关闭...":"关闭预览"})]})]})})}function Bde({target:e,onOpenChange:t,onRename:n}){return m.jsx(zde,{target:e,onOpenChange:t,onRename:n},(e==null?void 0:e.targetKey)??"closed")}function zde({target:e,onOpenChange:t,onRename:n}){const[r,i]=b.useState(()=>(e==null?void 0:e.name.trim())??""),[s,o]=b.useState(null),[l,u]=b.useState(!1),d=b.useRef((e==null?void 0:e.targetKey)??null);b.useLayoutEffect(()=>()=>{d.current=null},[]);function f(y){!y&&l||t(y)}async function p(y){y.preventDefault();const g=r.trim();if(!g){o("名称不能为空");return}if(!e||l)return;const _=e.targetKey;u(!0);try{if(await n(g),d.current!==_)return;t(!1)}catch(w){if(d.current!==_)return;o(w instanceof Error?w.message:String(w))}finally{d.current===_&&u(!1)}}return m.jsx(ss,{open:e!==null,onOpenChange:f,children:m.jsx(os,{showCloseButton:!l,className:"sm:max-w-md","data-slot":"preview-rename-dialog",children:m.jsxs("form",{className:"grid gap-4",onSubmit:y=>void p(y),children:[m.jsx(as,{children:m.jsx(Yi,{children:"重命名预览"})}),m.jsxs("div",{className:"grid gap-2",children:[m.jsx("label",{htmlFor:"preview-rename-name",className:"text-sm font-medium",children:"预览名称"}),m.jsx("input",{id:"preview-rename-name",value:r,autoFocus:!0,maxLength:256,autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-invalid":!!s,"aria-describedby":s?"preview-rename-error":void 0,"data-slot":"preview-rename-input",className:Ye("h-10 rounded-md border border-input bg-background px-3 text-sm shadow-xs outline-none transition-[border-color,box-shadow]","placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/75","disabled:cursor-not-allowed disabled:opacity-50",s&&"border-destructive focus-visible:ring-destructive/20"),disabled:l,onChange:y=>{i(y.target.value),s&&o(null)}}),s?m.jsx("p",{id:"preview-rename-error",className:"text-sm text-destructive",role:"alert",children:s}):null]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"outline",disabled:l,onClick:()=>f(!1),children:"取消"}),m.jsx(gt,{type:"submit",disabled:l,"data-slot":"preview-rename-submit",children:"保存"})]})]})})})}const jde={starting:{dot:"bg-[var(--color-status-working)] animate-pulse",text:"text-[var(--color-status-working)]",label:"正在创建",busy:!0},ready:{dot:"bg-[var(--color-status-success)]",text:"text-[var(--color-status-success)]",label:"可访问"},failed:{dot:"bg-[var(--color-status-error)]",text:"text-[var(--color-status-error)]",label:"连接失败"},disconnected:{dot:"bg-muted-foreground",text:"text-muted-foreground",label:"已断开"},stopping:{dot:"bg-muted-foreground animate-pulse",text:"text-muted-foreground",label:"正在关闭",busy:!0}};function Fde(e){return e.source.kind==="local"?e.source.url:`${e.source.rootPath.replace(/\/$/,"")}/${e.source.entryPath}`}async function $de(e){if(await Ap(e,{allowUserGestureFallback:!0})==="failed"){We.error("复制失败,请稍后重试");return}We.success("链接已复制")}async function Hde(e,t){if(typeof navigator.share=="function")try{await navigator.share({title:e,url:t})}catch(n){if(n instanceof DOMException&&n.name==="AbortError")return;We.error("无法打开系统分享面板")}}function Ude({preview:e,pendingOperation:t,onRename:n,onReconnect:r,onClose:i}){const s=jde[e.state],o=t==="reconnect"?{dot:"bg-[var(--color-status-working)] animate-pulse",text:"text-[var(--color-status-working)]",label:"正在重新连接",busy:!0}:t==="close"?{dot:"bg-muted-foreground animate-pulse",text:"text-muted-foreground",label:"正在关闭",busy:!0}:s,l=e.state==="ready"?e.publicUrl:null,u=l!==null,d=e.state==="failed"||e.state==="disconnected",f=u&&typeof navigator<"u"&&typeof navigator.share=="function",p=Fde(e),y=m.jsxs(m.Fragment,{children:[m.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[m.jsx("span",{className:Ye("inline-block size-2 shrink-0 rounded-full",o.dot),role:"status","aria-label":`预览状态:${o.label}`}),m.jsx("span",{className:"flex-1 truncate text-sm font-normal",title:e.name,children:e.name})]}),m.jsxs("span",{className:"flex h-5 min-w-0 items-center gap-1.5 text-xs leading-5",children:[m.jsx(JB,{className:"size-3.5 shrink-0 text-muted-foreground","aria-hidden":"true"}),m.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-muted-foreground",title:p,children:p}),m.jsx("span",{className:"shrink-0 text-muted-foreground/60","aria-hidden":"true",children:"·"}),m.jsx("span",{className:Ye("shrink-0",o.text),children:o.label})]}),e.state==="failed"?m.jsx("span",{"data-slot":"preview-row-error",className:"truncate text-xs text-destructive/90",title:e.error,children:e.error}):null]});return m.jsxs("li",{className:"relative flex min-h-[44px] w-full min-w-0 items-center gap-2 px-4 py-2 transition-colors hover:bg-accent","data-slot":"preview-row","data-preview-id":e.previewId,"data-preview-state":e.state,"data-preview-operation":t,children:[u?m.jsx("a",{href:l,target:"_blank",rel:"noopener noreferrer","data-slot":"preview-row-open",className:"flex min-h-11 min-w-0 flex-1 flex-col justify-center gap-1 rounded-sm text-left outline-none focus-visible:ring-2 focus-visible:ring-ring md:min-h-0",children:y}):m.jsx("div",{"data-slot":"preview-row-inactive","aria-disabled":"true",className:"flex min-h-11 min-w-0 flex-1 flex-col justify-center gap-1 md:min-h-0",children:y}),m.jsxs(uf,{children:[m.jsx(df,{asChild:!0,children:m.jsx(gt,{variant:"ghost",size:"icon-xs",className:"size-11 md:size-6","aria-label":"预览操作","data-slot":"preview-row-menu-trigger",disabled:e.state==="stopping"||t!==void 0,children:o.busy||t==="rename"?m.jsx(ii,{className:"animate-spin","aria-hidden":"true"}):m.jsx(Ky,{"aria-hidden":"true"})})}),m.jsxs(ff,{align:"end","data-slot":"preview-row-menu",children:[m.jsx(ni,{"data-slot":"preview-row-rename-item",onSelect:n,children:"重命名"}),u?m.jsx(ni,{"data-slot":"preview-row-copy-item",onSelect:()=>void $de(l),children:"复制链接"}):null,f?m.jsx(ni,{"data-slot":"preview-row-share-item",onSelect:()=>void Hde(e.name,l),children:"分享…"}):null,d?m.jsx(ni,{"data-slot":"preview-row-reconnect-item",onSelect:r,children:"重新连接"}):null,m.jsx(Ld,{}),m.jsx(ni,{variant:"destructive","data-slot":"preview-row-close-item",onSelect:i,children:"关闭预览"})]})]})]})}const Wde=Object.freeze([]),qde=Object.freeze([]);function ed(e,t,n){return Object.freeze({kind:e,previewId:t,scope:Object.freeze({proxyId:n.proxyId,bindingId:n.bindingId})})}function Ac(e,t){return e!==null&&e.kind===t.kind&&e.previewId===t.previewId&&tn(e.scope,t.scope)}function ep(e,t,n){return t!==null&&n!==void 0&&tn(e.scope,t)&&tn(e.scope,n)}function Sh(e){const t=Tt.getActiveScope(),n=e.kind==="web"?Kr.getState().authoritative:gr.getState().authoritative;return!n||!ep(e,t,n.scope)?!1:n.previews.some(r=>r.previewId===e.previewId)}function Do(e){const t=Tt.getActiveScope();return t!==null&&tn(t,e)}function Z2(){const e=Kr(A=>A.authoritative),t=gr(A=>A.authoritative),n=qo(A=>A.registry),r=Tt.getActiveScope(),i=r&&e&&tn(r,e.scope)?e.scope:null,s=r&&t&&tn(r,t.scope)?t.scope:null,o=i&&e?e.previews:Wde,l=s&&t?t.previews:qde,u=BB("/preview/device/:id"),d=ws(),[f,p]=b.useState(null),[y,g]=b.useState(null),_=(y==null?void 0:y.kind)==="web"&&ep(y,r,e==null?void 0:e.scope)?o.find(A=>A.previewId===y.previewId)??null:null,w=(y==null?void 0:y.kind)==="device"&&ep(y,r,t==null?void 0:t.scope)?l.find(A=>A.previewId===y.previewId)??null:null,x=_??w,S=(f==null?void 0:f.kind)==="web"&&ep(f,r,e==null?void 0:e.scope)?o.find(A=>A.previewId===f.previewId)??null:null,k=(f==null?void 0:f.kind)==="device"&&ep(f,r,t==null?void 0:t.scope)?l.find(A=>A.previewId===f.previewId)??null:null;b.useEffect(()=>{y&&!x&&g(A=>Ac(A,y)?null:A),f&&!S&&!k&&p(A=>Ac(A,f)?null:A)},[f,k,y,x,S]);function T(A,D,O){var I;return(I=Pj(n,A,D,O)[0])==null?void 0:I.kind}if(o.length===0&&l.length===0)return null;async function N(A){if(Sh(A))try{const D=await Tt.reconnectWebPreview(A.scope,A.previewId);if(!Do(A.scope))return;D.success||We.error(D.error)}catch(D){if(!Do(A.scope))return;We.error(D instanceof Error?D.message:"无法重新连接网页预览")}}async function P(A,D){if(!Sh(A))return;let O;try{O=A.kind==="web"?await Tt.renameWebPreview(A.scope,A.previewId,D):await Tt.renameDevicePreview(A.scope,A.previewId,D)}catch(I){if(!Do(A.scope))return;throw I}if(Do(A.scope)&&!O.success)throw new Error(O.error)}async function R(A){if(Sh(A))try{const D=await Tt.closeWebPreview(A.scope,A.previewId);if(!Do(A.scope))return;if(!D.success){We.error(D.error);return}p(O=>Ac(O,A)?null:O)}catch(D){if(!Do(A.scope))return;We.error(D instanceof Error?D.message:"无法关闭网页预览")}}async function M(A){if(Sh(A))try{const D=await Tt.reconnectDevicePreview(A.scope,A.previewId);if(!Do(A.scope))return;D.success||We.error(D.error)}catch(D){if(!Do(A.scope))return;We.error(D instanceof Error?D.message:"无法重新连接模拟器预览")}}async function L(A){if(Sh(A))try{const D=await Tt.closeDevicePreview(A.scope,A.previewId);if(!Do(A.scope))return;if(!D.success){We.error(D.error);return}p(O=>Ac(O,A)?null:O),(u==null?void 0:u.params.id)===A.previewId&&d("/sessions")}catch(D){if(!Do(A.scope))return;We.error(D instanceof Error?D.message:"无法停止模拟器预览")}}const X=(f==null?void 0:f.kind)==="web"&&T(f.scope,"web",f.previewId)==="close",U=(f==null?void 0:f.kind)==="device"&&T(f.scope,"device",f.previewId)==="close",V=y,j=f;return m.jsxs("section",{"data-slot":"preview-section","aria-labelledby":"preview-section-title",children:[m.jsxs("h3",{id:"preview-section-title",className:"px-4 pb-2 pt-3 text-sm font-semibold text-foreground",children:["预览",m.jsxs("span",{className:"ml-1 font-normal text-muted-foreground/70",children:["· ",o.length+l.length]})]}),m.jsxs("ul",{role:"list",className:"flex w-full min-w-0 flex-col",children:[o.map(A=>m.jsx(Ude,{preview:A,pendingOperation:i?T(i,"web",A.previewId):void 0,onRename:()=>i&&g(ed("web",A.previewId,i)),onReconnect:()=>i&&void N(ed("web",A.previewId,i)),onClose:()=>i&&p(ed("web",A.previewId,i))},A.previewId)),l.map(A=>m.jsx(Lde,{preview:A,selected:(u==null?void 0:u.params.id)===A.previewId,pendingOperation:s?T(s,"device",A.previewId):void 0,onRename:()=>s&&g(ed("device",A.previewId,s)),onReconnect:()=>s&&void M(ed("device",A.previewId,s)),onClose:()=>s&&p(ed("device",A.previewId,s))},A.previewId))]}),m.jsx(Bde,{target:V&&x?{targetKey:`${V.kind}\0${V.scope.proxyId}\0${V.scope.bindingId}\0${V.previewId}`,name:x.name}:null,onOpenChange:A=>{!A&&V&&g(D=>Ac(D,V)?null:D)},onRename:A=>V?P(V,A):Promise.resolve()}),m.jsx(Dde,{preview:S,closing:X,onOpenChange:A=>{!A&&!X&&j&&p(D=>Ac(D,j)?null:D)},onConfirm:()=>j&&void R(j)}),m.jsx(Ide,{preview:k,closing:U,onOpenChange:A=>{!A&&!U&&j&&p(D=>Ac(D,j)?null:D)},onConfirm:()=>j&&void L(j)})]})}function $4({layout:e}){const t=Gt(G=>G.sessions),n=Gt(G=>G.sessionListLoaded),r=Gt(G=>G.agentStatusBySessionId),i=Gt(G=>G.ptyStateBySessionId),s=Gt(G=>G.renameSession),o=an(G=>G.bySessionId),l=BB("/chat/:id"),u=(l==null?void 0:l.params.id)??null,d=Ie(G=>!!G.selectedProxyId),f=Ie(G=>G.proxyListLoaded),p=Ie(G=>G.proxySwitchTarget),y=Gt(G=>G.loadingProxyName),g=p!==null||!f||d&&!n,_=(p==null?void 0:p.name)??y,w=_?`正在连接 ${_}...`:"连接中...",x=ws(),[S,k]=b.useState(!1),[T,N]=b.useState(!1),[P,R]=b.useState(!1),[M,L]=b.useState(null),[X,U]=b.useState(null),{creatingTerminal:V,createTerminal:j}=H4(),[A,D]=b.useState(new Set),[O,I]=b.useState(()=>Date.now());b.useEffect(()=>{const G=setInterval(()=>I(Date.now()),6e4);return()=>clearInterval(G)},[]);function B(G,Z){x(`/chat/${G}?mode=${Z}`,{replace:!1})}function F(G){const Z=G.sessionId,ae=Ft;if(!ae){We.error("请先连接开发机");return}ae.sendControl({type:"session_terminate",sessionId:Z}),Gt.getState().removeSession(Z),an.getState().clearSession(Z),Z===u&&x("/sessions"),(G==null?void 0:G.kind)==="agent"&&G.mode==="pty"&&G.ptyOwner==="local-terminal"?We.info("已断开页面连接,本地终端仍在运行"):We.info("正在终止会话",{duration:1500})}async function Y(G,Z){const ae=Ft;if(!ae)throw new Error("请先连接开发机");const le=await ae.renameSession(G,Z);if(!le.success)throw new Error(le.error??"重命名失败");s(G,le.name??Z),We.success("已重命名会话")}function z(G){D(Z=>{const ae=new Set(Z);return ae.has(G)?ae.delete(G):ae.add(G),ae})}function q(G){var le;const Z=G.mode==="json"&&(((le=o[G.sessionId])==null?void 0:le.pendingApprovals.some(me=>me.status==="pending"))??!1),ae=Sde({session:G,agentStatus:r[G.sessionId],ptyState:i[G.sessionId],hasPendingApproval:Z});return ae===G.state?G:{...G,state:ae}}const K=t.length>0;if(e==="sidebar"&&(g||!d))return m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/70","data-slot":g?"session-list-loading":void 0,role:g?"status":void 0,"aria-live":g?"polite":void 0,children:g?w:"请先连接开发机"}),m.jsx(Qh,{open:S,onOpenChange:k}),m.jsx(iv,{open:X!==null,session:X,onOpenChange:G=>{G||U(null)},onConfirm:F}),m.jsx(Jh,{open:M!==null,sessionId:(M==null?void 0:M.sessionId)??null,initialName:M==null?void 0:M.name,onOpenChange:G=>{G||L(null)},onRename:Y})]});if(e==="page"&&g)return m.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 text-muted-foreground animate-in fade-in-0 duration-200 motion-reduce:animate-none","data-slot":"session-list-loading",role:"status","aria-live":"polite",children:[m.jsx(ii,{className:"h-5 w-5 animate-spin","aria-hidden":!0}),m.jsx("p",{className:"max-w-[min(24rem,calc(100%-2rem))] truncate text-sm",children:w})]});if(e==="page"&&!d)return m.jsxs("div",{className:"flex flex-col h-full",children:[m.jsx("div",{className:"flex-1",children:m.jsx(Uc,{variant:"no-proxy"})}),m.jsx(Qh,{open:S,onOpenChange:k}),m.jsx(iv,{open:X!==null,session:X,onOpenChange:G=>{G||U(null)},onConfirm:F}),m.jsx(Jh,{open:M!==null,sessionId:(M==null?void 0:M.sessionId)??null,initialName:M==null?void 0:M.name,onOpenChange:G=>{G||L(null)},onRename:Y})]});const $=m.jsxs("h3",{className:"px-4 pt-3 pb-2 text-sm font-semibold text-foreground","data-slot":"active-section-header",children:["活跃会话",K?m.jsxs("span",{className:"ml-1 text-muted-foreground/70 font-normal",children:["· ",t.length]}):null]}),re=K?m.jsx("ul",{role:"list",className:"flex flex-col w-full min-w-0",children:Vde(t).map(G=>m.jsxs("li",{children:[m.jsxs("button",{type:"button",onClick:()=>z(G.provider),"aria-expanded":!A.has(G.provider),className:Ye("flex w-full items-center gap-2 px-4 pt-2 pb-1 min-h-[32px]","text-xs text-muted-foreground","text-left outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"),children:[m.jsx("span",{className:"font-mono",children:Yde(G.provider)}),m.jsx("span",{className:"h-px flex-1 bg-border/70","aria-hidden":"true"}),m.jsx("span",{className:"tabular-nums",children:G.sessions.length}),m.jsx(dp,{className:Ye("size-3.5 shrink-0 text-muted-foreground/80 transition-transform",!A.has(G.provider)&&"rotate-90"),"aria-hidden":"true"})]}),A.has(G.provider)?null:m.jsx("ul",{role:"list",className:"flex flex-col",children:G.sessions.map(Z=>m.jsx(nde,{session:q(Z),selected:Z.sessionId===u,now:O,onClick:()=>B(Z.sessionId,Z.mode),onRename:()=>L(Z),onTerminate:()=>U(Z)},Z.sessionId))})]},G.provider))}):m.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/70","data-slot":"active-empty",children:"暂无活跃会话"}),Q=m.jsx(ode,{now:O});return e==="page"?m.jsxs("div",{className:"flex flex-col h-full",children:[m.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto overscroll-contain",children:[$,re,m.jsx(Z2,{}),Q]}),m.jsx("div",{className:"px-4 pt-4 pb-[calc(env(safe-area-inset-bottom)+1rem)] border-t border-border",children:m.jsxs(gt,{className:"min-h-11 w-full md:min-h-0","data-slot":"create-session-mobile-trigger",onClick:()=>N(!0),children:[m.jsx(ZB,{"aria-hidden":"true"}),"新建"]})}),m.jsx(Gde,{open:T,creatingTerminal:V,onOpenChange:N,onCreateAgent:()=>{N(!1),k(!0)},onCreateTerminal:()=>void j(()=>N(!1)),onCreatePreview:()=>{N(!1),R(!0)}}),m.jsx(Qh,{open:S,onOpenChange:k}),m.jsx(F4,{open:P,onOpenChange:R}),m.jsx(iv,{open:X!==null,session:X,onOpenChange:G=>{G||U(null)},onConfirm:F}),m.jsx(Jh,{open:M!==null,sessionId:(M==null?void 0:M.sessionId)??null,initialName:M==null?void 0:M.name,onOpenChange:G=>{G||L(null)},onRename:Y})]}):m.jsxs(m.Fragment,{children:[m.jsxs("div",{className:"dev-sidebar-scroll h-full overflow-y-auto overscroll-contain",children:[$,re,m.jsx(Z2,{}),Q]}),m.jsx(Qh,{open:S,onOpenChange:k}),m.jsx(iv,{open:X!==null,session:X,onOpenChange:G=>{G||U(null)},onConfirm:F}),m.jsx(Jh,{open:M!==null,sessionId:(M==null?void 0:M.sessionId)??null,initialName:M==null?void 0:M.name,onOpenChange:G=>{G||L(null)},onRename:Y})]})}function Vde(e){const t=new Map;for(const n of e){const r=n.kind==="terminal"?"terminal":n.provider,i=t.get(r);i?i.push(n):t.set(r,[n])}return Array.from(t.entries()).sort(([n],[r])=>Kde(n,r)).map(([n,r])=>({provider:n,sessions:r}))}function Yde(e){return e==="terminal"?"终端":Pb(e)}function Kde(e,t){return e===t?0:e==="terminal"?-1:t==="terminal"?1:A4(e,t)}function H4(){const e=ws(),[t,n]=b.useState(!1);async function r(i){if(!t){n(!0);try{const s=await vde({relay:Ft});if(s.type!=="success"){We.error(s.message);return}Gt.getState().addSession(s.session),i==null||i(),e(s.route)}finally{n(!1)}}}return{creatingTerminal:t,createTerminal:r}}function Q2({compact:e=!1}){const[t,n]=b.useState(!1),[r,i]=b.useState(!1),[s,o]=b.useState(!1),l=b.useRef(!1),u=Ie(N=>!!N.selectedProxyId),d=Ie(N=>N.proxySwitchTarget!==null),f=u&&!d,{creatingTerminal:p,createTerminal:y}=H4();function g(){o(!0),window.setTimeout(()=>o(!1),2e3)}function _(){if(!f){g();return}l.current=!0,n(!0)}function w(){if(!f){g();return}l.current=!0,y()}function x(){if(!f){g();return}l.current=!0,i(!0)}function S(N){N.preventDefault(),g()}const k=m.jsxs(gt,{variant:"outline","data-slot":"create-session-trigger",className:Ye(e?"h-11 w-11 justify-center border-border px-0":"h-[46px] w-full justify-center gap-2 border-border px-3",!f&&"opacity-50 hover:bg-background"),"aria-label":"新建","aria-disabled":!f,onClick:f?void 0:S,children:[m.jsx(ZB,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),!e&&m.jsx("span",{className:"truncate",children:"新建"})]}),T=f?m.jsxs(uf,{children:[m.jsx(df,{asChild:!0,children:k}),m.jsxs(ff,{align:e?"end":"start",className:"w-80","data-slot":"create-session-type-menu",onCloseAutoFocus:N=>{l.current&&(l.current=!1,N.preventDefault())},children:[m.jsxs(ni,{className:"min-h-9 gap-2.5","data-slot":"create-agent-session-item",onSelect:_,children:[m.jsx(GB,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),"Agent 会话"]}),m.jsxs(ni,{className:"min-h-9 gap-2.5","data-slot":"create-terminal-session-item",disabled:p,onSelect:w,children:[m.jsx(Ep,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),p?"正在创建终端会话...":"终端会话"]}),m.jsx(Ld,{}),m.jsxs(ni,{className:"min-h-[3.75rem] items-start gap-2.5 py-2","data-slot":"create-frontend-preview-item",onSelect:x,children:[m.jsx(oC,{className:"mt-0.5 size-4 text-muted-foreground","aria-hidden":"true"}),m.jsxs("span",{className:"min-w-0 flex-1",children:[m.jsx("span",{className:"flex items-center gap-1.5 font-medium",children:"预览"}),m.jsx("span",{className:"mt-0.5 block text-xs leading-4 text-muted-foreground",children:"在浏览器中预览网页或设备模拟器"})]})]})]})]}):k;return m.jsxs(m.Fragment,{children:[f?T:m.jsxs(hf,{open:f?void 0:s,onOpenChange:f?void 0:o,children:[m.jsx(pf,{asChild:!0,children:T}),m.jsx(mf,{side:"top",children:d?"正在切换开发机":"请先连接开发机"})]}),m.jsx(Qh,{open:t,onOpenChange:n}),m.jsx(F4,{open:r,onOpenChange:i})]})}function Gde({open:e,creatingTerminal:t,onOpenChange:n,onCreateAgent:r,onCreateTerminal:i,onCreatePreview:s}){const o=b.useRef(!1);function l(u){o.current=!0,u()}return m.jsx(fu,{open:e,onOpenChange:n,children:m.jsxs(hu,{side:"bottom",overlayClassName:"bg-black/10 dark:bg-black/30",className:"inset-x-2 w-auto rounded-t-xl border border-border/80 bg-background px-3 pb-[max(theme(spacing.4),env(safe-area-inset-bottom))] pt-3 shadow-2xl","data-slot":"create-session-type-sheet",focusSurfaceOnOpen:!0,onCloseAutoFocus:u=>{o.current&&(o.current=!1,u.preventDefault())},children:[m.jsx(gf,{className:"px-1 pb-1 pt-0 text-left",children:m.jsx(pu,{children:"新建"})}),m.jsxs("div",{className:"grid gap-2 pb-1","data-slot":"create-session-type-options",children:[m.jsxs(gt,{type:"button",variant:"ghost",className:"min-h-12 justify-start gap-3 rounded-md px-3 text-left","data-slot":"create-agent-session-sheet-item",onClick:()=>l(r),children:[m.jsx(GB,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),"Agent 会话"]}),m.jsxs(gt,{type:"button",variant:"ghost",className:"min-h-12 justify-start gap-3 rounded-md px-3 text-left","data-slot":"create-terminal-session-sheet-item",disabled:t,onClick:()=>l(i),children:[m.jsx(Ep,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),t?"正在创建终端会话...":"终端会话"]}),m.jsx("div",{className:"mx-1 h-px bg-border","aria-hidden":"true"}),m.jsxs(gt,{type:"button",variant:"ghost",className:"min-h-16 justify-start gap-3 rounded-md px-3 text-left","data-slot":"create-frontend-preview-sheet-item",onClick:()=>l(s),children:[m.jsx(oC,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),m.jsxs("span",{className:"min-w-0",children:[m.jsx("span",{className:"flex items-center gap-1.5 font-medium",children:"预览"}),m.jsx("span",{className:"mt-0.5 block text-xs leading-4 text-muted-foreground",children:"在浏览器中预览网页或设备模拟器"})]})]})]})]})})}const Xde="0.9.2",Zde={version:Xde},Qde={playback:"playback",capture:"play-and-record"};function Jde(){return typeof navigator>"u"?null:navigator.audioSession??null}function efe(){return{setMode:()=>{},release:()=>{}}}class tfe{constructor(t=Jde){je(this,"leases",new Map);je(this,"session",null);je(this,"baselineType",null);je(this,"nextLeaseId",1);je(this,"nextOrder",1);this.getAudioSession=t}acquire(t){const n=this.getAudioSession();if(!n)return efe();this.leases.size===0&&(this.session=n,this.baselineType=n.type);const r=this.nextLeaseId++;this.leases.set(r,{mode:t,order:this.nextOrder++});try{this.applyActiveMode()}catch(s){throw this.leases.delete(r),this.leases.size===0?this.restoreWhenUnused():this.applyActiveModeBestEffort(),s}let i=!1;return{setMode:s=>{if(i)return;const o=this.leases.get(r);if(!o)return;const l={...o};o.mode=s,o.order=this.nextOrder++;try{this.applyActiveMode()}catch(u){throw this.leases.set(r,l),this.applyActiveModeBestEffort(),u}},release:()=>{if(!i){if(i=!0,this.leases.delete(r),this.leases.size===0){this.restoreWhenUnused();return}this.applyActiveModeBestEffort()}}}}applyActiveMode(){const t=[...this.leases.values()].reduce((n,r)=>!n||r.order>n.order?r:n,null);!t||!this.session||this.setNativeType(Qde[t.mode])}applyActiveModeBestEffort(){try{this.applyActiveMode()}catch{}}restoreWhenUnused(){const t=this.session,n=this.baselineType;if(this.session=null,this.baselineType=null,!(!t||n===null))try{t.type=n}catch{}}setNativeType(t){if(!(!this.session||this.session.type===t)){try{this.session.type=t}catch{throw new Error("浏览器无法切换语音音频模式")}if(this.session.type!==t)throw new Error("浏览器无法切换语音音频模式")}}}const hk=new tfe,m1=64,J2=-60,U4=32;function eI(e){if(!Number.isFinite(e)||e===0)return 0;const t=Math.min(1,Math.abs(e)),n=20*Math.log10(t),r=Math.max(0,Math.min(1,(n-J2)/-J2));return e<0?-r:r}function tI(e,t=8){const n=Math.floor(e.byteLength/2);if(n===0||!Number.isFinite(t)||t<=0)return[];const r=Math.min(n,Math.max(1,Math.floor(t))),i=new DataView(e.buffer,e.byteOffset,e.byteLength),s=[];for(let o=0;o<r;o+=1){const l=Math.floor(o*n/r),u=Math.max(l+1,Math.floor((o+1)*n/r));let d=1,f=-1;for(let p=l;p<u;p+=1){const y=i.getInt16(p*2,!0)/32768;d=Math.min(d,y),f=Math.max(f,y)}s.push({min:d,max:f})}return s}function nfe(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=Math.floor(e.byteLength/2),r=new Float32Array(n);for(let i=0;i<n;i+=1)r[i]=t.getInt16(i*2,!0)/32768;return r}function rfe(e){if(e.length===0)return 0;const t=Math.max(1,Math.floor(e.length/512));let n=0,r=0;for(let i=0;i<e.length;i+=t){const s=e[i]??0;n+=s*s,r+=1}return r===0?0:Math.min(1,Math.sqrt(n/r)*10)}class W4{constructor(t,n=24e3,r={}){je(this,"nextStartTime",0);je(this,"activityEndToken",0);je(this,"timelineTimers",new Set);this.context=t,this.sampleRate=n,this.options=r}async resume(){this.emitPlaybackEvent("resume-start");try{if(this.context.state!=="running"&&this.context.state!=="closed"&&await this.context.resume(),this.context.state!=="running")throw new Error("浏览器未允许播放 Voice Pilot 提示音");this.emitPlaybackEvent("resume-finished")}catch(t){throw this.emitPlaybackEvent("resume-failed",{error:t instanceof Error?t.message:String(t)}),t}}enqueue(t){this.context.state==="suspended"&&this.resume().catch(()=>{});const n=nfe(t),r=this.context.createBuffer(1,n.length,this.sampleRate);r.getChannelData(0).set(n);const i=this.context.createBufferSource();i.buffer=r,i.connect(this.context.destination);const s=Math.max(this.context.currentTime,this.nextStartTime);i.start(s);const o=s+r.duration;this.nextStartTime=o,this.schedulePlaybackFrames(t,n,s,o);const l=Math.max(0,(o-this.context.currentTime)*1e3);return this.emitPlaybackEvent("pcm-scheduled",{bytes:t.byteLength,durationMs:r.duration*1e3}),typeof i.addEventListener=="function"&&i.addEventListener("ended",()=>{this.emitPlaybackEvent("source-ended",{bytes:t.byteLength,durationMs:r.duration*1e3})},{once:!0}),l}stop(){var t,n;this.nextStartTime=this.context.currentTime,this.activityEndToken+=1;for(const r of this.timelineTimers)clearTimeout(r);this.timelineTimers.clear(),(n=(t=this.options).onActivityLevel)==null||n.call(t,0),this.emitPlaybackEvent("stopped")}snapshot(){const t=this.context.currentTime;return{contextState:String(this.context.state??"unknown"),contextTime:t,nextStartTime:this.nextStartTime,queuedMs:Math.max(0,(this.nextStartTime-t)*1e3)}}schedulePlaybackFrames(t,n,r,i){if(!this.options.onActivityLevel&&!this.options.onPlaybackChunk)return;const s=Math.max(1,Math.round(this.sampleRate*U4/1e3)),o=this.activityEndToken+=1;for(let l=0;l<n.length;l+=s){const u=Math.min(n.length,l+s),d=r+l/this.sampleRate,f=Math.max(0,(d-this.context.currentTime)*1e3),p=t.slice(l*Int16Array.BYTES_PER_ELEMENT,u*Int16Array.BYTES_PER_ELEMENT),y=rfe(n.subarray(l,u));this.scheduleTimer(()=>{var g,_,w,x;(_=(g=this.options).onActivityLevel)==null||_.call(g,y),(x=(w=this.options).onPlaybackChunk)==null||x.call(w,p)},f)}if(this.options.onActivityLevel){const l=Math.max(0,(i-this.context.currentTime)*1e3);this.scheduleTimer(()=>{var u,d;o===this.activityEndToken&&((d=(u=this.options).onActivityLevel)==null||d.call(u,0))},l)}}scheduleTimer(t,n){const r=setTimeout(()=>{this.timelineTimers.delete(r),t()},n);this.timelineTimers.add(r)}emitPlaybackEvent(t,n={}){var r,i;(i=(r=this.options).onPlaybackEvent)==null||i.call(r,{event:t,...this.snapshot(),...n})}}const s0={provider:"aliyun-bailian",configured:!1,region:"cn",asrModel:"qwen3-asr-flash-realtime",ttsModel:"cosyvoice-v3-flash",ttsVoice:"longanyang",turnIdleSeconds:3},nI="min-h-11 min-w-0 rounded-md border border-border bg-input px-3 text-base outline-none transition-colors placeholder:text-muted-foreground/65 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring md:h-9 md:min-h-0 md:text-sm",ife=800,rI=300,sfe=1600;function g1(e,t){return e.filter(n=>!n.model||n.model===t)}function iI({label:e,children:t,help:n}){return m.jsxs("div",{className:"block min-w-0 rounded-lg border border-border/75 bg-card/55 p-3.5 transition-colors focus-within:border-ring/55 focus-within:bg-card/75 sm:p-3",children:[m.jsx("span",{className:"block text-[13px] font-medium leading-none text-muted-foreground",children:e}),m.jsx("div",{className:"mt-2 min-w-0",children:t}),n?m.jsx("span",{className:"mt-2 block text-xs leading-relaxed text-muted-foreground",children:n}):null]})}function sv({label:e,value:t,options:n,onChange:r,placeholder:i="请选择",help:s}){const[o,l]=b.useState(!1),u=b.useId(),d=n.find(g=>g.value===t),f=(d==null?void 0:d.label)??(t||i),p=n.filter(g=>!g.disabled),y=!!q4(f).detail;return m.jsxs("div",{className:"min-w-0 rounded-lg border border-border/75 bg-card/55 p-3.5 sm:p-3",onBlur:g=>{g.currentTarget.contains(g.relatedTarget)||l(!1)},children:[m.jsx("div",{id:u,className:"text-[13px] font-medium leading-none text-muted-foreground",children:e}),m.jsxs("button",{type:"button","aria-labelledby":u,"aria-haspopup":"listbox","aria-expanded":o,disabled:p.length===0,className:`mt-2 flex w-full min-w-0 items-center justify-between gap-3 rounded-md border border-border bg-input px-3 text-left outline-none transition-colors hover:border-primary/40 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60 ${y?"min-h-[60px] py-2":"min-h-11"}`,onClick:()=>l(g=>!g),"data-slot":"voice-settings-choice-trigger",children:[m.jsx(sI,{label:f,muted:!d&&!t}),m.jsx(Ql,{className:`size-4 shrink-0 text-muted-foreground transition-transform ${o?"rotate-180":""}`,"aria-hidden":"true"})]}),o?m.jsx("div",{role:"listbox","aria-labelledby":u,className:"mt-2 max-h-64 overflow-y-auto rounded-md border border-border/80 bg-popover p-1 shadow-sm",children:n.map(g=>{const _=g.value===t;return m.jsxs("button",{type:"button",role:"option","aria-label":g.label,"aria-selected":_,disabled:g.disabled,className:"flex w-full min-w-0 items-center gap-2 rounded-sm px-2.5 py-2.5 text-left text-sm outline-none transition-colors hover:bg-accent focus-visible:bg-accent disabled:cursor-not-allowed disabled:opacity-45",onClick:()=>{g.disabled||(r(g.value),l(!1))},children:[m.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center text-primary",children:_?m.jsx(Co,{className:"size-4","aria-hidden":"true"}):null}),m.jsx(sI,{label:g.label})]},g.value)})}):null,s?m.jsx("div",{className:"mt-2 text-xs leading-relaxed text-muted-foreground",children:s}):null]})}function sI({label:e,muted:t=!1}){const n=q4(e);return m.jsxs("span",{className:"min-w-0 flex-1",children:[m.jsx("span",{className:`block truncate text-base leading-6 md:text-sm ${t?"text-muted-foreground":"text-foreground"}`,children:n.title}),n.detail?m.jsx("span",{className:"mt-0.5 block truncate text-xs leading-4 text-muted-foreground",children:n.detail}):null]})}function ofe({scrollRef:e}={}){const[t,n]=b.useState(s0),[r,i]=b.useState(String(s0.turnIdleSeconds)),[s,o]=b.useState(()=>Wg()),[l,u]=b.useState(""),[d,f]=b.useState(!1),[p,y]=b.useState(!1),[g,_]=b.useState({kind:"idle"}),w=b.useRef(null),x=b.useRef(null),S=b.useRef(null),k=b.useRef(null),T=b.useRef(null),N=b.useRef(!1);b.useEffect(()=>{const Z=Ft;if(!Z){_({kind:"error",message:"请先连接 Relay 服务器"});return}let ae=!1;return _({kind:"loading"}),Z.requestVoiceConfig().then(le=>{if(!ae){if(le.error||!le.config){_({kind:"error",message:le.error??"读取语音设置失败"});return}n(le.config),i(String(le.config.turnIdleSeconds)),u(""),f(!1),y(!0),_({kind:"idle"})}}).catch(le=>{ae||_({kind:"error",message:le instanceof Error?le.message:"读取语音设置失败"})}),()=>{ae=!0}},[]),b.useEffect(()=>{const Z=Ft;if(!Z||!p)return;let ae=!1;return Z.requestVoiceCapabilities({region:t.region}).then(le=>{if(!ae){if(le.error||!le.capabilities){o(Wg());return}o(le.capabilities)}}).catch(()=>{ae||o(Wg())}),()=>{ae=!0}},[t.region,p]),b.useEffect(()=>(N.current=!0,()=>{N.current=!1,$(),re()}),[]);const P=b.useMemo(()=>g.kind==="loading"?"读取中...":g.kind==="saving"?"保存中...":g.kind==="testing"?"正在测试语音合成":g.kind==="playingTest"?"正在播放测试音频":g.kind==="testPassed"?"测试通过":g.kind==="saved"?"已保存":g.kind==="error"?g.message:null,[g]),R=g.kind==="saving"||g.kind==="loading"||g.kind==="testing"||g.kind==="playingTest",M=b.useMemo(()=>g1(s.ttsVoices,t.ttsModel),[s.ttsVoices,t.ttsModel]),X=M.some(Z=>Z.value===t.ttsVoice)?t.ttsVoice:"",U=M.length===0?"当前模型暂无可用音色":X?null:"请选择可用音色",V=b.useMemo(()=>ufe(r),[r]),j=V?null:"请输入正整数秒数",A=U??j,D=R||!!A,O=b.useMemo(()=>[{value:"cn",label:"中国大陆"},{value:"intl",label:"国际"}],[]),I=b.useMemo(()=>lI(s.asrModels,t.asrModel),[s.asrModels,t.asrModel]),B=b.useMemo(()=>dfe(s.ttsModels,s.ttsVoices,t.ttsModel),[s.ttsModels,s.ttsVoices,t.ttsModel]),F=b.useMemo(()=>lI(M,X),[M,X]);function Y(){return{...d?{clearApiKey:!0}:{},...!d&&l.trim()?{apiKey:l.trim()}:{},region:t.region,asrModel:t.asrModel.trim(),ttsModel:t.ttsModel.trim(),ttsVoice:t.ttsVoice.trim(),turnIdleSeconds:V??s0.turnIdleSeconds}}async function z(){if(R)return;if(A){_({kind:"error",message:A});return}const Z=Ft;if(!Z){_({kind:"error",message:"请先连接 Relay 服务器"});return}const ae=Y();re(),_({kind:"saving"});const le=performance.now();try{const me=await Z.updateVoiceConfig(ae);if(!N.current)return;const ke=performance.now()-le;if(ke<rI&&await cfe(rI-ke),!N.current)return;if(!me.success||me.error||!me.config){_({kind:"error",message:me.error??"保存语音设置失败"});return}n(me.config),i(String(me.config.turnIdleSeconds)),u(""),f(!1),_({kind:"saved"}),T.current=setTimeout(()=>{T.current=null,_($e=>$e.kind==="saved"?{kind:"idle"}:$e)},sfe),Z.requestVoiceCapabilities({region:me.config.region}).then($e=>{N.current&&$e.capabilities&&o($e.capabilities)}).catch(()=>{N.current&&o(Wg())})}catch(me){if(!N.current)return;_({kind:"error",message:me instanceof Error?me.message:"保存语音设置失败"})}}async function q(){if(R)return;if(A){_({kind:"error",message:A});return}const Z=Ft;if(!Z){_({kind:"error",message:"请先连接 Relay 服务器"});return}let ae;try{ae=K()}catch(le){_({kind:"error",message:aI(le)});return}_({kind:"testing"});try{const[le]=await Promise.all([Z.testVoiceConfig(Y()),ae.ready]);if(!le.success||le.error){$(),_({kind:"error",message:le.error??"语音配置测试失败"});return}const me=await Q(le,ae.context);_({kind:"playingTest",transcript:le.transcript}),k.current=setTimeout(()=>{k.current=null,$(),_({kind:"testPassed",transcript:le.transcript})},me)}catch(le){$(),_({kind:"error",message:aI(le)})}}function K(){$();const Z=hk.acquire("playback");x.current=Z;try{const ae=lfe();return w.current=ae,{context:ae,ready:oI(ae)}}catch(ae){throw Z.release(),x.current=null,ae}}function $(){var Z,ae,le;k.current&&(clearTimeout(k.current),k.current=null),(Z=S.current)==null||Z.stop(),S.current=null,(ae=w.current)==null||ae.close(),w.current=null,(le=x.current)==null||le.release(),x.current=null}function re(){T.current&&(clearTimeout(T.current),T.current=null)}async function Q(Z,ae){if(!Z.audioBase64)throw new Error("语音测试未返回可播放音频");if(Z.audioEncoding&&Z.audioEncoding!=="pcm_s16le")throw new Error("测试音频格式暂不支持");const le=Z.audioSampleRate??24e3,me=afe(Z.audioBase64);if(me.byteLength===0||me.byteLength%2!==0)throw new Error("测试音频数据无效");await oI(ae);const ke=new W4(ae,le);S.current=ke,ke.enqueue(me);const $e=Math.ceil(me.byteLength/2/le*1e3);return Math.max(ife,$e)}function G(Z){var ae;return((ae=g1(s.ttsVoices,Z)[0])==null?void 0:ae.value)??""}return m.jsxs("form",{className:"flex min-h-0 min-w-0 flex-1 flex-col","data-slot":"voice-settings-panel",autoComplete:"off",onSubmit:Z=>{Z.preventDefault(),z()},children:[m.jsx("div",{className:"flex min-h-0 flex-1 flex-col px-4 py-3 sm:px-5 sm:py-3.5","data-slot":"voice-settings-body-frame",children:m.jsx("div",{className:"dev-render-scroll min-h-0 flex-1 overflow-y-auto overscroll-contain pr-4 sm:pr-1","data-slot":"voice-settings-scroll",ref:e,children:m.jsxs("div",{className:"space-y-3","data-slot":"voice-settings-fields",children:[m.jsx("div",{className:"grid gap-2 rounded-lg border border-border/75 bg-card/55 p-3.5 sm:p-3",children:m.jsxs("div",{className:"flex items-center justify-between gap-3",children:[m.jsxs("div",{className:"min-w-0",children:[m.jsx("div",{className:"text-[13px] font-medium leading-none text-muted-foreground",children:"服务商"}),m.jsx("div",{className:"mt-2 truncate text-base font-medium text-foreground md:text-sm",children:"阿里云百炼"})]}),m.jsx("span",{className:"shrink-0 rounded-full border border-primary/35 bg-primary/10 px-2.5 py-1 text-xs font-medium text-primary",children:"Bailian"})]})}),m.jsx(iI,{label:"阿里云百炼 API Key",help:d?"保存后会清空已保存的 key":null,children:m.jsxs("div",{className:"flex min-w-0 gap-2",children:[m.jsxs("div",{className:"relative min-w-0 flex-1",children:[m.jsx(tz,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":"true"}),m.jsx("input",{"aria-label":"阿里云百炼 API Key",type:"password",name:"dev-anywhere-bailian-api-key",autoComplete:"off",value:l,onChange:Z=>{u(Z.target.value),f(!1)},placeholder:d?"保存后清空":t.configured?"••••••••••••••••":"输入 API Key",className:`${nI} w-full pl-9`})]}),t.configured&&m.jsxs(gt,{type:"button",variant:"outline",className:"min-h-11 shrink-0 px-3 md:h-9 md:min-h-0",onClick:()=>{u(""),f(!0)},children:[m.jsx(az,{className:"size-4","aria-hidden":"true"}),"清空"]})]})}),m.jsx(sv,{label:"地域",value:t.region,options:O,onChange:Z=>n(ae=>({...ae,region:Z==="intl"?"intl":"cn"}))}),m.jsx(sv,{label:"语音识别模型",value:t.asrModel,options:I,onChange:Z=>n(ae=>({...ae,asrModel:Z}))}),m.jsx(sv,{label:"语音合成模型",value:t.ttsModel,options:B,onChange:Z=>n(ae=>({...ae,ttsModel:Z,ttsVoice:G(Z)}))}),m.jsx(sv,{label:"语音音色",value:X,options:F,placeholder:M.length===0?"暂无可用音色":"请选择音色",onChange:Z=>n(ae=>({...ae,ttsVoice:Z})),help:U}),m.jsx(iI,{label:"结束停顿时间(秒)",help:j,children:m.jsx("input",{"aria-label":"结束停顿时间(秒)",type:"number",min:1,step:1,inputMode:"numeric",value:r,onChange:Z=>i(Z.target.value),className:`${nI} w-full`})})]})})}),m.jsxs("div",{className:"bg-background/95 px-4 pb-3.5 pt-0 backdrop-blur sm:px-5","data-slot":"voice-settings-footer",children:[m.jsx("div",{className:"mr-4 border-t border-border/70","data-slot":"voice-settings-footer-divider"}),m.jsxs("div",{className:"mt-3.5 flex items-center justify-end gap-2",children:[P?m.jsx("div",{role:g.kind==="error"?"alert":"status","aria-live":"polite",className:g.kind==="error"?"min-w-0 flex-1 text-sm text-destructive":"min-w-0 flex-1 text-sm text-muted-foreground",children:P}):null,m.jsxs(gt,{type:"button",variant:"outline",disabled:D,onClick:()=>void q(),children:[m.jsx(iz,{className:"size-4","aria-hidden":"true"}),"测试"]}),m.jsxs(gt,{type:"submit",disabled:D,children:[m.jsx(_Y,{className:"size-4","aria-hidden":"true"}),g.kind==="saving"?"保存中...":"保存"]})]})]})]})}function afe(e){const t=window.atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r+=1)n[r]=t.charCodeAt(r);return n}function lfe(){const e=window,t=e.AudioContext??e.webkitAudioContext;if(!t)throw new Error("当前浏览器不支持音频播放");return new t}async function oI(e){if(e.state!=="running")try{await e.resume()}catch{throw new Error("浏览器阻止了测试音频播放,请再次点击测试")}if(e.state!=="running")throw new Error("浏览器阻止了测试音频播放,请再次点击测试")}function aI(e){return e instanceof Error?e.message:"语音配置测试失败"}function cfe(e){return new Promise(t=>setTimeout(t,e))}function ufe(e){const t=e.trim();if(!/^[1-9]\d*$/.test(t))return null;const n=Number(t);return Number.isSafeInteger(n)?n:null}function lI(e,t){const n=e.map(r=>({value:r.value,label:V4(r)}));return!t||n.some(r=>r.value===t)?n:[{value:t,label:t},...n]}function dfe(e,t,n){const r=e.map(i=>{const s=g1(t,i.value).length===0;return{value:i.value,label:`${V4(i)}${s?" · 暂无音色":""}`,disabled:s}});return!n||r.some(i=>i.value===n)?r:[{value:n,label:`${n} · 暂无音色`,disabled:!0},...r]}function q4(e){const t=e.split(" · ").map(n=>n.trim()).filter(Boolean);return t.length<=1?{title:e,detail:null}:{title:t[0],detail:t.slice(1).join(" · ")}}function V4(e){if(!e.age)return e.label;const t=`年龄 ${e.age}`;if(e.label.includes(t))return e.label;const n=` · ${e.age}`;return e.label.endsWith(n)?`${e.label.slice(0,-n.length)} · ${t}`:`${e.label} · ${t}`}const ffe=[{value:"auto",label:"跟随系统"},{value:"light",label:"浅色"},{value:"dark",label:"深色"}],hfe=[{value:"auto",label:"自动"},{value:"touch",label:"触控优先"},{value:"hardware",label:"实体键盘优先"}],pk="dev-render-scroll min-h-0 space-y-3 overflow-y-auto overscroll-contain pr-4 sm:pr-1";function Y4(e){if(!Number.isFinite(e)||e<0)return"未知";if(e<60)return`${Math.floor(e)} 秒`;const t=Math.floor(e/60);if(t<60)return`${t} 分钟`;const n=Math.floor(t/60),r=t%60;if(n<24)return r>0?`${n} 小时 ${r} 分钟`:`${n} 小时`;const i=Math.floor(n/24),s=n%24;return s>0?`${i} 天 ${s} 小时`:`${i} 天`}function pfe(e){const t=e||window.location.origin;return new URL("/health",t).toString()}function mfe(e){return e==="version"?"版本":e==="relay-token"?"Relay Token":e==="clients"?"客户端管理":"设置 Voice Pilot"}function gfe(e){return e==="version"?"Web 与 Relay 服务器版本。":e==="relay-token"?"连接受保护的 Relay 服务器,保存后立即重连。":e==="clients"?"管理当前连接的 Web 客户端。":"连接语音服务后,即可以语音交互的形式驱动会话。"}function v1({open:e,onOpenChange:t}){const n=Ie(V=>V.relayUrl),r=Ie(V=>V.latencyMonitorEnabled),i=Ie(V=>V.setLatencyMonitorEnabled),s=Ie(V=>V.sessionIdleNotificationsEnabled),o=Ie(V=>V.setSessionIdleNotificationsEnabled),l=Ie(V=>V.inputModePreference),u=Ie(V=>V.setInputModePreference),d=Ie(V=>V.themePreference),f=Ie(V=>V.setThemePreference),p=Ie(V=>V.ptyScrollTraceEnabled),y=Ie(V=>V.setPtyScrollTraceEnabled),[g,_]=b.useState("menu"),[w,x]=b.useState(e),[S,k]=b.useState({kind:"idle"}),T=b.useRef(null),N=b.useRef(null),P=qie(),R=b.useMemo(()=>rf().osName==="iPad",[]);e!==w&&(x(e),e&&_("menu"));const M=b.useCallback(async V=>{if(!V){o(!1);return}const j=await gie();if(j==="granted"){o(!0);return}if(j==="denied"){We.error("浏览器未授予通知权限,请在浏览器设置中允许通知");return}if(j==="default"){We.info("未授予通知权限,会话通知保持关闭");return}We.error("当前浏览器不支持系统通知")},[o]),L=b.useCallback(async V=>{k({kind:"loading"});try{const j=await fetch(pfe(n),{cache:"no-store",signal:V});if(!j.ok)throw new Error(`HTTP ${j.status}`);const A=await j.json();if(A.status!=="ok")throw new Error("状态异常");k({kind:"ready",version:A.version??"未知",uptime:A.uptime??0})}catch(j){if(j instanceof DOMException&&j.name==="AbortError")return;k({kind:"error",message:j instanceof Error?"当前 Relay 服务器无法读取版本":"读取失败"})}},[n]);b.useEffect(()=>{if(!e||g!=="version")return;const V=new AbortController;return L(V.signal),()=>V.abort()},[L,e,g]),b.useEffect(()=>{if(!e||g!=="voice")return;const V=window.requestAnimationFrame(()=>{var j;(j=T.current)==null||j.focus({preventScroll:!0}),N.current&&(N.current.scrollTop=0)});return()=>window.cancelAnimationFrame(V)},[e,g]);const X=S.kind==="ready"?S.version:S.kind==="loading"?"读取中...":S.kind==="error"?"读取失败":"未读取",U=S.kind==="ready"?`运行 ${Y4(S.uptime)}`:S.kind==="error"?S.message:"从当前 Relay 服务器 /health 读取";return m.jsx(ss,{open:e,onOpenChange:t,children:m.jsxs(os,{className:Ye("grid max-h-[calc(100dvh-1rem)] grid-rows-[auto_minmax(0,1fr)] overflow-hidden p-4 sm:max-w-[440px] sm:p-6",g==="voice"&&"max-h-[min(760px,calc(100dvh-1rem))] !gap-0 !p-0 sm:max-w-[480px]",g==="voice"&&"max-sm:top-auto max-sm:bottom-0 max-sm:left-2 max-sm:right-2 max-sm:h-[calc(100dvh-1rem)] max-sm:w-auto max-sm:max-h-none max-sm:max-w-none max-sm:translate-x-0 max-sm:translate-y-0 max-sm:rounded-b-none max-sm:rounded-t-2xl max-sm:border-x max-sm:border-b-0"),"data-slot":"settings-dialog","data-view":g,focusSurfaceOnOpen:!0,ref:T,showCloseButton:g==="menu",children:[m.jsx(as,{className:Ye(g==="menu"&&"pr-12 text-left",g!=="menu"&&"text-left",g==="voice"&&"gap-0 px-4 pb-0 pt-3.5 text-left sm:px-5 sm:pt-4"),children:g!=="menu"?m.jsxs(m.Fragment,{children:[m.jsxs("div",{className:"flex items-start gap-2",children:[m.jsx(gt,{type:"button",variant:"ghost",size:"icon",className:"-ml-2 mt-0.5 size-11 sm:size-9","aria-label":"返回设置","data-slot":"voice-settings-back",onClick:()=>_("menu"),children:m.jsx(Qp,{className:"size-4","aria-hidden":"true"})}),m.jsxs("div",{className:"min-w-0 space-y-1.5 pt-0.5 text-left",children:[m.jsx(Yi,{children:mfe(g)}),m.jsx(_s,{className:"max-w-[28rem] leading-5",children:gfe(g)})]})]}),g==="voice"?m.jsx("div",{className:"mr-4 mt-3.5 border-t border-border/70","data-slot":"voice-settings-header-divider"}):null]}):m.jsxs(m.Fragment,{children:[m.jsx(Yi,{children:"设置"}),m.jsx(_s,{children:"连接、外观、通知和高级诊断选项。"})]})}),g==="version"?m.jsx(vfe,{relayVersion:X,relayDetail:U,relayMuted:S.kind==="error"}):g==="relay-token"?m.jsx(bfe,{saved:P}):g==="clients"?m.jsx(Efe,{}):g==="voice"?m.jsx(ofe,{scrollRef:N}):m.jsx(yfe,{relayTokenSaved:P,themePreference:d,onThemePreferenceChange:f,inputModePreference:l,onInputModePreferenceChange:u,showInputModeSetting:R,sessionIdleNotificationsEnabled:s,onSessionIdleNotificationsEnabledChange:M,ptyScrollTraceEnabled:p,onPtyScrollTraceEnabledChange:y,latencyMonitorEnabled:r,onLatencyMonitorEnabledChange:i,onOpenVoice:()=>_("voice"),onOpenRelayToken:()=>_("relay-token"),onOpenClients:()=>_("clients"),onOpenVersion:()=>_("version")})]})})}function vfe({relayVersion:e,relayDetail:t,relayMuted:n}){return m.jsxs("div",{className:pk,"data-slot":"settings-dialog-body",children:[m.jsx(uI,{icon:m.jsx(rz,{className:"size-4","aria-hidden":"true"}),label:"Web",value:Zde.version,detail:"当前浏览器加载的版本"}),m.jsx(uI,{icon:m.jsx(sz,{className:"size-4","aria-hidden":"true"}),label:"Relay 服务器",value:e,detail:t,muted:n})]})}function yfe({relayTokenSaved:e,themePreference:t,onThemePreferenceChange:n,inputModePreference:r,onInputModePreferenceChange:i,showInputModeSetting:s,sessionIdleNotificationsEnabled:o,onSessionIdleNotificationsEnabledChange:l,ptyScrollTraceEnabled:u,onPtyScrollTraceEnabledChange:d,latencyMonitorEnabled:f,onLatencyMonitorEnabledChange:p,onOpenVoice:y,onOpenRelayToken:g,onOpenClients:_,onOpenVersion:w}){return m.jsxs("div",{className:"dev-render-scroll min-h-0 space-y-4 overflow-y-auto overscroll-contain pr-4 sm:pr-1","data-slot":"settings-dialog-body",children:[m.jsxs(td,{title:"服务",children:[m.jsx(ov,{icon:m.jsx(K7,{className:"size-4","aria-hidden":"true"}),label:"Voice Pilot",detail:"用语音输入、听取回复和处理审批",onClick:y}),m.jsx(ov,{icon:m.jsx(tz,{className:"size-4","aria-hidden":"true"}),label:"Relay Token",detail:`${e?"已保存":"未设置"} · 受保护的 Relay 服务器`,onClick:g}),m.jsx(ov,{icon:m.jsx(HY,{className:"size-4","aria-hidden":"true"}),label:"客户端管理",detail:"已连接的浏览器页面和设备",onClick:_})]}),m.jsx(td,{title:"外观",children:m.jsx(cI,{icon:m.jsx(MY,{className:"size-4","aria-hidden":"true"}),label:"主题",value:t,options:ffe,onValueChange:n})}),m.jsx(td,{title:"通知",children:m.jsx(a0,{icon:m.jsx(X7,{className:"size-4","aria-hidden":"true"}),label:"会话空闲通知",detail:"会话从工作中转为空闲时发送浏览器通知",checked:o,onCheckedChange:l})}),s?m.jsx(td,{title:"交互",children:m.jsx(cI,{icon:m.jsx(nz,{className:"size-4","aria-hidden":"true"}),label:"输入方式",detail:"默认自动识别软键盘和实体键盘;必要时可强制一种方式",value:r,options:hfe,onValueChange:i})}):null,m.jsxs(td,{title:"高级诊断",children:[m.jsx(a0,{icon:m.jsx(Ep,{className:"size-4","aria-hidden":"true"}),label:"PTY 滚动追踪",detail:"记录终端滚动和视口同步现场,方便复制诊断报告",checked:u,onCheckedChange:d}),m.jsx(a0,{icon:m.jsx(YB,{className:"size-4","aria-hidden":"true"}),label:"延迟监控",detail:"显示可拖动的连接延迟浮窗",checked:f,onCheckedChange:p})]}),m.jsx(td,{title:"关于",children:m.jsx(ov,{icon:m.jsx(sz,{className:"size-4","aria-hidden":"true"}),label:"版本",onClick:w})})]})}function td({title:e,children:t}){return m.jsxs("section",{className:"space-y-2","data-slot":"settings-section",children:[m.jsx("h3",{className:"px-1 text-xs font-medium text-muted-foreground",children:e}),m.jsx("div",{className:"overflow-hidden rounded-lg border border-border bg-card/55 divide-y divide-border/70",children:t})]})}function cI({icon:e,label:t,detail:n,value:r,options:i,onValueChange:s}){const o=b.useId(),l=b.useId();return m.jsxs("div",{className:"flex w-full items-start gap-3 px-3 py-3 text-left","data-slot":"settings-choice-item",children:[m.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-md bg-background/55 text-muted-foreground",children:e}),m.jsxs("div",{className:"min-w-0 flex-1",children:[m.jsx("div",{id:o,className:"text-sm font-medium text-foreground",children:t}),n?m.jsx("div",{id:l,className:"mt-1 text-xs text-muted-foreground",children:n}):null,m.jsx("div",{role:"radiogroup","aria-labelledby":o,"aria-describedby":n?l:void 0,className:"mt-3 grid grid-cols-3 gap-1 rounded-md border border-border bg-muted/70 p-1","data-slot":"settings-segmented-choice",children:i.map(u=>{const d=u.value===r;return m.jsx("button",{type:"button",role:"radio","aria-checked":d,className:Ye("min-w-0 whitespace-nowrap rounded px-2 py-1.5 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",d?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:bg-background/55 hover:text-foreground"),onClick:()=>s(u.value),children:u.label},u.value)})})]})]})}function bfe({saved:e}){const t=b.useId(),n=b.useId(),[r,i]=b.useState(""),[s,o]=b.useState(null),l=()=>{Yj().catch(f=>{o(f instanceof Error?f.message:"Relay 重连失败。")})},u=()=>{const f=r.trim();if(!f){o("请输入 token。");return}if(!qj(f)){const p="Relay Token 保存失败,请检查浏览器存储权限。";o(p),We.error(p);return}o(null),We.success("Relay Token 已保存,正在重新连接"),l()},d=()=>{Vj(),l()};return m.jsxs("form",{className:pk,"data-slot":"settings-dialog-body",onSubmit:f=>{f.preventDefault(),u()},children:[m.jsxs("div",{className:"rounded-md border border-border bg-card/70 p-3","data-slot":"relay-token-card",children:[m.jsx("label",{htmlFor:t,className:"text-sm font-medium text-foreground",children:"Token"}),m.jsx("input",{id:t,type:"password",value:r,onChange:f=>{i(f.currentTarget.value),s&&o(null)},autoComplete:"off",spellCheck:!1,"aria-describedby":s?n:void 0,className:"mt-2 h-10 w-full rounded-md border border-border bg-background px-3 font-mono text-sm text-foreground outline-none transition-colors placeholder:text-muted-foreground focus:border-ring focus:ring-2 focus:ring-ring/75",placeholder:"粘贴 token"}),s?m.jsx("p",{id:n,className:"mt-2 text-xs text-destructive",children:s}):null]}),m.jsxs("div",{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",children:[e?m.jsx(gt,{type:"button",variant:"outline",onClick:d,children:"清空"}):null,m.jsx(gt,{type:"submit",disabled:!r.trim(),children:"保存"})]})]})}function _fe(e){return e.length<=16?e:`${e.slice(0,8)}...${e.slice(-4)}`}function wfe(e,t){var r;return((r=t.get(e))==null?void 0:r.trim())||_fe(e)}function xfe(e){return ane(e)}function Sfe(e){const t=Math.max(0,Math.floor((Date.now()-e)/1e3));return Y4(t)}function o0({label:e,value:t,title:n}){return m.jsxs("div",{className:"grid grid-cols-[3.75rem_minmax(0,1fr)] items-baseline gap-2 text-xs leading-5",children:[m.jsx("span",{className:"shrink-0 text-muted-foreground/80",children:e}),m.jsx("span",{className:"min-w-0 truncate text-muted-foreground",title:n??t,children:t})]})}function Efe(){const e=Ie(y=>y.proxies),[t,n]=b.useState([]),[r,i]=b.useState(!0),[s,o]=b.useState(null),[l,u]=b.useState(null),d=b.useMemo(()=>new Map(e.map(y=>[y.proxyId,y.name]).filter(y=>typeof y[1]=="string")),[e]),f=b.useCallback(async()=>{const y=Ft;if(!y){n([]),o("Relay 未连接。"),i(!1);return}i(!0),o(null);try{n(await y.requestRelayClients())}catch(g){o(g instanceof Error?g.message:"读取客户端列表失败。")}finally{i(!1)}},[]);b.useEffect(()=>{f()},[f]);const p=b.useCallback(async y=>{const g=Ft;if(!g){o("Relay 未连接。");return}u(y),o(null);try{const _=await g.kickRelayClient(y);if(!_.success){o(_.error??"断开客户端失败。");return}n(w=>w.filter(x=>x.clientId!==y))}catch(_){o(_ instanceof Error?_.message:"断开客户端失败。")}finally{u(null)}},[]);return m.jsxs("div",{className:pk,"data-slot":"settings-dialog-body",children:[m.jsxs("div",{className:"flex min-h-9 items-center gap-2","data-slot":"relay-clients-toolbar",children:[m.jsx("div",{className:"text-sm font-medium text-foreground",children:r?"正在读取客户端":`${t.length} 个在线客户端`}),m.jsx(gt,{type:"button",variant:"ghost",size:"icon-sm","aria-label":"刷新客户端列表",title:"刷新",onClick:()=>void f(),disabled:r,"data-slot":"relay-clients-refresh",children:m.jsx(em,{className:Ye("size-3.5",r&&"animate-spin"),"aria-hidden":"true"})})]}),s?m.jsx("div",{className:"rounded-md border border-destructive/35 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:s}):null,!r&&t.length===0?m.jsx("div",{className:"rounded-md border border-border bg-card/70 px-3 py-6 text-center text-sm text-muted-foreground",children:"当前没有在线客户端"}):null,t.map(y=>{const g=y.current===!0,_=l===y.clientId;return m.jsx("div",{className:"rounded-md border border-border bg-card/70 p-3","data-slot":"relay-client-row","data-client-id":y.clientId,title:`客户端 ${y.clientId}`,children:m.jsxs("div",{className:"grid gap-3 sm:grid-cols-[minmax(0,1fr)_7.5rem] sm:items-start",children:[m.jsxs("div",{className:"min-w-0 space-y-1.5",children:[m.jsx("div",{className:"min-w-0",children:m.jsx("div",{className:"truncate text-sm font-medium leading-5 text-foreground",children:xfe(y)})}),m.jsxs("div",{className:"space-y-1",children:[m.jsx(o0,{label:"已连接",value:Sfe(y.connectedAt)}),y.proxyId?m.jsx(o0,{label:"连接到",value:wfe(y.proxyId,d),title:y.proxyId}):null,y.remoteAddress?m.jsx(o0,{label:"来源 IP",value:y.remoteAddress}):null]})]}),g?m.jsx("div",{className:"inline-flex h-9 w-full items-center justify-center rounded-md border border-primary/30 bg-primary/10 px-3 text-sm font-normal text-primary","aria-label":"当前设备","data-slot":"relay-client-current-indicator",children:"当前设备"}):m.jsxs(gt,{type:"button",variant:"outline",size:"sm",className:"h-9 w-full justify-center",disabled:_,onClick:()=>void p(y.clientId),"data-slot":"relay-client-action",children:[m.jsx(GV,{className:"size-3.5","aria-hidden":"true"}),_?"断开中...":"断开"]})]})},y.clientId)})]})}function a0({icon:e,label:t,detail:n,checked:r,onCheckedChange:i}){const s=b.useId(),o=b.useId();return m.jsxs("button",{type:"button",role:"switch",className:"group flex w-full items-center gap-3 px-3 py-3 text-left transition-colors hover:bg-accent/55 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",onClick:()=>i(!r),"aria-checked":r,"aria-labelledby":s,"aria-describedby":o,"data-slot":"settings-toggle-item",children:[m.jsx("div",{className:Ye("flex size-8 shrink-0 items-center justify-center rounded-md bg-background/55 transition-colors",r?"text-primary":"text-muted-foreground"),children:e}),m.jsxs("div",{className:"min-w-0 flex-1",children:[m.jsx("div",{id:s,className:"text-sm font-medium text-foreground",children:t}),m.jsx("div",{id:o,className:"mt-1 text-xs text-muted-foreground",children:n})]}),m.jsx("span",{className:Ye("relative h-6 w-11 shrink-0 rounded-full border transition-colors",r?"border-primary/65 bg-primary/70":"border-border bg-muted/50"),"aria-hidden":"true","data-slot":"settings-toggle-switch",children:m.jsx("span",{className:Ye("absolute top-1/2 size-4 -translate-y-1/2 rounded-full bg-background shadow-sm transition-transform",r?"translate-x-[1.35rem]":"translate-x-1")})})]})}function ov({icon:e,label:t,detail:n,onClick:r}){const i=b.useId(),s=b.useId();return m.jsxs("button",{type:"button",className:"group flex w-full items-center gap-3 px-3 py-3 text-left transition-colors hover:bg-accent/55 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",onClick:r,"aria-labelledby":i,"aria-describedby":n?s:void 0,"data-slot":"settings-menu-item",children:[m.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-md bg-background/55 text-muted-foreground transition-colors group-hover:text-foreground",children:e}),m.jsxs("div",{className:"min-w-0 flex-1",children:[m.jsx("div",{id:i,className:"text-sm font-medium text-foreground",children:t}),n?m.jsx("div",{id:s,className:"mt-1 text-xs text-muted-foreground",children:n}):null]}),m.jsx(dp,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"})]})}function uI({icon:e,label:t,value:n,detail:r,muted:i=!1}){return m.jsxs("div",{className:"flex gap-3 rounded-md border border-border bg-card/70 p-3",children:[m.jsx("div",{className:Ye("mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-md border",i?"border-border text-muted-foreground":"border-primary/35 bg-primary/10 text-primary"),children:e}),m.jsxs("div",{className:"min-w-0 flex-1",children:[m.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[m.jsx("div",{className:"text-sm text-muted-foreground",children:t}),m.jsx("div",{className:"min-w-0 truncate font-mono text-sm text-foreground",children:n})]}),m.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:r})]})]})}const Cfe="xterm-helper-textarea";function kfe(e=document.activeElement){return!(e instanceof HTMLElement)||!e.classList.contains(Cfe)?!1:(e.blur(),!0)}function dI(e,t,n){if(!e||Math.abs(n)<1)return!1;let r=e instanceof Element?e:null;for(;r&&t.contains(r);){if(r instanceof HTMLElement&&Tfe(r,n))return!0;if(r===t)break;r=r.parentElement}return!1}function Tfe(e,t){if(e.scrollHeight<=e.clientHeight+1)return!1;const n=window.getComputedStyle(e).overflowY;return n!=="auto"&&n!=="scroll"&&n!=="overlay"?!1:t<0?e.scrollTop>0:e.scrollTop+e.clientHeight<e.scrollHeight-1}function Rfe({releasePtyFocus:e=!0,containVerticalScroll:t=!0}={}){const n=b.useRef(null),r=b.useCallback(()=>{e&&kfe()},[e]),i=b.useCallback(l=>{var u;n.current=((u=l.touches[0])==null?void 0:u.clientY)??null,r()},[r]),s=b.useCallback(l=>{if(!t)return;const u=l.touches[0];if(!u)return;const f=(n.current??u.clientY)-u.clientY;n.current=u.clientY,dI(l.target,l.currentTarget,f)||l.preventDefault()},[t]),o=b.useCallback(l=>{r(),t&&(dI(l.target,l.currentTarget,l.deltaY)||l.preventDefault())},[t,r]);return{onPointerDownCapture:r,onTouchStartCapture:i,onTouchMoveCapture:s,onWheelCapture:o}}function Afe({className:e}){const t=Ie(o=>o.sidebarCollapsed),n=Ie(o=>o.toggleSidebarCollapsed),[r,i]=b.useState(!1),s=Rfe();return t?m.jsxs(m.Fragment,{children:[m.jsxs("nav",{className:Ye("dev-sidebar-shell dev-sidebar-rail relative flex-col items-center w-12 shrink-0 bg-card border-r border-border overflow-hidden px-1.5 pb-[calc(var(--dev-safe-area-bottom,env(safe-area-inset-bottom))+0.5rem)] pt-[max(0.5rem,env(safe-area-inset-top))]",e),"aria-label":"侧边栏","data-slot":"sidebar-rail","data-collapsed":"true",...s,children:[m.jsx(hI,{collapsed:!0,onClick:n}),m.jsx("div",{className:"mt-3 h-px w-5 bg-border/70","aria-hidden":"true"}),m.jsxs("div",{className:"mt-auto flex flex-col gap-2",children:[m.jsx(fI,{compact:!0,tooltipSide:"right",onClick:()=>i(!0)}),m.jsx(Q2,{compact:!0})]})]}),m.jsx(v1,{open:r,onOpenChange:i})]}):m.jsxs(m.Fragment,{children:[m.jsxs("nav",{className:Ye("dev-sidebar-shell group/sidebar relative flex-col w-[280px] shrink-0 bg-card border-r border-border overflow-visible pt-[env(safe-area-inset-top)]",e),"aria-label":"侧边栏","data-slot":"sidebar","data-collapsed":"false",...s,children:[m.jsx("div",{className:"dev-sidebar-fade p-2.5","data-slot":"sidebar-proxy-switcher",children:m.jsxs("div",{className:"dev-sidebar-chrome rounded-lg border p-3",children:[m.jsxs("div",{className:"flex items-center justify-between gap-3",children:[m.jsx(Cz,{className:"text-[13px]",slot:"sidebar-brand"}),m.jsx(hI,{collapsed:!1,onClick:n})]}),m.jsx("div",{className:"mt-2.5",children:m.jsx(R4,{layout:"dropdown",variant:"sidebarChrome"})})]})}),m.jsx("div",{className:"dev-sidebar-fade flex min-h-0 flex-1 flex-col overflow-hidden","data-slot":"sidebar-session-list",children:m.jsx("div",{className:"flex-1 min-h-0",children:m.jsx($4,{layout:"sidebar"})})}),m.jsxs("div",{className:"dev-sidebar-fade flex shrink-0 gap-2 px-2 pb-[calc(var(--dev-safe-area-bottom,env(safe-area-inset-bottom))+0.5rem)] pt-2","data-slot":"sidebar-new-session",children:[m.jsx("div",{className:"min-w-0 flex-1",children:m.jsx(Q2,{})}),m.jsx("div",{className:"min-w-0 flex-1",children:m.jsx(fI,{onClick:()=>i(!0)})})]})]}),m.jsx(v1,{open:r,onOpenChange:i})]})}function fI({compact:e=!1,tooltipSide:t="top",onClick:n}){return m.jsxs(hf,{delayDuration:500,children:[m.jsx(pf,{asChild:!0,children:m.jsxs("button",{type:"button","aria-label":"设置","data-slot":"sidebar-settings-trigger",onClick:n,className:Ye("inline-flex items-center justify-center shrink-0 border text-muted-foreground outline-none transition-[color,background-color,border-color,box-shadow]","focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",e?"h-11 w-11 rounded-md border-border bg-card/70 hover:border-primary/60 hover:bg-accent hover:text-foreground":"h-[46px] w-full gap-2 rounded-md border-border bg-background hover:border-primary/50 hover:bg-accent hover:text-foreground"),children:[m.jsx(oz,{className:"size-4","aria-hidden":"true"}),!e&&m.jsx("span",{className:"truncate text-sm font-medium",children:"设置"})]})}),m.jsx(mf,{side:t,sideOffset:10,hideArrow:!0,className:"border border-border/80 bg-card/95 px-2.5 py-1 text-muted-foreground shadow-sm backdrop-blur",children:"设置"})]})}function hI({collapsed:e,onClick:t}){const n=e?"展开侧边栏":"收起侧边栏",r=e?oY:iY;return m.jsxs(hf,{delayDuration:500,children:[m.jsx(pf,{asChild:!0,children:m.jsx("button",{type:"button","aria-label":n,"data-slot":e?"sidebar-expand-trigger":"sidebar-collapse-trigger",onClick:t,className:Ye("group inline-flex items-center justify-center text-muted-foreground outline-none transition-[opacity,color,background-color,border-color,box-shadow,transform]","outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",e?"h-9 w-9 rounded-md border border-border/80 bg-card/70 hover:border-primary/60 hover:bg-accent hover:text-foreground":"h-9 w-9 rounded-full border border-primary/25 bg-primary/10 hover:border-primary/60 hover:bg-primary/15 hover:text-foreground"),children:m.jsx(r,{className:Ye("size-3.5 transition-transform",e&&"group-hover:translate-x-0.5",!e&&"group-hover:-translate-x-0.5"),"aria-hidden":"true"})})}),m.jsx(mf,{side:e?"right":"top",sideOffset:10,hideArrow:!0,className:"border border-border/80 bg-card/95 px-2.5 py-1 text-muted-foreground shadow-sm backdrop-blur",children:n})]})}const Nfe=1500,Mfe=300,pI=70,mI=35;function K4({texts:e,className:t}){const[n,r]=b.useState(""),[i,s]=b.useState(!0),o=b.useRef("typing"),l=b.useRef(0),u=b.useRef(0);b.useEffect(()=>{const f=setInterval(()=>s(p=>!p),530);return()=>clearInterval(f)},[]),b.useEffect(()=>{let f;const p=()=>e[u.current%e.length],y=()=>{const g=o.current;if(g==="typing"){const _=p();l.current<_.length?(l.current+=1,r(_.slice(0,l.current)),f=setTimeout(y,pI)):(o.current="paused",f=setTimeout(y,Nfe))}else g==="paused"?(o.current="deleting",f=setTimeout(y,mI)):g==="deleting"?l.current>0?(l.current-=1,r(p().slice(0,l.current)),f=setTimeout(y,mI)):(u.current+=1,o.current="waiting",f=setTimeout(y,Mfe)):(o.current="typing",f=setTimeout(y,pI))};return f=setTimeout(y,500),()=>clearTimeout(f)},[e]);const d=n.startsWith("DEV")?3:n.length<=3&&"DEV".startsWith(n)?n.length:0;return m.jsxs("div",{className:`font-mono leading-tight select-none ${t??""}`,"data-slot":"brand-typewriter",children:[m.jsx("span",{className:"text-green-500",children:"> "}),m.jsx("span",{className:"text-primary","data-slot":"brand-typewriter-dev",children:n.slice(0,d)}),m.jsx("span",{className:"text-foreground/90",children:n.slice(d)}),m.jsx("span",{className:`text-primary ${i?"opacity-100":"opacity-0"}`,children:"_"})]})}const G4=["DEV Anywhere","/unlimited @anytime"];function Pfe({subtitle:e,action:t}){return m.jsx("section",{className:"dev-mobile-brand-hero border-b border-border/80 px-4 pb-5 pt-[calc(env(safe-area-inset-top)+1.25rem)] md:hidden","data-slot":"mobile-brand-hero","aria-label":"DEV Anywhere",children:m.jsxs("div",{className:"dev-mobile-brand-content min-w-0 space-y-3 pr-12",children:[m.jsx(K4,{texts:G4,className:"dev-mobile-brand-typewriter max-w-full overflow-hidden text-ellipsis whitespace-nowrap font-bold tracking-normal"}),e?m.jsx("p",{className:"dev-mobile-brand-subtitle max-w-[34rem] text-sm leading-5 text-muted-foreground",children:e}):null,t?m.jsx("div",{className:"dev-mobile-brand-action flex max-w-full min-w-0 pt-1",children:t}):null]})})}const Ife=3e3,Ofe=1e4,av=12,Lfe=4,gI={webRelay:"浏览器 ↔ Relay 服务器",relayProxy:"Relay 服务器 ↔ 开发机",webProxy:"浏览器 ↔ 开发机"},Dfe={webRelay:{state:"idle"},relayProxy:{state:"idle"},webProxy:{state:"idle"}};function l0(e){if(!e.success||e.rttMs===void 0)return{state:"unavailable",error:e.error??"不可用",updatedAt:Date.now()};const t=e.rttMs;return{state:t<=120?"ok":t<=300?"warn":"bad",rttMs:t,updatedAt:Date.now()}}function nd(e){return{state:"unavailable",error:e,updatedAt:Date.now()}}function tp(e){return e===void 0||!Number.isFinite(e)?"--":`${Math.max(0,Math.round(e))}ms`}function vI(e){switch(e){case"bad":return 4;case"unavailable":return 3;case"warn":return 2;case"measuring":return 1;default:return 0}}function X4(e){return e==="bad"||e==="unavailable"?"bad":e==="warn"?"warn":e==="ok"?"ok":"neutral"}function Bfe(e){switch(e){case"ok":return"border-emerald-500/35 bg-emerald-500/10 text-emerald-300";case"warn":return"border-amber-500/40 bg-amber-500/10 text-amber-300";case"bad":return"border-destructive/55 bg-destructive/10 text-destructive";default:return"border-border bg-card/90 text-muted-foreground"}}function zfe(e){return e.state==="measuring"?"检测中":e.state==="unavailable"?e.error??"不可用":e.rttMs!==void 0?tp(e.rttMs):"等待检测"}function jfe(){const e=Si("local",wn.latencyMonitorPosition);if(!e)return null;try{const t=JSON.parse(e);return!Number.isFinite(t.x)||!Number.isFinite(t.y)?null:{x:Number(t.x),y:Number(t.y)}}catch{return null}}function yI(e){Tr("local",wn.latencyMonitorPosition,JSON.stringify(e))}function Ffe(){var e,t;return{width:((e=window.visualViewport)==null?void 0:e.width)??window.innerWidth??document.documentElement.clientWidth??0,height:((t=window.visualViewport)==null?void 0:t.height)??window.innerHeight??document.documentElement.clientHeight??0}}function c0(e,t){const n=Ffe(),r=av,i=av,s=Math.max(r,n.width-t.width-av),o=Math.max(i,n.height-t.height-av);return{x:Math.min(s,Math.max(r,Math.round(e.x))),y:Math.min(o,Math.max(i,Math.round(e.y)))}}function $fe(){const e=Ie(R=>R.latencyMonitorEnabled),t=Ie(R=>R.connected),n=Ie(R=>R.proxyOnline),r=Ie(R=>R.selectedProxyId),[i,s]=b.useState(Dfe),[o,l]=b.useState(()=>jfe()),u=b.useRef(!1),d=b.useRef(null),f=b.useRef(null),p=b.useRef(!1),y=b.useMemo(()=>(Object.values(i).sort((R,M)=>vI(M.state)-vI(R.state))[0]??{state:"idle"}).state,[i]),g=X4(y);async function _(){if(u.current)return;const R=Ft;if(!R||!t){const U=nd("Relay 服务器未连接");s({webRelay:U,relayProxy:U,webProxy:U});return}u.current=!0,s(U=>({webRelay:{...U.webRelay,state:"measuring"},relayProxy:n?{...U.relayProxy,state:"measuring"}:nd("未连接开发机"),webProxy:n?{...U.webProxy,state:"measuring"}:nd("未连接开发机")}));const[M,L,X]=await Promise.allSettled([R.measureWebRelayLatency(),n?R.measureRelayProxyLatency():Promise.resolve({success:!1}),n?R.measureWebProxyLatency():Promise.resolve({success:!1})]);s({webRelay:M.status==="fulfilled"?l0(M.value):nd(M.reason instanceof Error?M.reason.message:"测速失败"),relayProxy:L.status==="fulfilled"?l0(L.value):nd(L.reason instanceof Error?L.reason.message:"测速失败"),webProxy:X.status==="fulfilled"?l0(X.value):nd(X.reason instanceof Error?X.reason.message:"测速失败")}),u.current=!1}if(b.useEffect(()=>{if(!e)return;let R=!1,M=null;const L=async()=>{await _(),!R&&(M=setTimeout(L,document.hidden?Ofe:Ife))};return L(),()=>{R=!0,u.current=!1,M&&clearTimeout(M)}},[e,t,n,r]),b.useEffect(()=>{if(!e||!o)return;const R=d.current;if(!R)return;const M=R.getBoundingClientRect(),L=c0(o,{width:M.width,height:M.height});L.x===o.x&&L.y===o.y||(l(L),yI(L))},[e,o]),!e)return null;const w=i.webProxy.rttMs!==void 0?i.webProxy:i.relayProxy,x=o!==null?{left:`${o.x}px`,top:`${o.y}px`}:void 0;function S(R){var L,X;if(R.button!==0)return;const M=R.currentTarget.getBoundingClientRect();f.current={pointerId:R.pointerId,startX:R.clientX,startY:R.clientY,originX:M.left,originY:M.top,width:M.width,height:M.height,dragging:!1},(X=(L=R.currentTarget).setPointerCapture)==null||X.call(L,R.pointerId)}function k(R){const M=f.current;if(!M||M.pointerId!==R.pointerId)return;const L=R.clientX-M.startX,X=R.clientY-M.startY;if(!M.dragging&&Math.hypot(L,X)<Lfe)return;M.dragging=!0,R.preventDefault();const U=c0({x:M.originX+L,y:M.originY+X},{width:M.width,height:M.height});l(U)}function T(R){var V,j;const M=f.current;if(!M||M.pointerId!==R.pointerId||(f.current=null,(j=(V=R.currentTarget).releasePointerCapture)==null||j.call(V,R.pointerId),!M.dragging))return;R.preventDefault(),p.current=!0,window.setTimeout(()=>{p.current=!1},200);const L=R.clientX-M.startX,X=R.clientY-M.startY,U=c0({x:M.originX+L,y:M.originY+X},{width:M.width,height:M.height});l(U),yI(U)}function N(R){var L,X;const M=f.current;!M||M.pointerId!==R.pointerId||(f.current=null,(X=(L=R.currentTarget).releasePointerCapture)==null||X.call(L,R.pointerId))}function P(R){p.current&&(p.current=!1,R.preventDefault(),R.stopPropagation())}return m.jsxs(Rb,{children:[m.jsx(Ab,{asChild:!0,children:m.jsxs("button",{ref:d,type:"button",className:Ye("fixed z-40 flex max-w-[calc(100vw-1.5rem)] touch-none cursor-move select-none items-center gap-2 rounded-md border px-2.5 py-1.5 text-xs shadow-lg backdrop-blur transition-colors",o===null&&"right-[calc(env(safe-area-inset-right)+0.75rem)] top-[calc(env(safe-area-inset-top)+3.75rem)] md:right-4 md:top-4",Bfe(g)),style:x,"data-slot":"latency-monitor-trigger","aria-label":`延迟监控,Relay 服务器 ${tp(i.webRelay.rttMs)},开发机 ${tp(w.rttMs)}`,onPointerDown:S,onPointerMove:k,onPointerUp:T,onPointerCancel:N,onClickCapture:P,children:[m.jsx(YB,{className:"size-3.5","aria-hidden":"true"}),m.jsx("span",{className:"font-medium text-foreground",children:"延迟"}),m.jsxs("span",{className:"hidden text-muted-foreground sm:inline",children:["Relay ",tp(i.webRelay.rttMs)]}),m.jsxs("span",{className:"text-muted-foreground",children:["开发机 ",tp(w.rttMs)]}),m.jsx(Ql,{className:"size-3 text-muted-foreground","aria-hidden":"true"})]})}),m.jsxs(Nb,{align:"end",className:"w-[320px] p-3","data-slot":"latency-monitor-popover",children:[m.jsxs("div",{className:"flex items-start justify-between gap-3",children:[m.jsxs("div",{children:[m.jsx("div",{className:"text-sm font-medium text-foreground",children:"连接延迟"}),m.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:"数值越低,操作响应通常越快。"})]}),m.jsx(gt,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"立即测速",onClick:()=>void _(),children:m.jsx(em,{className:"size-3","aria-hidden":"true"})})]}),m.jsx("div",{className:"mt-3 space-y-2",children:Object.keys(gI).map(R=>m.jsx(Hfe,{label:gI[R],measurement:i[R]},R))})]})]})}function Hfe({label:e,measurement:t}){const n=X4(t.state);return m.jsxs("div",{className:"flex min-h-10 items-center justify-between gap-3 rounded-md border border-border/70 bg-card/60 px-3 py-2",children:[m.jsx("div",{className:"min-w-0 truncate text-xs font-medium text-foreground",children:e}),m.jsxs("div",{className:"flex items-center gap-2",children:[m.jsx("span",{className:Ye("size-1.5 rounded-full",n==="ok"?"bg-emerald-400":n==="warn"?"bg-amber-400":n==="bad"?"bg-destructive":"bg-muted-foreground/60"),"aria-hidden":"true"}),m.jsx("span",{className:"min-w-[4rem] text-right font-mono text-xs text-foreground",children:zfe(t)})]})]})}const Z4="/__dev_anywhere_debug/browser-state-dumps",Ufe=1500,Wfe=10,u0=80,mk=500,qfe=["id","class","data-slot","data-state","data-testid","role","aria-label","aria-hidden","name","type","autocomplete","autocorrect","autocapitalize","inputmode","enterkeyhint","virtualkeyboardpolicy","contenteditable","placeholder","href","src"],Vfe=["display","position","visibility","opacity","pointer-events","z-index","overflow","overflow-x","overflow-y","touch-action","transform","translate","color-scheme","background-color","color","font-size","line-height","padding-top","padding-right","padding-bottom","padding-left","margin-top","margin-right","margin-bottom","margin-left"];function bI(){if(typeof window>"u")return"off";const e=sF("debugDump");return e==="auto"?"auto":e!==null||the("debugInput")?"manual":"off"}function Yfe(e="manual"){const t={count:0,truncated:!1},n=window,r={schemaVersion:1,createdAt:new Date().toISOString(),trigger:e,url:{href:window.location.href,origin:window.location.origin,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash},browser:{userAgent:navigator.userAgent,language:navigator.language,languages:Array.from(navigator.languages??[]),platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints??0,cookieEnabled:navigator.cookieEnabled,onLine:navigator.onLine},viewport:Zfe(),document:{title:document.title,readyState:document.readyState,visibilityState:document.visibilityState,activeElement:_I(document.activeElement),selection:Qfe(),focusedInputs:Array.from(document.querySelectorAll("input, textarea, select, [contenteditable]")).filter(i=>i===document.activeElement||i.matches(":focus")).map(i=>_I(i)).filter(i=>!!i),root:Q4(document.documentElement,0,t),truncated:t.truncated,nodeCount:t.count},devAnywhere:{ptyDebug:rd(()=>{var i;return((i=n.__devAnywherePtyDebug)==null?void 0:i.call(n))??null}),ptyInputDebugSnapshot:rd(()=>n.__devAnywherePtyInputDebugSnapshot??null),ptyInputDebugText:n.__devAnywherePtyInputDebugText??null,ptyInputDebugEvents:rd(()=>n.__devAnywherePtyInputDebugEvents??null),ptyScrollTraceTail:rd(()=>wI(n.__devAnywherePtyScrollTrace)),jsonScrollTraceTail:rd(()=>wI(n.__devAnywhereJsonScrollTrace)),voicePilotDiagnostics:rd(()=>{var i;return((i=n.__devAnywhereVoicePilotDiagnostics)==null?void 0:i.snapshot())??null})}};return window.__devAnywhereLastBrowserStateDump=r,r}async function Kfe(e="manual"){const t=Yfe(e);return Gfe(t)}async function Gfe(e){const t=JSON.stringify(e,null,2),n=new Blob([t]).size;try{const r=await Xfe(t);return{status:"saved",path:r.path,bytes:r.bytes,endpoint:Z4}}catch(r){const i=oF(r),s=Jfe(e.createdAt);return ehe(s,t,"application/json")?{status:"downloaded",filename:s,bytes:n,endpointError:i}:{status:"failed",error:"无法保存或下载诊断包",endpointError:i}}}async function Xfe(e){const t=await fetch(Z4,{method:"POST",headers:{"content-type":"application/json"},body:e});if(!t.ok)throw new Error(`${t.status} ${await t.text()}`);const n=await t.json();if(!n.ok||!n.path||typeof n.bytes!="number")throw new Error("debug endpoint returned an invalid response");return{path:n.path,bytes:n.bytes}}function Q4(e,t,n){if(n.count>=Ufe||t>Wfe)return n.truncated=!0,{kind:"truncated"};if(n.count+=1,e.nodeType===Node.TEXT_NODE){const u=xI(e.textContent??"");return u?{kind:"text",text:zb(u,mk)}:{kind:"text",text:""}}if(!(e instanceof HTMLElement))return{kind:"truncated"};const r=[];let i=0;const s=Array.from(e.childNodes);for(const u of s.slice(0,u0))u.nodeType===Node.TEXT_NODE&&!xI(u.textContent??"")||r.push(Q4(u,t+1,n));s.length>u0&&(i=s.length-u0,n.truncated=!0);const o={kind:"element",tag:e.tagName.toLowerCase(),path:iF(e),attrs:J4(e),rect:eF(e),scroll:tF(e),style:nF(e)},l=rF(e);return l&&(o.value=l),r.length>0&&(o.children=r),i>0&&(o.omittedChildren=i),o}function _I(e){if(!(e instanceof HTMLElement))return null;const t=rF(e);return{path:iF(e),tag:e.tagName.toLowerCase(),id:e.id||null,className:e.className||null,attrs:J4(e),rect:eF(e),scroll:tF(e),style:nF(e),...t?{value:t}:{}}}function Zfe(){var n;const e=window.visualViewport,t=((n=screen.orientation)==null?void 0:n.type)??null;return{window:{innerWidth:window.innerWidth,innerHeight:window.innerHeight,outerWidth:window.outerWidth,outerHeight:window.outerHeight,devicePixelRatio:window.devicePixelRatio,scrollX:window.scrollX,scrollY:window.scrollY},visualViewport:e?{width:e.width,height:e.height,offsetLeft:e.offsetLeft,offsetTop:e.offsetTop,pageLeft:e.pageLeft,pageTop:e.pageTop,scale:e.scale}:null,screen:{width:screen.width,height:screen.height,availWidth:screen.availWidth,availHeight:screen.availHeight,orientation:t}}}function J4(e){const t={};for(const n of qfe){const r=e.getAttribute(n);r!==null&&(t[n]=zb(r,500))}return t}function eF(e){const t=e.getBoundingClientRect();return{x:bs(t.x),y:bs(t.y),width:bs(t.width),height:bs(t.height),top:bs(t.top),right:bs(t.right),bottom:bs(t.bottom),left:bs(t.left)}}function tF(e){return{top:bs(e.scrollTop),left:bs(e.scrollLeft),height:bs(e.scrollHeight),width:bs(e.scrollWidth),clientHeight:bs(e.clientHeight),clientWidth:bs(e.clientWidth)}}function nF(e){const t=window.getComputedStyle(e),n={};for(const r of Vfe)n[r]=t.getPropertyValue(r);return n}function rF(e){if(!(!(e instanceof HTMLInputElement)&&!(e instanceof HTMLTextAreaElement)))return{length:e.value.length,preview:zb(e.value,mk),selectionStart:e.selectionStart,selectionEnd:e.selectionEnd}}function Qfe(){var e;try{return zb(((e=window.getSelection())==null?void 0:e.toString())??"",mk)}catch{return null}}function iF(e){const t=[];let n=e;for(;n&&n!==document.documentElement;){let r=n.tagName.toLowerCase();if(n.id){r+=`#${n.id}`,t.unshift(r);break}const i=n.getAttribute("data-slot");i?r+=`[data-slot="${i}"]`:n.classList.length>0&&(r+=`.${Array.from(n.classList).slice(0,3).join(".")}`);const s=n.parentElement;if(s){const o=n.tagName,l=Array.from(s.children).filter(u=>u instanceof HTMLElement&&u.tagName===o);l.length>1&&(r+=`:nth-of-type(${l.indexOf(n)+1})`)}t.unshift(r),n=s}return`html>${t.join(">")}`}function Jfe(e){return`dev-anywhere-browser-state-${e.replace(/[:.]/g,"-")}.json`}function ehe(e,t,n){if(typeof document>"u")return!1;const r=new Blob([t],{type:n}),i=URL.createObjectURL(r),s=document.createElement("a");return s.href=i,s.download=e,s.rel="noopener",document.body.append(s),s.click(),s.remove(),window.setTimeout(()=>URL.revokeObjectURL(i),1e3),!0}function the(e){return sF(e)!==null}function sF(e){const t=new URLSearchParams(window.location.search);if(t.has(e))return t.get(e)??"";const[,n=""]=window.location.hash.split("?"),r=new URLSearchParams(n);return r.has(e)?r.get(e)??"":null}function wI(e){return e?Ry(e.slice(-200)):null}function rd(e){try{return Ry(e())}catch(t){return{error:oF(t)}}}function Ry(e){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)?e:String(e);if(Array.isArray(e))return e.map(Ry);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=Ry(r);return t}return String(e)}function xI(e){return e.replace(/\s+/g," ").trim()}function zb(e,t){return e.length>t?`${e.slice(0,t)}...`:e}function bs(e){return Math.round(e*100)/100}function oF(e){return e instanceof Error?e.message:String(e)}const nhe=500,rhe=1e3,ihe=60;function she(){const[e,t]=b.useState(()=>bI()),[n,r]=b.useState(!1),[i,s]=b.useState(null),o=b.useRef(null),l=b.useRef(!1),u=b.useRef(0),d=b.useRef(0),f=b.useRef(null);b.useEffect(()=>{const _=()=>t(bI());return window.addEventListener("hashchange",_),window.addEventListener("popstate",_),()=>{window.removeEventListener("hashchange",_),window.removeEventListener("popstate",_)}},[]);const p=b.useCallback(async(_="manual")=>{if(l.current)return o.current??{status:"failed",error:"dump already running"};l.current=!0,r(!0);try{const w=await Kfe(_);return o.current=w,s(w),(_==="manual"||w.status==="failed")&&ohe(w),w}finally{l.current=!1,r(!1)}},[]);if(b.useEffect(()=>(window.__devAnywhereDumpBrowserState=p,()=>{window.__devAnywhereDumpBrowserState===p&&delete window.__devAnywhereDumpBrowserState}),[p]),b.useEffect(()=>{var k,T;if(e!=="auto")return;const _=()=>{f.current!==null&&(window.clearTimeout(f.current),f.current=null)},w=N=>{d.current>=ihe||(_(),f.current=window.setTimeout(()=>{f.current=null;const P=Date.now(),R=rhe-(P-u.current);if(R>0){f.current=window.setTimeout(()=>w(N),R);return}u.current=Date.now(),d.current+=1,p(`auto:${d.current}:${N}`)},nhe))};w("initial");const x=["focusin","focusout","beforeinput","input","compositionstart","compositionupdate","compositionend","keydown","keyup","pointerdown","pointerup","resize","visibilitychange"],S=N=>w(N.type);return x.forEach(N=>window.addEventListener(N,S,!0)),(k=window.visualViewport)==null||k.addEventListener("resize",S),(T=window.visualViewport)==null||T.addEventListener("scroll",S),()=>{var N,P;_(),x.forEach(R=>window.removeEventListener(R,S,!0)),(N=window.visualViewport)==null||N.removeEventListener("resize",S),(P=window.visualViewport)==null||P.removeEventListener("scroll",S)}},[p,e]),e==="off")return null;const y=e==="auto"?"自动诊断中":"保存诊断",g=ahe(i);return m.jsxs("div",{className:"fixed bottom-3 right-3 z-[90] flex max-w-[min(360px,calc(100vw-24px))] flex-col items-end gap-1",children:[g?m.jsx("div",{className:"max-w-full truncate rounded-md border border-border/70 bg-popover/95 px-2 py-1 text-[10px] text-muted-foreground shadow",children:g}):null,m.jsxs(gt,{type:"button",size:"sm",variant:e==="auto"?"secondary":"outline",className:"h-9 rounded-md px-3 text-xs shadow-lg",onClick:()=>void p("manual"),disabled:n,"data-slot":"browser-state-dump",children:[n?m.jsx(ii,{className:"size-3.5 animate-spin","aria-hidden":"true"}):m.jsx(MV,{className:"size-3.5","aria-hidden":"true"}),m.jsx("span",{children:y})]})]})}function ohe(e){if(e.status==="saved"){We.success(`诊断已保存: ${e.path}`);return}if(e.status==="downloaded"){We.info(`诊断已下载: ${e.filename}`);return}We.error(e.endpointError?`${e.error}: ${e.endpointError}`:e.error)}function ahe(e){return e?e.status==="saved"?`已保存 ${e.path}`:e.status==="downloaded"?`已下载 ${e.filename}`:`失败 ${e.endpointError??e.error}`:null}function lhe({issue:e}){const t=e==="unreachable"?"暂时无法连接":e==="page_outdated"?"当前页面版本较旧,请刷新后重试":e==="service_outdated"?"服务端版本较旧,请更新服务后重试":e==="protocol_mismatch"?"页面与服务端版本不一致,请刷新后重试":"连接已断开",n=e==="page_outdated"||e==="protocol_mismatch"?"刷新页面":e==="service_outdated"?"重新检测":null;return m.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 px-6 text-center text-muted-foreground","data-slot":"relay-connection-state","data-state":"unavailable","data-issue":e,role:"status","aria-live":"polite",children:[e==="unreachable"?m.jsx(ii,{className:"size-5 animate-spin","aria-hidden":"true"}):null,m.jsx("p",{className:"text-sm",children:t}),n?m.jsx(gt,{type:"button",size:"sm",onClick:()=>window.location.reload(),children:n}):null]})}function che(e){if(typeof window>"u")return null;try{const t=window.localStorage;return!t||typeof t.getItem!="function"?null:t.getItem(e)}catch{return null}}function gk(e){const{windowKey:t,storageKey:n,maxEntries:r=5e3,dedupeKey:i}=e,s=new Map,o=()=>typeof window>"u"?!1:che(n)==="1",l=()=>typeof window>"u"?[]:window[t]??[],u=d=>{typeof window>"u"||(window[t]=d)};return{isEnabled:o,append(d){if(typeof window>"u")return;const f=l();if(i){const p=i(d);if(p!==null){const y=s.get(d.event);if(y&&i(y)===p&&f.includes(y)){y.t=d.t,y.repeat=(y.repeat??0)+1;const g=f.indexOf(y);g>=0&&g!==f.length-1&&(f.splice(g,1),f.push(y)),u(f);return}}}if(f.push(d),i&&s.set(d.event,d),f.length>r){const p=f.splice(0,f.length-r);if(i)for(const y of p)s.get(y.event)===y&&s.delete(y.event)}u(f)},getAll:l}}function Gn(e){return Math.round(e*10)/10}function Nl(e){return e.length===0?"":`${Gn(Math.min(...e))}..${Gn(Math.max(...e))}`}function kd(e){return[...new Set(e.filter(t=>t!==void 0).map(Gn))]}function aF(e){let t=0,n=0;for(let r=1;r<e.length;r+=1){const i=e[r]-e[r-1];if(Math.abs(i)<1)continue;const s=Math.sign(i);t!==0&&s!==t&&(n+=1),t=s}return n}const uhe="dev_anywhere_pty_input_latency_trace",SI=80,dhe=1e4,fhe=new TextDecoder;let hhe=0;const Zd=new Map,mu=gk({windowKey:"__devAnywherePtyInputLatencyTrace",storageKey:uhe,dedupeKey:e=>e.event.startsWith("input")?null:`${e.event}|${e.sessionId}|${e.outputSeq??""}|${e.pendingInputs??""}`});function phe(){typeof window>"u"||(window.__devAnywherePtyInputLatencyReport=yhe)}function mhe(e,t){if(!mu.isEnabled())return null;const n=`pty-in-${Date.now().toString(36)}-${++hhe}`,r=performance.now(),i={inputId:n,sessionId:e,data:t,kind:whe(t),dataLength:t.length,startedAt:r,sentAt:null,firstOutputAt:null,echoMatchedAt:null,xtermWriteAt:null,paintAt:null},s=Zd.get(e)??[];return s.push(i),yk(s,r),Zd.set(e,s),fm({t:r,event:"input:start",sessionId:e,inputId:n,inputKind:i.kind,dataLength:i.dataLength,pendingInputs:s.length}),{inputId:n,sessionId:e}}function EI(e,t){if(!e||!mu.isEnabled())return;const n=performance.now(),r=bhe(e.sessionId,e.inputId);r&&(r.sentAt=n),fm({t:n,event:"input:ws-send",sessionId:e.sessionId,inputId:e.inputId,inputKind:r==null?void 0:r.kind,dataLength:r==null?void 0:r.dataLength,sent:t.sent,queueWhenDisconnected:t.queueWhenDisconnected,deltaFromInputMs:r?n-r.startedAt:null,details:t.details})}function ghe(e,t,n){if(!mu.isEnabled())return;const r=performance.now(),i=vk(e,r),s=Ehe(t),o=[],l=[];for(const u of i)u.firstOutputAt===null&&(u.firstOutputAt=r,o.push(u.inputId)),u.echoMatchedAt===null&&She(u)&&s.includes(u.data)&&(u.echoMatchedAt=r,l.push(u.inputId));fm({t:r,event:"output:received",sessionId:e,outputSeq:n,bytes:t.byteLength,pendingInputs:i.length,deltaFromInputMs:bk(i,r),details:Che([o.length>0?`first=${o.length}`:"",l.length>0?`echo=${l.length}`:""])})}function vhe(e,t,n=1){if(!mu.isEnabled())return;const r=performance.now(),i=vk(e,r),s=[];for(const o of i)o.xtermWriteAt===null&&(o.xtermWriteAt=r,s.push(o.inputId));fm({t:r,event:"output:xterm-write",sessionId:e,bytes:t,chunkCount:n,pendingInputs:i.length,deltaFromInputMs:bk(i,r),details:s.length>0?`firstWrite=${s.length}`:""}),typeof requestAnimationFrame=="function"&&s.length>0&&requestAnimationFrame(()=>_he(e,s))}function yhe(){const e=mu.getAll(),t=e.slice(-200),n=[...Zd.values()].flat(),r=n.slice(-80).map(s=>[s.inputId,s.sessionId,s.kind,s.dataLength,s.sentAt===null?"":Gn(s.sentAt-s.startedAt),s.firstOutputAt===null?"":Gn(s.firstOutputAt-s.startedAt),s.echoMatchedAt===null?"":Gn(s.echoMatchedAt-s.startedAt),s.xtermWriteAt===null?"":Gn(s.xtermWriteAt-s.startedAt),s.paintAt===null?"":Gn(s.paintAt-s.startedAt)].join(" ")),i=t.map(s=>[Gn(s.t),s.repeat&&s.repeat>0?`${s.event} +${s.repeat}`:s.event,s.sessionId,s.inputId??"",s.inputKind??"",s.dataLength??"",s.sent===void 0?"":s.sent?"sent":"not-sent",s.queueWhenDisconnected?"queue-ok":"",s.outputSeq??"",s.bytes??"",s.chunkCount??"",s.pendingInputs??"",s.deltaFromInputMs===void 0||s.deltaFromInputMs===null?"":Gn(s.deltaFromInputMs),s.details??""].join(" "));return["DEV Anywhere PTY input latency trace",`events=${e.length}, included=${t.length}, pendingInputs=${n.length}`,"pending input summary:","inputId sessionId kind len wsSendMs firstOutputMs echoMatchMs xtermWriteMs paintMs",...r,"events:","t event sessionId inputId kind len sent queue outputSeq bytes chunks pending deltaMs details",...i].join(`
580
+ For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return b.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},Coe="DialogDescriptionWarning",koe=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${C5(Coe).contentName}}.`;return b.useEffect(()=>{var s;const i=(s=e.current)==null?void 0:s.getAttribute("aria-describedby");t&&i&&(document.getElementById(t)||console.warn(r))},[r,e,t]),null},UC=d5,Toe=h5,WC=m5,qC=g5,VC=v5,k5=b5,T5=w5,db=S5;function Roe(e){const t=b.useRef({value:e,previous:e});return b.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}function Aoe(e){const[t,n]=b.useState(void 0);return Vi(()=>{if(e){n({width:e.offsetWidth,height:e.offsetHeight});const r=new ResizeObserver(i=>{if(!Array.isArray(i)||!i.length)return;const s=i[0];let o,l;if("borderBoxSize"in s){const u=s.borderBoxSize,d=Array.isArray(u)?u[0]:u;o=d.inlineSize,l=d.blockSize}else o=e.offsetWidth,l=e.offsetHeight;n({width:o,height:l})});return r.observe(e,{box:"border-box"}),()=>r.unobserve(e)}else n(void 0)},[e]),t}const Noe=["top","right","bottom","left"],Yl=Math.min,Ds=Math.max,wy=Math.round,tv=Math.floor,Jo=e=>({x:e,y:e}),Moe={left:"right",right:"left",bottom:"top",top:"bottom"};function ZS(e,t,n){return Ds(e,Yl(t,n))}function ja(e,t){return typeof e=="function"?e(t):e}function Fa(e){return e.split("-")[0]}function af(e){return e.split("-")[1]}function YC(e){return e==="x"?"y":"x"}function KC(e){return e==="y"?"height":"width"}function Zo(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function GC(e){return YC(Zo(e))}function Poe(e,t,n){n===void 0&&(n=!1);const r=af(e),i=GC(e),s=KC(i);let o=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(o=xy(o)),[o,xy(o)]}function Ioe(e){const t=xy(e);return[QS(e),t,QS(t)]}function QS(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const T2=["left","right"],R2=["right","left"],Ooe=["top","bottom"],Loe=["bottom","top"];function Doe(e,t,n){switch(e){case"top":case"bottom":return n?t?R2:T2:t?T2:R2;case"left":case"right":return t?Ooe:Loe;default:return[]}}function Boe(e,t,n,r){const i=af(e);let s=Doe(Fa(e),n==="start",r);return i&&(s=s.map(o=>o+"-"+i),t&&(s=s.concat(s.map(QS)))),s}function xy(e){const t=Fa(e);return Moe[t]+e.slice(t.length)}function zoe(e){return{top:0,right:0,bottom:0,left:0,...e}}function R5(e){return typeof e!="number"?zoe(e):{top:e,right:e,bottom:e,left:e}}function Sy(e){const{x:t,y:n,width:r,height:i}=e;return{width:r,height:i,top:n,left:t,right:t+r,bottom:n+i,x:t,y:n}}function A2(e,t,n){let{reference:r,floating:i}=e;const s=Zo(t),o=GC(t),l=KC(o),u=Fa(t),d=s==="y",f=r.x+r.width/2-i.width/2,p=r.y+r.height/2-i.height/2,y=r[l]/2-i[l]/2;let g;switch(u){case"top":g={x:f,y:r.y-i.height};break;case"bottom":g={x:f,y:r.y+r.height};break;case"right":g={x:r.x+r.width,y:p};break;case"left":g={x:r.x-i.width,y:p};break;default:g={x:r.x,y:r.y}}switch(af(t)){case"start":g[o]-=y*(n&&d?-1:1);break;case"end":g[o]+=y*(n&&d?-1:1);break}return g}async function joe(e,t){var n;t===void 0&&(t={});const{x:r,y:i,platform:s,rects:o,elements:l,strategy:u}=e,{boundary:d="clippingAncestors",rootBoundary:f="viewport",elementContext:p="floating",altBoundary:y=!1,padding:g=0}=ja(t,e),_=R5(g),x=l[y?p==="floating"?"reference":"floating":p],S=Sy(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(x)))==null||n?x:x.contextElement||await(s.getDocumentElement==null?void 0:s.getDocumentElement(l.floating)),boundary:d,rootBoundary:f,strategy:u})),k=p==="floating"?{x:r,y:i,width:o.floating.width,height:o.floating.height}:o.reference,T=await(s.getOffsetParent==null?void 0:s.getOffsetParent(l.floating)),N=await(s.isElement==null?void 0:s.isElement(T))?await(s.getScale==null?void 0:s.getScale(T))||{x:1,y:1}:{x:1,y:1},P=Sy(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:k,offsetParent:T,strategy:u}):k);return{top:(S.top-P.top+_.top)/N.y,bottom:(P.bottom-S.bottom+_.bottom)/N.y,left:(S.left-P.left+_.left)/N.x,right:(P.right-S.right+_.right)/N.x}}const Foe=50,$oe=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:s=[],platform:o}=n,l=o.detectOverflow?o:{...o,detectOverflow:joe},u=await(o.isRTL==null?void 0:o.isRTL(t));let d=await o.getElementRects({reference:e,floating:t,strategy:i}),{x:f,y:p}=A2(d,r,u),y=r,g=0;const _={};for(let w=0;w<s.length;w++){const x=s[w];if(!x)continue;const{name:S,fn:k}=x,{x:T,y:N,data:P,reset:R}=await k({x:f,y:p,initialPlacement:r,placement:y,strategy:i,middlewareData:_,rects:d,platform:l,elements:{reference:e,floating:t}});f=T??f,p=N??p,_[S]={..._[S],...P},R&&g<Foe&&(g++,typeof R=="object"&&(R.placement&&(y=R.placement),R.rects&&(d=R.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:i}):R.rects),{x:f,y:p}=A2(d,y,u)),w=-1)}return{x:f,y:p,placement:y,strategy:i,middlewareData:_}},Hoe=e=>({name:"arrow",options:e,async fn(t){const{x:n,y:r,placement:i,rects:s,platform:o,elements:l,middlewareData:u}=t,{element:d,padding:f=0}=ja(e,t)||{};if(d==null)return{};const p=R5(f),y={x:n,y:r},g=GC(i),_=KC(g),w=await o.getDimensions(d),x=g==="y",S=x?"top":"left",k=x?"bottom":"right",T=x?"clientHeight":"clientWidth",N=s.reference[_]+s.reference[g]-y[g]-s.floating[_],P=y[g]-s.reference[g],R=await(o.getOffsetParent==null?void 0:o.getOffsetParent(d));let M=R?R[T]:0;(!M||!await(o.isElement==null?void 0:o.isElement(R)))&&(M=l.floating[T]||s.floating[_]);const L=N/2-P/2,X=M/2-w[_]/2-1,U=Yl(p[S],X),V=Yl(p[k],X),j=U,A=M-w[_]-V,D=M/2-w[_]/2+L,O=ZS(j,D,A),I=!u.arrow&&af(i)!=null&&D!==O&&s.reference[_]/2-(D<j?U:V)-w[_]/2<0,B=I?D<j?D-j:D-A:0;return{[g]:y[g]+B,data:{[g]:O,centerOffset:D-O-B,...I&&{alignmentOffset:B}},reset:I}}}),Uoe=function(e){return e===void 0&&(e={}),{name:"flip",options:e,async fn(t){var n,r;const{placement:i,middlewareData:s,rects:o,initialPlacement:l,platform:u,elements:d}=t,{mainAxis:f=!0,crossAxis:p=!0,fallbackPlacements:y,fallbackStrategy:g="bestFit",fallbackAxisSideDirection:_="none",flipAlignment:w=!0,...x}=ja(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const S=Fa(i),k=Zo(l),T=Fa(l)===l,N=await(u.isRTL==null?void 0:u.isRTL(d.floating)),P=y||(T||!w?[xy(l)]:Ioe(l)),R=_!=="none";!y&&R&&P.push(...Boe(l,w,_,N));const M=[l,...P],L=await u.detectOverflow(t,x),X=[];let U=((r=s.flip)==null?void 0:r.overflows)||[];if(f&&X.push(L[S]),p){const D=Poe(i,o,N);X.push(L[D[0]],L[D[1]])}if(U=[...U,{placement:i,overflows:X}],!X.every(D=>D<=0)){var V,j;const D=(((V=s.flip)==null?void 0:V.index)||0)+1,O=M[D];if(O&&(!(p==="alignment"?k!==Zo(O):!1)||U.every(F=>Zo(F.placement)===k?F.overflows[0]>0:!0)))return{data:{index:D,overflows:U},reset:{placement:O}};let I=(j=U.filter(B=>B.overflows[0]<=0).sort((B,F)=>B.overflows[1]-F.overflows[1])[0])==null?void 0:j.placement;if(!I)switch(g){case"bestFit":{var A;const B=(A=U.filter(F=>{if(R){const Y=Zo(F.placement);return Y===k||Y==="y"}return!0}).map(F=>[F.placement,F.overflows.filter(Y=>Y>0).reduce((Y,z)=>Y+z,0)]).sort((F,Y)=>F[1]-Y[1])[0])==null?void 0:A[0];B&&(I=B);break}case"initialPlacement":I=l;break}if(i!==I)return{reset:{placement:I}}}return{}}}};function N2(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function M2(e){return Noe.some(t=>e[t]>=0)}const Woe=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...s}=ja(e,t);switch(i){case"referenceHidden":{const o=await r.detectOverflow(t,{...s,elementContext:"reference"}),l=N2(o,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:M2(l)}}}case"escaped":{const o=await r.detectOverflow(t,{...s,altBoundary:!0}),l=N2(o,n.floating);return{data:{escapedOffsets:l,escaped:M2(l)}}}default:return{}}}}},A5=new Set(["left","top"]);async function qoe(e,t){const{placement:n,platform:r,elements:i}=e,s=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=Fa(n),l=af(n),u=Zo(n)==="y",d=A5.has(o)?-1:1,f=s&&u?-1:1,p=ja(t,e);let{mainAxis:y,crossAxis:g,alignmentAxis:_}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return l&&typeof _=="number"&&(g=l==="end"?_*-1:_),u?{x:g*f,y:y*d}:{x:y*d,y:g*f}}const Voe=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var n,r;const{x:i,y:s,placement:o,middlewareData:l}=t,u=await qoe(t,e);return o===((n=l.offset)==null?void 0:n.placement)&&(r=l.arrow)!=null&&r.alignmentOffset?{}:{x:i+u.x,y:s+u.y,data:{...u,placement:o}}}}},Yoe=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:n,y:r,placement:i,platform:s}=t,{mainAxis:o=!0,crossAxis:l=!1,limiter:u={fn:S=>{let{x:k,y:T}=S;return{x:k,y:T}}},...d}=ja(e,t),f={x:n,y:r},p=await s.detectOverflow(t,d),y=Zo(Fa(i)),g=YC(y);let _=f[g],w=f[y];if(o){const S=g==="y"?"top":"left",k=g==="y"?"bottom":"right",T=_+p[S],N=_-p[k];_=ZS(T,_,N)}if(l){const S=y==="y"?"top":"left",k=y==="y"?"bottom":"right",T=w+p[S],N=w-p[k];w=ZS(T,w,N)}const x=u.fn({...t,[g]:_,[y]:w});return{...x,data:{x:x.x-n,y:x.y-r,enabled:{[g]:o,[y]:l}}}}}},Koe=function(e){return e===void 0&&(e={}),{options:e,fn(t){const{x:n,y:r,placement:i,rects:s,middlewareData:o}=t,{offset:l=0,mainAxis:u=!0,crossAxis:d=!0}=ja(e,t),f={x:n,y:r},p=Zo(i),y=YC(p);let g=f[y],_=f[p];const w=ja(l,t),x=typeof w=="number"?{mainAxis:w,crossAxis:0}:{mainAxis:0,crossAxis:0,...w};if(u){const T=y==="y"?"height":"width",N=s.reference[y]-s.floating[T]+x.mainAxis,P=s.reference[y]+s.reference[T]-x.mainAxis;g<N?g=N:g>P&&(g=P)}if(d){var S,k;const T=y==="y"?"width":"height",N=A5.has(Fa(i)),P=s.reference[p]-s.floating[T]+(N&&((S=o.offset)==null?void 0:S[p])||0)+(N?0:x.crossAxis),R=s.reference[p]+s.reference[T]+(N?0:((k=o.offset)==null?void 0:k[p])||0)-(N?x.crossAxis:0);_<P?_=P:_>R&&(_=R)}return{[y]:g,[p]:_}}}},Goe=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){var n,r;const{placement:i,rects:s,platform:o,elements:l}=t,{apply:u=()=>{},...d}=ja(e,t),f=await o.detectOverflow(t,d),p=Fa(i),y=af(i),g=Zo(i)==="y",{width:_,height:w}=s.floating;let x,S;p==="top"||p==="bottom"?(x=p,S=y===(await(o.isRTL==null?void 0:o.isRTL(l.floating))?"start":"end")?"left":"right"):(S=p,x=y==="end"?"top":"bottom");const k=w-f.top-f.bottom,T=_-f.left-f.right,N=Yl(w-f[x],k),P=Yl(_-f[S],T),R=!t.middlewareData.shift;let M=N,L=P;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(L=T),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(M=k),R&&!y){const U=Ds(f.left,0),V=Ds(f.right,0),j=Ds(f.top,0),A=Ds(f.bottom,0);g?L=_-2*(U!==0||V!==0?U+V:Ds(f.left,f.right)):M=w-2*(j!==0||A!==0?j+A:Ds(f.top,f.bottom))}await u({...t,availableWidth:L,availableHeight:M});const X=await o.getDimensions(l.floating);return _!==X.width||w!==X.height?{reset:{rects:!0}}:{}}}};function fb(){return typeof window<"u"}function lf(e){return N5(e)?(e.nodeName||"").toLowerCase():"#document"}function zs(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function oa(e){var t;return(t=(N5(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function N5(e){return fb()?e instanceof Node||e instanceof zs(e).Node:!1}function ko(e){return fb()?e instanceof Element||e instanceof zs(e).Element:!1}function Wa(e){return fb()?e instanceof HTMLElement||e instanceof zs(e).HTMLElement:!1}function P2(e){return!fb()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof zs(e).ShadowRoot}function im(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=To(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function Xoe(e){return/^(table|td|th)$/.test(lf(e))}function hb(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const Zoe=/transform|translate|scale|rotate|perspective|filter/,Qoe=/paint|layout|strict|content/,Rc=e=>!!e&&e!=="none";let Zx;function XC(e){const t=ko(e)?To(e):e;return Rc(t.transform)||Rc(t.translate)||Rc(t.scale)||Rc(t.rotate)||Rc(t.perspective)||!ZC()&&(Rc(t.backdropFilter)||Rc(t.filter))||Zoe.test(t.willChange||"")||Qoe.test(t.contain||"")}function Joe(e){let t=Kl(e);for(;Wa(t)&&!Kd(t);){if(XC(t))return t;if(hb(t))return null;t=Kl(t)}return null}function ZC(){return Zx==null&&(Zx=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Zx}function Kd(e){return/^(html|body|#document)$/.test(lf(e))}function To(e){return zs(e).getComputedStyle(e)}function pb(e){return ko(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Kl(e){if(lf(e)==="html")return e;const t=e.assignedSlot||e.parentNode||P2(e)&&e.host||oa(e);return P2(t)?t.host:t}function M5(e){const t=Kl(e);return Kd(t)?e.ownerDocument?e.ownerDocument.body:e.body:Wa(t)&&im(t)?t:M5(t)}function Np(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=M5(e),s=i===((r=e.ownerDocument)==null?void 0:r.body),o=zs(i);if(s){const l=JS(o);return t.concat(o,o.visualViewport||[],im(i)?i:[],l&&n?Np(l):[])}else return t.concat(i,Np(i,[],n))}function JS(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function P5(e){const t=To(e);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const i=Wa(e),s=i?e.offsetWidth:n,o=i?e.offsetHeight:r,l=wy(n)!==s||wy(r)!==o;return l&&(n=s,r=o),{width:n,height:r,$:l}}function QC(e){return ko(e)?e:e.contextElement}function Od(e){const t=QC(e);if(!Wa(t))return Jo(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:s}=P5(t);let o=(s?wy(n.width):n.width)/r,l=(s?wy(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!l||!Number.isFinite(l))&&(l=1),{x:o,y:l}}const eae=Jo(0);function I5(e){const t=zs(e);return!ZC()||!t.visualViewport?eae:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function tae(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==zs(e)?!1:t}function Xc(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),s=QC(e);let o=Jo(1);t&&(r?ko(r)&&(o=Od(r)):o=Od(e));const l=tae(s,n,r)?I5(s):Jo(0);let u=(i.left+l.x)/o.x,d=(i.top+l.y)/o.y,f=i.width/o.x,p=i.height/o.y;if(s){const y=zs(s),g=r&&ko(r)?zs(r):r;let _=y,w=JS(_);for(;w&&r&&g!==_;){const x=Od(w),S=w.getBoundingClientRect(),k=To(w),T=S.left+(w.clientLeft+parseFloat(k.paddingLeft))*x.x,N=S.top+(w.clientTop+parseFloat(k.paddingTop))*x.y;u*=x.x,d*=x.y,f*=x.x,p*=x.y,u+=T,d+=N,_=zs(w),w=JS(_)}}return Sy({width:f,height:p,x:u,y:d})}function mb(e,t){const n=pb(e).scrollLeft;return t?t.left+n:Xc(oa(e)).left+n}function O5(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-mb(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function nae(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const s=i==="fixed",o=oa(r),l=t?hb(t.floating):!1;if(r===o||l&&s)return n;let u={scrollLeft:0,scrollTop:0},d=Jo(1);const f=Jo(0),p=Wa(r);if((p||!p&&!s)&&((lf(r)!=="body"||im(o))&&(u=pb(r)),p)){const g=Xc(r);d=Od(r),f.x=g.x+r.clientLeft,f.y=g.y+r.clientTop}const y=o&&!p&&!s?O5(o,u):Jo(0);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-u.scrollLeft*d.x+f.x+y.x,y:n.y*d.y-u.scrollTop*d.y+f.y+y.y}}function rae(e){return Array.from(e.getClientRects())}function iae(e){const t=oa(e),n=pb(e),r=e.ownerDocument.body,i=Ds(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=Ds(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let o=-n.scrollLeft+mb(e);const l=-n.scrollTop;return To(r).direction==="rtl"&&(o+=Ds(t.clientWidth,r.clientWidth)-i),{width:i,height:s,x:o,y:l}}const I2=25;function sae(e,t){const n=zs(e),r=oa(e),i=n.visualViewport;let s=r.clientWidth,o=r.clientHeight,l=0,u=0;if(i){s=i.width,o=i.height;const f=ZC();(!f||f&&t==="fixed")&&(l=i.offsetLeft,u=i.offsetTop)}const d=mb(r);if(d<=0){const f=r.ownerDocument,p=f.body,y=getComputedStyle(p),g=f.compatMode==="CSS1Compat"&&parseFloat(y.marginLeft)+parseFloat(y.marginRight)||0,_=Math.abs(r.clientWidth-p.clientWidth-g);_<=I2&&(s-=_)}else d<=I2&&(s+=d);return{width:s,height:o,x:l,y:u}}function oae(e,t){const n=Xc(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,s=Wa(e)?Od(e):Jo(1),o=e.clientWidth*s.x,l=e.clientHeight*s.y,u=i*s.x,d=r*s.y;return{width:o,height:l,x:u,y:d}}function O2(e,t,n){let r;if(t==="viewport")r=sae(e,n);else if(t==="document")r=iae(oa(e));else if(ko(t))r=oae(t,n);else{const i=I5(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return Sy(r)}function L5(e,t){const n=Kl(e);return n===t||!ko(n)||Kd(n)?!1:To(n).position==="fixed"||L5(n,t)}function aae(e,t){const n=t.get(e);if(n)return n;let r=Np(e,[],!1).filter(l=>ko(l)&&lf(l)!=="body"),i=null;const s=To(e).position==="fixed";let o=s?Kl(e):e;for(;ko(o)&&!Kd(o);){const l=To(o),u=XC(o);!u&&l.position==="fixed"&&(i=null),(s?!u&&!i:!u&&l.position==="static"&&!!i&&(i.position==="absolute"||i.position==="fixed")||im(o)&&!u&&L5(e,o))?r=r.filter(f=>f!==o):i=l,o=Kl(o)}return t.set(e,r),r}function lae(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[...n==="clippingAncestors"?hb(t)?[]:aae(t,this._c):[].concat(n),r],l=O2(t,o[0],i);let u=l.top,d=l.right,f=l.bottom,p=l.left;for(let y=1;y<o.length;y++){const g=O2(t,o[y],i);u=Ds(g.top,u),d=Yl(g.right,d),f=Yl(g.bottom,f),p=Ds(g.left,p)}return{width:d-p,height:f-u,x:p,y:u}}function cae(e){const{width:t,height:n}=P5(e);return{width:t,height:n}}function uae(e,t,n){const r=Wa(t),i=oa(t),s=n==="fixed",o=Xc(e,!0,s,t);let l={scrollLeft:0,scrollTop:0};const u=Jo(0);function d(){u.x=mb(i)}if(r||!r&&!s)if((lf(t)!=="body"||im(i))&&(l=pb(t)),r){const g=Xc(t,!0,s,t);u.x=g.x+t.clientLeft,u.y=g.y+t.clientTop}else i&&d();s&&!r&&i&&d();const f=i&&!r&&!s?O5(i,l):Jo(0),p=o.left+l.scrollLeft-u.x-f.x,y=o.top+l.scrollTop-u.y-f.y;return{x:p,y,width:o.width,height:o.height}}function Qx(e){return To(e).position==="static"}function L2(e,t){if(!Wa(e)||To(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return oa(e)===n&&(n=n.ownerDocument.body),n}function D5(e,t){const n=zs(e);if(hb(e))return n;if(!Wa(e)){let i=Kl(e);for(;i&&!Kd(i);){if(ko(i)&&!Qx(i))return i;i=Kl(i)}return n}let r=L2(e,t);for(;r&&Xoe(r)&&Qx(r);)r=L2(r,t);return r&&Kd(r)&&Qx(r)&&!XC(r)?n:r||Joe(e)||n}const dae=async function(e){const t=this.getOffsetParent||D5,n=this.getDimensions,r=await n(e.floating);return{reference:uae(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function fae(e){return To(e).direction==="rtl"}const hae={convertOffsetParentRelativeRectToViewportRelativeRect:nae,getDocumentElement:oa,getClippingRect:lae,getOffsetParent:D5,getElementRects:dae,getClientRects:rae,getDimensions:cae,getScale:Od,isElement:ko,isRTL:fae};function B5(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function pae(e,t){let n=null,r;const i=oa(e);function s(){var l;clearTimeout(r),(l=n)==null||l.disconnect(),n=null}function o(l,u){l===void 0&&(l=!1),u===void 0&&(u=1),s();const d=e.getBoundingClientRect(),{left:f,top:p,width:y,height:g}=d;if(l||t(),!y||!g)return;const _=tv(p),w=tv(i.clientWidth-(f+y)),x=tv(i.clientHeight-(p+g)),S=tv(f),T={rootMargin:-_+"px "+-w+"px "+-x+"px "+-S+"px",threshold:Ds(0,Yl(1,u))||1};let N=!0;function P(R){const M=R[0].intersectionRatio;if(M!==u){if(!N)return o();M?o(!1,M):r=setTimeout(()=>{o(!1,1e-7)},1e3)}M===1&&!B5(d,e.getBoundingClientRect())&&o(),N=!1}try{n=new IntersectionObserver(P,{...T,root:i.ownerDocument})}catch{n=new IntersectionObserver(P,T)}n.observe(e)}return o(!0),s}function mae(e,t,n,r){r===void 0&&(r={});const{ancestorScroll:i=!0,ancestorResize:s=!0,elementResize:o=typeof ResizeObserver=="function",layoutShift:l=typeof IntersectionObserver=="function",animationFrame:u=!1}=r,d=QC(e),f=i||s?[...d?Np(d):[],...t?Np(t):[]]:[];f.forEach(S=>{i&&S.addEventListener("scroll",n,{passive:!0}),s&&S.addEventListener("resize",n)});const p=d&&l?pae(d,n):null;let y=-1,g=null;o&&(g=new ResizeObserver(S=>{let[k]=S;k&&k.target===d&&g&&t&&(g.unobserve(t),cancelAnimationFrame(y),y=requestAnimationFrame(()=>{var T;(T=g)==null||T.observe(t)})),n()}),d&&!u&&g.observe(d),t&&g.observe(t));let _,w=u?Xc(e):null;u&&x();function x(){const S=Xc(e);w&&!B5(w,S)&&n(),w=S,_=requestAnimationFrame(x)}return n(),()=>{var S;f.forEach(k=>{i&&k.removeEventListener("scroll",n),s&&k.removeEventListener("resize",n)}),p==null||p(),(S=g)==null||S.disconnect(),g=null,u&&cancelAnimationFrame(_)}}const gae=Voe,vae=Yoe,yae=Uoe,bae=Goe,_ae=Woe,D2=Hoe,wae=Koe,xae=(e,t,n)=>{const r=new Map,i={platform:hae,...n},s={...i.platform,_c:r};return $oe(e,t,{...i,platform:s})};var Sae=typeof document<"u",Eae=function(){},Hv=Sae?b.useLayoutEffect:Eae;function Ey(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(typeof e=="function"&&e.toString()===t.toString())return!0;let n,r,i;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(n=e.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Ey(e[r],t[r]))return!1;return!0}if(i=Object.keys(e),n=i.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,i[r]))return!1;for(r=n;r--!==0;){const s=i[r];if(!(s==="_owner"&&e.$$typeof)&&!Ey(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function z5(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function B2(e,t){const n=z5(e);return Math.round(t*n)/n}function Jx(e){const t=b.useRef(e);return Hv(()=>{t.current=e}),t}function Cae(e){e===void 0&&(e={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:i,elements:{reference:s,floating:o}={},transform:l=!0,whileElementsMounted:u,open:d}=e,[f,p]=b.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[y,g]=b.useState(r);Ey(y,r)||g(r);const[_,w]=b.useState(null),[x,S]=b.useState(null),k=b.useCallback(F=>{F!==R.current&&(R.current=F,w(F))},[]),T=b.useCallback(F=>{F!==M.current&&(M.current=F,S(F))},[]),N=s||_,P=o||x,R=b.useRef(null),M=b.useRef(null),L=b.useRef(f),X=u!=null,U=Jx(u),V=Jx(i),j=Jx(d),A=b.useCallback(()=>{if(!R.current||!M.current)return;const F={placement:t,strategy:n,middleware:y};V.current&&(F.platform=V.current),xae(R.current,M.current,F).then(Y=>{const z={...Y,isPositioned:j.current!==!1};D.current&&!Ey(L.current,z)&&(L.current=z,cu.flushSync(()=>{p(z)}))})},[y,t,n,V,j]);Hv(()=>{d===!1&&L.current.isPositioned&&(L.current.isPositioned=!1,p(F=>({...F,isPositioned:!1})))},[d]);const D=b.useRef(!1);Hv(()=>(D.current=!0,()=>{D.current=!1}),[]),Hv(()=>{if(N&&(R.current=N),P&&(M.current=P),N&&P){if(U.current)return U.current(N,P,A);A()}},[N,P,A,U,X]);const O=b.useMemo(()=>({reference:R,floating:M,setReference:k,setFloating:T}),[k,T]),I=b.useMemo(()=>({reference:N,floating:P}),[N,P]),B=b.useMemo(()=>{const F={position:n,left:0,top:0};if(!I.floating)return F;const Y=B2(I.floating,f.x),z=B2(I.floating,f.y);return l?{...F,transform:"translate("+Y+"px, "+z+"px)",...z5(I.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:Y,top:z}},[n,l,I.floating,f.x,f.y]);return b.useMemo(()=>({...f,update:A,refs:O,elements:I,floatingStyles:B}),[f,A,O,I,B])}const kae=e=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:e,fn(n){const{element:r,padding:i}=typeof e=="function"?e(n):e;return r&&t(r)?r.current!=null?D2({element:r.current,padding:i}).fn(n):{}:r?D2({element:r,padding:i}).fn(n):{}}}},Tae=(e,t)=>{const n=gae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Rae=(e,t)=>{const n=vae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Aae=(e,t)=>({fn:wae(e).fn,options:[e,t]}),Nae=(e,t)=>{const n=yae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Mae=(e,t)=>{const n=bae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Pae=(e,t)=>{const n=_ae(e);return{name:n.name,fn:n.fn,options:[e,t]}},Iae=(e,t)=>{const n=kae(e);return{name:n.name,fn:n.fn,options:[e,t]}};var Oae="Arrow",j5=b.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...s}=e;return m.jsx(bn.svg,{...s,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:m.jsx("polygon",{points:"0,0 30,0 15,10"})})});j5.displayName=Oae;var Lae=j5,JC="Popper",[F5,nc]=Ua(JC),[Dae,$5]=F5(JC),H5=e=>{const{__scopePopper:t,children:n}=e,[r,i]=b.useState(null);return m.jsx(Dae,{scope:t,anchor:r,onAnchorChange:i,children:n})};H5.displayName=JC;var U5="PopperAnchor",W5=b.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,s=$5(U5,n),o=b.useRef(null),l=sr(t,o),u=b.useRef(null);return b.useEffect(()=>{const d=u.current;u.current=(r==null?void 0:r.current)||o.current,d!==u.current&&s.onAnchorChange(u.current)}),r?null:m.jsx(bn.div,{...i,ref:l})});W5.displayName=U5;var ek="PopperContent",[Bae,zae]=F5(ek),q5=b.forwardRef((e,t)=>{var Z,ae,le,me,ke,$e;const{__scopePopper:n,side:r="bottom",sideOffset:i=0,align:s="center",alignOffset:o=0,arrowPadding:l=0,avoidCollisions:u=!0,collisionBoundary:d=[],collisionPadding:f=0,sticky:p="partial",hideWhenDetached:y=!1,updatePositionStrategy:g="optimized",onPlaced:_,...w}=e,x=$5(ek,n),[S,k]=b.useState(null),T=sr(t,he=>k(he)),[N,P]=b.useState(null),R=Aoe(N),M=(R==null?void 0:R.width)??0,L=(R==null?void 0:R.height)??0,X=r+(s!=="center"?"-"+s:""),U=typeof f=="number"?f:{top:0,right:0,bottom:0,left:0,...f},V=Array.isArray(d)?d:[d],j=V.length>0,A={padding:U,boundary:V.filter(Fae),altBoundary:j},{refs:D,floatingStyles:O,placement:I,isPositioned:B,middlewareData:F}=Cae({strategy:"fixed",placement:X,whileElementsMounted:(...he)=>mae(...he,{animationFrame:g==="always"}),elements:{reference:x.anchor},middleware:[Tae({mainAxis:i+L,alignmentAxis:o}),u&&Rae({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?Aae():void 0,...A}),u&&Nae({...A}),Mae({...A,apply:({elements:he,rects:He,availableWidth:Nt,availableHeight:ye})=>{const{width:Ze,height:Oe}=He.reference,ze=he.floating.style;ze.setProperty("--radix-popper-available-width",`${Nt}px`),ze.setProperty("--radix-popper-available-height",`${ye}px`),ze.setProperty("--radix-popper-anchor-width",`${Ze}px`),ze.setProperty("--radix-popper-anchor-height",`${Oe}px`)}}),N&&Iae({element:N,padding:l}),$ae({arrowWidth:M,arrowHeight:L}),y&&Pae({strategy:"referenceHidden",...A})]}),[Y,z]=K5(I),q=ra(_);Vi(()=>{B&&(q==null||q())},[B,q]);const K=(Z=F.arrow)==null?void 0:Z.x,$=(ae=F.arrow)==null?void 0:ae.y,re=((le=F.arrow)==null?void 0:le.centerOffset)!==0,[Q,G]=b.useState();return Vi(()=>{S&&G(window.getComputedStyle(S).zIndex)},[S]),m.jsx("div",{ref:D.setFloating,"data-radix-popper-content-wrapper":"",style:{...O,transform:B?O.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Q,"--radix-popper-transform-origin":[(me=F.transformOrigin)==null?void 0:me.x,(ke=F.transformOrigin)==null?void 0:ke.y].join(" "),...(($e=F.hide)==null?void 0:$e.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:m.jsx(Bae,{scope:n,placedSide:Y,onArrowChange:P,arrowX:K,arrowY:$,shouldHideArrow:re,children:m.jsx(bn.div,{"data-side":Y,"data-align":z,...w,ref:T,style:{...w.style,animation:B?void 0:"none"}})})})});q5.displayName=ek;var V5="PopperArrow",jae={top:"bottom",right:"left",bottom:"top",left:"right"},Y5=b.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,s=zae(V5,r),o=jae[s.placedSide];return m.jsx("span",{ref:s.onArrowChange,style:{position:"absolute",left:s.arrowX,top:s.arrowY,[o]:0,transformOrigin:{top:"",right:"0 0",bottom:"center 0",left:"100% 0"}[s.placedSide],transform:{top:"translateY(100%)",right:"translateY(50%) rotate(90deg) translateX(-50%)",bottom:"rotate(180deg)",left:"translateY(50%) rotate(-90deg) translateX(50%)"}[s.placedSide],visibility:s.shouldHideArrow?"hidden":void 0},children:m.jsx(Lae,{...i,ref:n,style:{...i.style,display:"block"}})})});Y5.displayName=V5;function Fae(e){return e!==null}var $ae=e=>({name:"transformOrigin",options:e,fn(t){var x,S,k;const{placement:n,rects:r,middlewareData:i}=t,o=((x=i.arrow)==null?void 0:x.centerOffset)!==0,l=o?0:e.arrowWidth,u=o?0:e.arrowHeight,[d,f]=K5(n),p={start:"0%",center:"50%",end:"100%"}[f],y=(((S=i.arrow)==null?void 0:S.x)??0)+l/2,g=(((k=i.arrow)==null?void 0:k.y)??0)+u/2;let _="",w="";return d==="bottom"?(_=o?p:`${y}px`,w=`${-u}px`):d==="top"?(_=o?p:`${y}px`,w=`${r.floating.height+u}px`):d==="right"?(_=`${-u}px`,w=o?p:`${g}px`):d==="left"&&(_=`${r.floating.width+u}px`,w=o?p:`${g}px`),{data:{x:_,y:w}}}});function K5(e){const[t,n="center"]=e.split("-");return[t,n]}var gb=H5,sm=W5,vb=q5,yb=Y5,e0="rovingFocusGroup.onEntryFocus",Hae={bubbles:!1,cancelable:!0},om="RovingFocusGroup",[e1,G5,Uae]=zC(om),[Wae,X5]=Ua(om,[Uae]),[qae,Vae]=Wae(om),Z5=b.forwardRef((e,t)=>m.jsx(e1.Provider,{scope:e.__scopeRovingFocusGroup,children:m.jsx(e1.Slot,{scope:e.__scopeRovingFocusGroup,children:m.jsx(Yae,{...e,ref:t})})}));Z5.displayName=om;var Yae=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:i=!1,dir:s,currentTabStopId:o,defaultCurrentTabStopId:l,onCurrentTabStopIdChange:u,onEntryFocus:d,preventScrollOnEntryFocus:f=!1,...p}=e,y=b.useRef(null),g=sr(t,y),_=jC(s),[w,x]=Kc({prop:o,defaultProp:l??null,onChange:u,caller:om}),[S,k]=b.useState(!1),T=ra(d),N=G5(n),P=b.useRef(!1),[R,M]=b.useState(0);return b.useEffect(()=>{const L=y.current;if(L)return L.addEventListener(e0,T),()=>L.removeEventListener(e0,T)},[T]),m.jsx(qae,{scope:n,orientation:r,dir:_,loop:i,currentTabStopId:w,onItemFocus:b.useCallback(L=>x(L),[x]),onItemShiftTab:b.useCallback(()=>k(!0),[]),onFocusableItemAdd:b.useCallback(()=>M(L=>L+1),[]),onFocusableItemRemove:b.useCallback(()=>M(L=>L-1),[]),children:m.jsx(bn.div,{tabIndex:S||R===0?-1:0,"data-orientation":r,...p,ref:g,style:{outline:"none",...e.style},onMouseDown:$t(e.onMouseDown,()=>{P.current=!0}),onFocus:$t(e.onFocus,L=>{const X=!P.current;if(L.target===L.currentTarget&&X&&!S){const U=new CustomEvent(e0,Hae);if(L.currentTarget.dispatchEvent(U),!U.defaultPrevented){const V=N().filter(I=>I.focusable),j=V.find(I=>I.active),A=V.find(I=>I.id===w),O=[j,A,...V].filter(Boolean).map(I=>I.ref.current);e3(O,f)}}P.current=!1}),onBlur:$t(e.onBlur,()=>k(!1))})})}),Q5="RovingFocusGroupItem",J5=b.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:s,children:o,...l}=e,u=Di(),d=s||u,f=Vae(Q5,n),p=f.currentTabStopId===d,y=G5(n),{onFocusableItemAdd:g,onFocusableItemRemove:_,currentTabStopId:w}=f;return b.useEffect(()=>{if(r)return g(),()=>_()},[r,g,_]),m.jsx(e1.ItemSlot,{scope:n,id:d,focusable:r,active:i,children:m.jsx(bn.span,{tabIndex:p?0:-1,"data-orientation":f.orientation,...l,ref:t,onMouseDown:$t(e.onMouseDown,x=>{r?f.onItemFocus(d):x.preventDefault()}),onFocus:$t(e.onFocus,()=>f.onItemFocus(d)),onKeyDown:$t(e.onKeyDown,x=>{if(x.key==="Tab"&&x.shiftKey){f.onItemShiftTab();return}if(x.target!==x.currentTarget)return;const S=Xae(x,f.orientation,f.dir);if(S!==void 0){if(x.metaKey||x.ctrlKey||x.altKey||x.shiftKey)return;x.preventDefault();let T=y().filter(N=>N.focusable).map(N=>N.ref.current);if(S==="last")T.reverse();else if(S==="prev"||S==="next"){S==="prev"&&T.reverse();const N=T.indexOf(x.currentTarget);T=f.loop?Zae(T,N+1):T.slice(N+1)}setTimeout(()=>e3(T))}}),children:typeof o=="function"?o({isCurrentTabStop:p,hasTabStop:w!=null}):o})})});J5.displayName=Q5;var Kae={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Gae(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Xae(e,t,n){const r=Gae(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Kae[r]}function e3(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Zae(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Qae=Z5,Jae=J5,t1=["Enter"," "],ele=["ArrowDown","PageUp","Home"],t3=["ArrowUp","PageDown","End"],tle=[...ele,...t3],nle={ltr:[...t1,"ArrowRight"],rtl:[...t1,"ArrowLeft"]},rle={ltr:["ArrowLeft"],rtl:["ArrowRight"]},am="Menu",[Mp,ile,sle]=zC(am),[uu,n3]=Ua(am,[sle,nc,X5]),bb=nc(),r3=X5(),[ole,du]=uu(am),[ale,lm]=uu(am),i3=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:s,modal:o=!0}=e,l=bb(t),[u,d]=b.useState(null),f=b.useRef(!1),p=ra(s),y=jC(i);return b.useEffect(()=>{const g=()=>{f.current=!0,document.addEventListener("pointerdown",_,{capture:!0,once:!0}),document.addEventListener("pointermove",_,{capture:!0,once:!0})},_=()=>f.current=!1;return document.addEventListener("keydown",g,{capture:!0}),()=>{document.removeEventListener("keydown",g,{capture:!0}),document.removeEventListener("pointerdown",_,{capture:!0}),document.removeEventListener("pointermove",_,{capture:!0})}},[]),m.jsx(gb,{...l,children:m.jsx(ole,{scope:t,open:n,onOpenChange:p,content:u,onContentChange:d,children:m.jsx(ale,{scope:t,onClose:b.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:f,dir:y,modal:o,children:r})})})};i3.displayName=am;var lle="MenuAnchor",tk=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=bb(n);return m.jsx(sm,{...i,...r,ref:t})});tk.displayName=lle;var nk="MenuPortal",[cle,s3]=uu(nk,{forceMount:void 0}),o3=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,s=du(nk,t);return m.jsx(cle,{scope:t,forceMount:n,children:m.jsx(ho,{present:n||s.open,children:m.jsx(of,{asChild:!0,container:i,children:r})})})};o3.displayName=nk;var oo="MenuContent",[ule,rk]=uu(oo),a3=b.forwardRef((e,t)=>{const n=s3(oo,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,s=du(oo,e.__scopeMenu),o=lm(oo,e.__scopeMenu);return m.jsx(Mp.Provider,{scope:e.__scopeMenu,children:m.jsx(ho,{present:r||s.open,children:m.jsx(Mp.Slot,{scope:e.__scopeMenu,children:o.modal?m.jsx(dle,{...i,ref:t}):m.jsx(fle,{...i,ref:t})})})})}),dle=b.forwardRef((e,t)=>{const n=du(oo,e.__scopeMenu),r=b.useRef(null),i=sr(t,r);return b.useEffect(()=>{const s=r.current;if(s)return cb(s)},[]),m.jsx(ik,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:$t(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),fle=b.forwardRef((e,t)=>{const n=du(oo,e.__scopeMenu);return m.jsx(ik,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),hle=Vl("MenuContent.ScrollLock"),ik=b.forwardRef((e,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:i,onOpenAutoFocus:s,onCloseAutoFocus:o,disableOutsidePointerEvents:l,onEntryFocus:u,onEscapeKeyDown:d,onPointerDownOutside:f,onFocusOutside:p,onInteractOutside:y,onDismiss:g,disableOutsideScroll:_,...w}=e,x=du(oo,n),S=lm(oo,n),k=bb(n),T=r3(n),N=ile(n),[P,R]=b.useState(null),M=b.useRef(null),L=sr(t,M,x.onContentChange),X=b.useRef(0),U=b.useRef(""),V=b.useRef(0),j=b.useRef(null),A=b.useRef("right"),D=b.useRef(0),O=_?rm:b.Fragment,I=_?{as:hle,allowPinchZoom:!0}:void 0,B=Y=>{var Z,ae;const z=U.current+Y,q=N().filter(le=>!le.disabled),K=document.activeElement,$=(Z=q.find(le=>le.ref.current===K))==null?void 0:Z.textValue,re=q.map(le=>le.textValue),Q=Cle(re,z,$),G=(ae=q.find(le=>le.textValue===Q))==null?void 0:ae.ref.current;(function le(me){U.current=me,window.clearTimeout(X.current),me!==""&&(X.current=window.setTimeout(()=>le(""),1e3))})(z),G&&setTimeout(()=>G.focus())};b.useEffect(()=>()=>window.clearTimeout(X.current),[]),ab();const F=b.useCallback(Y=>{var q,K;return A.current===((q=j.current)==null?void 0:q.side)&&Tle(Y,(K=j.current)==null?void 0:K.area)},[]);return m.jsx(ule,{scope:n,searchRef:U,onItemEnter:b.useCallback(Y=>{F(Y)&&Y.preventDefault()},[F]),onItemLeave:b.useCallback(Y=>{var z;F(Y)||((z=M.current)==null||z.focus(),R(null))},[F]),onTriggerLeave:b.useCallback(Y=>{F(Y)&&Y.preventDefault()},[F]),pointerGraceTimerRef:V,onPointerGraceIntentChange:b.useCallback(Y=>{j.current=Y},[]),children:m.jsx(O,{...I,children:m.jsx(nm,{asChild:!0,trapped:i,onMountAutoFocus:$t(s,Y=>{var z;Y.preventDefault(),(z=M.current)==null||z.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:m.jsx(sf,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:f,onFocusOutside:p,onInteractOutside:y,onDismiss:g,children:m.jsx(Qae,{asChild:!0,...T,dir:S.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:R,onEntryFocus:$t(u,Y=>{S.isUsingKeyboardRef.current||Y.preventDefault()}),preventScrollOnEntryFocus:!0,children:m.jsx(vb,{role:"menu","aria-orientation":"vertical","data-state":S3(x.open),"data-radix-menu-content":"",dir:S.dir,...k,...w,ref:L,style:{outline:"none",...w.style},onKeyDown:$t(w.onKeyDown,Y=>{const q=Y.target.closest("[data-radix-menu-content]")===Y.currentTarget,K=Y.ctrlKey||Y.altKey||Y.metaKey,$=Y.key.length===1;q&&(Y.key==="Tab"&&Y.preventDefault(),!K&&$&&B(Y.key));const re=M.current;if(Y.target!==re||!tle.includes(Y.key))return;Y.preventDefault();const G=N().filter(Z=>!Z.disabled).map(Z=>Z.ref.current);t3.includes(Y.key)&&G.reverse(),Sle(G)}),onBlur:$t(e.onBlur,Y=>{Y.currentTarget.contains(Y.target)||(window.clearTimeout(X.current),U.current="")}),onPointerMove:$t(e.onPointerMove,Pp(Y=>{const z=Y.target,q=D.current!==Y.clientX;if(Y.currentTarget.contains(z)&&q){const K=Y.clientX>D.current?"right":"left";A.current=K,D.current=Y.clientX}}))})})})})})})});a3.displayName=oo;var ple="MenuGroup",sk=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return m.jsx(bn.div,{role:"group",...r,ref:t})});sk.displayName=ple;var mle="MenuLabel",l3=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return m.jsx(bn.div,{...r,ref:t})});l3.displayName=mle;var Cy="MenuItem",z2="menu.itemSelect",_b=b.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,s=b.useRef(null),o=lm(Cy,e.__scopeMenu),l=rk(Cy,e.__scopeMenu),u=sr(t,s),d=b.useRef(!1),f=()=>{const p=s.current;if(!n&&p){const y=new CustomEvent(z2,{bubbles:!0,cancelable:!0});p.addEventListener(z2,g=>r==null?void 0:r(g),{once:!0}),Gj(p,y),y.defaultPrevented?d.current=!1:o.onClose()}};return m.jsx(c3,{...i,ref:u,disabled:n,onClick:$t(e.onClick,f),onPointerDown:p=>{var y;(y=e.onPointerDown)==null||y.call(e,p),d.current=!0},onPointerUp:$t(e.onPointerUp,p=>{var y;d.current||(y=p.currentTarget)==null||y.click()}),onKeyDown:$t(e.onKeyDown,p=>{const y=l.searchRef.current!=="";n||y&&p.key===" "||t1.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});_b.displayName=Cy;var c3=b.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...s}=e,o=rk(Cy,n),l=r3(n),u=b.useRef(null),d=sr(t,u),[f,p]=b.useState(!1),[y,g]=b.useState("");return b.useEffect(()=>{const _=u.current;_&&g((_.textContent??"").trim())},[s.children]),m.jsx(Mp.ItemSlot,{scope:n,disabled:r,textValue:i??y,children:m.jsx(Jae,{asChild:!0,...l,focusable:!r,children:m.jsx(bn.div,{role:"menuitem","data-highlighted":f?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:d,onPointerMove:$t(e.onPointerMove,Pp(_=>{r?o.onItemLeave(_):(o.onItemEnter(_),_.defaultPrevented||_.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:$t(e.onPointerLeave,Pp(_=>o.onItemLeave(_))),onFocus:$t(e.onFocus,()=>p(!0)),onBlur:$t(e.onBlur,()=>p(!1))})})})}),gle="MenuCheckboxItem",u3=b.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return m.jsx(m3,{scope:e.__scopeMenu,checked:n,children:m.jsx(_b,{role:"menuitemcheckbox","aria-checked":ky(n)?"mixed":n,...i,ref:t,"data-state":ak(n),onSelect:$t(i.onSelect,()=>r==null?void 0:r(ky(n)?!0:!n),{checkForDefaultPrevented:!1})})})});u3.displayName=gle;var d3="MenuRadioGroup",[vle,yle]=uu(d3,{value:void 0,onValueChange:()=>{}}),f3=b.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,s=ra(r);return m.jsx(vle,{scope:e.__scopeMenu,value:n,onValueChange:s,children:m.jsx(sk,{...i,ref:t})})});f3.displayName=d3;var h3="MenuRadioItem",p3=b.forwardRef((e,t)=>{const{value:n,...r}=e,i=yle(h3,e.__scopeMenu),s=n===i.value;return m.jsx(m3,{scope:e.__scopeMenu,checked:s,children:m.jsx(_b,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":ak(s),onSelect:$t(r.onSelect,()=>{var o;return(o=i.onValueChange)==null?void 0:o.call(i,n)},{checkForDefaultPrevented:!1})})})});p3.displayName=h3;var ok="MenuItemIndicator",[m3,ble]=uu(ok,{checked:!1}),g3=b.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,s=ble(ok,n);return m.jsx(ho,{present:r||ky(s.checked)||s.checked===!0,children:m.jsx(bn.span,{...i,ref:t,"data-state":ak(s.checked)})})});g3.displayName=ok;var _le="MenuSeparator",v3=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return m.jsx(bn.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});v3.displayName=_le;var wle="MenuArrow",y3=b.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=bb(n);return m.jsx(yb,{...i,...r,ref:t})});y3.displayName=wle;var xle="MenuSub",[tLe,b3]=uu(xle),Xh="MenuSubTrigger",_3=b.forwardRef((e,t)=>{const n=du(Xh,e.__scopeMenu),r=lm(Xh,e.__scopeMenu),i=b3(Xh,e.__scopeMenu),s=rk(Xh,e.__scopeMenu),o=b.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=s,d={__scopeMenu:e.__scopeMenu},f=b.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);return b.useEffect(()=>f,[f]),b.useEffect(()=>{const p=l.current;return()=>{window.clearTimeout(p),u(null)}},[l,u]),m.jsx(tk,{asChild:!0,...d,children:m.jsx(c3,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":i.contentId,"data-state":S3(n.open),...e,ref:za(t,i.onTriggerChange),onClick:p=>{var y;(y=e.onClick)==null||y.call(e,p),!(e.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:$t(e.onPointerMove,Pp(p=>{s.onItemEnter(p),!p.defaultPrevented&&!e.disabled&&!n.open&&!o.current&&(s.onPointerGraceIntentChange(null),o.current=window.setTimeout(()=>{n.onOpenChange(!0),f()},100))})),onPointerLeave:$t(e.onPointerLeave,Pp(p=>{var g,_;f();const y=(g=n.content)==null?void 0:g.getBoundingClientRect();if(y){const w=(_=n.content)==null?void 0:_.dataset.side,x=w==="right",S=x?-5:5,k=y[x?"left":"right"],T=y[x?"right":"left"];s.onPointerGraceIntentChange({area:[{x:p.clientX+S,y:p.clientY},{x:k,y:y.top},{x:T,y:y.top},{x:T,y:y.bottom},{x:k,y:y.bottom}],side:w}),window.clearTimeout(l.current),l.current=window.setTimeout(()=>s.onPointerGraceIntentChange(null),300)}else{if(s.onTriggerLeave(p),p.defaultPrevented)return;s.onPointerGraceIntentChange(null)}})),onKeyDown:$t(e.onKeyDown,p=>{var g;const y=s.searchRef.current!=="";e.disabled||y&&p.key===" "||nle[r.dir].includes(p.key)&&(n.onOpenChange(!0),(g=n.content)==null||g.focus(),p.preventDefault())})})})});_3.displayName=Xh;var w3="MenuSubContent",x3=b.forwardRef((e,t)=>{const n=s3(oo,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,s=du(oo,e.__scopeMenu),o=lm(oo,e.__scopeMenu),l=b3(w3,e.__scopeMenu),u=b.useRef(null),d=sr(t,u);return m.jsx(Mp.Provider,{scope:e.__scopeMenu,children:m.jsx(ho,{present:r||s.open,children:m.jsx(Mp.Slot,{scope:e.__scopeMenu,children:m.jsx(ik,{id:l.contentId,"aria-labelledby":l.triggerId,...i,ref:d,align:"start",side:o.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:f=>{var p;o.isUsingKeyboardRef.current&&((p=u.current)==null||p.focus()),f.preventDefault()},onCloseAutoFocus:f=>f.preventDefault(),onFocusOutside:$t(e.onFocusOutside,f=>{f.target!==l.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:$t(e.onEscapeKeyDown,f=>{o.onClose(),f.preventDefault()}),onKeyDown:$t(e.onKeyDown,f=>{var g;const p=f.currentTarget.contains(f.target),y=rle[o.dir].includes(f.key);p&&y&&(s.onOpenChange(!1),(g=l.trigger)==null||g.focus(),f.preventDefault())})})})})})});x3.displayName=w3;function S3(e){return e?"open":"closed"}function ky(e){return e==="indeterminate"}function ak(e){return ky(e)?"indeterminate":e?"checked":"unchecked"}function Sle(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function Ele(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function Cle(e,t,n){const i=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let o=Ele(e,Math.max(s,0));i.length===1&&(o=o.filter(d=>d!==n));const u=o.find(d=>d.toLowerCase().startsWith(i.toLowerCase()));return u!==n?u:void 0}function kle(e,t){const{x:n,y:r}=e;let i=!1;for(let s=0,o=t.length-1;s<t.length;o=s++){const l=t[s],u=t[o],d=l.x,f=l.y,p=u.x,y=u.y;f>r!=y>r&&n<(p-d)*(r-f)/(y-f)+d&&(i=!i)}return i}function Tle(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return kle(n,t)}function Pp(e){return t=>t.pointerType==="mouse"?e(t):void 0}var Rle=i3,Ale=tk,Nle=o3,Mle=a3,Ple=sk,Ile=l3,Ole=_b,Lle=u3,Dle=f3,Ble=p3,zle=g3,jle=v3,Fle=y3,$le=_3,Hle=x3,wb="DropdownMenu",[Ule]=Ua(wb,[n3]),is=n3(),[Wle,E3]=Ule(wb),C3=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:s,onOpenChange:o,modal:l=!0}=e,u=is(t),d=b.useRef(null),[f,p]=Kc({prop:i,defaultProp:s??!1,onChange:o,caller:wb});return m.jsx(Wle,{scope:t,triggerId:Di(),triggerRef:d,contentId:Di(),open:f,onOpenChange:p,onOpenToggle:b.useCallback(()=>p(y=>!y),[p]),modal:l,children:m.jsx(Rle,{...u,open:f,onOpenChange:p,dir:r,modal:l,children:n})})};C3.displayName=wb;var k3="DropdownMenuTrigger",T3=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,s=E3(k3,n),o=is(n);return m.jsx(Ale,{asChild:!0,...o,children:m.jsx(bn.button,{type:"button",id:s.triggerId,"aria-haspopup":"menu","aria-expanded":s.open,"aria-controls":s.open?s.contentId:void 0,"data-state":s.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...i,ref:za(t,s.triggerRef),onPointerDown:$t(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(s.onOpenToggle(),s.open||l.preventDefault())}),onKeyDown:$t(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&s.onOpenToggle(),l.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});T3.displayName=k3;var qle="DropdownMenuPortal",R3=e=>{const{__scopeDropdownMenu:t,...n}=e,r=is(t);return m.jsx(Nle,{...r,...n})};R3.displayName=qle;var A3="DropdownMenuContent",N3=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=E3(A3,n),s=is(n),o=b.useRef(!1);return m.jsx(Mle,{id:i.contentId,"aria-labelledby":i.triggerId,...s,...r,ref:t,onCloseAutoFocus:$t(e.onCloseAutoFocus,l=>{var u;o.current||(u=i.triggerRef.current)==null||u.focus(),o.current=!1,l.preventDefault()}),onInteractOutside:$t(e.onInteractOutside,l=>{const u=l.detail.originalEvent,d=u.button===0&&u.ctrlKey===!0,f=u.button===2||d;(!i.modal||f)&&(o.current=!0)}),style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});N3.displayName=A3;var Vle="DropdownMenuGroup",Yle=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(Ple,{...i,...r,ref:t})});Yle.displayName=Vle;var Kle="DropdownMenuLabel",M3=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(Ile,{...i,...r,ref:t})});M3.displayName=Kle;var Gle="DropdownMenuItem",P3=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(Ole,{...i,...r,ref:t})});P3.displayName=Gle;var Xle="DropdownMenuCheckboxItem",I3=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(Lle,{...i,...r,ref:t})});I3.displayName=Xle;var Zle="DropdownMenuRadioGroup",Qle=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(Dle,{...i,...r,ref:t})});Qle.displayName=Zle;var Jle="DropdownMenuRadioItem",ece=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(Ble,{...i,...r,ref:t})});ece.displayName=Jle;var tce="DropdownMenuItemIndicator",O3=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(zle,{...i,...r,ref:t})});O3.displayName=tce;var nce="DropdownMenuSeparator",L3=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(jle,{...i,...r,ref:t})});L3.displayName=nce;var rce="DropdownMenuArrow",ice=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(Fle,{...i,...r,ref:t})});ice.displayName=rce;var sce="DropdownMenuSubTrigger",oce=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx($le,{...i,...r,ref:t})});oce.displayName=sce;var ace="DropdownMenuSubContent",lce=b.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=is(n);return m.jsx(Hle,{...i,...r,ref:t,style:{...e.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});lce.displayName=ace;var cce=C3,uce=T3,dce=R3,fce=N3,hce=M3,pce=P3,mce=I3,gce=O3,vce=L3;function j2(e,[t,n]){return Math.min(n,Math.max(t,e))}var xb="Popover",[D3]=Ua(xb,[nc]),cm=nc(),[yce,rc]=D3(xb),B3=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:s,modal:o=!1}=e,l=cm(t),u=b.useRef(null),[d,f]=b.useState(!1),[p,y]=Kc({prop:r,defaultProp:i??!1,onChange:s,caller:xb});return m.jsx(gb,{...l,children:m.jsx(yce,{scope:t,contentId:Di(),triggerRef:u,open:p,onOpenChange:y,onOpenToggle:b.useCallback(()=>y(g=>!g),[y]),hasCustomAnchor:d,onCustomAnchorAdd:b.useCallback(()=>f(!0),[]),onCustomAnchorRemove:b.useCallback(()=>f(!1),[]),modal:o,children:n})})};B3.displayName=xb;var z3="PopoverAnchor",bce=b.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=rc(z3,n),s=cm(n),{onCustomAnchorAdd:o,onCustomAnchorRemove:l}=i;return b.useEffect(()=>(o(),()=>l()),[o,l]),m.jsx(sm,{...s,...r,ref:t})});bce.displayName=z3;var j3="PopoverTrigger",F3=b.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=rc(j3,n),s=cm(n),o=sr(t,i.triggerRef),l=m.jsx(bn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":q3(i.open),...r,ref:o,onClick:$t(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?l:m.jsx(sm,{asChild:!0,...s,children:l})});F3.displayName=j3;var lk="PopoverPortal",[_ce,wce]=D3(lk,{forceMount:void 0}),$3=e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,s=rc(lk,t);return m.jsx(_ce,{scope:t,forceMount:n,children:m.jsx(ho,{present:n||s.open,children:m.jsx(of,{asChild:!0,container:i,children:r})})})};$3.displayName=lk;var Gd="PopoverContent",H3=b.forwardRef((e,t)=>{const n=wce(Gd,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,s=rc(Gd,e.__scopePopover);return m.jsx(ho,{present:r||s.open,children:s.modal?m.jsx(Sce,{...i,ref:t}):m.jsx(Ece,{...i,ref:t})})});H3.displayName=Gd;var xce=Vl("PopoverContent.RemoveScroll"),Sce=b.forwardRef((e,t)=>{const n=rc(Gd,e.__scopePopover),r=b.useRef(null),i=sr(t,r),s=b.useRef(!1);return b.useEffect(()=>{const o=r.current;if(o)return cb(o)},[]),m.jsx(rm,{as:xce,allowPinchZoom:!0,children:m.jsx(U3,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:$t(e.onCloseAutoFocus,o=>{var l;o.preventDefault(),s.current||(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:$t(e.onPointerDownOutside,o=>{const l=o.detail.originalEvent,u=l.button===0&&l.ctrlKey===!0,d=l.button===2||u;s.current=d},{checkForDefaultPrevented:!1}),onFocusOutside:$t(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1})})})}),Ece=b.forwardRef((e,t)=>{const n=rc(Gd,e.__scopePopover),r=b.useRef(!1),i=b.useRef(!1);return m.jsx(U3,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:s=>{var o,l;(o=e.onCloseAutoFocus)==null||o.call(e,s),s.defaultPrevented||(r.current||(l=n.triggerRef.current)==null||l.focus(),s.preventDefault()),r.current=!1,i.current=!1},onInteractOutside:s=>{var u,d;(u=e.onInteractOutside)==null||u.call(e,s),s.defaultPrevented||(r.current=!0,s.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const o=s.target;((d=n.triggerRef.current)==null?void 0:d.contains(o))&&s.preventDefault(),s.detail.originalEvent.type==="focusin"&&i.current&&s.preventDefault()}})}),U3=b.forwardRef((e,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:i,onCloseAutoFocus:s,disableOutsidePointerEvents:o,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onInteractOutside:f,...p}=e,y=rc(Gd,n),g=cm(n);return ab(),m.jsx(nm,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:s,children:m.jsx(sf,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:f,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onDismiss:()=>y.onOpenChange(!1),children:m.jsx(vb,{"data-state":q3(y.open),role:"dialog",id:y.contentId,...g,...p,ref:t,style:{...p.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),W3="PopoverClose",Cce=b.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=rc(W3,n);return m.jsx(bn.button,{type:"button",...r,ref:t,onClick:$t(e.onClick,()=>i.onOpenChange(!1))})});Cce.displayName=W3;var kce="PopoverArrow",Tce=b.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=cm(n);return m.jsx(yb,{...i,...r,ref:t})});Tce.displayName=kce;function q3(e){return e?"open":"closed"}var Rce=B3,Ace=F3,Nce=$3,Mce=H3,Pce=[" ","Enter","ArrowUp","ArrowDown"],Ice=[" ","Enter"],Zc="Select",[Sb,Eb,Oce]=zC(Zc),[cf]=Ua(Zc,[Oce,nc]),Cb=nc(),[Lce,ic]=cf(Zc),[Dce,Bce]=cf(Zc),V3=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:i,onOpenChange:s,value:o,defaultValue:l,onValueChange:u,dir:d,name:f,autoComplete:p,disabled:y,required:g,form:_}=e,w=Cb(t),[x,S]=b.useState(null),[k,T]=b.useState(null),[N,P]=b.useState(!1),R=jC(d),[M,L]=Kc({prop:r,defaultProp:i??!1,onChange:s,caller:Zc}),[X,U]=Kc({prop:o,defaultProp:l,onChange:u,caller:Zc}),V=b.useRef(null),j=x?_||!!x.closest("form"):!0,[A,D]=b.useState(new Set),O=Array.from(A).map(I=>I.props.value).join(";");return m.jsx(gb,{...w,children:m.jsxs(Lce,{required:g,scope:t,trigger:x,onTriggerChange:S,valueNode:k,onValueNodeChange:T,valueNodeHasChildren:N,onValueNodeHasChildrenChange:P,contentId:Di(),value:X,onValueChange:U,open:M,onOpenChange:L,dir:R,triggerPointerDownPosRef:V,disabled:y,children:[m.jsx(Sb.Provider,{scope:t,children:m.jsx(Dce,{scope:e.__scopeSelect,onNativeOptionAdd:b.useCallback(I=>{D(B=>new Set(B).add(I))},[]),onNativeOptionRemove:b.useCallback(I=>{D(B=>{const F=new Set(B);return F.delete(I),F})},[]),children:n})}),j?m.jsxs(p4,{"aria-hidden":!0,required:g,tabIndex:-1,name:f,autoComplete:p,value:X,onChange:I=>U(I.target.value),disabled:y,form:_,children:[X===void 0?m.jsx("option",{value:""}):null,Array.from(A)]},O):null]})})};V3.displayName=Zc;var Y3="SelectTrigger",K3=b.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...i}=e,s=Cb(n),o=ic(Y3,n),l=o.disabled||r,u=sr(t,o.onTriggerChange),d=Eb(n),f=b.useRef("touch"),[p,y,g]=g4(w=>{const x=d().filter(T=>!T.disabled),S=x.find(T=>T.value===o.value),k=v4(x,w,S);k!==void 0&&o.onValueChange(k.value)}),_=w=>{l||(o.onOpenChange(!0),g()),w&&(o.triggerPointerDownPosRef.current={x:Math.round(w.pageX),y:Math.round(w.pageY)})};return m.jsx(sm,{asChild:!0,...s,children:m.jsx(bn.button,{type:"button",role:"combobox","aria-controls":o.contentId,"aria-expanded":o.open,"aria-required":o.required,"aria-autocomplete":"none",dir:o.dir,"data-state":o.open?"open":"closed",disabled:l,"data-disabled":l?"":void 0,"data-placeholder":m4(o.value)?"":void 0,...i,ref:u,onClick:$t(i.onClick,w=>{w.currentTarget.focus(),f.current!=="mouse"&&_(w)}),onPointerDown:$t(i.onPointerDown,w=>{f.current=w.pointerType;const x=w.target;x.hasPointerCapture(w.pointerId)&&x.releasePointerCapture(w.pointerId),w.button===0&&w.ctrlKey===!1&&w.pointerType==="mouse"&&(_(w),w.preventDefault())}),onKeyDown:$t(i.onKeyDown,w=>{const x=p.current!=="";!(w.ctrlKey||w.altKey||w.metaKey)&&w.key.length===1&&y(w.key),!(x&&w.key===" ")&&Pce.includes(w.key)&&(_(),w.preventDefault())})})})});K3.displayName=Y3;var G3="SelectValue",X3=b.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:i,children:s,placeholder:o="",...l}=e,u=ic(G3,n),{onValueNodeHasChildrenChange:d}=u,f=s!==void 0,p=sr(t,u.onValueNodeChange);return Vi(()=>{d(f)},[d,f]),m.jsx(bn.span,{...l,ref:p,style:{pointerEvents:"none"},children:m4(u.value)?m.jsx(m.Fragment,{children:o}):s})});X3.displayName=G3;var zce="SelectIcon",Z3=b.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...i}=e;return m.jsx(bn.span,{"aria-hidden":!0,...i,ref:t,children:r||"▼"})});Z3.displayName=zce;var jce="SelectPortal",Q3=e=>m.jsx(of,{asChild:!0,...e});Q3.displayName=jce;var Qc="SelectContent",J3=b.forwardRef((e,t)=>{const n=ic(Qc,e.__scopeSelect),[r,i]=b.useState();if(Vi(()=>{i(new DocumentFragment)},[]),!n.open){const s=r;return s?cu.createPortal(m.jsx(e4,{scope:e.__scopeSelect,children:m.jsx(Sb.Slot,{scope:e.__scopeSelect,children:m.jsx("div",{children:e.children})})}),s):null}return m.jsx(t4,{...e,ref:t})});J3.displayName=Qc;var _o=10,[e4,sc]=cf(Qc),Fce="SelectContentImpl",$ce=Vl("SelectContent.RemoveScroll"),t4=b.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:s,onPointerDownOutside:o,side:l,sideOffset:u,align:d,alignOffset:f,arrowPadding:p,collisionBoundary:y,collisionPadding:g,sticky:_,hideWhenDetached:w,avoidCollisions:x,...S}=e,k=ic(Qc,n),[T,N]=b.useState(null),[P,R]=b.useState(null),M=sr(t,Z=>N(Z)),[L,X]=b.useState(null),[U,V]=b.useState(null),j=Eb(n),[A,D]=b.useState(!1),O=b.useRef(!1);b.useEffect(()=>{if(T)return cb(T)},[T]),ab();const I=b.useCallback(Z=>{const[ae,...le]=j().map($e=>$e.ref.current),[me]=le.slice(-1),ke=document.activeElement;for(const $e of Z)if($e===ke||($e==null||$e.scrollIntoView({block:"nearest"}),$e===ae&&P&&(P.scrollTop=0),$e===me&&P&&(P.scrollTop=P.scrollHeight),$e==null||$e.focus(),document.activeElement!==ke))return},[j,P]),B=b.useCallback(()=>I([L,T]),[I,L,T]);b.useEffect(()=>{A&&B()},[A,B]);const{onOpenChange:F,triggerPointerDownPosRef:Y}=k;b.useEffect(()=>{if(T){let Z={x:0,y:0};const ae=me=>{var ke,$e;Z={x:Math.abs(Math.round(me.pageX)-(((ke=Y.current)==null?void 0:ke.x)??0)),y:Math.abs(Math.round(me.pageY)-((($e=Y.current)==null?void 0:$e.y)??0))}},le=me=>{Z.x<=10&&Z.y<=10?me.preventDefault():T.contains(me.target)||F(!1),document.removeEventListener("pointermove",ae),Y.current=null};return Y.current!==null&&(document.addEventListener("pointermove",ae),document.addEventListener("pointerup",le,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",ae),document.removeEventListener("pointerup",le,{capture:!0})}}},[T,F,Y]),b.useEffect(()=>{const Z=()=>F(!1);return window.addEventListener("blur",Z),window.addEventListener("resize",Z),()=>{window.removeEventListener("blur",Z),window.removeEventListener("resize",Z)}},[F]);const[z,q]=g4(Z=>{const ae=j().filter(ke=>!ke.disabled),le=ae.find(ke=>ke.ref.current===document.activeElement),me=v4(ae,Z,le);me&&setTimeout(()=>me.ref.current.focus())}),K=b.useCallback((Z,ae,le)=>{const me=!O.current&&!le;(k.value!==void 0&&k.value===ae||me)&&(X(Z),me&&(O.current=!0))},[k.value]),$=b.useCallback(()=>T==null?void 0:T.focus(),[T]),re=b.useCallback((Z,ae,le)=>{const me=!O.current&&!le;(k.value!==void 0&&k.value===ae||me)&&V(Z)},[k.value]),Q=r==="popper"?n1:n4,G=Q===n1?{side:l,sideOffset:u,align:d,alignOffset:f,arrowPadding:p,collisionBoundary:y,collisionPadding:g,sticky:_,hideWhenDetached:w,avoidCollisions:x}:{};return m.jsx(e4,{scope:n,content:T,viewport:P,onViewportChange:R,itemRefCallback:K,selectedItem:L,onItemLeave:$,itemTextRefCallback:re,focusSelectedItem:B,selectedItemText:U,position:r,isPositioned:A,searchRef:z,children:m.jsx(rm,{as:$ce,allowPinchZoom:!0,children:m.jsx(nm,{asChild:!0,trapped:k.open,onMountAutoFocus:Z=>{Z.preventDefault()},onUnmountAutoFocus:$t(i,Z=>{var ae;(ae=k.trigger)==null||ae.focus({preventScroll:!0}),Z.preventDefault()}),children:m.jsx(sf,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:Z=>Z.preventDefault(),onDismiss:()=>k.onOpenChange(!1),children:m.jsx(Q,{role:"listbox",id:k.contentId,"data-state":k.open?"open":"closed",dir:k.dir,onContextMenu:Z=>Z.preventDefault(),...S,...G,onPlaced:()=>D(!0),ref:M,style:{display:"flex",flexDirection:"column",outline:"none",...S.style},onKeyDown:$t(S.onKeyDown,Z=>{const ae=Z.ctrlKey||Z.altKey||Z.metaKey;if(Z.key==="Tab"&&Z.preventDefault(),!ae&&Z.key.length===1&&q(Z.key),["ArrowUp","ArrowDown","Home","End"].includes(Z.key)){let me=j().filter(ke=>!ke.disabled).map(ke=>ke.ref.current);if(["ArrowUp","End"].includes(Z.key)&&(me=me.slice().reverse()),["ArrowUp","ArrowDown"].includes(Z.key)){const ke=Z.target,$e=me.indexOf(ke);me=me.slice($e+1)}setTimeout(()=>I(me)),Z.preventDefault()}})})})})})})});t4.displayName=Fce;var Hce="SelectItemAlignedPosition",n4=b.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...i}=e,s=ic(Qc,n),o=sc(Qc,n),[l,u]=b.useState(null),[d,f]=b.useState(null),p=sr(t,M=>f(M)),y=Eb(n),g=b.useRef(!1),_=b.useRef(!0),{viewport:w,selectedItem:x,selectedItemText:S,focusSelectedItem:k}=o,T=b.useCallback(()=>{if(s.trigger&&s.valueNode&&l&&d&&w&&x&&S){const M=s.trigger.getBoundingClientRect(),L=d.getBoundingClientRect(),X=s.valueNode.getBoundingClientRect(),U=S.getBoundingClientRect();if(s.dir!=="rtl"){const ke=U.left-L.left,$e=X.left-ke,he=M.left-$e,He=M.width+he,Nt=Math.max(He,L.width),ye=window.innerWidth-_o,Ze=j2($e,[_o,Math.max(_o,ye-Nt)]);l.style.minWidth=He+"px",l.style.left=Ze+"px"}else{const ke=L.right-U.right,$e=window.innerWidth-X.right-ke,he=window.innerWidth-M.right-$e,He=M.width+he,Nt=Math.max(He,L.width),ye=window.innerWidth-_o,Ze=j2($e,[_o,Math.max(_o,ye-Nt)]);l.style.minWidth=He+"px",l.style.right=Ze+"px"}const V=y(),j=window.innerHeight-_o*2,A=w.scrollHeight,D=window.getComputedStyle(d),O=parseInt(D.borderTopWidth,10),I=parseInt(D.paddingTop,10),B=parseInt(D.borderBottomWidth,10),F=parseInt(D.paddingBottom,10),Y=O+I+A+F+B,z=Math.min(x.offsetHeight*5,Y),q=window.getComputedStyle(w),K=parseInt(q.paddingTop,10),$=parseInt(q.paddingBottom,10),re=M.top+M.height/2-_o,Q=j-re,G=x.offsetHeight/2,Z=x.offsetTop+G,ae=O+I+Z,le=Y-ae;if(ae<=re){const ke=V.length>0&&x===V[V.length-1].ref.current;l.style.bottom="0px";const $e=d.clientHeight-w.offsetTop-w.offsetHeight,he=Math.max(Q,G+(ke?$:0)+$e+B),He=ae+he;l.style.height=He+"px"}else{const ke=V.length>0&&x===V[0].ref.current;l.style.top="0px";const he=Math.max(re,O+w.offsetTop+(ke?K:0)+G)+le;l.style.height=he+"px",w.scrollTop=ae-re+w.offsetTop}l.style.margin=`${_o}px 0`,l.style.minHeight=z+"px",l.style.maxHeight=j+"px",r==null||r(),requestAnimationFrame(()=>g.current=!0)}},[y,s.trigger,s.valueNode,l,d,w,x,S,s.dir,r]);Vi(()=>T(),[T]);const[N,P]=b.useState();Vi(()=>{d&&P(window.getComputedStyle(d).zIndex)},[d]);const R=b.useCallback(M=>{M&&_.current===!0&&(T(),k==null||k(),_.current=!1)},[T,k]);return m.jsx(Wce,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:g,onScrollButtonChange:R,children:m.jsx("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:N},children:m.jsx(bn.div,{...i,ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})});n4.displayName=Hce;var Uce="SelectPopperPosition",n1=b.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:i=_o,...s}=e,o=Cb(n);return m.jsx(vb,{...o,...s,ref:t,align:r,collisionPadding:i,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});n1.displayName=Uce;var[Wce,ck]=cf(Qc,{}),r1="SelectViewport",r4=b.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...i}=e,s=sc(r1,n),o=ck(r1,n),l=sr(t,s.onViewportChange),u=b.useRef(0);return m.jsxs(m.Fragment,{children:[m.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),m.jsx(Sb.Slot,{scope:n,children:m.jsx(bn.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:l,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:$t(i.onScroll,d=>{const f=d.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:y}=o;if(y!=null&&y.current&&p){const g=Math.abs(u.current-f.scrollTop);if(g>0){const _=window.innerHeight-_o*2,w=parseFloat(p.style.minHeight),x=parseFloat(p.style.height),S=Math.max(w,x);if(S<_){const k=S+g,T=Math.min(_,k),N=k-T;p.style.height=T+"px",p.style.bottom==="0px"&&(f.scrollTop=N>0?N:0,p.style.justifyContent="flex-end")}}}u.current=f.scrollTop})})})]})});r4.displayName=r1;var i4="SelectGroup",[qce,Vce]=cf(i4),Yce=b.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,i=Di();return m.jsx(qce,{scope:n,id:i,children:m.jsx(bn.div,{role:"group","aria-labelledby":i,...r,ref:t})})});Yce.displayName=i4;var s4="SelectLabel",Kce=b.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,i=Vce(s4,n);return m.jsx(bn.div,{id:i.id,...r,ref:t})});Kce.displayName=s4;var Ty="SelectItem",[Gce,o4]=cf(Ty),a4=b.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:i=!1,textValue:s,...o}=e,l=ic(Ty,n),u=sc(Ty,n),d=l.value===r,[f,p]=b.useState(s??""),[y,g]=b.useState(!1),_=sr(t,k=>{var T;return(T=u.itemRefCallback)==null?void 0:T.call(u,k,r,i)}),w=Di(),x=b.useRef("touch"),S=()=>{i||(l.onValueChange(r),l.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return m.jsx(Gce,{scope:n,value:r,disabled:i,textId:w,isSelected:d,onItemTextChange:b.useCallback(k=>{p(T=>T||((k==null?void 0:k.textContent)??"").trim())},[]),children:m.jsx(Sb.ItemSlot,{scope:n,value:r,disabled:i,textValue:f,children:m.jsx(bn.div,{role:"option","aria-labelledby":w,"data-highlighted":y?"":void 0,"aria-selected":d&&y,"data-state":d?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...o,ref:_,onFocus:$t(o.onFocus,()=>g(!0)),onBlur:$t(o.onBlur,()=>g(!1)),onClick:$t(o.onClick,()=>{x.current!=="mouse"&&S()}),onPointerUp:$t(o.onPointerUp,()=>{x.current==="mouse"&&S()}),onPointerDown:$t(o.onPointerDown,k=>{x.current=k.pointerType}),onPointerMove:$t(o.onPointerMove,k=>{var T;x.current=k.pointerType,i?(T=u.onItemLeave)==null||T.call(u):x.current==="mouse"&&k.currentTarget.focus({preventScroll:!0})}),onPointerLeave:$t(o.onPointerLeave,k=>{var T;k.currentTarget===document.activeElement&&((T=u.onItemLeave)==null||T.call(u))}),onKeyDown:$t(o.onKeyDown,k=>{var N;((N=u.searchRef)==null?void 0:N.current)!==""&&k.key===" "||(Ice.includes(k.key)&&S(),k.key===" "&&k.preventDefault())})})})})});a4.displayName=Ty;var Zh="SelectItemText",l4=b.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:i,...s}=e,o=ic(Zh,n),l=sc(Zh,n),u=o4(Zh,n),d=Bce(Zh,n),[f,p]=b.useState(null),y=sr(t,S=>p(S),u.onItemTextChange,S=>{var k;return(k=l.itemTextRefCallback)==null?void 0:k.call(l,S,u.value,u.disabled)}),g=f==null?void 0:f.textContent,_=b.useMemo(()=>m.jsx("option",{value:u.value,disabled:u.disabled,children:g},u.value),[u.disabled,u.value,g]),{onNativeOptionAdd:w,onNativeOptionRemove:x}=d;return Vi(()=>(w(_),()=>x(_)),[w,x,_]),m.jsxs(m.Fragment,{children:[m.jsx(bn.span,{id:u.textId,...s,ref:y}),u.isSelected&&o.valueNode&&!o.valueNodeHasChildren?cu.createPortal(s.children,o.valueNode):null]})});l4.displayName=Zh;var c4="SelectItemIndicator",u4=b.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return o4(c4,n).isSelected?m.jsx(bn.span,{"aria-hidden":!0,...r,ref:t}):null});u4.displayName=c4;var i1="SelectScrollUpButton",d4=b.forwardRef((e,t)=>{const n=sc(i1,e.__scopeSelect),r=ck(i1,e.__scopeSelect),[i,s]=b.useState(!1),o=sr(t,r.onScrollButtonChange);return Vi(()=>{if(n.viewport&&n.isPositioned){let l=function(){const d=u.scrollTop>0;s(d)};const u=n.viewport;return l(),u.addEventListener("scroll",l),()=>u.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),i?m.jsx(h4,{...e,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}}):null});d4.displayName=i1;var s1="SelectScrollDownButton",f4=b.forwardRef((e,t)=>{const n=sc(s1,e.__scopeSelect),r=ck(s1,e.__scopeSelect),[i,s]=b.useState(!1),o=sr(t,r.onScrollButtonChange);return Vi(()=>{if(n.viewport&&n.isPositioned){let l=function(){const d=u.scrollHeight-u.clientHeight,f=Math.ceil(u.scrollTop)<d;s(f)};const u=n.viewport;return l(),u.addEventListener("scroll",l),()=>u.removeEventListener("scroll",l)}},[n.viewport,n.isPositioned]),i?m.jsx(h4,{...e,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}}):null});f4.displayName=s1;var h4=b.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...i}=e,s=sc("SelectScrollButton",n),o=b.useRef(null),l=Eb(n),u=b.useCallback(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return b.useEffect(()=>()=>u(),[u]),Vi(()=>{var f;const d=l().find(p=>p.ref.current===document.activeElement);(f=d==null?void 0:d.ref.current)==null||f.scrollIntoView({block:"nearest"})},[l]),m.jsx(bn.div,{"aria-hidden":!0,...i,ref:t,style:{flexShrink:0,...i.style},onPointerDown:$t(i.onPointerDown,()=>{o.current===null&&(o.current=window.setInterval(r,50))}),onPointerMove:$t(i.onPointerMove,()=>{var d;(d=s.onItemLeave)==null||d.call(s),o.current===null&&(o.current=window.setInterval(r,50))}),onPointerLeave:$t(i.onPointerLeave,()=>{u()})})}),Xce="SelectSeparator",Zce=b.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return m.jsx(bn.div,{"aria-hidden":!0,...r,ref:t})});Zce.displayName=Xce;var o1="SelectArrow",Qce=b.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,i=Cb(n),s=ic(o1,n),o=sc(o1,n);return s.open&&o.position==="popper"?m.jsx(yb,{...i,...r,ref:t}):null});Qce.displayName=o1;var Jce="SelectBubbleInput",p4=b.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const i=b.useRef(null),s=sr(r,i),o=Roe(t);return b.useEffect(()=>{const l=i.current;if(!l)return;const u=window.HTMLSelectElement.prototype,f=Object.getOwnPropertyDescriptor(u,"value").set;if(o!==t&&f){const p=new Event("change",{bubbles:!0});f.call(l,t),l.dispatchEvent(p)}},[o,t]),m.jsx(bn.select,{...n,style:{...Xj,...n.style},ref:s,defaultValue:t})});p4.displayName=Jce;function m4(e){return e===""||e===void 0}function g4(e){const t=ra(e),n=b.useRef(""),r=b.useRef(0),i=b.useCallback(o=>{const l=n.current+o;t(l),(function u(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>u(""),1e3))})(l)},[t]),s=b.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return b.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,i,s]}function v4(e,t,n){const i=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let o=eue(e,Math.max(s,0));i.length===1&&(o=o.filter(d=>d!==n));const u=o.find(d=>d.textValue.toLowerCase().startsWith(i.toLowerCase()));return u!==n?u:void 0}function eue(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var tue=V3,nue=K3,rue=X3,iue=Z3,sue=Q3,oue=J3,aue=r4,lue=a4,cue=l4,uue=u4,due=d4,fue=f4,[kb]=Ua("Tooltip",[nc]),Tb=nc(),y4="TooltipProvider",hue=700,a1="tooltip.open",[pue,uk]=kb(y4),b4=e=>{const{__scopeTooltip:t,delayDuration:n=hue,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:s}=e,o=b.useRef(!0),l=b.useRef(!1),u=b.useRef(0);return b.useEffect(()=>{const d=u.current;return()=>window.clearTimeout(d)},[]),m.jsx(pue,{scope:t,isOpenDelayedRef:o,delayDuration:n,onOpen:b.useCallback(()=>{window.clearTimeout(u.current),o.current=!1},[]),onClose:b.useCallback(()=>{window.clearTimeout(u.current),u.current=window.setTimeout(()=>o.current=!0,r)},[r]),isPointerInTransitRef:l,onPointerInTransitChange:b.useCallback(d=>{l.current=d},[]),disableHoverableContent:i,children:s})};b4.displayName=y4;var Ip="Tooltip",[mue,um]=kb(Ip),_4=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:s,disableHoverableContent:o,delayDuration:l}=e,u=uk(Ip,e.__scopeTooltip),d=Tb(t),[f,p]=b.useState(null),y=Di(),g=b.useRef(0),_=o??u.disableHoverableContent,w=l??u.delayDuration,x=b.useRef(!1),[S,k]=Kc({prop:r,defaultProp:i??!1,onChange:M=>{M?(u.onOpen(),document.dispatchEvent(new CustomEvent(a1))):u.onClose(),s==null||s(M)},caller:Ip}),T=b.useMemo(()=>S?x.current?"delayed-open":"instant-open":"closed",[S]),N=b.useCallback(()=>{window.clearTimeout(g.current),g.current=0,x.current=!1,k(!0)},[k]),P=b.useCallback(()=>{window.clearTimeout(g.current),g.current=0,k(!1)},[k]),R=b.useCallback(()=>{window.clearTimeout(g.current),g.current=window.setTimeout(()=>{x.current=!0,k(!0),g.current=0},w)},[w,k]);return b.useEffect(()=>()=>{g.current&&(window.clearTimeout(g.current),g.current=0)},[]),m.jsx(gb,{...d,children:m.jsx(mue,{scope:t,contentId:y,open:S,stateAttribute:T,trigger:f,onTriggerChange:p,onTriggerEnter:b.useCallback(()=>{u.isOpenDelayedRef.current?R():N()},[u.isOpenDelayedRef,R,N]),onTriggerLeave:b.useCallback(()=>{_?P():(window.clearTimeout(g.current),g.current=0)},[P,_]),onOpen:N,onClose:P,disableHoverableContent:_,children:n})})};_4.displayName=Ip;var l1="TooltipTrigger",w4=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=um(l1,n),s=uk(l1,n),o=Tb(n),l=b.useRef(null),u=sr(t,l,i.onTriggerChange),d=b.useRef(!1),f=b.useRef(!1),p=b.useCallback(()=>d.current=!1,[]);return b.useEffect(()=>()=>document.removeEventListener("pointerup",p),[p]),m.jsx(sm,{asChild:!0,...o,children:m.jsx(bn.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:u,onPointerMove:$t(e.onPointerMove,y=>{y.pointerType!=="touch"&&!f.current&&!s.isPointerInTransitRef.current&&(i.onTriggerEnter(),f.current=!0)}),onPointerLeave:$t(e.onPointerLeave,()=>{i.onTriggerLeave(),f.current=!1}),onPointerDown:$t(e.onPointerDown,()=>{i.open&&i.onClose(),d.current=!0,document.addEventListener("pointerup",p,{once:!0})}),onFocus:$t(e.onFocus,()=>{d.current||i.onOpen()}),onBlur:$t(e.onBlur,i.onClose),onClick:$t(e.onClick,i.onClose)})})});w4.displayName=l1;var dk="TooltipPortal",[gue,vue]=kb(dk,{forceMount:void 0}),x4=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,s=um(dk,t);return m.jsx(gue,{scope:t,forceMount:n,children:m.jsx(ho,{present:n||s.open,children:m.jsx(of,{asChild:!0,container:i,children:r})})})};x4.displayName=dk;var Xd="TooltipContent",S4=b.forwardRef((e,t)=>{const n=vue(Xd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...s}=e,o=um(Xd,e.__scopeTooltip);return m.jsx(ho,{present:r||o.open,children:o.disableHoverableContent?m.jsx(E4,{side:i,...s,ref:t}):m.jsx(yue,{side:i,...s,ref:t})})}),yue=b.forwardRef((e,t)=>{const n=um(Xd,e.__scopeTooltip),r=uk(Xd,e.__scopeTooltip),i=b.useRef(null),s=sr(t,i),[o,l]=b.useState(null),{trigger:u,onClose:d}=n,f=i.current,{onPointerInTransitChange:p}=r,y=b.useCallback(()=>{l(null),p(!1)},[p]),g=b.useCallback((_,w)=>{const x=_.currentTarget,S={x:_.clientX,y:_.clientY},k=xue(S,x.getBoundingClientRect()),T=Sue(S,k),N=Eue(w.getBoundingClientRect()),P=kue([...T,...N]);l(P),p(!0)},[p]);return b.useEffect(()=>()=>y(),[y]),b.useEffect(()=>{if(u&&f){const _=x=>g(x,f),w=x=>g(x,u);return u.addEventListener("pointerleave",_),f.addEventListener("pointerleave",w),()=>{u.removeEventListener("pointerleave",_),f.removeEventListener("pointerleave",w)}}},[u,f,g,y]),b.useEffect(()=>{if(o){const _=w=>{const x=w.target,S={x:w.clientX,y:w.clientY},k=(u==null?void 0:u.contains(x))||(f==null?void 0:f.contains(x)),T=!Cue(S,o);k?y():T&&(y(),d())};return document.addEventListener("pointermove",_),()=>document.removeEventListener("pointermove",_)}},[u,f,o,d,y]),m.jsx(E4,{...e,ref:s})}),[bue,_ue]=kb(Ip,{isInside:!1}),wue=ese("TooltipContent"),E4=b.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:s,onPointerDownOutside:o,...l}=e,u=um(Xd,n),d=Tb(n),{onClose:f}=u;return b.useEffect(()=>(document.addEventListener(a1,f),()=>document.removeEventListener(a1,f)),[f]),b.useEffect(()=>{if(u.trigger){const p=y=>{const g=y.target;g!=null&&g.contains(u.trigger)&&f()};return window.addEventListener("scroll",p,{capture:!0}),()=>window.removeEventListener("scroll",p,{capture:!0})}},[u.trigger,f]),m.jsx(sf,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:p=>p.preventDefault(),onDismiss:f,children:m.jsxs(vb,{"data-state":u.stateAttribute,...d,...l,ref:t,style:{...l.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[m.jsx(wue,{children:r}),m.jsx(bue,{scope:n,isInside:!0,children:m.jsx(Qj,{id:u.contentId,role:"tooltip",children:i||r})})]})})});S4.displayName=Xd;var C4="TooltipArrow",k4=b.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=Tb(n);return _ue(C4,n).isInside?null:m.jsx(yb,{...i,...r,ref:t})});k4.displayName=C4;function xue(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),i=Math.abs(t.right-e.x),s=Math.abs(t.left-e.x);switch(Math.min(n,r,i,s)){case s:return"left";case i:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function Sue(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function Eue(e){const{top:t,right:n,bottom:r,left:i}=e;return[{x:i,y:t},{x:n,y:t},{x:n,y:r},{x:i,y:r}]}function Cue(e,t){const{x:n,y:r}=e;let i=!1;for(let s=0,o=t.length-1;s<t.length;o=s++){const l=t[s],u=t[o],d=l.x,f=l.y,p=u.x,y=u.y;f>r!=y>r&&n<(p-d)*(r-f)/(y-f)+d&&(i=!i)}return i}function kue(e){const t=e.slice();return t.sort((n,r)=>n.x<r.x?-1:n.x>r.x?1:n.y<r.y?-1:n.y>r.y?1:0),Tue(t)}function Tue(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const i=e[r];for(;t.length>=2;){const s=t[t.length-1],o=t[t.length-2];if((s.x-o.x)*(i.y-o.y)>=(s.y-o.y)*(i.x-o.x))t.pop();else break}t.push(i)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const i=e[r];for(;n.length>=2;){const s=n[n.length-1],o=n[n.length-2];if((s.x-o.x)*(i.y-o.y)>=(s.y-o.y)*(i.x-o.x))n.pop();else break}n.push(i)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var Rue=b4,Aue=_4,Nue=w4,Mue=x4,Pue=S4,Iue=k4;const T4=b.createContext(!1);function Oue({blocked:e,children:t}){return m.jsx(T4.Provider,{value:e,children:t})}function dm(){return b.useContext(T4)}function Rb({...e}){return m.jsx(Rce,{"data-slot":"popover",...e})}function Ab({...e}){return m.jsx(Ace,{"data-slot":"popover-trigger",...e})}function Nb({className:e,align:t="center",sideOffset:n=4,inert:r,"aria-disabled":i,...s}){const o=dm();return m.jsx(Nce,{children:m.jsx(Mce,{"data-slot":"popover-content",align:t,sideOffset:n,className:Ye("z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-hidden data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),inert:o||r?!0:void 0,"aria-disabled":o?!0:i,"data-relay-interaction-blocked":o?"true":void 0,...s})})}const F2=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,$2=uz,Lue=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return $2(e,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:i,defaultVariants:s}=t,o=Object.keys(i).map(d=>{const f=n==null?void 0:n[d],p=s==null?void 0:s[d];if(f===null)return null;const y=F2(f)||F2(p);return i[d][y]}),l=n&&Object.entries(n).reduce((d,f)=>{let[p,y]=f;return y===void 0||(d[p]=y),d},{}),u=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,f)=>{let{class:p,className:y,...g}=f;return Object.entries(g).every(_=>{let[w,x]=_;return Array.isArray(x)?x.includes({...s,...l}[w]):{...s,...l}[w]===x})?[...d,p,y]:d},[]);return $2(e,o,u,n==null?void 0:n.class,n==null?void 0:n.className)},Due=Lue("inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-normal whitespace-nowrap transition-[color,background-color,border-color,box-shadow,opacity] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/75 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-white hover:bg-destructive/90 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",xs:"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm:"h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9","icon-xs":"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3","icon-sm":"size-8","icon-lg":"size-10"}},defaultVariants:{variant:"default",size:"default"}});function gt({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const s=r?Qie:"button";return m.jsx(s,{"data-slot":"button","data-variant":t,"data-size":n,className:Ye(Due({variant:t,size:n,className:e})),...i})}function uf({...e}){return m.jsx(cce,{"data-slot":"dropdown-menu",...e})}function df({...e}){return m.jsx(uce,{"data-slot":"dropdown-menu-trigger",...e})}function ff({className:e,sideOffset:t=4,inert:n,"aria-disabled":r,...i}){const s=dm();return m.jsx(dce,{children:m.jsx(fce,{"data-slot":"dropdown-menu-content",sideOffset:t,className:Ye("z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",e),inert:s||n?!0:void 0,"aria-disabled":s?!0:r,"data-relay-interaction-blocked":s?"true":void 0,...i})})}function ni({className:e,inset:t,variant:n="default",...r}){return m.jsx(pce,{"data-slot":"dropdown-menu-item","data-inset":t,"data-variant":n,className:Ye("relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!",e),...r})}function t0({className:e,children:t,checked:n,...r}){return m.jsxs(mce,{"data-slot":"dropdown-menu-checkbox-item",className:Ye("relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),checked:n,...r,children:[m.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:m.jsx(gce,{children:m.jsx(Co,{className:"size-4"})})}),t]})}function nv({className:e,inset:t,...n}){return m.jsx(hce,{"data-slot":"dropdown-menu-label","data-inset":t,className:Ye("px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",e),...n})}function Ld({className:e,...t}){return m.jsx(vce,{"data-slot":"dropdown-menu-separator",className:Ye("-mx-1 my-1 h-px bg-border",e),...t})}const Bue={"no-proxy":{heading:"还没有连接开发机",body:"在开发机上启动 DEV Anywhere,本页会显示可连接的开发机"},"client-token-missing":{heading:"需要 client token",body:"Relay 已启用客户端访问控制,请在设置中填写"},"client-token-invalid":{heading:"client token 无效",body:"client token 无效或已过期,请在设置中更新"},"no-session":{heading:"没有选中的会话",body:""},"no-messages":{heading:"开始对话",body:""}};function Uc({variant:e,action:t}){const{heading:n,body:r}=Bue[e];return e==="no-messages"?m.jsx("div",{className:"flex h-full w-full items-center justify-center animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:m.jsx("p",{className:"text-sm text-muted-foreground",children:n})}):m.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-6 px-6 text-center animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[m.jsx("h2",{className:"text-2xl font-semibold",children:n}),r&&m.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:r}),t&&m.jsx("div",{children:t})]})}const zue={online:"bg-[var(--color-status-success)]",offline:"bg-[var(--muted-foreground)]",connecting:"bg-[var(--color-status-working)] animate-pulse"},jue={online:"开发机在线",offline:"开发机离线",connecting:"正在连接开发机"};function c1({status:e,className:t}){return m.jsx("span",{className:Ye("inline-block w-2 h-2 rounded-full shrink-0",zue[e],t),role:"status","aria-label":jue[e]})}function ss({...e}){return m.jsx(UC,{"data-slot":"dialog",...e})}function Fue({...e}){return m.jsx(WC,{"data-slot":"dialog-portal",...e})}function $ue({...e}){return m.jsx(db,{"data-slot":"dialog-close",...e})}function Hue({className:e,...t}){return m.jsx(qC,{"data-slot":"dialog-overlay",className:Ye("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function os({className:e,children:t,showCloseButton:n=!0,focusSurfaceOnOpen:r=!1,onOpenAutoFocus:i,inert:s,"aria-disabled":o,...l}){const u=dm();return m.jsxs(Fue,{"data-slot":"dialog-portal",children:[m.jsx(Hue,{}),m.jsxs(VC,{"data-slot":"dialog-content",className:Ye("fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",e),onOpenAutoFocus:d=>{i==null||i(d),!(!r||d.defaultPrevented)&&(d.preventDefault(),d.currentTarget.focus({preventScroll:!0}))},inert:u||s?!0:void 0,"aria-disabled":u?!0:o,"data-relay-interaction-blocked":u?"true":void 0,...l,children:[t,n&&m.jsxs(db,{"data-slot":"dialog-close",className:"absolute top-2 right-2 flex size-11 items-center justify-center rounded-md opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",children:[m.jsx(ou,{}),m.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function as({className:e,...t}){return m.jsx("div",{"data-slot":"dialog-header",className:Ye("flex flex-col gap-2 text-center sm:text-left",e),...t})}function Fs({className:e,showCloseButton:t=!1,children:n,...r}){return m.jsxs("div",{"data-slot":"dialog-footer",className:Ye("flex flex-col-reverse gap-2 sm:flex-row sm:justify-end max-sm:[&_button]:min-h-11",e),...r,children:[n,t&&m.jsx(db,{asChild:!0,children:m.jsx(gt,{variant:"outline",children:"Close"})})]})}function Yi({className:e,...t}){return m.jsx(k5,{"data-slot":"dialog-title",className:Ye("text-lg leading-none font-semibold",e),...t})}function _s({className:e,...t}){return m.jsx(T5,{"data-slot":"dialog-description",className:Ye("text-sm text-muted-foreground",e),...t})}function Uue(e){return`“${(e==null?void 0:e.name)??(e==null?void 0:e.proxyId)??"这台开发机"}”只会从当前 Relay 的开发机列表中移除。不会删除机器上的文件或会话,也不会阻止它再次连接;以后重新运行时,它会重新出现在列表中。`}function Wue({open:e,target:t,removing:n,onOpenChange:r,onConfirm:i}){return m.jsx(ss,{open:e,onOpenChange:s=>{n||r(s)},children:m.jsxs(os,{"data-slot":"proxy-removal-dialog",showCloseButton:!n,onEscapeKeyDown:s=>{n&&s.preventDefault()},onPointerDownOutside:s=>{n&&s.preventDefault()},children:[m.jsxs(as,{children:[m.jsx(Yi,{children:"移除离线开发机?"}),m.jsx(_s,{children:Uue(t)})]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"ghost",disabled:n,onClick:()=>r(!1),children:"取消"}),m.jsxs(gt,{type:"button",variant:"destructive",disabled:n||!t,"aria-busy":n||void 0,onClick:i,"data-slot":"proxy-removal-confirm",children:[n&&m.jsx(ii,{className:"size-4 animate-spin","aria-hidden":"true"}),n?"正在移除":"移除"]})]})]})})}const Uv=80,que=8,Vue=1.2;function H2(e){return Math.max(0,Math.min(Uv,e))}function Yue({proxyId:e,name:t,selected:n,revealed:r,disabled:i=!1,onRevealedChange:s,onRemove:o}){const l=t??e,u=b.useRef(null),d=b.useRef(!1),[f,p]=b.useState(null),y=f??(r?Uv:0),g=f!==null;function _(k){var T,N;if(!(i||k.pointerType!=="touch"&&k.pointerType!=="pen")&&!k.target.closest("button")){u.current={pointerId:k.pointerId,startX:k.clientX,startY:k.clientY,startOffset:r?Uv:0,axis:"pending"};try{(N=(T=k.currentTarget).setPointerCapture)==null||N.call(T,k.pointerId)}catch{}}}function w(k){const T=u.current;if(!T||T.pointerId!==k.pointerId)return;const N=k.clientX-T.startX,P=k.clientY-T.startY;if(T.axis==="pending"){if(Math.hypot(N,P)<que)return;T.axis=Math.abs(N)>Math.abs(P)*Vue?"horizontal":"vertical"}T.axis!=="vertical"&&(k.preventDefault(),p(H2(T.startOffset-N)))}function x(k,T=!1){var R,M;const N=u.current;if(!N||N.pointerId!==k.pointerId)return;u.current=null;try{(M=(R=k.currentTarget).releasePointerCapture)==null||M.call(R,k.pointerId)}catch{}if(N.axis!=="horizontal"||T){p(null);return}k.preventDefault();const P=f??H2(N.startOffset-(k.clientX-N.startX));p(null),s(P>=Uv/2),d.current=!0,window.setTimeout(()=>{d.current=!1},0)}function S(k){if(d.current){d.current=!1,k.preventDefault();return}r&&s(!1)}return m.jsxs("li",{className:"relative h-11 overflow-hidden rounded-md border border-border bg-card","data-slot":"proxy-item","data-swipeable":"true","data-proxy-id":e,"data-online":"false","data-revealed":r||void 0,children:[m.jsxs("div",{className:"relative z-10 flex h-full w-full touch-pan-y select-none items-center gap-3 bg-card px-3 text-left text-muted-foreground transition-transform duration-200 ease-out motion-reduce:transition-none",style:{transform:`translateX(-${y}px)`,transitionDuration:g?"0ms":void 0},title:"这台开发机离线。向左滑动可移除。","data-slot":"proxy-swipe-foreground","data-offset":y,onPointerDown:_,onPointerMove:w,onPointerUp:k=>x(k),onPointerCancel:k=>x(k,!0),onClick:S,children:[m.jsx(c1,{status:"offline"}),m.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-normal",children:l}),n&&m.jsx(Co,{className:"size-4 shrink-0 text-primary","aria-label":"已选"}),m.jsx("span",{className:"shrink-0 text-xs",children:"离线"})]}),m.jsx("button",{type:"button",className:`absolute inset-y-0 right-0 z-0 flex w-20 items-center justify-center bg-destructive text-sm font-medium text-white outline-none transition-colors hover:bg-destructive/90 focus-visible:z-20 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset disabled:pointer-events-none disabled:opacity-50 ${r?"":"pointer-events-none"}`,tabIndex:r?0:-1,disabled:i,"aria-label":`移除 ${l}`,"aria-hidden":r?void 0:!0,"data-slot":"proxy-mobile-remove",onClick:o,children:"移除"})]})}function R4({layout:e,variant:t="default"}){const n=Ie(M=>M.proxies),r=Ie(M=>M.proxyListLoaded),i=Ie(M=>M.relayClientAuthIssue),s=Ie(M=>M.selectedProxyId),o=Ie(M=>M.proxySwitchTarget),l=rs(),u=ws(),[d,f]=b.useState(!1),[p,y]=b.useState(null),[g,_]=b.useState(null),[w,x]=b.useState(null);async function S(M,L){if(o)return;const X=Ft;if(!X){We.error("请先连接开发机");return}const U=L??M,V=s!==null&&s!==M;Ie.getState().setProxySwitchTarget({proxyId:M,name:U});try{const j=await X.selectProxy(M);if(!j.success){We.error(`无法连接 ${U}:${j.error??"未知错误"}`);return}const A=X.getPreviewScope();if(!A||A.proxyId!==M||A.bindingId!==j.bindingId)throw Tt.dispose(),X.clearBoundProxy(),new Error("开发机绑定状态无效,请重试");Tt.activate(X,A),Tt.syncWebSnapshot(A).catch(D=>{D instanceof Error&&D.name==="AbortError"||console.error("[proxy-switcher] web preview snapshot failed",D)}),Tt.syncDeviceSnapshot(A).catch(D=>{D instanceof Error&&D.name==="AbortError"||console.error("[proxy-switcher] device preview snapshot failed",D)}),V&&(Gt.getState().prepareForProxySwitch(U),Li.getState().prepareForProxySwitch()),Tr("local",wn.proxyId,M),Ie.getState().setProxy(M,L??null),Ie.getState().setProxyOnline(!0),Ie.getState().transitionToPhase("session_browsing"),X.sendControl({type:"session_list_request"}),X.requestProxyInfo().then(D=>{if(Ie.getState().selectedProxyId!==M||!Tt.isActive(X,A))return;const O=Li.getState();O.setHomePath(D.homePath),O.setAgentCli(D.agentCli)}).catch(D=>{Tt.isActive(X,A)&&console.error("[proxy-switcher] post-bind proxy info fetch failed",D)}),X.requestAgentStatuses().then(D=>{if(Ie.getState().selectedProxyId!==M||!Tt.isActive(X,A))return;const O=Gt.getState();for(const I of D)O.setAgentStatus(I.sessionId,I.payload)}).catch(D=>{Tt.isActive(X,A)&&console.error("[proxy-switcher] post-bind data fetch failed",D)}),MC(X).then(D=>{D.status==="failed"&&console.error("[proxy-switcher] post-bind data fetch failed",D.error)}),f(!1),(e==="page"||l.pathname.startsWith("/chat/")||l.pathname.startsWith("/preview/device/"))&&u("/sessions")}catch(j){const A=j instanceof Error?j.message:"未知错误";We.error(`无法连接 ${U}:${A}`)}finally{Ie.getState().setProxySwitchTarget(null)}}function k(M){M.online||w||(y(null),_({proxyId:M.proxyId,...M.name?{name:M.name}:{}}))}async function T(){const M=g;if(!M||w)return;const L=Ft;if(!L){We.error("Relay 连接不可用,请稍后重试");return}const X=Ie.getState().proxies.find(U=>U.proxyId===M.proxyId);if(!X){if(!Ie.getState().proxyListLoaded){We.info("正在重新连接 Relay,请稍后再试");return}fp(M.proxyId,L)&&u("/"),We.info("这台开发机已经不在列表中"),_(null);return}if(X.online){We.warning("这台开发机已重新上线,未移除"),_(null);return}x(M.proxyId),$re(M.proxyId);try{const U=await L.removeOfflineProxy(M.proxyId);if(U.success){Cd(M.proxyId),fp(M.proxyId,L)&&u("/"),We.success(`已移除 ${M.name??M.proxyId}`),_(null);return}if(U.errorCode===Rr.PROXY_ONLINE){Cd(M.proxyId),We.warning("这台开发机已重新上线,未移除"),_(null),L.listProxies();return}if(U.errorCode===Rr.PROXY_NOT_FOUND){Cd(M.proxyId),fp(M.proxyId,L)&&u("/"),We.info("这台开发机已经不在列表中"),_(null),L.listProxies();return}Cd(M.proxyId),We.error(U.error??"无法移除开发机,请重试")}catch(U){We.error(U instanceof Error?U.message:"无法移除开发机,请重试"),L.listProxies()}finally{x(null)}}const N=m.jsx(Wue,{open:g!==null,target:g,removing:w!==null,onOpenChange:M=>{M||_(null)},onConfirm:()=>void T()});if(e==="page")return i==="missing_client_token"?m.jsx(Uc,{variant:"client-token-missing"}):i==="invalid_client_token"?m.jsx(Uc,{variant:"client-token-invalid"}):r?n.length===0?m.jsx(Uc,{variant:"no-proxy"}):m.jsxs(m.Fragment,{children:[m.jsxs("div",{className:"flex h-full flex-col gap-3 overflow-auto p-4",children:[m.jsx("h3",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"开发机"}),m.jsx("ul",{role:"list",className:"flex flex-col gap-2",children:n.map(M=>{const L=(o==null?void 0:o.proxyId)===M.proxyId,X=o!==null;return M.online?m.jsx("li",{children:m.jsxs("button",{type:"button","data-slot":"proxy-item","data-proxy-id":M.proxyId,"data-online":"true","data-selecting":L||void 0,disabled:X||w!==null,"aria-busy":L||void 0,onClick:()=>S(M.proxyId,M.name),className:Ye("flex h-11 min-h-[44px] w-full items-center gap-3 rounded-md border bg-card px-3 text-left transition-colors disabled:cursor-not-allowed disabled:hover:bg-card",L?"border-primary/40 bg-accent text-accent-foreground":"border-border hover:bg-accent",X&&!L||w!==null?"opacity-50":""),"aria-pressed":s===M.proxyId,children:[m.jsx(c1,{status:"online"}),m.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-normal",children:M.name??M.proxyId}),L?m.jsxs(m.Fragment,{children:[m.jsx("span",{className:"shrink-0 text-xs text-muted-foreground",children:"正在连接"}),m.jsx(ii,{className:"size-4 shrink-0 animate-spin text-primary","aria-hidden":!0})]}):s===M.proxyId?m.jsx(Co,{className:"size-4 shrink-0 text-primary","aria-label":"已选"}):null]})},M.proxyId):m.jsx(Yue,{proxyId:M.proxyId,name:M.name,selected:s===M.proxyId,revealed:p===M.proxyId,disabled:X||w!==null,onRevealedChange:U=>y(U?M.proxyId:null),onRemove:()=>k(M)},M.proxyId)})})]}),N]}):m.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 text-muted-foreground animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:[m.jsx(ii,{className:"h-5 w-5 animate-spin","aria-hidden":!0}),m.jsx("p",{className:"text-sm",children:"连接中..."})]});const P=n.find(M=>M.proxyId===s),R=(P==null?void 0:P.name)??(P==null?void 0:P.proxyId)??"未选择开发机";return m.jsxs(m.Fragment,{children:[m.jsxs(Rb,{open:d,onOpenChange:f,children:[m.jsx(Ab,{asChild:!0,children:m.jsxs("button",{type:"button","data-slot":"proxy-switcher-trigger",className:Ye("group transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",t==="sidebarChrome"?"inline-flex min-h-9 min-w-0 max-w-full items-center justify-start gap-1.5 rounded-md text-left text-foreground hover:text-primary":"flex h-10 w-full items-center gap-2 rounded-md border border-border bg-background px-4 hover:bg-accent"),"aria-label":`当前连接:${R}`,children:[t==="default"&&m.jsx("span",{className:"h-4 w-4 shrink-0","aria-hidden":!0}),m.jsx("span",{className:Ye("truncate",t==="sidebarChrome"?"min-w-0 text-base font-semibold leading-none":"flex-1 text-center text-sm font-normal"),children:R}),m.jsx(Ql,{className:"h-4 w-4 text-muted-foreground shrink-0 transition-transform group-data-[state=open]:rotate-180","aria-hidden":!0})]})}),m.jsx(Nb,{align:"start",className:"w-[260px] p-1",children:n.length===0?m.jsx("div",{className:"text-xs text-muted-foreground p-2",children:"暂无可连接开发机"}):m.jsx("ul",{role:"list",className:"flex flex-col",children:n.map(M=>{const L=(o==null?void 0:o.proxyId)===M.proxyId,X=o!==null;return m.jsxs("li",{className:"group flex min-w-0 items-center rounded-md",children:[m.jsxs("button",{type:"button","data-slot":"proxy-item","data-proxy-id":M.proxyId,"data-online":M.online,"data-selecting":L||void 0,disabled:!M.online||X,"aria-busy":L||void 0,onClick:()=>S(M.proxyId,M.name),className:Ye("flex h-9 min-w-0 flex-1 items-center gap-2 rounded-md px-2 text-left transition-colors disabled:cursor-not-allowed disabled:hover:bg-transparent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",L?"bg-accent text-accent-foreground":"hover:bg-accent",X&&!L?"opacity-50":"",M.online?"":"opacity-50"),"aria-pressed":s===M.proxyId,title:M.online?void 0:"这台开发机离线",children:[m.jsx(c1,{status:M.online?"online":"offline"}),m.jsx("span",{className:"text-sm font-normal flex-1 truncate min-w-0",children:M.name??M.proxyId}),L?m.jsx(ii,{className:"h-4 w-4 animate-spin text-primary shrink-0","aria-label":"正在连接"}):s===M.proxyId?m.jsx(Co,{className:"h-4 w-4 text-primary shrink-0","aria-label":"已选"}):null,!M.online&&!L&&m.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:"离线"})]}),!M.online&&m.jsxs(uf,{children:[m.jsx(df,{asChild:!0,children:m.jsx(gt,{type:"button",variant:"ghost",size:"icon-xs",className:"mr-1 size-8 text-muted-foreground opacity-60 hover:opacity-100 focus-visible:opacity-100",disabled:X||w!==null,"aria-label":`${M.name??M.proxyId} 操作`,"data-slot":"proxy-row-menu-trigger",children:m.jsx(Ky,{"aria-hidden":"true"})})}),m.jsx(ff,{align:"end","data-slot":"proxy-row-menu",children:m.jsxs(ni,{variant:"destructive","data-slot":"proxy-row-remove-item",onSelect:U=>{U.stopPropagation(),k(M)},children:[m.jsx(az,{"aria-hidden":"true"}),"移除开发机"]})})]})]},M.proxyId)})})})]}),N]})}function Kue({delayDuration:e=0,...t}){return m.jsx(Rue,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function hf({...e}){return m.jsx(Aue,{"data-slot":"tooltip",...e})}function pf({...e}){return m.jsx(Nue,{"data-slot":"tooltip-trigger",...e})}function mf({className:e,sideOffset:t=0,children:n,hideArrow:r=!1,...i}){return m.jsx(Mue,{children:m.jsxs(Pue,{"data-slot":"tooltip-content",sideOffset:t,className:Ye("z-50 w-fit origin-(--radix-tooltip-content-transform-origin) animate-in rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background fade-in-0 zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95",e),...i,children:[n,!r&&m.jsx(Iue,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}function fu({...e}){return m.jsx(UC,{"data-slot":"sheet",...e})}function Gue({...e}){return m.jsx(Toe,{"data-slot":"sheet-trigger",...e})}function Xue({...e}){return m.jsx(WC,{"data-slot":"sheet-portal",...e})}function Zue({className:e,...t}){return m.jsx(qC,{"data-slot":"sheet-overlay",className:Ye("fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",e),...t})}function hu({className:e,overlayClassName:t,children:n,side:r="right",showCloseButton:i=!0,focusSurfaceOnOpen:s=!1,onOpenAutoFocus:o,inert:l,"aria-disabled":u,...d}){const f=dm();return m.jsxs(Xue,{children:[m.jsx(Zue,{className:t}),m.jsxs(VC,{"data-slot":"sheet-content",className:Ye("fixed z-50 flex flex-col gap-4 bg-background shadow-lg transition ease-in-out data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:animate-in data-[state=open]:duration-500",r==="right"&&"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",r==="left"&&"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",r==="top"&&"inset-x-0 top-0 h-auto border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",r==="bottom"&&"inset-x-0 bottom-0 h-auto border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",e),onOpenAutoFocus:p=>{o==null||o(p),!(!s||p.defaultPrevented)&&(p.preventDefault(),p.currentTarget.focus({preventScroll:!0}))},inert:f||l?!0:void 0,"aria-disabled":f?!0:u,"data-relay-interaction-blocked":f?"true":void 0,...d,children:[n,i&&m.jsxs(db,{"data-slot":"sheet-close",className:"absolute top-2 right-2 flex size-11 items-center justify-center rounded-md opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-hidden disabled:pointer-events-none data-[state=open]:bg-secondary",children:[m.jsx(ou,{className:"size-4"}),m.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function gf({className:e,...t}){return m.jsx("div",{"data-slot":"sheet-header",className:Ye("flex flex-col gap-1.5 p-4",e),...t})}function pu({className:e,...t}){return m.jsx(k5,{"data-slot":"sheet-title",className:Ye("font-semibold text-foreground",e),...t})}function Mb({className:e,...t}){return m.jsx(T5,{"data-slot":"sheet-description",className:Ye("text-sm text-muted-foreground",e),...t})}const Que={claude:"Claude Code",codex:"Codex",kimi:"Kimi Code"},U2=["claude","codex","kimi"];function Pb(e){return Que[e]}function A4(e,t){return U2.indexOf(e)-U2.indexOf(t)}function Op(e){return e.provider}const u1=60*1e3,d1=60*u1,Jue=24*d1;function N4(e,t=Date.now()){const n=t-e;if(n<u1)return"刚刚";if(n<d1)return`${Math.floor(n/u1)} 分钟前`;if(n<Jue)return`${Math.floor(n/d1)} 小时前`;const r=new Date(e),i=r.getMonth()+1,s=r.getDate(),o=String(r.getHours()).padStart(2,"0"),l=String(r.getMinutes()).padStart(2,"0");return`${i} 月 ${s} 日 ${o}:${l}`}const W2={idle:{dot:"bg-[var(--color-status-success)]",text:"text-[var(--color-status-success)]",label:"空闲"},working:{dot:"bg-[var(--color-status-working)] animate-pulse",text:"text-[var(--color-status-working)]",label:"工作中"},compacting:{dot:"bg-[var(--color-status-compacting)] animate-pulse",text:"text-[var(--color-status-compacting)]",label:"压缩中"},waiting_approval:{dot:"bg-[var(--color-status-warning)]",text:"text-[var(--color-status-warning)]",label:"等待审批"},error:{dot:"bg-[var(--color-status-error)]",text:"text-[var(--color-status-error)]",label:"出错"},terminated:{dot:"bg-muted-foreground",text:"text-muted-foreground",label:"已终止"}};function f1(e){return e.kind!=="terminal"?W2[e.state]:e.state==="terminated"?W2.terminated:e.state==="error"?{dot:"bg-[var(--color-status-error)]",text:"text-[var(--color-status-error)]",label:"已断开"}:{dot:"bg-[var(--color-status-success)]",text:"text-[var(--color-status-success)]",label:"运行中"}}function ede({session:e}){const t=f1(e);return m.jsx("span",{className:Ye("inline-block size-2 rounded-full shrink-0",t.dot),"aria-label":`会话状态:${t.label}`,role:"status"})}function tde({mode:e}){if(e!=="pty"&&e!=="json")return null;const t=e==="json"?"聊天视图":"终端视图",n=e==="json"?sC:aC;return m.jsx("span",{className:"inline-flex h-5 w-4 shrink-0 items-center justify-center text-muted-foreground",role:"img","aria-label":t,title:t,"data-slot":"session-mode-icon","data-mode":e,children:m.jsx(n,{className:"size-3.5","aria-hidden":"true"})})}function nde({session:e,selected:t,now:n,onClick:r,onRename:i,onTerminate:s}){const o=e.lastActive,l=e.cwd,u=sb(e.name),d=LC(e),f=e.nameLocked&&e.name?e.name:d||(u==="New Session"?e.sessionId.slice(0,8):u),p=N4(o,n),y=e.mode==="pty"&&e.ptyOwner==="local-terminal",g=e.kind==="terminal"?"终止终端":y?"断开远程连接":"终止会话";return m.jsxs("li",{className:Ye("relative flex items-center gap-2 px-4 py-2 w-full min-w-0 transition-colors","min-h-[44px]","hover:bg-accent",t&&"dev-sidebar-active-row"),"data-slot":"session-row","data-session-id":e.sessionId,"data-selected":t,children:[t&&m.jsx("span",{className:"dev-sidebar-active-indicator absolute left-0 top-0 bottom-0 w-[2px]","aria-hidden":"true"}),m.jsxs("button",{type:"button","data-slot":"session-row-select",onClick:r,className:"flex min-h-11 flex-col justify-center gap-1 flex-1 min-w-0 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring rounded-sm md:min-h-0","aria-pressed":t,children:[m.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[m.jsx(ede,{session:e}),m.jsx("span",{className:"text-sm font-normal truncate flex-1",title:l,children:f})]}),m.jsxs("span",{className:"flex items-center gap-1.5 text-xs leading-5 h-5",children:[m.jsx(tde,{mode:e.mode}),m.jsx("span",{className:"text-muted-foreground/60 shrink-0","aria-hidden":"true",children:"·"}),e.kind!=="terminal"&&m.jsxs(m.Fragment,{children:[m.jsx("span",{className:"font-mono text-muted-foreground shrink-0",children:Pb(e.provider)}),m.jsx("span",{className:"text-muted-foreground/60 shrink-0","aria-hidden":"true",children:"·"})]}),m.jsx("span",{className:Ye("shrink-0",f1(e).text),children:f1(e).label}),p&&m.jsxs(m.Fragment,{children:[m.jsx("span",{className:"text-muted-foreground/60 shrink-0","aria-hidden":"true",children:"·"}),m.jsx("span",{className:"text-muted-foreground shrink-0 tabular-nums",children:p})]})]})]}),(i||s)&&m.jsxs(uf,{children:[m.jsx(df,{asChild:!0,children:m.jsx(gt,{variant:"ghost",size:"icon-xs",className:"size-11 md:size-6","aria-label":"会话操作","data-slot":"session-row-menu-trigger",onClick:_=>_.stopPropagation(),children:m.jsx(Ky,{"aria-hidden":"true"})})}),m.jsxs(ff,{align:"end","data-slot":"session-row-menu",children:[i&&m.jsx(ni,{"data-slot":"session-row-rename-item",onSelect:_=>{_.stopPropagation(),i()},children:"重命名"}),s&&m.jsx(ni,{variant:"destructive","data-slot":"session-row-terminate-item",onSelect:_=>{_.stopPropagation(),s()},children:g})]})]})]})}function co(e){const[t,n]=b.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(e).matches);return b.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const r=window.matchMedia(e),i=s=>n(s.matches);return n(r.matches),r.addEventListener("change",i),()=>r.removeEventListener("change",i)},[e]),t}function rde({session:e,now:t,disabled:n,loading:r,onClick:i,modeTag:s}){const o=m.jsx(ide,{title:e.title,modeTag:s}),l=m.jsx("span",{className:"text-xs text-muted-foreground tabular-nums",children:N4(e.updatedAt,t)}),u=m.jsxs("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[o,l]});return m.jsx("li",{"data-slot":"history-row","data-session-id":e.id,"data-loading":r?"true":void 0,className:"group w-full flex items-stretch",children:m.jsxs("button",{type:"button",onClick:i,disabled:n,"data-slot":"history-row-primary",className:Ye("min-w-0 flex-1 flex items-start gap-2 pl-10 pr-4 py-2 min-h-[50px]","text-left transition-colors outline-none","hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring","disabled:opacity-50 disabled:cursor-wait disabled:hover:bg-transparent"),"aria-label":`恢复会话:${e.title}`,children:[u,m.jsx(W7,{className:Ye("mt-0.5 size-3.5 shrink-0 text-muted-foreground transition-opacity",r?"animate-pulse opacity-100":"opacity-0 group-hover:opacity-100 group-focus-visible:opacity-100"),"aria-hidden":"true"})]})})}function ide({title:e,modeTag:t}){return m.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[m.jsx("span",{className:"text-sm font-normal truncate min-w-0",title:e,children:e}),t&&m.jsx(sde,{mode:t})]})}function sde({mode:e}){const t=e==="json"?"聊天视图":"终端视图",n=e==="json"?sC:aC;return m.jsx("span",{"data-slot":"history-mode-tag","data-mode":e,role:"img","aria-label":t,title:t,className:Ye("inline-flex size-5 shrink-0 items-center justify-center rounded border","border-border bg-muted/50 text-muted-foreground"),children:m.jsx(n,{className:"size-3","aria-hidden":"true"})})}function M4({providerLabel:e}){return m.jsx("div",{className:"grid min-w-0 gap-4","data-slot":"bypass-permission-warning",role:"alert",children:m.jsxs("div",{className:"flex min-w-0 items-start gap-3 text-sm",children:[m.jsx(LY,{className:"mt-0.5 size-5 shrink-0 text-destructive","aria-hidden":"true"}),m.jsxs("div",{className:"grid min-w-0 gap-2",children:[m.jsxs("p",{className:"font-medium text-foreground",children:[e," 将不再请求工具审批。"]}),m.jsx("p",{className:"text-muted-foreground",children:"Agent 可以直接执行命令、修改或删除文件,并可能绕过部分沙箱保护。"})]})]})})}function ode({now:e}){const t=Gt(V=>V.historySessions),n=Gt(V=>V.historyLoadStatus),[r,i]=b.useState(null),[s,o]=b.useState(null),[l,u]=b.useState("json"),[d,f]=b.useState("default"),[p,y]=b.useState(!1),[g,_]=b.useState(new Set),[w,x]=b.useState(new Set),S=ws(),k=b.useMemo(()=>{const V=new Map;for(const j of t){const A=Op(j);let D=V.get(A);D||(D=new Map,V.set(A,D));const O=P4(j.projectDir),I=D.get(O);I?I.sessions.push(j):D.set(O,{dir:O,sessions:[j]})}return Array.from(V.entries()).sort(([j],[A])=>A4(j,A)).map(([j,A])=>({provider:j,sessions:Array.from(A.values()).flatMap(D=>D.sessions),projects:Array.from(A.values()).map(D=>({dir:D.dir,shortDir:sb(D.dir),sessions:D.sessions}))}))},[t]);function T(V){o(V),u(ade(V)),f(lde(V))}async function N(V,j,A){if(r)return;const D=Ft;if(!D){We.error("请先连接开发机");return}i(V.id);const O=Op(V);try{const I=await D.createSession({kind:"agent",cwd:V.projectDir,mode:j,provider:O,resumeSessionId:V.id,...A?{permissionMode:A}:{}});if(!I.success){if(I.errorCode===Rr.SESSION_ALREADY_ACTIVE){Gt.getState().setCodexActiveWriterConflict({...I.activeWriterPid?{activeWriterPid:I.activeWriterPid}:{}}),o(null);return}We.error(`恢复失败:${I.error}`);return}if(I.kind!=="agent"){We.error("恢复失败:开发机返回了错误的会话类型");return}const B={sessionId:I.sessionId,kind:"agent",...I.name!==void 0?{name:I.name}:{},...I.nameLocked!==void 0?{nameLocked:I.nameLocked}:{},state:"idle",cwd:I.cwd,lastActive:I.lastActive,provider:I.provider},F=I.mode==="pty"?{...B,mode:"pty",ptyOwner:I.ptyOwner}:{...B,mode:"json"};Gt.getState().addSession(F),S(`/chat/${I.sessionId}?mode=${I.mode}`),o(null)}catch(I){We.error(`恢复失败:${I instanceof Error?I.message:String(I)}`)}finally{i(null)}}function P(){const V=Ft;!V||Gt.getState().historyLoadStatus==="loading"||MC(V).then(j=>{j.status==="failed"&&We.error(j.error instanceof Error?j.error.message:String(j.error))})}function R(V,j){const A=q2(V,j);x(D=>{const O=new Set(D);return O.has(A)?O.delete(A):O.add(A),O})}function M(V){_(j=>{const A=new Set(j);return A.has(V)?A.delete(V):A.add(V),A})}const L=t.length>0,X=n==="loading",U=s?I4():[];return m.jsxs("div",{"data-slot":"history-list",className:"flex flex-col",children:[m.jsxs("div",{className:"flex min-h-11 w-full items-center gap-1.5 px-4 py-1.5 md:min-h-[36px]",children:[m.jsxs("button",{type:"button",onClick:()=>L&&y(V=>!V),disabled:!L,"aria-expanded":L?p:void 0,"data-slot":"history-section-header","data-expanded":p,className:Ye("flex min-w-0 flex-1 items-center gap-1.5 rounded-md py-0.5 text-left","transition-colors outline-none","hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring","disabled:cursor-default disabled:hover:text-inherit"),children:[m.jsxs("h3",{className:"min-w-0 text-sm font-semibold text-foreground",children:["全部会话",L?m.jsxs("span",{className:"ml-1 text-muted-foreground/70 font-normal",children:["· ",t.length]}):null]}),L?m.jsx(dp,{className:Ye("size-3.5 shrink-0 text-muted-foreground/80 transition-transform",p&&"rotate-90"),"aria-hidden":"true"}):null]}),m.jsx(gt,{type:"button",variant:"ghost",size:"icon-sm","aria-label":"刷新全部会话","aria-busy":X,title:X?"正在加载":"刷新",onClick:P,disabled:X,"data-slot":"history-refresh",className:"size-11 md:size-8",children:m.jsx(em,{className:Ye("size-3.5",X&&"animate-spin motion-reduce:animate-none"),"aria-hidden":"true"})})]}),!L&&X&&m.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 text-sm text-muted-foreground/80","data-slot":"history-loading",role:"status","aria-live":"polite",children:[m.jsx(ii,{className:"size-3.5 shrink-0 animate-spin motion-reduce:animate-none","aria-hidden":"true"}),m.jsx("span",{children:"正在加载会话记录..."})]}),!L&&n==="idle"&&m.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/80","data-slot":"history-idle",role:"status",children:"会话记录尚未加载"}),!L&&n==="error"&&m.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/80","data-slot":"history-error",role:"status",children:"会话记录加载失败,请点击刷新重试"}),L&&n==="error"&&m.jsx("div",{className:"px-4 pb-2 text-xs text-muted-foreground/80","data-slot":"history-stale",role:"status",children:"刷新失败,当前显示上次加载的结果"}),!L&&n==="loaded"&&m.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/70","data-slot":"history-empty",children:"暂无会话记录"}),L&&p&&m.jsx("ul",{role:"list",className:"flex flex-col",children:k.map(V=>{const j=g.has(V.provider);return m.jsxs("li",{children:[m.jsxs("button",{type:"button",onClick:()=>M(V.provider),"aria-expanded":!j,"data-slot":"history-provider-header","data-expanded":!j,className:Ye("w-full flex items-center gap-2 px-4 pt-2 pb-1 min-h-[32px]","text-xs text-muted-foreground text-left transition-colors outline-none","hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"),children:[m.jsx("span",{className:"font-mono",children:Pb(V.provider)}),m.jsx("span",{className:"h-px flex-1 bg-border/70","aria-hidden":"true"}),m.jsx("span",{className:"tabular-nums",children:V.sessions.length}),m.jsx(dp,{className:Ye("size-3.5 shrink-0 text-muted-foreground/80 transition-transform",!j&&"rotate-90"),"aria-hidden":"true"})]}),!j&&m.jsx("ul",{role:"list",className:"flex flex-col",children:V.projects.map(A=>{const D=q2(V.provider,A.dir),O=w.has(D);return m.jsxs("li",{children:[m.jsxs("button",{type:"button",onClick:()=>R(V.provider,A.dir),"aria-expanded":O,"data-slot":"history-group-header","data-expanded":O,className:Ye("w-full flex items-center gap-1.5 pl-6 pr-4 py-2 min-h-[36px]","text-left transition-colors outline-none","hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"),children:[m.jsx("span",{className:"text-sm font-mono truncate flex-1 min-w-0",title:A.dir,children:A.shortDir}),m.jsx("span",{className:"text-xs text-muted-foreground/80 tabular-nums shrink-0",children:A.sessions.length}),m.jsx(dp,{className:Ye("size-3.5 shrink-0 text-muted-foreground/80 transition-transform",O&&"rotate-90"),"aria-hidden":"true"})]}),O&&m.jsx("ul",{role:"list",className:"flex flex-col",children:A.sessions.map(I=>m.jsx(rde,{session:I,now:e,disabled:r!==null,loading:r===I.id,onClick:()=>T(I),modeTag:I.preferredMode},I.id))})]},D)})})]},V.provider)})}),m.jsx(cde,{session:s,open:s!==null,modes:U,mode:l,permissionMode:d,submitting:r!==null,onOpenChange:V=>{V||o(null)},onModeChange:u,onPermissionModeChange:f,onConfirm:()=>{s&&N(s,l,d)}})]})}function q2(e,t){return`${e}:${P4(t)}`}function P4(e){const t=e.trim();return!t||t==="/"?t||"/":t.replace(/\/+$/,"")||"/"}function I4(){return["json","pty"]}function ade(e){const t=I4();return e.preferredMode&&t.includes(e.preferredMode)?e.preferredMode:t[0]??"json"}function lde(e){return Op(e)==="codex"?"auto":"default"}function cde({session:e,open:t,modes:n,mode:r,permissionMode:i,submitting:s,onOpenChange:o,onModeChange:l,onPermissionModeChange:u,onConfirm:d}){const[f,p]=b.useState(!1),y=i==="bypassPermissions",g=co("(min-width: 768px)"),_=e?Op(e):null,w=_==="codex",x=_==="kimi";b.useEffect(()=>{t||p(!1)},[t]);const S=f?m.jsx(M4,{providerLabel:e?Pb(Op(e)):"Agent"}):m.jsxs("div",{className:"grid min-w-0 gap-4",children:[m.jsxs("div",{className:"grid min-w-0 gap-2",children:[m.jsx("span",{className:"text-sm font-medium",children:"模式"}),m.jsxs("div",{role:"radiogroup","aria-label":"恢复模式",className:"grid min-w-0 grid-cols-2 gap-2",children:[n.includes("json")&&m.jsx(V2,{checked:r==="json",label:"聊天",icon:m.jsx(sC,{className:"size-4","aria-hidden":"true"}),disabled:s,onClick:()=>l("json")}),n.includes("pty")&&m.jsx(V2,{checked:r==="pty",label:"终端",icon:m.jsx(aC,{className:"size-4","aria-hidden":"true"}),disabled:s,onClick:()=>l("pty")})]})]}),m.jsxs("div",{className:"grid min-w-0 gap-2",children:[m.jsx("span",{className:"text-sm font-medium",children:"权限模式"}),m.jsxs("div",{role:"radiogroup","aria-label":"权限模式",className:"grid min-w-0 gap-2",children:[!w&&m.jsx(rv,{checked:i==="default",label:x?"手工审批":"严格审批",description:x?"工具调用会在 Web 中请求确认。":"所有需要权限的操作都要确认。",disabled:s,onClick:()=>u("default")}),m.jsx(rv,{checked:i==="auto",label:w?"按需审批":x?"自动审批":"自动判定",description:w?"Codex 在需要时请求确认。":x?"Kimi Code 使用原生 yolo 模式自动审批。":"交给 Agent CLI 的原生策略判断。",disabled:s,onClick:()=>u("auto")}),x&&m.jsx(rv,{checked:i==="plan",label:"只读规划",description:"Kimi Code 使用只读规划模式。",disabled:s,onClick:()=>u("plan")}),m.jsx(rv,{checked:i==="bypassPermissions",label:x?"全自动":"跳过全部审批",description:x?"危险模式,Kimi Code 将全自动执行。":"危险模式,会跳过工具审批和部分沙箱保护。",destructive:!0,disabled:s,onClick:()=>u("bypassPermissions")})]})]})]}),k=m.jsxs(m.Fragment,{children:[m.jsx(gt,{type:"button",variant:"ghost",disabled:s,onClick:()=>{f?p(!1):o(!1)},children:f?"返回":"取消"}),m.jsx(gt,{type:"button",variant:f?"destructive":"default",disabled:s,onClick:()=>{if(y&&!f){p(!0);return}d()},"data-slot":f?"bypass-permission-confirm":void 0,children:s?"恢复中...":f?"确认":"恢复"})]});return g?m.jsx(ss,{open:t,onOpenChange:o,children:m.jsxs(os,{focusSurfaceOnOpen:!0,className:"min-w-0 sm:max-w-md","data-slot":"history-restore-dialog",children:[m.jsxs(as,{className:"min-w-0",children:[m.jsx(Yi,{children:f?"跳过全部审批?":"恢复会话"}),m.jsx(_s,{className:"min-w-0 truncate pr-10 sm:pr-0",title:e==null?void 0:e.title,children:(e==null?void 0:e.title)??""})]}),S,m.jsx(Fs,{children:k})]})}):m.jsx(fu,{open:t,onOpenChange:o,children:m.jsxs(hu,{side:"bottom",focusSurfaceOnOpen:!0,className:"inset-x-2 w-auto max-h-[calc(100dvh-0.75rem)] min-w-0 overflow-hidden rounded-t-xl border bg-background p-0","data-slot":"history-restore-dialog",children:[m.jsxs(gf,{className:"min-w-0 shrink-0 px-4 pb-2 pt-4 text-left",children:[m.jsx(pu,{children:f?"跳过全部审批?":"恢复会话"}),m.jsx(Mb,{className:"min-w-0 truncate pr-10",title:e==null?void 0:e.title,children:(e==null?void 0:e.title)??""})]}),m.jsx("div",{className:"min-h-0 overflow-y-auto px-4 pb-3","data-slot":"history-restore-body",children:S}),m.jsx("div",{className:"shrink-0 border-t border-border/70 bg-background px-4 pb-[max(theme(spacing.4),env(safe-area-inset-bottom))] pt-3","data-slot":"history-restore-footer",children:m.jsx("div",{className:"flex flex-col-reverse gap-2 [&_button]:min-h-11 [&_button]:w-full",children:k})})]})})}function V2({checked:e,label:t,icon:n,disabled:r,onClick:i}){return m.jsxs("button",{type:"button",role:"radio","aria-label":t,"aria-checked":e,disabled:r,onClick:i,className:Ye("grid min-h-11 w-full min-w-0 max-w-full grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-2 rounded-md border px-3 text-sm outline-none transition-colors md:h-10 md:min-h-0","focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-wait disabled:opacity-60",e?"border-primary text-foreground":"border-border text-muted-foreground hover:bg-accent/60 hover:text-foreground"),children:[n,m.jsx("span",{className:"min-w-0 text-center",children:t}),m.jsx(Co,{className:Ye("size-3.5 justify-self-end transition-opacity",e?"opacity-100":"opacity-0"),"aria-hidden":"true"})]})}function rv({checked:e,label:t,description:n,destructive:r,disabled:i,onClick:s}){return m.jsxs("button",{type:"button",role:"radio","aria-label":t,"aria-checked":e,disabled:i,onClick:s,className:Ye("grid w-full min-w-0 max-w-full grid-cols-[auto_minmax(0,1fr)_auto] items-start gap-3 rounded-md border p-3 text-left outline-none transition-colors","focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-wait disabled:opacity-60",e?r?"border-destructive/70":"border-primary":"border-border hover:bg-accent/60"),children:[m.jsx("span",{className:Ye("mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-full border",e?r?"border-destructive":"border-primary":"border-muted-foreground/50"),"aria-hidden":"true",children:e&&m.jsx("span",{className:Ye("size-2 rounded-full",r?"bg-destructive":"bg-primary")})}),m.jsxs("span",{className:"grid min-w-0 gap-1",children:[m.jsx("span",{className:Ye("text-sm font-medium",r?"text-destructive":"text-foreground"),children:t}),m.jsx("span",{className:"min-w-0 break-words text-xs leading-5 text-muted-foreground",children:n})]}),e&&m.jsx(Co,{className:Ye("mt-0.5 size-4 shrink-0",r?"text-destructive":"text-primary"),"aria-hidden":"true"})]})}function Ib({...e}){return m.jsx(tue,{"data-slot":"select",...e})}function Ob({...e}){return m.jsx(rue,{"data-slot":"select-value",...e})}function Lb({className:e,size:t="default",children:n,...r}){return m.jsxs(nue,{"data-slot":"select-trigger","data-size":t,className:Ye("flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/75 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",e),...r,children:[n,m.jsx(iue,{asChild:!0,children:m.jsx(Ql,{className:"size-4 opacity-50"})})]})}function Db({className:e,children:t,position:n="item-aligned",align:r="center",inert:i,"aria-disabled":s,...o}){const l=dm();return m.jsx(sue,{children:m.jsxs(oue,{"data-slot":"select-content",className:Ye("relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,align:r,inert:l||i?!0:void 0,"aria-disabled":l?!0:s,"data-relay-interaction-blocked":l?"true":void 0,...o,children:[m.jsx(ude,{}),m.jsx(aue,{className:Ye("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"),children:t}),m.jsx(dde,{})]})})}function Bb({className:e,children:t,...n}){return m.jsxs(lue,{"data-slot":"select-item",className:Ye("relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",e),...n,children:[m.jsx("span",{"data-slot":"select-item-indicator",className:"absolute right-2 flex size-3.5 items-center justify-center",children:m.jsx(uue,{children:m.jsx(Co,{className:"size-4"})})}),m.jsx(cue,{children:t})]})}function ude({className:e,...t}){return m.jsx(due,{"data-slot":"select-scroll-up-button",className:Ye("flex cursor-default items-center justify-center py-1",e),...t,children:m.jsx(rC,{className:"size-4"})})}function dde({className:e,...t}){return m.jsx(fue,{"data-slot":"select-scroll-down-button",className:Ye("flex cursor-default items-center justify-center py-1",e),...t,children:m.jsx(Ql,{className:"size-4"})})}function fde(e,t,n){var u;if(t==="insert"){const d=e.split("@").pop()??"",f=qd((n==null?void 0:n.baseCwd)??d)==="\\",p=Math.max(d.lastIndexOf("/"),f?d.lastIndexOf("\\"):-1);return{currentPath:p>=0?d.slice(0,p+1):f?".\\":"./",query:d.slice(p+1).toLowerCase()}}const r=Hl((n==null?void 0:n.baseCwd)??"");if(!e)return{currentPath:wo(r),query:""};const i=AC(r,e);if(!i)return{currentPath:"",query:""};const s=RC(i),o=qd(i);return e.endsWith("/")||o==="\\"&&e.endsWith("\\")||i===s||i===r||((u=n==null?void 0:n.knownDirs)==null?void 0:u.has(i))?{currentPath:wo(i),query:""}:{currentPath:wo(s),query:i.slice(i.lastIndexOf(o)+1).toLowerCase()}}function n0(e,t){return AC(e,t)}const O4=b.forwardRef(function({filter:t,onSelect:n,onNavigate:r,onSelectCurrentDirectory:i,onCreateDirectory:s,mode:o="insert",placement:l="floating",dirsOnly:u=!1,fileExtensions:d,includeHidden:f=!1,autoHighlightFirst:p=!0,title:y},g){const _=Li(he=>f?he.treeWithHidden:he.tree),w=Li(he=>he.cwd),x=Li(he=>he.homePath),S=o==="insert"?w:x||w,k=b.useMemo(()=>new Set(_.keys()),[_]),T=b.useMemo(()=>fde(t,o,{baseCwd:S,knownDirs:k}),[t,o,S,k]),N=T.currentPath,P=b.useMemo(()=>n0(S,N),[S,N]),R=T.query,M=b.useRef(new Map),[L,X]=b.useState(!1),[U,V]=b.useState(""),[j,A]=b.useState(!1),[D,O]=b.useState(null),[I,B]=b.useState(0);b.useEffect(()=>{if(!P)return;const he=`${f?"hidden":"default"}\0${P}`;if(_.has(P))return;const He=Ft;if(!He)return;let Nt=!1;O(Ze=>(Ze==null?void 0:Ze.path)===P?null:Ze);let ye=M.current.get(he);if(!ye){ye=He.requestDirectoryList(P,{includeHidden:f}),M.current.set(he,ye);const Ze=()=>{M.current.get(he)===ye&&M.current.delete(he)};ye.then(Ze,Ze)}return ye.then(Ze=>{if(!Nt){if(Ze.error!==void 0||Ze.errorCode!==void 0){O({path:P,message:Ze.error||"读取失败"});return}Li.getState().setDirEntries(Ze.path,Ze.entries,Ze.includeHidden)}},Ze=>{Nt||O({path:P,message:Ze instanceof Error?Ze.message:"读取失败"})}),()=>{Nt=!0}},[P,f,_,I]);const F=(D==null?void 0:D.path)===P?D:null,Y=!_.has(P)&&!F,z=b.useMemo(()=>d==null?void 0:d.map(he=>he.startsWith(".")?he.toLowerCase():`.${he.toLowerCase()}`),[d]),q=b.useMemo(()=>{let he=_.get(P)??[];return u?he=he.filter(He=>He.isDir):z!=null&&z.length&&(he=he.filter(He=>He.isDir||z.some(Nt=>He.name.toLowerCase().endsWith(Nt)))),R&&(he=he.filter(He=>He.name.toLowerCase().includes(R))),he},[_,P,R,u,z]),[K,$]=b.useState(p?0:-1);b.useEffect(()=>$(p?0:-1),[p,N,R]),b.useEffect(()=>{X(!1),V("")},[P]),b.useEffect(()=>{K>=q.length&&q.length>0&&$(q.length-1)},[q.length,K]);const re=b.useRef(null),Q=b.useRef(!1);b.useEffect(()=>{var He;if(!Q.current)return;Q.current=!1;const he=(He=re.current)==null?void 0:He.querySelector(`[data-entry-index="${K}"]`);he==null||he.scrollIntoView({block:"nearest"})},[K]);const G=b.useCallback(he=>{const He=qd(S),Nt=`${wo(N,S)}${he.name}${he.isDir?He:""}`;if(o==="insert")return Nt.replace(He==="\\"?/^\.[\\/]/:/^\.\//,"");const ye=n0(S,Nt);return he.isDir?wo(ye):ye},[S,N,o]),Z=b.useCallback(he=>{const He=n0(S,he);if(!He)return;const Nt=wo(He);if(o==="select"){r(Nt);return}n(Nt)},[S,o,r,n]),ae=b.useCallback(he=>{const He=G(he);if(he.isDir){Z(He);return}n(He)},[G,Z,n]);async function le(){const he=HP(P,U);if(!(!he||!s)){A(!0);try{const He=await s(he);if(!He)return;if(V(""),X(!1),i){i(wo(He));return}Z(He)}finally{A(!1)}}}b.useImperativeHandle(g,()=>({handleKey(he){return q.length===0?!1:he.key==="ArrowDown"?(Q.current=!0,$(He=>Math.min(q.length-1,He+1)),!0):he.key==="ArrowUp"?(Q.current=!0,$(He=>Math.max(0,He-1)),!0):he.key==="Enter"&&K>=0&&!he.nativeEvent.isComposing?(ae(q[K]),!0):!1}}),[q,K,ae]);const me=b.useMemo(()=>RC(P),[P]),ke=l==="inline"?"relative w-full bg-popover border border-border rounded-md overflow-hidden":o==="insert"?"absolute bottom-full left-0 right-0 z-50 mb-2 bg-popover border border-border rounded-md shadow-lg overflow-hidden":"absolute left-0 right-0 top-full z-50 mt-2 bg-popover border border-border rounded-md shadow-lg overflow-hidden",$e=l==="inline"?"max-h-[min(11rem,30dvh)] overflow-y-auto overscroll-contain":o==="select"?"max-h-44 overflow-y-auto overscroll-contain":"max-h-60 overflow-y-auto overscroll-contain";return m.jsxs("div",{className:ke,"data-slot":"file-path-picker","data-mode":o,"data-placement":l,children:[o==="select"?m.jsxs("div",{className:"border-b border-border/70 px-3 py-2",children:[m.jsxs("div",{className:"min-w-0",children:[y?m.jsx("p",{className:"mb-2 truncate text-xs text-muted-foreground","data-slot":"file-path-picker-title",children:y}):null,m.jsx("p",{className:"truncate font-mono text-xs text-foreground","data-slot":"file-path-picker-current-directory",title:P,children:P||"正在读取路径"})]}),m.jsxs("div",{className:"mt-1 flex items-center justify-between gap-2",role:"toolbar","aria-label":"路径操作","data-slot":"file-path-picker-actions",children:[m.jsx("button",{type:"button","data-slot":"file-path-picker-parent",className:"inline-flex min-h-11 min-w-11 items-center justify-start px-0 text-xs font-medium text-primary hover:underline focus-visible:underline focus-visible:outline-none disabled:cursor-not-allowed disabled:text-muted-foreground disabled:no-underline md:min-h-8 md:min-w-0",disabled:!P||P===me,onClick:()=>Z(me),children:"上一级"}),i||s?m.jsxs("span",{className:"flex shrink-0 items-center gap-4",children:[s?m.jsx("button",{type:"button","data-slot":"file-path-picker-create-directory-toggle",className:"inline-flex min-h-11 min-w-11 items-center justify-center px-0 text-xs font-medium text-primary hover:underline focus-visible:underline focus-visible:outline-none disabled:cursor-not-allowed disabled:text-muted-foreground disabled:no-underline md:min-h-8 md:min-w-0",disabled:!P||j,onClick:()=>X(he=>!he),children:"新建目录"}):null,i?m.jsx("button",{type:"button","data-slot":"select-current-directory",className:"inline-flex min-h-11 min-w-11 items-center justify-center px-0 text-xs font-medium text-primary hover:underline focus-visible:underline focus-visible:outline-none disabled:cursor-not-allowed disabled:text-muted-foreground disabled:no-underline md:min-h-8 md:min-w-0",disabled:!P,onClick:()=>i(wo(P)),children:"选定"}):null]}):null]}),L?m.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[m.jsx("input",{type:"text","data-slot":"file-path-picker-create-directory-name",value:U,onChange:he=>V(he.target.value),onKeyDown:he=>{he.key==="Enter"&&!he.nativeEvent.isComposing&&(he.preventDefault(),le()),he.key==="Escape"&&(X(!1),V(""))},placeholder:"目录名称",className:"min-h-11 min-w-0 flex-1 rounded-md border border-border bg-input px-2 text-base outline-none focus-visible:ring-2 focus-visible:ring-ring md:h-8 md:min-h-0 md:text-sm",autoComplete:"off",autoCorrect:"off",spellCheck:!1}),m.jsx("button",{type:"button","data-slot":"file-path-picker-create-directory-submit",className:"min-h-11 rounded-md bg-primary px-3 text-sm text-primary-foreground disabled:cursor-not-allowed disabled:opacity-50 md:h-8 md:min-h-0",disabled:!HP(P,U)||j,onClick:()=>void le(),children:j?"创建中...":"创建目录"})]}):null]}):null,m.jsx("div",{className:$e,"data-slot":"file-path-picker-entries",children:F?m.jsxs("div",{"data-slot":"file-path-picker-error",className:"flex items-center justify-between gap-3 px-3 py-2",role:"alert",children:[m.jsx("span",{className:"min-w-0 text-xs text-destructive",title:F.message,children:"无法读取这个文件夹"}),m.jsx("button",{type:"button","data-slot":"file-path-picker-retry",className:"shrink-0 rounded px-2 py-1 text-xs text-primary hover:bg-primary/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",onClick:()=>B(he=>he+1),children:"重试"})]}):q.length===0?m.jsx("div",{className:"px-3 py-2 text-xs text-muted-foreground",children:Y?"加载中...":"没有匹配的路径"}):m.jsx("ul",{ref:re,role:"list",className:"flex flex-col",children:q.map((he,He)=>m.jsx("li",{children:m.jsx("button",{type:"button",onClick:()=>ae(he),onMouseEnter:()=>$(He),className:Ye("w-full flex min-h-11 items-center gap-2 px-3 py-2 text-sm text-left transition-colors md:h-9 md:min-h-0 md:py-0",He===K&&"bg-[color-mix(in_srgb,var(--primary)_15%,transparent)]",he.isDir&&"font-semibold"),"data-slot":"file-entry","data-entry-type":he.isDir?"dir":"file","data-entry-name":he.name,"data-entry-index":He,children:m.jsxs("span",{className:"font-mono text-[13px]",children:[he.name,he.isDir?"/":""]})})},he.name))})})]})});function Y2(e,t,n){const r=Wv(e,t);return r?n==="file"?wo(RC(r)):r:t}function Wv(e,t){const n=Hl(e,t);return n?e.endsWith("/")||qd(n)==="\\"&&e.endsWith("\\")?wo(n):n:""}function fk({value:e,onValueChange:t,selectionKind:n,fileExtensions:r,includeHidden:i=!1,onCreateDirectory:s,disabled:o=!1,placeholder:l="选择路径",label:u,labelActions:d,id:f,name:p,required:y,autoFocus:g,"aria-describedby":_,"aria-invalid":w,"data-slot":x,className:S,onKeyDown:k}){const T=b.useId(),N=f??`remote-path-${T}`,P=`${N}-label`,R=Li(Q=>Q.homePath),M=co("(pointer: coarse), (hover: none)"),L=rf().deviceKind,X=M||L==="phone"||L==="tablet",[U,V]=b.useState(!1),[j,A]=b.useState(()=>Y2(e,R,n)),[D,O]=b.useState(e),I=b.useRef(null),B=b.useRef(null);b.useEffect(()=>{U||D===e||O(e)},[D,U,e]),b.useEffect(()=>{if(!U)return;function Q(G){const Z=I.current,ae=G.target;Z&&(G.composedPath().includes(Z)||ae instanceof Node&&Z.contains(ae))||(V(!1),O(e))}return document.addEventListener("click",Q),()=>document.removeEventListener("click",Q)},[U,e]),b.useEffect(()=>{o&&(V(!1),O(e))},[o,e]);const F=n!=="file";function Y(){if(o)return;const Q=Y2(e,R,n);A(Q),O(e),V(!0)}function z(){V(!1),O(e)}function q(Q){const G=Wv(Q,R);G&&(A(G),O(G),t(G),V(!1))}function K(Q){const G=Wv(Q,R);G&&A(G)}function $(Q){var G;if(U&&((G=B.current)!=null&&G.handleKey(Q))){Q.preventDefault();return}if(Q.key==="Escape"&&U){Q.preventDefault(),z();return}k==null||k(Q)}const re=U?m.jsx("div",{className:Ye(X&&"mt-2"),"data-slot":"remote-path-browser",children:m.jsx(O4,{ref:B,mode:"select",placement:X?"inline":"floating",filter:j,dirsOnly:n==="directory",fileExtensions:r,includeHidden:i,autoHighlightFirst:!X,title:l,onNavigate:K,onSelect:q,onSelectCurrentDirectory:F?q:void 0,onCreateDirectory:s})}):null;return m.jsxs("div",{className:Ye("flex min-w-0 flex-col gap-1",S),children:[m.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-3",children:[m.jsx("span",{id:P,className:"min-w-0 text-sm",children:u}),d?m.jsx("div",{className:"flex shrink-0 items-center gap-4",children:d}):null]}),m.jsx("div",{ref:I,className:"relative min-w-0",onBlur:Q=>{if(!U||X)return;const G=Q.relatedTarget;G instanceof Node&&Q.currentTarget.contains(G)||window.setTimeout(()=>{var Z;(Z=I.current)!=null&&Z.contains(document.activeElement)||z()},0)},children:X?m.jsxs(m.Fragment,{children:[m.jsxs("button",{id:N,type:"button","aria-labelledby":P,"aria-describedby":_,"aria-invalid":w,"aria-expanded":U,"aria-controls":`${N}-browser`,disabled:o,"data-slot":x,"data-path-control":"button",onClick:()=>{U?z():Y()},className:"flex min-h-11 w-full min-w-0 items-center gap-2 rounded-md border border-border bg-input px-3 text-left text-base outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60",children:[m.jsx(DV,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),m.jsx("span",{className:Ye("min-w-0 flex-1 truncate font-mono",e?"text-foreground":"text-muted-foreground"),title:e||void 0,children:e||l})]}),p?m.jsx("input",{type:"hidden",name:p,value:e,required:y}):null,m.jsx("div",{id:`${N}-browser`,children:re})]}):m.jsxs(m.Fragment,{children:[m.jsx("input",{id:N,type:"text","aria-labelledby":P,"aria-describedby":_,"aria-invalid":w,name:p,required:y,autoFocus:g,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:o,value:D,"data-slot":x,"data-path-control":"input",onFocus:Y,onChange:Q=>{const G=Q.target.value,Z=Wv(G,R);O(G),A(Z||R),t(Z||G),V(!0)},onKeyDown:$,placeholder:l,className:"min-h-11 min-w-0 w-full rounded-md border border-border bg-input px-3 font-mono text-base outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60 md:h-9 md:min-h-0 md:text-sm"}),re]})})]})}const K2="工作目录不存在或不可访问:",hde=[{value:"default",label:"严格审批"},{value:"auto",label:"自动判定"},{value:"acceptEdits",label:"自动接受编辑"},{value:"plan",label:"只读规划"},{value:"bypassPermissions",label:"跳过全部审批"}],L4=[{value:"auto",label:"按需审批"},{value:"bypassPermissions",label:"跳过全部审批"}],D4=[{value:"default",label:"手工审批"},{value:"auto",label:"自动审批"},{value:"plan",label:"只读规划"},{value:"bypassPermissions",label:"全自动"}],Lp={claude:"Claude Code",codex:"Codex",kimi:"Kimi Code"};function pde(e,t){return t!==Rr.PATH_NOT_FOUND||!e.startsWith(K2)?null:e.slice(K2.length).trim()||null}function B4(e,t){if(!t)return{label:"检测中",disabled:!0};const n=t[e];return n.available?{label:"可用",disabled:!1,title:n.command}:{label:"未找到",disabled:!0,title:n.error}}function mde(e,t){return e==="codex"?L4.some(n=>n.value===t)?t:"auto":e==="kimi"?D4.some(n=>n.value===t)?t:"default":t}async function gde({relay:e,agentCli:t,form:n,timeoutMs:r=kC}){var d,f;const i=n.cwd.trim();if(!i)return{type:"validation_error",message:"请输入工作目录"};if(!e)return{type:"relay_missing",message:"请先连接开发机"};if(B4(n.provider,t).disabled){const p=(d=t==null?void 0:t[n.provider])==null?void 0:d.error;return{type:"provider_unavailable",message:p?`${Lp[n.provider]} 不可用:${p}`:`${Lp[n.provider]} 暂不可用`}}const o=n.mode,l=n.provider,u=n.name.trim();try{const p=await e.createSession({kind:"agent",cwd:i,name:u||void 0,mode:o,provider:l,permissionMode:n.permissionMode},r);if(!p.success){const w=pde(p.error,p.errorCode);return w?{type:"missing_cwd",path:w,message:"找不到这个工作目录"}:{type:"create_error",message:`创建失败:${p.error}`}}if(p.kind!=="agent")return{type:"create_error",message:"创建失败:开发机返回了错误的会话类型"};const y=((f=p.name)==null?void 0:f.trim())||void 0,g={sessionId:p.sessionId,kind:"agent",name:y,...p.nameLocked!==void 0?{nameLocked:p.nameLocked}:{},state:"idle",cwd:p.cwd,lastActive:p.lastActive,provider:p.provider};return{type:"success",session:p.mode==="pty"?{...g,mode:"pty",ptyOwner:p.ptyOwner}:{...g,mode:"json"},route:`/chat/${p.sessionId}?mode=${p.mode}`}}catch(p){return{type:"exception",message:p instanceof Error?p.message:String(p)}}}async function vde({relay:e,timeoutMs:t=kC}){var n;if(!e)return{type:"relay_missing",message:"请先连接开发机"};try{const r=await e.createSession({kind:"terminal",mode:"pty"},t);return r.success?r.kind!=="terminal"?{type:"create_error",message:"创建终端失败:开发机返回了错误的会话类型"}:{type:"success",session:{sessionId:r.sessionId,kind:"terminal",name:((n=r.name)==null?void 0:n.trim())||void 0,...r.nameLocked!==void 0?{nameLocked:r.nameLocked}:{},state:"idle",cwd:r.cwd,lastActive:r.lastActive,mode:"pty",provider:r.provider,ptyOwner:r.ptyOwner},route:`/chat/${r.sessionId}?mode=pty`}:{type:"create_error",message:`创建终端失败:${r.error}`}}catch(r){return{type:"exception",message:r instanceof Error?r.message:String(r)}}}const yde=["claude","codex","kimi"];function bde({agentCli:e,provider:t,cliPathDraftProvider:n,cliPathDraft:r,savingCliPath:i,onProviderChange:s,onCliPathDraftChange:o,onDiscardCliPathDraft:l,onSaveCliPath:u}){const d=e==null?void 0:e[t],f=(d==null?void 0:d.command)??"",p=n===t,y=p?r:f,g=p&&r.trim()!==f;return m.jsxs("section",{"aria-label":"Agent CLI",className:"flex min-w-0 flex-col gap-2",children:[m.jsx("span",{className:"text-sm",children:"Agent CLI"}),m.jsxs(Ib,{value:t,disabled:i,onValueChange:_=>s(_),children:[m.jsx(Lb,{className:"min-h-11 w-full md:min-h-0","aria-label":"Agent CLI","data-slot":"agent-cli-provider-select",children:m.jsx(Ob,{})}),m.jsx(Db,{"data-slot":"agent-cli-provider-options",children:yde.map(_=>m.jsx(Bb,{value:_,className:"min-h-11 md:min-h-0",children:Lp[_]},_))})]}),m.jsxs("div",{className:"relative min-w-0","data-slot":"agent-cli-path-card",children:[m.jsx(fk,{id:`agent-cli-path-${t}`,"data-slot":"agent-cli-path",label:"CLI 路径",value:y,onValueChange:_=>o(t,_),selectionKind:"file",includeHidden:!0,disabled:i,placeholder:"选择 CLI 可执行文件",labelActions:g?m.jsxs("div",{className:"flex items-center gap-4","data-slot":"agent-cli-path-actions",children:[m.jsx("button",{type:"button",className:"inline-flex min-h-11 min-w-11 items-center justify-center px-0 text-xs font-medium text-muted-foreground hover:underline focus-visible:underline focus-visible:outline-none disabled:cursor-not-allowed disabled:no-underline md:min-h-8 md:min-w-0",onClick:l,disabled:i,children:"取消"}),m.jsx("button",{type:"button",className:"inline-flex min-h-11 min-w-11 items-center justify-center px-0 text-xs font-medium text-primary hover:underline focus-visible:underline focus-visible:outline-none disabled:cursor-not-allowed disabled:text-muted-foreground disabled:no-underline md:min-h-8 md:min-w-0",onClick:u,disabled:i||!r.trim(),children:i?"保存中...":"保存"})]}):void 0,onKeyDown:_=>{_.key==="Enter"&&g&&(_.preventDefault(),_.stopPropagation(),u()),_.key==="Escape"&&p&&(_.preventDefault(),_.stopPropagation(),l())}},t),d!=null&&d.error&&!g?m.jsx("p",{className:"mt-1 break-all text-xs text-destructive",children:d.error}):null]})]})}function Qh({open:e,onOpenChange:t}){var Z;const[n,r]=b.useState(""),[i,s]=b.useState(""),[o,l]=b.useState("claude"),[u,d]=b.useState("pty"),[f,p]=b.useState("default"),[y,g]=b.useState(!1),[_,w]=b.useState(!1),[x,S]=b.useState(null),[k,T]=b.useState(null),[N,P]=b.useState(""),[R,M]=b.useState(!1),L=b.useRef(e);L.current=e;const X=ws(),U=Li(ae=>ae.homePath),V=Li(ae=>ae.agentCli),j=co("(min-width: 768px)");b.useEffect(()=>{e&&!i&&U&&s(U)},[e,U,i]),b.useEffect(()=>{if(!e||U&&V)return;const ae=Ft==null?void 0:Ft.requestProxyInfo();ae&&ae.then(le=>{const me=Li.getState();me.setHomePath(le.homePath),me.setAgentCli(le.agentCli)}).catch(le=>{console.error("[create-session-dialog] requestProxyInfo failed",le)})},[e,U,V]);function A(){r(""),s(""),l("claude"),d("pty"),p("default"),g(!1),S(null),T(null),P(""),M(!1)}function D(){if(f==="bypassPermissions"){g(!0);return}q()}async function O(){await q(),L.current&&g(!1)}const I=o==="codex"?L4:o==="kimi"?D4:hde,B=B4(o,V),F=k===o&&N.trim()!==(((Z=V==null?void 0:V[o])==null?void 0:Z.command)??""),Y=_||R||B.disabled||F;function z(ae){const le=mde(ae,f);le!==f&&p(le)}async function q(ae){S(null),w(!0);try{const le=await gde({relay:Ft,agentCli:V,form:{cwd:ae??i,name:n,provider:o,permissionMode:f,mode:u}});if(le.type==="success"){if(Gt.getState().addSession(le.session),!L.current)return;t(!1),A(),X(le.route);return}if(le.type==="missing_cwd"&&S(le.path),We.error(le.message),le.type==="validation_error"||le.type==="relay_missing")return}finally{w(!1)}}async function K(ae){const le=Ft;if(!le)return We.error("请先连接开发机"),null;try{const me=await le.createDirectory(ae);return me.success?(S(null),We.success("目录已创建"),me.path):(We.error(`目录创建失败:${me.error??"未知错误"}`),null)}catch(me){return We.error(me instanceof Error?me.message:String(me)),null}}function $(ae,le){T(ae),P(le)}async function re(){if(!k)return;const ae=k,le=N.trim();if(!le){We.error("请选择 Agent CLI 可执行文件");return}const me=Ft;if(!me){We.error("请先连接开发机");return}M(!0);try{const ke=await me.updateAgentCliPath(ae,le);if(ke.error||!ke.agentCli){We.error(`路径保存失败:${ke.error??"未知错误"}`);return}Li.getState().setAgentCli(ke.agentCli),We.success(`${Lp[ae]} 路径已保存`),T(null),P("")}catch(ke){We.error(ke instanceof Error?ke.message:String(ke))}finally{M(!1)}}function Q(ae){d(ae),z(o)}const G=y?m.jsxs("div",{className:"grid min-w-0 gap-5","data-slot":"bypass-permission-confirmation",children:[m.jsx(M4,{providerLabel:Lp[o]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"ghost",className:"min-h-11 md:min-h-0",onClick:()=>g(!1),disabled:_,children:"返回"}),m.jsx(gt,{type:"button",variant:"destructive",className:"min-h-11 md:min-h-0",onClick:()=>void O(),disabled:_,"data-slot":"bypass-permission-confirm",children:_?"创建中...":"确认"})]})]}):m.jsxs("form",{className:"flex min-w-0 flex-col gap-4","data-slot":"create-session-form",autoComplete:"off",onSubmit:ae=>{ae.preventDefault(),D()},children:[m.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[m.jsx("span",{className:"text-sm",children:"名称(可选)"}),m.jsx("input",{type:"text",name:"dev-anywhere-session-name",autoComplete:"off",autoCorrect:"off",spellCheck:!1,value:n,onChange:ae=>r(ae.target.value),className:"min-h-11 min-w-0 rounded-md border border-border bg-input px-3 text-base outline-none focus-visible:ring-2 focus-visible:ring-ring md:h-9 md:min-h-0 md:text-sm",placeholder:"自动生成"})]}),m.jsx(fk,{id:"create-session-cwd",name:"dev-anywhere-session-cwd","data-slot":"create-session-cwd",label:"工作目录",value:i,selectionKind:"directory",placeholder:"选择工作目录",onCreateDirectory:K,onValueChange:ae=>{s(ae),S(null)}}),x?m.jsxs("section",{role:"status","aria-live":"polite",className:"rounded-md border border-primary/50 bg-primary/10 p-3",children:[m.jsx("p",{className:"text-sm font-medium",children:"工作目录不存在"}),m.jsx("p",{className:"mt-1 break-all font-mono text-xs text-muted-foreground",children:x})]}):null,m.jsxs("section",{"aria-label":"交互方式",className:"flex min-w-0 flex-col gap-2",children:[m.jsx("span",{className:"text-sm",children:"交互方式"}),m.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-2 sm:grid-cols-2",children:[m.jsxs("button",{type:"button","aria-pressed":u==="pty",onClick:()=>Q("pty"),className:Ye("flex min-h-14 min-w-0 flex-col items-start justify-center gap-1 rounded-md border px-3 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring",u==="pty"?"border-primary/70 bg-primary/10":"border-border bg-muted/20"),children:[m.jsx("span",{className:"text-sm font-medium",children:"终端模式"}),m.jsx("span",{className:"text-xs text-muted-foreground",children:"像本地终端一样操作"})]}),m.jsxs("button",{type:"button","aria-pressed":u==="json",onClick:()=>Q("json"),className:Ye("flex min-h-14 min-w-0 flex-col items-start justify-center gap-1 rounded-md border px-3 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring",u==="json"?"border-primary/70 bg-primary/10":"border-border bg-muted/20"),children:[m.jsx("span",{className:"text-sm font-medium",children:"聊天模式"}),m.jsx("span",{className:"text-xs text-muted-foreground",children:"气泡式对话,支持 Voice Pilot"})]})]})]}),m.jsx(bde,{agentCli:V,provider:o,cliPathDraftProvider:k,cliPathDraft:N,savingCliPath:R,onProviderChange:ae=>{l(ae),z(ae),T(null),P("")},onCliPathDraftChange:$,onDiscardCliPathDraft:()=>{T(null),P("")},onSaveCliPath:()=>void re()}),m.jsxs("label",{className:"flex min-w-0 flex-col gap-2",children:[m.jsx("span",{className:"text-sm",children:"权限模式"}),m.jsxs(Ib,{value:f,onValueChange:ae=>p(ae),children:[m.jsx(Lb,{className:"w-full",children:m.jsx(Ob,{})}),m.jsx(Db,{children:I.map(ae=>m.jsx(Bb,{value:ae.value,children:ae.label},ae.value))})]})]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"ghost",className:"min-h-11 md:min-h-0",onClick:()=>t(!1),disabled:_,children:"取消"}),m.jsx(gt,{type:"submit",className:"min-h-11 md:min-h-0",disabled:Y,children:_?"创建中...":"创建"})]})]});return j?m.jsx(ss,{open:e,onOpenChange:t,children:m.jsxs(os,{className:"!w-[calc(100vw-2rem)] !max-w-none max-h-[calc(100dvh-2rem)] overflow-y-auto sm:!w-[44rem]","data-slot":"create-session-dialog",focusSurfaceOnOpen:!0,children:[m.jsx(as,{children:m.jsx(Yi,{children:y?"跳过全部审批?":"新建会话"})}),G]})}):m.jsx(fu,{open:e,onOpenChange:t,children:m.jsxs(hu,{side:"bottom",className:"inset-x-2 max-h-[calc(100dvh-0.75rem)] w-auto overflow-x-hidden overflow-y-auto rounded-t-xl border bg-background px-4 pb-[max(theme(spacing.4),env(safe-area-inset-bottom))] pt-3","data-slot":"create-session-dialog",focusSurfaceOnOpen:!0,children:[m.jsx(gf,{className:"px-0 pb-1 pt-0 text-left",children:m.jsx(pu,{children:y?"跳过全部审批?":"新建会话"})}),G]})})}function Jh({open:e,sessionId:t,initialName:n,onOpenChange:r,onRename:i}){const s=b.useMemo(()=>(n==null?void 0:n.trim())??"",[n]),[o,l]=b.useState(s),[u,d]=b.useState(null),[f,p]=b.useState(!1);b.useEffect(()=>{e&&(l(s),d(null),p(!1))},[s,e]);async function y(g){g.preventDefault();const _=o.trim();if(!_){d("会话标题不能为空");return}if(t){p(!0);try{await i(t,_),r(!1)}catch(w){d(w instanceof Error?w.message:String(w))}finally{p(!1)}}}return m.jsx(ss,{open:e,onOpenChange:r,children:m.jsx(os,{className:"sm:max-w-md","data-slot":"session-rename-dialog",children:m.jsxs("form",{className:"grid gap-4",onSubmit:g=>void y(g),children:[m.jsxs(as,{children:[m.jsx(Yi,{children:"重命名会话"}),m.jsx(_s,{children:"自定义名称会显示在会话列表和顶部标题中。"})]}),m.jsxs("div",{className:"grid gap-2",children:[m.jsx("label",{htmlFor:"session-rename-title",className:"text-sm font-medium",children:"会话标题"}),m.jsx("input",{id:"session-rename-title",value:o,autoFocus:!0,maxLength:100,"aria-invalid":!!u,"aria-describedby":u?"session-rename-error":void 0,className:Ye("h-10 rounded-md border border-input bg-background px-3 text-sm shadow-xs outline-none transition-[border-color,box-shadow]","placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/75","disabled:cursor-not-allowed disabled:opacity-50",u&&"border-destructive focus-visible:ring-destructive/20"),disabled:f,onChange:g=>{l(g.target.value),u&&d(null)}}),u?m.jsx("p",{id:"session-rename-error",className:"text-sm text-destructive",children:u}):null]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"outline",onClick:()=>r(!1),children:"取消"}),m.jsx(gt,{type:"submit",disabled:f,children:"保存"})]})]})})})}function _de(e){return(e==null?void 0:e.kind)==="agent"&&e.mode==="pty"&&e.ptyOwner==="local-terminal"}function wde(e){return(e==null?void 0:e.kind)==="terminal"}function xde(e){return _de(e)?{title:"断开远程连接?",description:"这只会断开当前页面和本地终端的连接,本地终端里的 Claude Code/Codex/Kimi Code 会继续运行。重新接入前,页面不能继续查看或输入这个会话。",confirmLabel:"断开远程连接",destructive:!1}:wde(e)?{title:"终止终端?",description:"这会停止当前终端进程,并清理这个终端会话的运行状态。终止后不能继续输入,也无法恢复正在执行的命令。",confirmLabel:"终止终端",destructive:!0}:{title:"终止会话?",description:"这会停止当前 Agent 进程,并清理这个会话的运行状态。终止后不能继续输入,也无法恢复正在执行的任务。",confirmLabel:"终止会话",destructive:!0}}function iv({open:e,session:t,onOpenChange:n,onConfirm:r}){const i=xde(t);function s(){t&&(r(t),n(!1))}return m.jsx(ss,{open:e,onOpenChange:n,children:m.jsxs(os,{"data-slot":"session-termination-dialog",children:[m.jsxs(as,{children:[m.jsx(Yi,{children:i.title}),m.jsx(_s,{children:i.description})]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"ghost",onClick:()=>n(!1),children:"取消"}),m.jsx(gt,{type:"button",variant:i.destructive?"destructive":"default",onClick:s,"data-slot":"session-termination-confirm",children:i.confirmLabel})]})]})})}function z4(e){var t,n,r,i,s,o,l,u,d,f,p,y;return e.connected===!1||e.proxyOnline===!1?"disconnected":e.routeSessionEnded||((t=e.session)==null?void 0:t.state)==="terminated"?"terminated":((n=e.session)==null?void 0:n.state)==="error"?"error":e.hasPendingApproval||((r=e.session)==null?void 0:r.state)==="waiting_approval"?"waiting_approval":((i=e.session)==null?void 0:i.state)==="compacting"?"compacting":((s=e.session)==null?void 0:s.state)==="working"?"working":((o=e.session)==null?void 0:o.state)==="idle"?"idle":((l=e.agentStatus)==null?void 0:l.phase)==="waiting_permission"||((u=e.ptyState)==null?void 0:u.state)==="approval_wait"?"waiting_approval":((d=e.agentStatus)==null?void 0:d.phase)==="thinking"||((f=e.agentStatus)==null?void 0:f.phase)==="tool_use"||((p=e.agentStatus)==null?void 0:p.phase)==="outputting"||((y=e.ptyState)==null?void 0:y.state)==="working"?"working":"idle"}function Sde(e){if(e.session.state==="error")return"error";const t=z4(e);return t==="disconnected"?e.session.state:t}const Ede=new Set(["localhost","127.0.0.1","[::1]"]),h1={cloudflare:{label:"Cloudflare Tunnel",executable:"cloudflared",installUrl:"https://developers.cloudflare.com/tunnel/downloads/"},cpolar:{label:"Cpolar",executable:"cpolar"}};function Cde(){return Si("local",wn.webPreviewTunnelProvider)==="cpolar"?"cpolar":"cloudflare"}function j4(e,t){if(e)return t==="cloudflare"?e.cloudflared:e.cpolar}function r0(e,t){var n;return((n=j4(e,t))==null?void 0:n.available)===!0}function kde(e){const t=e.trim();if(!t)return"请输入本机网站地址";let n;try{n=new URL(t)}catch{return"请输入完整的 http:// 本机网站地址"}return n.protocol!=="http:"||!Ede.has(n.hostname)||n.username!==""||n.password!==""?"只支持 localhost、127.0.0.1 或 [::1] 的 http:// 地址":null}function xh(){return{status:"idle"}}function Tde({open:e,onOpenChange:t}){const[n,r]=b.useState(""),[i,s]=b.useState(Cde),[o,l]=b.useState("local"),[u,d]=b.useState(""),[f,p]=b.useState(""),[y,g]=b.useState(""),[_,w]=b.useState(xh),[x,S]=b.useState(!1),k=b.useRef(null),T=b.useRef(null),N=b.useRef(null),P=b.useRef(null),R=b.useRef(i);R.current=i;const M=b.useRef(e);M.current=e;const L=co("(min-width: 768px)"),X=Ie(G=>G.selectedProxyId),U=Kr(G=>G.capability),V=Kr(G=>G.capabilityStatus),j=Kr(G=>G.capabilityError),A=Kr(G=>{var Z;return((Z=G.authoritative)==null?void 0:Z.scope)??null}),D=A?`${A.proxyId}\0${A.bindingId}`:null,O=b.useCallback(G=>{R.current=G,s(G),Tr("local",wn.webPreviewTunnelProvider,G)},[]);function I(){var G,Z;r(""),l("local"),d(""),p(""),g(""),w(xh()),S(!1),(G=k.current)==null||G.abort(),k.current=null,(Z=T.current)==null||Z.abort(),T.current=null,N.current=null,P.current=null}const B=b.useCallback(async G=>{var le;(le=k.current)==null||le.abort();const Z=new AbortController;k.current=Z;const ae=Tt.getActiveScope();if(!(!ae||ae.proxyId!==X))try{const me=await Tt.requestWebPreviewCapability(ae,G,{signal:Z.signal});if(!me||Z.signal.aborted||!M.current||!me.success)return;const ke=R.current,$e=ke==="cloudflare"?"cpolar":"cloudflare";!r0(me.capability,ke)&&r0(me.capability,$e)&&O($e)}catch{}},[O,X]);function F(G){!G&&x||t(G)}b.useEffect(()=>{if(!e){I();return}return B(!1),()=>{var G;(G=k.current)==null||G.abort(),k.current=null}},[B,e,D]),b.useEffect(()=>{var le;if(!e||o!=="static")return;(le=T.current)==null||le.abort(),T.current=null;const G=f.trim();if(!G){w(xh()),g("");return}const Z=new AbortController;T.current=Z,w({status:"loading"}),g("");const ae=window.setTimeout(()=>{const me=Ft,ke=Tt.getActiveScope();if(!me||!ke||ke.proxyId!==X){w({status:"error",message:"请先连接开发机"});return}Tt.inspectStaticWebPreview(ke,G,{signal:Z.signal}).then($e=>{if(!$e||Z.signal.aborted||!M.current||!Tt.isActive(me,ke))return;if(!$e.success){w({status:"error",message:$e.error});return}const he=$e.htmlEntries;if(he.length===0&&!$e.entryPath){w({status:"error",message:"这里没有可以预览的网页"});return}const He={entryPath:$e.entryPath,htmlEntries:he};w({status:"ready",path:G,result:He}),g($e.entryPath??"")}).catch($e=>{Z.signal.aborted||!M.current||$e instanceof Error&&$e.name==="AbortError"||!Tt.isActive(me,ke)||w({status:"error",message:$e instanceof Error?$e.message:"检查网页失败"})})},300);return()=>{window.clearTimeout(ae),Z.abort(),T.current===Z&&(T.current=null)}},[e,D,X,o,f]);const Y=o==="local"?kde(u):null,z=o==="static"&&_.status==="ready"&&_.path===f.trim()&&!!(_.result.entryPath||y),q=V==="loaded"&&r0(U,i),$=x||!q||!(o==="local"?Y===null:z);async function re(){var me,ke,$e;if($)return;const G=Ft;if(!G){We.error("请先连接开发机");return}let Z;if(o==="local")Z={kind:"local",url:u.trim()};else{if(_.status!=="ready"||_.path!==f.trim())return;const he=_.result.entryPath??y;if(!he)return;Z={kind:"static",path:_.path,entryPath:he}}S(!0);const ae=Tt.getActiveScope();if(!ae){S(!1),We.error("请先连接开发机");return}let le=null;try{const he=n.trim(),He=JSON.stringify({proxyId:ae.proxyId,tunnelProvider:i,source:Z,name:he||void 0});((me=N.current)==null?void 0:me.sourceKey)!==He&&(N.current={sourceKey:He,operationId:tb(`preview-operation-${i}`)}),le=N.current.operationId,P.current=le;const Nt=await Tt.createWebPreview(ae,Z,{tunnelProvider:i,operationId:le,...he?{name:he}:{}});if(P.current!==le)return;if(!Nt.accepted){((ke=N.current)==null?void 0:ke.operationId)===le&&(N.current=null),We.error(Nt.error);return}if((($e=N.current)==null?void 0:$e.operationId)===le&&(N.current=null),!M.current||!Tt.isActive(G,ae))return;t(!1)}catch(he){if(!le||P.current!==le||!M.current||!Tt.isActive(G,ae))return;We.error(he instanceof Error?he.message:"无法创建网页预览")}finally{le&&P.current===le&&(P.current=null,M.current&&S(!1))}}const Q=m.jsxs("form",{className:"flex min-w-0 flex-col gap-4","data-slot":"create-web-preview-form",autoComplete:"off",onSubmit:G=>{G.preventDefault(),re()},children:[m.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[m.jsx("span",{className:"text-sm",children:"名称(可选)"}),m.jsx("input",{type:"text",name:"dev-anywhere-web-preview-name",value:n,maxLength:256,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:x,placeholder:"自动生成","data-slot":"web-preview-name",onChange:G=>{r(G.target.value)},className:"min-h-11 min-w-0 rounded-md border border-border bg-input px-3 text-base outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60 md:h-9 md:min-h-0 md:text-sm"})]}),m.jsxs("section",{className:"flex min-w-0 flex-col gap-1","data-slot":"web-preview-tunnel-provider-field","data-provider":i,children:[m.jsx("span",{className:"text-sm",children:"内网穿透服务"}),m.jsxs(Ib,{value:i,disabled:x,onValueChange:G=>O(G),children:[m.jsx(Lb,{"aria-label":"内网穿透服务","data-slot":"web-preview-tunnel-provider-select","data-provider":i,className:"min-h-11 w-full md:min-h-0",children:m.jsx(Ob,{})}),m.jsx(Db,{"data-slot":"web-preview-tunnel-provider-options",children:Object.keys(h1).map(G=>m.jsx(Bb,{value:G,"data-slot":"web-preview-tunnel-provider-option","data-provider":G,children:h1[G].label},G))})]})]}),m.jsx(Rde,{status:V,capability:U,provider:i,error:j,disabled:x,onRetry:()=>void B(!0)}),m.jsxs("section",{"aria-label":"网页来源",className:"flex min-w-0 flex-col gap-2",children:[m.jsx("span",{className:"text-sm",children:"网页来源"}),m.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-2 sm:grid-cols-2",children:[m.jsxs("button",{type:"button","data-slot":"web-preview-source-local",disabled:x,"aria-pressed":o==="local",onClick:()=>{var G;(G=T.current)==null||G.abort(),T.current=null,w(xh()),g(""),l("local")},className:Ye("flex min-h-16 min-w-0 flex-col items-start justify-center gap-1 rounded-md border px-3 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60",o==="local"?"border-primary/70 bg-primary/10":"border-border bg-muted/20"),children:[m.jsx("span",{className:"text-sm font-medium",children:"本机网站"}),m.jsx("span",{className:"text-xs text-muted-foreground",children:"输入 localhost 地址"})]}),m.jsxs("button",{type:"button","data-slot":"web-preview-source-static",disabled:x,"aria-pressed":o==="static",onClick:()=>{var G;(G=T.current)==null||G.abort(),T.current=null,w(xh()),g(""),l("static")},className:Ye("flex min-h-16 min-w-0 flex-col items-start justify-center gap-1 rounded-md border px-3 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60",o==="static"?"border-primary/70 bg-primary/10":"border-border bg-muted/20"),children:[m.jsx("span",{className:"text-sm font-medium",children:"网页文件"}),m.jsx("span",{className:"text-xs text-muted-foreground",children:"选择 HTML 网页文件或目录"})]})]})]}),o==="local"?m.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[m.jsx("span",{className:"text-sm",children:"本机网站地址"}),m.jsx("input",{type:"url","data-slot":"web-preview-local-url","aria-label":"本机网站地址",inputMode:"url",name:"dev-anywhere-preview-local-url",autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:x,value:u,onChange:G=>{d(G.target.value)},placeholder:"http://localhost:5173","aria-invalid":u.length>0&&Y!==null,className:"min-h-11 min-w-0 rounded-md border border-border bg-input px-3 font-mono text-base outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60 md:h-9 md:min-h-0 md:text-sm"}),u.length>0&&Y?m.jsx("span",{"data-slot":"web-preview-local-url-error",className:"text-xs text-destructive",role:"alert",children:Y}):null]}):m.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[m.jsx(fk,{id:"create-web-preview-path",name:"dev-anywhere-preview-static-path","data-slot":"web-preview-static-path",label:"网页位置",value:f,selectionKind:"file-or-directory",fileExtensions:[".html",".htm"],disabled:x,placeholder:"选择 HTML 网页文件或目录",onValueChange:p}),m.jsx(Ade,{inspection:_,selectedEntryPath:y,disabled:x,onEntryPathChange:G=>{g(G)}})]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"ghost","data-slot":"create-web-preview-cancel",className:"min-h-11 md:min-h-0",onClick:()=>F(!1),disabled:x,children:"取消"}),m.jsx(gt,{type:"submit",className:"min-h-11 md:min-h-0",disabled:$,"data-slot":"create-web-preview-submit",children:x?"正在创建...":"创建预览"})]})]});return L?m.jsx(ss,{open:e,onOpenChange:F,children:m.jsxs(os,{showCloseButton:!x,onEscapeKeyDown:G=>{x&&G.preventDefault()},onPointerDownOutside:G=>{x&&G.preventDefault()},className:"!w-[calc(100vw-2rem)] !max-w-none max-h-[calc(100dvh-2rem)] overflow-y-auto sm:!w-[40rem]","data-slot":"create-web-preview-dialog",focusSurfaceOnOpen:!0,children:[m.jsxs(as,{children:[m.jsx(Yi,{children:"新建网页预览"}),m.jsx(_s,{children:"输入本机网站地址,或选择 HTML 网页文件或目录。"})]}),Q]})}):m.jsx(fu,{open:e,onOpenChange:F,children:m.jsxs(hu,{side:"bottom",showCloseButton:!x,onEscapeKeyDown:G=>{x&&G.preventDefault()},onPointerDownOutside:G=>{x&&G.preventDefault()},className:"inset-x-2 max-h-[calc(100dvh-0.75rem)] w-auto overflow-x-hidden overflow-y-auto rounded-t-xl border bg-background px-4 pb-[max(theme(spacing.4),env(safe-area-inset-bottom))] pt-3","data-slot":"create-web-preview-dialog",focusSurfaceOnOpen:!0,children:[m.jsxs(gf,{className:"px-0 pb-1 pt-0 text-left",children:[m.jsx(pu,{children:"新建网页预览"}),m.jsx(Mb,{children:"输入本机网站地址,或选择 HTML 网页文件或目录。"})]}),Q]})})}function Rde({status:e,capability:t,provider:n,error:r,disabled:i,onRetry:s}){const o=h1[n];if(e==="loading"||e==="idle")return m.jsxs("div",{"data-slot":"web-preview-capability-status","data-status":"loading","data-provider":n,className:"flex items-center gap-2 rounded-md border border-border/70 bg-muted/20 px-3 py-2 text-sm text-muted-foreground",role:"status",children:[m.jsx(ii,{className:"size-4 animate-spin","aria-hidden":"true"}),"正在检测 ",o.label,"..."]});if(e==="error")return m.jsx("div",{"data-slot":"web-preview-capability-status","data-status":"error","data-provider":n,className:"rounded-md border border-destructive/45 bg-destructive/5 p-3",role:"alert",children:m.jsxs("div",{className:"flex items-start gap-2",children:[m.jsx(XB,{className:"mt-0.5 size-4 shrink-0 text-destructive","aria-hidden":"true"}),m.jsxs("div",{className:"min-w-0 flex-1",children:[m.jsxs("p",{className:"text-sm font-medium",children:["无法检测 ",o.label]}),r?m.jsx("p",{className:"mt-1 break-words text-xs text-muted-foreground",children:r}):null]}),m.jsx(G2,{onClick:s,disabled:i})]})});const l=j4(t,n);if(!(l!=null&&l.available)){const u=(l==null?void 0:l.suggestions)??[],d=`未找到 ${o.label}`,f=(l==null?void 0:l.error)&&l.error!==d;return m.jsx("div",{"data-slot":"web-preview-capability-status","data-status":"missing","data-provider":n,className:"rounded-md border border-[var(--color-status-warning)]/45 bg-[var(--color-status-warning)]/5 p-3",role:"alert",children:m.jsxs("div",{className:"flex items-start gap-2",children:[m.jsx(fV,{className:"mt-0.5 size-4 shrink-0 text-[var(--color-status-warning)]","aria-hidden":"true"}),m.jsxs("div",{className:"min-w-0 flex-1",children:[m.jsx("p",{className:"text-sm font-medium",children:d}),m.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["请先安装 ",o.executable,",并确保它在用户 Shell 的 PATH 中,然后重新检测。"]}),u.length>0?m.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:[m.jsx("span",{children:"检测到的位置:"}),m.jsx("ul",{className:"mt-1 space-y-1",children:u.map(p=>m.jsx("li",{"data-slot":n==="cloudflare"?"web-preview-cloudflared-suggestion":"web-preview-cpolar-suggestion","data-provider":n,"data-path":p,children:m.jsx("code",{className:"break-all rounded bg-muted px-1 py-0.5",children:p})},p))})]}):null,o.installUrl?m.jsx("a",{"data-slot":"web-preview-cloudflared-install-link","data-provider":n,href:o.installUrl,target:"_blank",rel:"noopener noreferrer",className:"mt-2 inline-block text-xs text-primary underline-offset-4 hover:underline",children:"查看官方安装说明"}):null,f?m.jsx("p",{className:"mt-1 break-words text-xs text-muted-foreground/80",children:l.error}):null]}),m.jsx(G2,{onClick:s,disabled:i})]})})}return m.jsxs("div",{"data-slot":"web-preview-capability-status","data-status":"ready","data-provider":n,className:"flex items-center gap-2 rounded-md border border-[var(--color-status-success)]/35 bg-[var(--color-status-success)]/5 px-3 py-2 text-sm",role:"status",children:[m.jsx(iV,{className:"size-4 text-[var(--color-status-success)]","aria-hidden":"true"}),m.jsxs("span",{children:[o.label," 已安装"]}),l.version?m.jsxs("span",{className:"truncate text-xs text-muted-foreground",children:["· ",l.version]}):null]})}function G2({onClick:e,disabled:t}){return m.jsxs(gt,{type:"button",variant:"outline",size:"sm","data-slot":"web-preview-capability-retry",className:"shrink-0",onClick:e,disabled:t,children:[m.jsx(em,{className:"size-3.5","aria-hidden":"true"}),"重新检测"]})}function Ade({inspection:e,selectedEntryPath:t,disabled:n,onEntryPathChange:r}){if(e.status==="idle")return null;if(e.status==="loading")return m.jsxs("span",{"data-slot":"web-preview-static-inspection","data-status":"loading",className:"flex items-center gap-2 text-xs text-muted-foreground",role:"status",children:[m.jsx(ii,{className:"size-3.5 animate-spin","aria-hidden":"true"}),"正在检查网页..."]});if(e.status==="error")return m.jsx("span",{"data-slot":"web-preview-static-inspection","data-status":"error",className:"text-xs text-destructive",role:"alert",children:e.message});if(!e.result.entryPath&&e.result.htmlEntries.length>1)return m.jsxs("label",{"data-slot":"web-preview-static-inspection","data-status":"choose-entry",className:"mt-1 flex min-w-0 flex-col gap-2",children:[m.jsx("span",{className:"text-sm",children:"这个文件夹里有多个网页,打开预览时先显示哪个?"}),m.jsxs(Ib,{value:t,onValueChange:r,disabled:n,children:[m.jsx(Lb,{"data-slot":"web-preview-entry-select",className:"w-full font-mono",children:m.jsx(Ob,{placeholder:"选择网页"})}),m.jsx(Db,{children:e.result.htmlEntries.map(o=>m.jsx(Bb,{value:o,"data-entry-path":o,children:o},o))})]})]});const s=e.result.entryPath;return s?m.jsxs("span",{"data-slot":"web-preview-static-inspection","data-status":"ready","data-entry-path":s,className:"truncate text-xs text-muted-foreground",title:s,children:["打开时显示:",m.jsx("span",{className:"font-mono",children:s})]}):null}const p1={ios:"iOS Simulator",android:"Android Emulator"};function Nde({open:e,platform:t,onOpenChange:n}){const r=ws(),i=co("(min-width: 768px)"),s=Ie(F=>F.selectedProxyId),o=gr(F=>F.capability),l=gr(F=>F.targets),u=gr(F=>F.targetsStatus),d=gr(F=>F.targetsError),f=gr(Dj),p=gr(F=>{var Y;return((Y=F.authoritative)==null?void 0:Y.scope)??null}),y=p?`${p.proxyId}\0${p.bindingId}`:null,[g,_]=b.useState(""),[w,x]=b.useState(null),[S,k]=b.useState(!1),T=b.useRef(null),N=b.useRef(e);N.current=e;const P=b.useRef(null),R=b.useRef(null),M=b.useMemo(()=>l.filter(F=>F.platform===t),[t,l]),L=b.useMemo(()=>new Set(f.map(F=>F.targetId)),[f]),X=b.useMemo(()=>M.filter(F=>!L.has(F.targetId)),[L,M]),U=X.find(F=>F.targetId===w),V=o==null?void 0:o[t],j=b.useCallback(async F=>{var K;(K=T.current)==null||K.abort();const Y=new AbortController;T.current=Y;const z=Ft,q=Tt.getActiveScope();if(!(!z||!q||q.proxyId!==s))try{const $=await Tt.requestDevicePreviewCapability(q,F,{signal:Y.signal});if(!$||Y.signal.aborted||!N.current||!$.success)return;await Tt.requestDevicePreviewTargets(q,!0,{signal:Y.signal})}catch{}},[s]);b.useEffect(()=>{var F;if(!e){(F=T.current)==null||F.abort(),T.current=null,_(""),x(null),k(!1),P.current=null,R.current=null;return}return j(!1),()=>{var Y;(Y=T.current)==null||Y.abort(),T.current=null}},[j,e,t,y]),b.useEffect(()=>{if(e){if(w&&!U){x(null);return}!w&&X.length===1&&x(X[0].targetId)}},[e,X,U,w]);async function A(){var K,$,re;const F=U;if(!F||S||(V==null?void 0:V.available)!==!0)return;const Y=Ft,z=Tt.getActiveScope();if(!Y||!z||z.proxyId!==s){We.error("请先连接开发机");return}k(!0);let q=null;try{const Q=g.trim(),G=((K=P.current)==null?void 0:K.proxyId)===z.proxyId&&P.current.targetId===F.targetId&&P.current.name===Q?P.current:{proxyId:z.proxyId,targetId:F.targetId,name:Q,operationId:tb("device-preview-operation")};P.current=G,q=G.operationId,R.current=q;const Z=await Tt.createDevicePreview(z,F.targetId,{operationId:G.operationId,...Q?{name:Q}:{}});if(R.current!==G.operationId)return;if(!Z.accepted){if((($=P.current)==null?void 0:$.operationId)===G.operationId&&(P.current=null),!N.current||!Tt.isActive(Y,z))return;We.error(Z.error);return}if(((re=P.current)==null?void 0:re.operationId)===G.operationId&&(P.current=null),!N.current||!Tt.isActive(Y,z))return;n(!1),r(`/preview/device/${Z.previewId}`)}catch(Q){if(!q||R.current!==q||!N.current||!Tt.isActive(Y,z))return;We.error(Q instanceof Error?Q.message:"无法创建模拟器预览")}finally{q&&R.current===q&&(R.current=null,N.current&&k(!1))}}function D(F){var Y;!F&&S||(F||((Y=T.current)==null||Y.abort(),T.current=null,P.current=null,R.current=null,_(""),x(null)),n(F))}const O=m.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-4",children:[m.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[m.jsx("span",{className:"text-sm",children:"名称(可选)"}),m.jsx("input",{type:"text",name:"dev-anywhere-device-preview-name",value:g,maxLength:256,autoComplete:"off",autoCorrect:"off",spellCheck:!1,disabled:S,placeholder:"自动生成","data-slot":"device-preview-name",onChange:F=>{_(F.target.value)},className:"min-h-11 min-w-0 rounded-md border border-border bg-input px-3 text-base outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-60 md:h-9 md:min-h-0 md:text-sm"})]}),m.jsx(Mde,{platform:t,tool:V}),m.jsx("div",{className:"grid min-w-0 grid-cols-1 gap-2","data-slot":"device-preview-targets",children:u==="loading"?m.jsxs("div",{className:"flex min-h-28 items-center justify-center gap-2 text-sm text-muted-foreground",children:[m.jsx(ii,{className:"size-4 animate-spin","aria-hidden":"true"}),"正在查找已启动的模拟器..."]}):u==="error"?m.jsx(X2,{message:d??"无法读取模拟器列表"}):M.length===0?m.jsx(X2,{message:`没有已启动的 ${p1[t]}`}):M.map(F=>{const Y=F.targetId===w,z=L.has(F.targetId);return m.jsx(Pde,{target:F,selected:Y,disabled:z||S,alreadyOpen:z,onClick:()=>{x(F.targetId)}},F.targetId)})}),m.jsxs(Fs,{className:"gap-2 sm:gap-2",children:[m.jsxs(gt,{type:"button",variant:"outline",disabled:S||u==="loading",onClick:()=>void j(!0),"data-slot":"device-preview-refresh",children:[m.jsx(em,{className:"size-4","aria-hidden":"true"}),"重新检测"]}),m.jsx(gt,{type:"button",disabled:!U||S||(V==null?void 0:V.available)!==!0,onClick:()=>void A(),"data-slot":"create-device-preview-submit",children:S?"正在创建...":"创建预览"})]})]}),I=`新建 ${p1[t]} 预览`,B="选择开发机上已经启动的模拟器。";return i?m.jsx(ss,{open:e,onOpenChange:D,children:m.jsxs(os,{showCloseButton:!S,className:"sm:max-w-xl","data-slot":"create-device-preview-dialog","data-platform":t,focusSurfaceOnOpen:!0,children:[m.jsxs(as,{children:[m.jsx(Yi,{children:I}),m.jsx(_s,{children:B})]}),O]})}):m.jsx(fu,{open:e,onOpenChange:D,children:m.jsxs(hu,{side:"bottom",showCloseButton:!S,className:"inset-x-2 max-h-[calc(100dvh-0.75rem)] w-auto min-w-0 max-w-[calc(100%-1rem)] overflow-x-hidden overflow-y-auto rounded-t-xl border bg-background px-4 pb-[max(theme(spacing.4),env(safe-area-inset-bottom))] pt-3","data-slot":"create-device-preview-dialog","data-platform":t,focusSurfaceOnOpen:!0,children:[m.jsxs(gf,{className:"px-0 pb-1 pt-0 text-left",children:[m.jsx(pu,{children:I}),m.jsx(Mb,{children:B})]}),O]})})}function Mde({platform:e,tool:t}){if(!t||t.available)return null;const n=e==="android"&&!!t.command,r=e==="ios"?"Baguette":"adb",i=t.supported?e==="ios"&&t.version?"outdated":t.command?"unavailable":"missing":"unsupported",s=n?"Android 模拟器预览不可用":i==="unsupported"?`${p1[e]} 不可用`:i==="outdated"?`需要更新 ${r}`:i==="unavailable"?`${r} 暂时不可用`:`未找到 ${r}`,o=t.error??(e==="ios"?"需要先在开发机上安装 Baguette 0.1.96 或更高版本。":"需要先在开发机上安装 adb。"),l=o.trim()!==s.trim();return m.jsx("div",{className:"rounded-lg border border-amber-500/45 bg-amber-500/5 p-3 text-sm","data-slot":"device-preview-tool-status","data-status":i,children:m.jsxs("div",{className:"flex gap-2",children:[m.jsx(XB,{className:"mt-0.5 size-4 shrink-0 text-amber-600","aria-hidden":"true"}),m.jsxs("div",{className:"min-w-0",children:[m.jsx("p",{className:"font-medium",children:s}),l?m.jsx("p",{className:"mt-1 text-muted-foreground","data-slot":"device-preview-tool-description",children:o}):null,i!=="unsupported"&&!n?m.jsx("a",{href:e==="ios"?"https://github.com/tddworks/baguette#install":"https://developer.android.com/tools/releases/platform-tools",target:"_blank",rel:"noreferrer",className:"mt-1 inline-block text-primary underline underline-offset-4",children:"查看安装方法"}):null]})]})})}function X2({message:e}){return m.jsx("div",{className:"flex min-h-28 items-center justify-center rounded-lg border border-dashed px-4 text-center text-sm text-muted-foreground",children:e})}function Pde({target:e,selected:t,disabled:n,alreadyOpen:r,onClick:i}){const s=e.platform==="ios"?"iOS":"Android",o=`${e.model} · ${s} ${e.osVersion}`;return m.jsxs("button",{type:"button",className:Ye("flex min-h-16 w-full min-w-0 max-w-full items-center gap-3 overflow-hidden rounded-lg border px-3 py-2 text-left outline-none transition-colors",t?"border-primary bg-primary/5":"border-border hover:bg-accent",n&&"cursor-not-allowed opacity-55"),disabled:n,"aria-pressed":t,onClick:i,"data-slot":"device-preview-target","data-target-id":e.targetId,"data-already-open":r?"true":"false","data-interactive":e.interactive?"true":"false",children:[m.jsx(uy,{className:"size-5 shrink-0 text-muted-foreground","aria-hidden":"true"}),m.jsxs("span",{className:"min-w-0 flex-1",children:[m.jsx("span",{className:"block truncate text-sm font-medium",children:e.name}),m.jsx("span",{className:"mt-0.5 block truncate text-xs text-muted-foreground","data-slot":"device-preview-target-device","data-device-model":e.model,"data-os-version":e.osVersion,children:o})]}),r?m.jsx("span",{className:"text-xs text-muted-foreground",children:"已在预览"}):t?m.jsx(Co,{className:"size-4 text-primary","aria-hidden":"true"}):null]})}function F4({open:e,onOpenChange:t}){const[n,r]=b.useState(()=>e?"chooser":"closed"),i=b.useRef(null),s=co("(min-width: 768px)");b.useLayoutEffect(()=>{if(e){n==="closed"&&r("chooser");return}n!=="closed"&&(i.current=n,r("closed"))},[e,n]);function o(){t(!1)}const l=m.jsxs("div",{className:"grid gap-2 pt-2","data-slot":"frontend-preview-options",children:[m.jsx(i0,{icon:m.jsx(JB,{className:"size-5","aria-hidden":"true"}),title:"网页",description:"通过临时链接访问或分享本机网页",slot:"frontend-preview-web",onClick:()=>r("web")}),m.jsx(i0,{icon:m.jsx(uy,{className:"size-5","aria-hidden":"true"}),title:"iOS Simulator",description:"查看和操控开发机上已启动的 iPhone 或 iPad 模拟器",slot:"frontend-preview-ios",onClick:()=>r("ios")}),m.jsx(i0,{icon:m.jsx(uy,{className:"size-5","aria-hidden":"true"}),title:"Android Emulator",description:"查看和操控开发机上已启动的 Android 模拟器",slot:"frontend-preview-android",onClick:()=>r("android")})]}),u=n==="closed"?i.current:n,d=e&&n!=="closed";switch(u){case"chooser":return s?m.jsx(ss,{open:d,onOpenChange:f=>!f&&o(),children:m.jsxs(os,{className:"sm:max-w-lg","data-slot":"create-frontend-preview-dialog",children:[m.jsxs(as,{children:[m.jsx(Yi,{children:"新建预览"}),m.jsx(_s,{children:"选择预览类型。"})]}),l]})},"chooser"):m.jsx(fu,{open:d,onOpenChange:f=>!f&&o(),children:m.jsxs(hu,{side:"bottom",className:"inset-x-2 w-auto rounded-t-xl border bg-background px-4 pb-[max(theme(spacing.4),env(safe-area-inset-bottom))] pt-3","data-slot":"create-frontend-preview-dialog",focusSurfaceOnOpen:!0,children:[m.jsxs(gf,{className:"px-0 pb-1 pt-0 text-left",children:[m.jsx(pu,{children:"新建预览"}),m.jsx(Mb,{children:"选择预览类型。"})]}),l]})},"chooser");case"web":return m.jsx(Tde,{open:d,onOpenChange:f=>!f&&o()},"web");case"ios":case"android":return m.jsx(Nde,{open:d,platform:u,onOpenChange:f=>!f&&o()},u);case null:return null}}function i0({icon:e,title:t,description:n,slot:r,onClick:i}){return m.jsxs(gt,{type:"button",variant:"outline",className:"h-auto min-h-[4.5rem] justify-start gap-3 px-4 py-3 text-left","data-slot":r,onClick:i,children:[m.jsx("span",{className:"text-muted-foreground",children:e}),m.jsxs("span",{className:"min-w-0",children:[m.jsx("span",{className:"block font-medium text-foreground",children:t}),m.jsx("span",{className:"mt-0.5 block whitespace-normal text-xs leading-5 text-muted-foreground",children:n})]})]})}function Ide({preview:e,closing:t,onOpenChange:n,onConfirm:r}){return m.jsx(ss,{open:e!==null,onOpenChange:n,children:m.jsxs(os,{"data-slot":"device-preview-close-dialog",children:[m.jsxs(as,{children:[m.jsx(Yi,{children:"停止预览?"}),m.jsx(_s,{children:"模拟器会继续在开发机上运行。"})]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"ghost",disabled:t,onClick:()=>n(!1),children:"取消"}),m.jsx(gt,{type:"button",variant:"destructive",disabled:!e||t,onClick:()=>e&&r(e),"data-slot":"device-preview-close-confirm",children:t?"正在停止...":"停止预览"})]})]})})}const Ode={ready:{dot:"bg-[var(--color-status-success)]",text:"text-[var(--color-status-success)]",label:"已连接"},disconnected:{dot:"bg-muted-foreground",text:"text-muted-foreground",label:"已断开"}};function Lde({preview:e,selected:t,pendingOperation:n,onRename:r,onReconnect:i,onClose:s}){const o=Ode[e.state],l=n==="reconnect"?{dot:"bg-[var(--color-status-working)] animate-pulse",text:"text-[var(--color-status-working)]",label:"正在重新连接",busy:!0}:n==="close"?{dot:"bg-muted-foreground animate-pulse",text:"text-muted-foreground",label:"正在停止",busy:!0}:o,u=e.state==="ready",d=e.state==="disconnected",f=e.platform==="ios"?"iOS":"Android",p=m.jsxs(m.Fragment,{children:[m.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[m.jsx("span",{className:Ye("inline-block size-2 shrink-0 rounded-full",l.dot),role:"status","aria-label":`预览状态:${l.label}`}),m.jsx("span",{className:"flex-1 truncate text-sm font-normal",title:e.name,children:e.name})]}),m.jsxs("span",{className:"flex h-5 min-w-0 items-center gap-1.5 text-xs leading-5",children:[m.jsx(uy,{className:"size-3.5 shrink-0 text-muted-foreground","aria-hidden":"true"}),m.jsxs("span",{className:"min-w-0 flex-1 truncate text-muted-foreground","data-slot":"device-preview-row-device","data-device-model":e.model,"data-os-version":e.osVersion,children:[e.model," · ",f," ",e.osVersion]}),m.jsx("span",{className:Ye("shrink-0",l.text),children:l.label})]})]});return m.jsxs("li",{className:Ye("relative flex min-h-[44px] w-full min-w-0 items-center gap-2 px-4 py-2 transition-colors hover:bg-accent",t&&"bg-accent"),"data-slot":"device-preview-row","data-preview-id":e.previewId,"data-preview-state":e.state,"data-preview-operation":n,children:[u?m.jsx(nC,{to:`/preview/device/${e.previewId}`,className:"flex min-h-11 min-w-0 flex-1 flex-col justify-center gap-1 rounded-sm text-left outline-none focus-visible:ring-2 focus-visible:ring-ring md:min-h-0","data-slot":"device-preview-row-open",children:p}):m.jsx("div",{className:"flex min-h-11 min-w-0 flex-1 flex-col justify-center gap-1 md:min-h-0",children:p}),m.jsxs(uf,{children:[m.jsx(df,{asChild:!0,children:m.jsx(gt,{variant:"ghost",size:"icon-xs",className:"size-11 md:size-6","aria-label":"模拟器预览操作",disabled:n!==void 0,"data-slot":"device-preview-row-menu-trigger",children:l.busy||n==="rename"?m.jsx(ii,{className:"animate-spin","aria-hidden":"true"}):m.jsx(Ky,{"aria-hidden":"true"})})}),m.jsxs(ff,{align:"end","data-slot":"device-preview-row-menu",children:[m.jsx(ni,{"data-slot":"device-preview-row-rename-item",onSelect:r,children:"重命名"}),d?m.jsx(ni,{"data-slot":"device-preview-row-reconnect-item",onSelect:i,children:"重新连接"}):null,m.jsx(Ld,{}),m.jsx(ni,{variant:"destructive","data-slot":"device-preview-row-close-item",onSelect:s,children:"停止预览"})]})]})]})}function Dde({preview:e,closing:t,onOpenChange:n,onConfirm:r}){return m.jsx(ss,{open:e!==null,onOpenChange:n,children:m.jsxs(os,{"data-slot":"preview-close-dialog",children:[m.jsxs(as,{children:[m.jsx(Yi,{children:"关闭预览?"}),m.jsx(_s,{children:"关闭后,当前预览链接将立即失效。"})]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"ghost",disabled:t,onClick:()=>n(!1),children:"取消"}),m.jsx(gt,{type:"button",variant:"destructive",disabled:!e||t,onClick:()=>e&&r(e),"data-slot":"preview-close-confirm",children:t?"正在关闭...":"关闭预览"})]})]})})}function Bde({target:e,onOpenChange:t,onRename:n}){return m.jsx(zde,{target:e,onOpenChange:t,onRename:n},(e==null?void 0:e.targetKey)??"closed")}function zde({target:e,onOpenChange:t,onRename:n}){const[r,i]=b.useState(()=>(e==null?void 0:e.name.trim())??""),[s,o]=b.useState(null),[l,u]=b.useState(!1),d=b.useRef((e==null?void 0:e.targetKey)??null);b.useLayoutEffect(()=>()=>{d.current=null},[]);function f(y){!y&&l||t(y)}async function p(y){y.preventDefault();const g=r.trim();if(!g){o("名称不能为空");return}if(!e||l)return;const _=e.targetKey;u(!0);try{if(await n(g),d.current!==_)return;t(!1)}catch(w){if(d.current!==_)return;o(w instanceof Error?w.message:String(w))}finally{d.current===_&&u(!1)}}return m.jsx(ss,{open:e!==null,onOpenChange:f,children:m.jsx(os,{showCloseButton:!l,className:"sm:max-w-md","data-slot":"preview-rename-dialog",children:m.jsxs("form",{className:"grid gap-4",onSubmit:y=>void p(y),children:[m.jsx(as,{children:m.jsx(Yi,{children:"重命名预览"})}),m.jsxs("div",{className:"grid gap-2",children:[m.jsx("label",{htmlFor:"preview-rename-name",className:"text-sm font-medium",children:"预览名称"}),m.jsx("input",{id:"preview-rename-name",value:r,autoFocus:!0,maxLength:256,autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-invalid":!!s,"aria-describedby":s?"preview-rename-error":void 0,"data-slot":"preview-rename-input",className:Ye("h-10 rounded-md border border-input bg-background px-3 text-sm shadow-xs outline-none transition-[border-color,box-shadow]","placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/75","disabled:cursor-not-allowed disabled:opacity-50",s&&"border-destructive focus-visible:ring-destructive/20"),disabled:l,onChange:y=>{i(y.target.value),s&&o(null)}}),s?m.jsx("p",{id:"preview-rename-error",className:"text-sm text-destructive",role:"alert",children:s}):null]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"outline",disabled:l,onClick:()=>f(!1),children:"取消"}),m.jsx(gt,{type:"submit",disabled:l,"data-slot":"preview-rename-submit",children:"保存"})]})]})})})}const jde={starting:{dot:"bg-[var(--color-status-working)] animate-pulse",text:"text-[var(--color-status-working)]",label:"正在创建",busy:!0},ready:{dot:"bg-[var(--color-status-success)]",text:"text-[var(--color-status-success)]",label:"可访问"},failed:{dot:"bg-[var(--color-status-error)]",text:"text-[var(--color-status-error)]",label:"连接失败"},disconnected:{dot:"bg-muted-foreground",text:"text-muted-foreground",label:"已断开"},stopping:{dot:"bg-muted-foreground animate-pulse",text:"text-muted-foreground",label:"正在关闭",busy:!0}};function Fde(e){return e.source.kind==="local"?e.source.url:`${e.source.rootPath.replace(/\/$/,"")}/${e.source.entryPath}`}async function $de(e){if(await Ap(e,{allowUserGestureFallback:!0})==="failed"){We.error("复制失败,请稍后重试");return}We.success("链接已复制")}async function Hde(e,t){if(typeof navigator.share=="function")try{await navigator.share({title:e,url:t})}catch(n){if(n instanceof DOMException&&n.name==="AbortError")return;We.error("无法打开系统分享面板")}}function Ude({preview:e,pendingOperation:t,onRename:n,onReconnect:r,onClose:i}){const s=jde[e.state],o=t==="reconnect"?{dot:"bg-[var(--color-status-working)] animate-pulse",text:"text-[var(--color-status-working)]",label:"正在重新连接",busy:!0}:t==="close"?{dot:"bg-muted-foreground animate-pulse",text:"text-muted-foreground",label:"正在关闭",busy:!0}:s,l=e.state==="ready"?e.publicUrl:null,u=l!==null,d=e.state==="failed"||e.state==="disconnected",f=u&&typeof navigator<"u"&&typeof navigator.share=="function",p=Fde(e),y=m.jsxs(m.Fragment,{children:[m.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[m.jsx("span",{className:Ye("inline-block size-2 shrink-0 rounded-full",o.dot),role:"status","aria-label":`预览状态:${o.label}`}),m.jsx("span",{className:"flex-1 truncate text-sm font-normal",title:e.name,children:e.name})]}),m.jsxs("span",{className:"flex h-5 min-w-0 items-center gap-1.5 text-xs leading-5",children:[m.jsx(JB,{className:"size-3.5 shrink-0 text-muted-foreground","aria-hidden":"true"}),m.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-muted-foreground",title:p,children:p}),m.jsx("span",{className:"shrink-0 text-muted-foreground/60","aria-hidden":"true",children:"·"}),m.jsx("span",{className:Ye("shrink-0",o.text),children:o.label})]}),e.state==="failed"?m.jsx("span",{"data-slot":"preview-row-error",className:"truncate text-xs text-destructive/90",title:e.error,children:e.error}):null]});return m.jsxs("li",{className:"relative flex min-h-[44px] w-full min-w-0 items-center gap-2 px-4 py-2 transition-colors hover:bg-accent","data-slot":"preview-row","data-preview-id":e.previewId,"data-preview-state":e.state,"data-preview-operation":t,children:[u?m.jsx("a",{href:l,target:"_blank",rel:"noopener noreferrer","data-slot":"preview-row-open",className:"flex min-h-11 min-w-0 flex-1 flex-col justify-center gap-1 rounded-sm text-left outline-none focus-visible:ring-2 focus-visible:ring-ring md:min-h-0",children:y}):m.jsx("div",{"data-slot":"preview-row-inactive","aria-disabled":"true",className:"flex min-h-11 min-w-0 flex-1 flex-col justify-center gap-1 md:min-h-0",children:y}),m.jsxs(uf,{children:[m.jsx(df,{asChild:!0,children:m.jsx(gt,{variant:"ghost",size:"icon-xs",className:"size-11 md:size-6","aria-label":"预览操作","data-slot":"preview-row-menu-trigger",disabled:e.state==="stopping"||t!==void 0,children:o.busy||t==="rename"?m.jsx(ii,{className:"animate-spin","aria-hidden":"true"}):m.jsx(Ky,{"aria-hidden":"true"})})}),m.jsxs(ff,{align:"end","data-slot":"preview-row-menu",children:[m.jsx(ni,{"data-slot":"preview-row-rename-item",onSelect:n,children:"重命名"}),u?m.jsx(ni,{"data-slot":"preview-row-copy-item",onSelect:()=>void $de(l),children:"复制链接"}):null,f?m.jsx(ni,{"data-slot":"preview-row-share-item",onSelect:()=>void Hde(e.name,l),children:"分享…"}):null,d?m.jsx(ni,{"data-slot":"preview-row-reconnect-item",onSelect:r,children:"重新连接"}):null,m.jsx(Ld,{}),m.jsx(ni,{variant:"destructive","data-slot":"preview-row-close-item",onSelect:i,children:"关闭预览"})]})]})]})}const Wde=Object.freeze([]),qde=Object.freeze([]);function ed(e,t,n){return Object.freeze({kind:e,previewId:t,scope:Object.freeze({proxyId:n.proxyId,bindingId:n.bindingId})})}function Ac(e,t){return e!==null&&e.kind===t.kind&&e.previewId===t.previewId&&tn(e.scope,t.scope)}function ep(e,t,n){return t!==null&&n!==void 0&&tn(e.scope,t)&&tn(e.scope,n)}function Sh(e){const t=Tt.getActiveScope(),n=e.kind==="web"?Kr.getState().authoritative:gr.getState().authoritative;return!n||!ep(e,t,n.scope)?!1:n.previews.some(r=>r.previewId===e.previewId)}function Do(e){const t=Tt.getActiveScope();return t!==null&&tn(t,e)}function Z2(){const e=Kr(A=>A.authoritative),t=gr(A=>A.authoritative),n=qo(A=>A.registry),r=Tt.getActiveScope(),i=r&&e&&tn(r,e.scope)?e.scope:null,s=r&&t&&tn(r,t.scope)?t.scope:null,o=i&&e?e.previews:Wde,l=s&&t?t.previews:qde,u=BB("/preview/device/:id"),d=ws(),[f,p]=b.useState(null),[y,g]=b.useState(null),_=(y==null?void 0:y.kind)==="web"&&ep(y,r,e==null?void 0:e.scope)?o.find(A=>A.previewId===y.previewId)??null:null,w=(y==null?void 0:y.kind)==="device"&&ep(y,r,t==null?void 0:t.scope)?l.find(A=>A.previewId===y.previewId)??null:null,x=_??w,S=(f==null?void 0:f.kind)==="web"&&ep(f,r,e==null?void 0:e.scope)?o.find(A=>A.previewId===f.previewId)??null:null,k=(f==null?void 0:f.kind)==="device"&&ep(f,r,t==null?void 0:t.scope)?l.find(A=>A.previewId===f.previewId)??null:null;b.useEffect(()=>{y&&!x&&g(A=>Ac(A,y)?null:A),f&&!S&&!k&&p(A=>Ac(A,f)?null:A)},[f,k,y,x,S]);function T(A,D,O){var I;return(I=Pj(n,A,D,O)[0])==null?void 0:I.kind}if(o.length===0&&l.length===0)return null;async function N(A){if(Sh(A))try{const D=await Tt.reconnectWebPreview(A.scope,A.previewId);if(!Do(A.scope))return;D.success||We.error(D.error)}catch(D){if(!Do(A.scope))return;We.error(D instanceof Error?D.message:"无法重新连接网页预览")}}async function P(A,D){if(!Sh(A))return;let O;try{O=A.kind==="web"?await Tt.renameWebPreview(A.scope,A.previewId,D):await Tt.renameDevicePreview(A.scope,A.previewId,D)}catch(I){if(!Do(A.scope))return;throw I}if(Do(A.scope)&&!O.success)throw new Error(O.error)}async function R(A){if(Sh(A))try{const D=await Tt.closeWebPreview(A.scope,A.previewId);if(!Do(A.scope))return;if(!D.success){We.error(D.error);return}p(O=>Ac(O,A)?null:O)}catch(D){if(!Do(A.scope))return;We.error(D instanceof Error?D.message:"无法关闭网页预览")}}async function M(A){if(Sh(A))try{const D=await Tt.reconnectDevicePreview(A.scope,A.previewId);if(!Do(A.scope))return;D.success||We.error(D.error)}catch(D){if(!Do(A.scope))return;We.error(D instanceof Error?D.message:"无法重新连接模拟器预览")}}async function L(A){if(Sh(A))try{const D=await Tt.closeDevicePreview(A.scope,A.previewId);if(!Do(A.scope))return;if(!D.success){We.error(D.error);return}p(O=>Ac(O,A)?null:O),(u==null?void 0:u.params.id)===A.previewId&&d("/sessions")}catch(D){if(!Do(A.scope))return;We.error(D instanceof Error?D.message:"无法停止模拟器预览")}}const X=(f==null?void 0:f.kind)==="web"&&T(f.scope,"web",f.previewId)==="close",U=(f==null?void 0:f.kind)==="device"&&T(f.scope,"device",f.previewId)==="close",V=y,j=f;return m.jsxs("section",{"data-slot":"preview-section","aria-labelledby":"preview-section-title",children:[m.jsxs("h3",{id:"preview-section-title",className:"px-4 pb-2 pt-3 text-sm font-semibold text-foreground",children:["预览",m.jsxs("span",{className:"ml-1 font-normal text-muted-foreground/70",children:["· ",o.length+l.length]})]}),m.jsxs("ul",{role:"list",className:"flex w-full min-w-0 flex-col",children:[o.map(A=>m.jsx(Ude,{preview:A,pendingOperation:i?T(i,"web",A.previewId):void 0,onRename:()=>i&&g(ed("web",A.previewId,i)),onReconnect:()=>i&&void N(ed("web",A.previewId,i)),onClose:()=>i&&p(ed("web",A.previewId,i))},A.previewId)),l.map(A=>m.jsx(Lde,{preview:A,selected:(u==null?void 0:u.params.id)===A.previewId,pendingOperation:s?T(s,"device",A.previewId):void 0,onRename:()=>s&&g(ed("device",A.previewId,s)),onReconnect:()=>s&&void M(ed("device",A.previewId,s)),onClose:()=>s&&p(ed("device",A.previewId,s))},A.previewId))]}),m.jsx(Bde,{target:V&&x?{targetKey:`${V.kind}\0${V.scope.proxyId}\0${V.scope.bindingId}\0${V.previewId}`,name:x.name}:null,onOpenChange:A=>{!A&&V&&g(D=>Ac(D,V)?null:D)},onRename:A=>V?P(V,A):Promise.resolve()}),m.jsx(Dde,{preview:S,closing:X,onOpenChange:A=>{!A&&!X&&j&&p(D=>Ac(D,j)?null:D)},onConfirm:()=>j&&void R(j)}),m.jsx(Ide,{preview:k,closing:U,onOpenChange:A=>{!A&&!U&&j&&p(D=>Ac(D,j)?null:D)},onConfirm:()=>j&&void L(j)})]})}function $4({layout:e}){const t=Gt(G=>G.sessions),n=Gt(G=>G.sessionListLoaded),r=Gt(G=>G.agentStatusBySessionId),i=Gt(G=>G.ptyStateBySessionId),s=Gt(G=>G.renameSession),o=an(G=>G.bySessionId),l=BB("/chat/:id"),u=(l==null?void 0:l.params.id)??null,d=Ie(G=>!!G.selectedProxyId),f=Ie(G=>G.proxyListLoaded),p=Ie(G=>G.proxySwitchTarget),y=Gt(G=>G.loadingProxyName),g=p!==null||!f||d&&!n,_=(p==null?void 0:p.name)??y,w=_?`正在连接 ${_}...`:"连接中...",x=ws(),[S,k]=b.useState(!1),[T,N]=b.useState(!1),[P,R]=b.useState(!1),[M,L]=b.useState(null),[X,U]=b.useState(null),{creatingTerminal:V,createTerminal:j}=H4(),[A,D]=b.useState(new Set),[O,I]=b.useState(()=>Date.now());b.useEffect(()=>{const G=setInterval(()=>I(Date.now()),6e4);return()=>clearInterval(G)},[]);function B(G,Z){x(`/chat/${G}?mode=${Z}`,{replace:!1})}function F(G){const Z=G.sessionId,ae=Ft;if(!ae){We.error("请先连接开发机");return}ae.sendControl({type:"session_terminate",sessionId:Z}),Gt.getState().removeSession(Z),an.getState().clearSession(Z),Z===u&&x("/sessions"),(G==null?void 0:G.kind)==="agent"&&G.mode==="pty"&&G.ptyOwner==="local-terminal"?We.info("已断开页面连接,本地终端仍在运行"):We.info("正在终止会话",{duration:1500})}async function Y(G,Z){const ae=Ft;if(!ae)throw new Error("请先连接开发机");const le=await ae.renameSession(G,Z);if(!le.success)throw new Error(le.error??"重命名失败");s(G,le.name??Z),We.success("已重命名会话")}function z(G){D(Z=>{const ae=new Set(Z);return ae.has(G)?ae.delete(G):ae.add(G),ae})}function q(G){var le;const Z=G.mode==="json"&&(((le=o[G.sessionId])==null?void 0:le.pendingApprovals.some(me=>me.status==="pending"))??!1),ae=Sde({session:G,agentStatus:r[G.sessionId],ptyState:i[G.sessionId],hasPendingApproval:Z});return ae===G.state?G:{...G,state:ae}}const K=t.length>0;if(e==="sidebar"&&(g||!d))return m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/70","data-slot":g?"session-list-loading":void 0,role:g?"status":void 0,"aria-live":g?"polite":void 0,children:g?w:"请先连接开发机"}),m.jsx(Qh,{open:S,onOpenChange:k}),m.jsx(iv,{open:X!==null,session:X,onOpenChange:G=>{G||U(null)},onConfirm:F}),m.jsx(Jh,{open:M!==null,sessionId:(M==null?void 0:M.sessionId)??null,initialName:M==null?void 0:M.name,onOpenChange:G=>{G||L(null)},onRename:Y})]});if(e==="page"&&g)return m.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 text-muted-foreground animate-in fade-in-0 duration-200 motion-reduce:animate-none","data-slot":"session-list-loading",role:"status","aria-live":"polite",children:[m.jsx(ii,{className:"h-5 w-5 animate-spin","aria-hidden":!0}),m.jsx("p",{className:"max-w-[min(24rem,calc(100%-2rem))] truncate text-sm",children:w})]});if(e==="page"&&!d)return m.jsxs("div",{className:"flex flex-col h-full",children:[m.jsx("div",{className:"flex-1",children:m.jsx(Uc,{variant:"no-proxy"})}),m.jsx(Qh,{open:S,onOpenChange:k}),m.jsx(iv,{open:X!==null,session:X,onOpenChange:G=>{G||U(null)},onConfirm:F}),m.jsx(Jh,{open:M!==null,sessionId:(M==null?void 0:M.sessionId)??null,initialName:M==null?void 0:M.name,onOpenChange:G=>{G||L(null)},onRename:Y})]});const $=m.jsxs("h3",{className:"px-4 pt-3 pb-2 text-sm font-semibold text-foreground","data-slot":"active-section-header",children:["活跃会话",K?m.jsxs("span",{className:"ml-1 text-muted-foreground/70 font-normal",children:["· ",t.length]}):null]}),re=K?m.jsx("ul",{role:"list",className:"flex flex-col w-full min-w-0",children:Vde(t).map(G=>m.jsxs("li",{children:[m.jsxs("button",{type:"button",onClick:()=>z(G.provider),"aria-expanded":!A.has(G.provider),className:Ye("flex w-full items-center gap-2 px-4 pt-2 pb-1 min-h-[32px]","text-xs text-muted-foreground","text-left outline-none transition-colors hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring"),children:[m.jsx("span",{className:"font-mono",children:Yde(G.provider)}),m.jsx("span",{className:"h-px flex-1 bg-border/70","aria-hidden":"true"}),m.jsx("span",{className:"tabular-nums",children:G.sessions.length}),m.jsx(dp,{className:Ye("size-3.5 shrink-0 text-muted-foreground/80 transition-transform",!A.has(G.provider)&&"rotate-90"),"aria-hidden":"true"})]}),A.has(G.provider)?null:m.jsx("ul",{role:"list",className:"flex flex-col",children:G.sessions.map(Z=>m.jsx(nde,{session:q(Z),selected:Z.sessionId===u,now:O,onClick:()=>B(Z.sessionId,Z.mode),onRename:()=>L(Z),onTerminate:()=>U(Z)},Z.sessionId))})]},G.provider))}):m.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/70","data-slot":"active-empty",children:"暂无活跃会话"}),Q=m.jsx(ode,{now:O});return e==="page"?m.jsxs("div",{className:"flex flex-col h-full",children:[m.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto overscroll-contain",children:[$,re,m.jsx(Z2,{}),Q]}),m.jsx("div",{className:"px-4 pt-4 pb-[calc(env(safe-area-inset-bottom)+1rem)] border-t border-border",children:m.jsxs(gt,{className:"min-h-11 w-full md:min-h-0","data-slot":"create-session-mobile-trigger",onClick:()=>N(!0),children:[m.jsx(ZB,{"aria-hidden":"true"}),"新建"]})}),m.jsx(Gde,{open:T,creatingTerminal:V,onOpenChange:N,onCreateAgent:()=>{N(!1),k(!0)},onCreateTerminal:()=>void j(()=>N(!1)),onCreatePreview:()=>{N(!1),R(!0)}}),m.jsx(Qh,{open:S,onOpenChange:k}),m.jsx(F4,{open:P,onOpenChange:R}),m.jsx(iv,{open:X!==null,session:X,onOpenChange:G=>{G||U(null)},onConfirm:F}),m.jsx(Jh,{open:M!==null,sessionId:(M==null?void 0:M.sessionId)??null,initialName:M==null?void 0:M.name,onOpenChange:G=>{G||L(null)},onRename:Y})]}):m.jsxs(m.Fragment,{children:[m.jsxs("div",{className:"dev-sidebar-scroll h-full overflow-y-auto overscroll-contain",children:[$,re,m.jsx(Z2,{}),Q]}),m.jsx(Qh,{open:S,onOpenChange:k}),m.jsx(iv,{open:X!==null,session:X,onOpenChange:G=>{G||U(null)},onConfirm:F}),m.jsx(Jh,{open:M!==null,sessionId:(M==null?void 0:M.sessionId)??null,initialName:M==null?void 0:M.name,onOpenChange:G=>{G||L(null)},onRename:Y})]})}function Vde(e){const t=new Map;for(const n of e){const r=n.kind==="terminal"?"terminal":n.provider,i=t.get(r);i?i.push(n):t.set(r,[n])}return Array.from(t.entries()).sort(([n],[r])=>Kde(n,r)).map(([n,r])=>({provider:n,sessions:r}))}function Yde(e){return e==="terminal"?"终端":Pb(e)}function Kde(e,t){return e===t?0:e==="terminal"?-1:t==="terminal"?1:A4(e,t)}function H4(){const e=ws(),[t,n]=b.useState(!1);async function r(i){if(!t){n(!0);try{const s=await vde({relay:Ft});if(s.type!=="success"){We.error(s.message);return}Gt.getState().addSession(s.session),i==null||i(),e(s.route)}finally{n(!1)}}}return{creatingTerminal:t,createTerminal:r}}function Q2({compact:e=!1}){const[t,n]=b.useState(!1),[r,i]=b.useState(!1),[s,o]=b.useState(!1),l=b.useRef(!1),u=Ie(N=>!!N.selectedProxyId),d=Ie(N=>N.proxySwitchTarget!==null),f=u&&!d,{creatingTerminal:p,createTerminal:y}=H4();function g(){o(!0),window.setTimeout(()=>o(!1),2e3)}function _(){if(!f){g();return}l.current=!0,n(!0)}function w(){if(!f){g();return}l.current=!0,y()}function x(){if(!f){g();return}l.current=!0,i(!0)}function S(N){N.preventDefault(),g()}const k=m.jsxs(gt,{variant:"outline","data-slot":"create-session-trigger",className:Ye(e?"h-11 w-11 justify-center border-border px-0":"h-[46px] w-full justify-center gap-2 border-border px-3",!f&&"opacity-50 hover:bg-background"),"aria-label":"新建","aria-disabled":!f,onClick:f?void 0:S,children:[m.jsx(ZB,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),!e&&m.jsx("span",{className:"truncate",children:"新建"})]}),T=f?m.jsxs(uf,{children:[m.jsx(df,{asChild:!0,children:k}),m.jsxs(ff,{align:e?"end":"start",className:"w-80","data-slot":"create-session-type-menu",onCloseAutoFocus:N=>{l.current&&(l.current=!1,N.preventDefault())},children:[m.jsxs(ni,{className:"min-h-9 gap-2.5","data-slot":"create-agent-session-item",onSelect:_,children:[m.jsx(GB,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),"Agent 会话"]}),m.jsxs(ni,{className:"min-h-9 gap-2.5","data-slot":"create-terminal-session-item",disabled:p,onSelect:w,children:[m.jsx(Ep,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),p?"正在创建终端会话...":"终端会话"]}),m.jsx(Ld,{}),m.jsxs(ni,{className:"min-h-[3.75rem] items-start gap-2.5 py-2","data-slot":"create-frontend-preview-item",onSelect:x,children:[m.jsx(oC,{className:"mt-0.5 size-4 text-muted-foreground","aria-hidden":"true"}),m.jsxs("span",{className:"min-w-0 flex-1",children:[m.jsx("span",{className:"flex items-center gap-1.5 font-medium",children:"预览"}),m.jsx("span",{className:"mt-0.5 block text-xs leading-4 text-muted-foreground",children:"在浏览器中预览网页或设备模拟器"})]})]})]})]}):k;return m.jsxs(m.Fragment,{children:[f?T:m.jsxs(hf,{open:f?void 0:s,onOpenChange:f?void 0:o,children:[m.jsx(pf,{asChild:!0,children:T}),m.jsx(mf,{side:"top",children:d?"正在切换开发机":"请先连接开发机"})]}),m.jsx(Qh,{open:t,onOpenChange:n}),m.jsx(F4,{open:r,onOpenChange:i})]})}function Gde({open:e,creatingTerminal:t,onOpenChange:n,onCreateAgent:r,onCreateTerminal:i,onCreatePreview:s}){const o=b.useRef(!1);function l(u){o.current=!0,u()}return m.jsx(fu,{open:e,onOpenChange:n,children:m.jsxs(hu,{side:"bottom",overlayClassName:"bg-black/10 dark:bg-black/30",className:"inset-x-2 w-auto rounded-t-xl border border-border/80 bg-background px-3 pb-[max(theme(spacing.4),env(safe-area-inset-bottom))] pt-3 shadow-2xl","data-slot":"create-session-type-sheet",focusSurfaceOnOpen:!0,onCloseAutoFocus:u=>{o.current&&(o.current=!1,u.preventDefault())},children:[m.jsx(gf,{className:"px-1 pb-1 pt-0 text-left",children:m.jsx(pu,{children:"新建"})}),m.jsxs("div",{className:"grid gap-2 pb-1","data-slot":"create-session-type-options",children:[m.jsxs(gt,{type:"button",variant:"ghost",className:"min-h-12 justify-start gap-3 rounded-md px-3 text-left","data-slot":"create-agent-session-sheet-item",onClick:()=>l(r),children:[m.jsx(GB,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),"Agent 会话"]}),m.jsxs(gt,{type:"button",variant:"ghost",className:"min-h-12 justify-start gap-3 rounded-md px-3 text-left","data-slot":"create-terminal-session-sheet-item",disabled:t,onClick:()=>l(i),children:[m.jsx(Ep,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),t?"正在创建终端会话...":"终端会话"]}),m.jsx("div",{className:"mx-1 h-px bg-border","aria-hidden":"true"}),m.jsxs(gt,{type:"button",variant:"ghost",className:"min-h-16 justify-start gap-3 rounded-md px-3 text-left","data-slot":"create-frontend-preview-sheet-item",onClick:()=>l(s),children:[m.jsx(oC,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),m.jsxs("span",{className:"min-w-0",children:[m.jsx("span",{className:"flex items-center gap-1.5 font-medium",children:"预览"}),m.jsx("span",{className:"mt-0.5 block text-xs leading-4 text-muted-foreground",children:"在浏览器中预览网页或设备模拟器"})]})]})]})]})})}const Xde="0.9.3",Zde={version:Xde},Qde={playback:"playback",capture:"play-and-record"};function Jde(){return typeof navigator>"u"?null:navigator.audioSession??null}function efe(){return{setMode:()=>{},release:()=>{}}}class tfe{constructor(t=Jde){je(this,"leases",new Map);je(this,"session",null);je(this,"baselineType",null);je(this,"nextLeaseId",1);je(this,"nextOrder",1);this.getAudioSession=t}acquire(t){const n=this.getAudioSession();if(!n)return efe();this.leases.size===0&&(this.session=n,this.baselineType=n.type);const r=this.nextLeaseId++;this.leases.set(r,{mode:t,order:this.nextOrder++});try{this.applyActiveMode()}catch(s){throw this.leases.delete(r),this.leases.size===0?this.restoreWhenUnused():this.applyActiveModeBestEffort(),s}let i=!1;return{setMode:s=>{if(i)return;const o=this.leases.get(r);if(!o)return;const l={...o};o.mode=s,o.order=this.nextOrder++;try{this.applyActiveMode()}catch(u){throw this.leases.set(r,l),this.applyActiveModeBestEffort(),u}},release:()=>{if(!i){if(i=!0,this.leases.delete(r),this.leases.size===0){this.restoreWhenUnused();return}this.applyActiveModeBestEffort()}}}}applyActiveMode(){const t=[...this.leases.values()].reduce((n,r)=>!n||r.order>n.order?r:n,null);!t||!this.session||this.setNativeType(Qde[t.mode])}applyActiveModeBestEffort(){try{this.applyActiveMode()}catch{}}restoreWhenUnused(){const t=this.session,n=this.baselineType;if(this.session=null,this.baselineType=null,!(!t||n===null))try{t.type=n}catch{}}setNativeType(t){if(!(!this.session||this.session.type===t)){try{this.session.type=t}catch{throw new Error("浏览器无法切换语音音频模式")}if(this.session.type!==t)throw new Error("浏览器无法切换语音音频模式")}}}const hk=new tfe,m1=64,J2=-60,U4=32;function eI(e){if(!Number.isFinite(e)||e===0)return 0;const t=Math.min(1,Math.abs(e)),n=20*Math.log10(t),r=Math.max(0,Math.min(1,(n-J2)/-J2));return e<0?-r:r}function tI(e,t=8){const n=Math.floor(e.byteLength/2);if(n===0||!Number.isFinite(t)||t<=0)return[];const r=Math.min(n,Math.max(1,Math.floor(t))),i=new DataView(e.buffer,e.byteOffset,e.byteLength),s=[];for(let o=0;o<r;o+=1){const l=Math.floor(o*n/r),u=Math.max(l+1,Math.floor((o+1)*n/r));let d=1,f=-1;for(let p=l;p<u;p+=1){const y=i.getInt16(p*2,!0)/32768;d=Math.min(d,y),f=Math.max(f,y)}s.push({min:d,max:f})}return s}function nfe(e){const t=new DataView(e.buffer,e.byteOffset,e.byteLength),n=Math.floor(e.byteLength/2),r=new Float32Array(n);for(let i=0;i<n;i+=1)r[i]=t.getInt16(i*2,!0)/32768;return r}function rfe(e){if(e.length===0)return 0;const t=Math.max(1,Math.floor(e.length/512));let n=0,r=0;for(let i=0;i<e.length;i+=t){const s=e[i]??0;n+=s*s,r+=1}return r===0?0:Math.min(1,Math.sqrt(n/r)*10)}class W4{constructor(t,n=24e3,r={}){je(this,"nextStartTime",0);je(this,"activityEndToken",0);je(this,"timelineTimers",new Set);this.context=t,this.sampleRate=n,this.options=r}async resume(){this.emitPlaybackEvent("resume-start");try{if(this.context.state!=="running"&&this.context.state!=="closed"&&await this.context.resume(),this.context.state!=="running")throw new Error("浏览器未允许播放 Voice Pilot 提示音");this.emitPlaybackEvent("resume-finished")}catch(t){throw this.emitPlaybackEvent("resume-failed",{error:t instanceof Error?t.message:String(t)}),t}}enqueue(t){this.context.state==="suspended"&&this.resume().catch(()=>{});const n=nfe(t),r=this.context.createBuffer(1,n.length,this.sampleRate);r.getChannelData(0).set(n);const i=this.context.createBufferSource();i.buffer=r,i.connect(this.context.destination);const s=Math.max(this.context.currentTime,this.nextStartTime);i.start(s);const o=s+r.duration;this.nextStartTime=o,this.schedulePlaybackFrames(t,n,s,o);const l=Math.max(0,(o-this.context.currentTime)*1e3);return this.emitPlaybackEvent("pcm-scheduled",{bytes:t.byteLength,durationMs:r.duration*1e3}),typeof i.addEventListener=="function"&&i.addEventListener("ended",()=>{this.emitPlaybackEvent("source-ended",{bytes:t.byteLength,durationMs:r.duration*1e3})},{once:!0}),l}stop(){var t,n;this.nextStartTime=this.context.currentTime,this.activityEndToken+=1;for(const r of this.timelineTimers)clearTimeout(r);this.timelineTimers.clear(),(n=(t=this.options).onActivityLevel)==null||n.call(t,0),this.emitPlaybackEvent("stopped")}snapshot(){const t=this.context.currentTime;return{contextState:String(this.context.state??"unknown"),contextTime:t,nextStartTime:this.nextStartTime,queuedMs:Math.max(0,(this.nextStartTime-t)*1e3)}}schedulePlaybackFrames(t,n,r,i){if(!this.options.onActivityLevel&&!this.options.onPlaybackChunk)return;const s=Math.max(1,Math.round(this.sampleRate*U4/1e3)),o=this.activityEndToken+=1;for(let l=0;l<n.length;l+=s){const u=Math.min(n.length,l+s),d=r+l/this.sampleRate,f=Math.max(0,(d-this.context.currentTime)*1e3),p=t.slice(l*Int16Array.BYTES_PER_ELEMENT,u*Int16Array.BYTES_PER_ELEMENT),y=rfe(n.subarray(l,u));this.scheduleTimer(()=>{var g,_,w,x;(_=(g=this.options).onActivityLevel)==null||_.call(g,y),(x=(w=this.options).onPlaybackChunk)==null||x.call(w,p)},f)}if(this.options.onActivityLevel){const l=Math.max(0,(i-this.context.currentTime)*1e3);this.scheduleTimer(()=>{var u,d;o===this.activityEndToken&&((d=(u=this.options).onActivityLevel)==null||d.call(u,0))},l)}}scheduleTimer(t,n){const r=setTimeout(()=>{this.timelineTimers.delete(r),t()},n);this.timelineTimers.add(r)}emitPlaybackEvent(t,n={}){var r,i;(i=(r=this.options).onPlaybackEvent)==null||i.call(r,{event:t,...this.snapshot(),...n})}}const s0={provider:"aliyun-bailian",configured:!1,region:"cn",asrModel:"qwen3-asr-flash-realtime",ttsModel:"cosyvoice-v3-flash",ttsVoice:"longanyang",turnIdleSeconds:3},nI="min-h-11 min-w-0 rounded-md border border-border bg-input px-3 text-base outline-none transition-colors placeholder:text-muted-foreground/65 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring md:h-9 md:min-h-0 md:text-sm",ife=800,rI=300,sfe=1600;function g1(e,t){return e.filter(n=>!n.model||n.model===t)}function iI({label:e,children:t,help:n}){return m.jsxs("div",{className:"block min-w-0 rounded-lg border border-border/75 bg-card/55 p-3.5 transition-colors focus-within:border-ring/55 focus-within:bg-card/75 sm:p-3",children:[m.jsx("span",{className:"block text-[13px] font-medium leading-none text-muted-foreground",children:e}),m.jsx("div",{className:"mt-2 min-w-0",children:t}),n?m.jsx("span",{className:"mt-2 block text-xs leading-relaxed text-muted-foreground",children:n}):null]})}function sv({label:e,value:t,options:n,onChange:r,placeholder:i="请选择",help:s}){const[o,l]=b.useState(!1),u=b.useId(),d=n.find(g=>g.value===t),f=(d==null?void 0:d.label)??(t||i),p=n.filter(g=>!g.disabled),y=!!q4(f).detail;return m.jsxs("div",{className:"min-w-0 rounded-lg border border-border/75 bg-card/55 p-3.5 sm:p-3",onBlur:g=>{g.currentTarget.contains(g.relatedTarget)||l(!1)},children:[m.jsx("div",{id:u,className:"text-[13px] font-medium leading-none text-muted-foreground",children:e}),m.jsxs("button",{type:"button","aria-labelledby":u,"aria-haspopup":"listbox","aria-expanded":o,disabled:p.length===0,className:`mt-2 flex w-full min-w-0 items-center justify-between gap-3 rounded-md border border-border bg-input px-3 text-left outline-none transition-colors hover:border-primary/40 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-60 ${y?"min-h-[60px] py-2":"min-h-11"}`,onClick:()=>l(g=>!g),"data-slot":"voice-settings-choice-trigger",children:[m.jsx(sI,{label:f,muted:!d&&!t}),m.jsx(Ql,{className:`size-4 shrink-0 text-muted-foreground transition-transform ${o?"rotate-180":""}`,"aria-hidden":"true"})]}),o?m.jsx("div",{role:"listbox","aria-labelledby":u,className:"mt-2 max-h-64 overflow-y-auto rounded-md border border-border/80 bg-popover p-1 shadow-sm",children:n.map(g=>{const _=g.value===t;return m.jsxs("button",{type:"button",role:"option","aria-label":g.label,"aria-selected":_,disabled:g.disabled,className:"flex w-full min-w-0 items-center gap-2 rounded-sm px-2.5 py-2.5 text-left text-sm outline-none transition-colors hover:bg-accent focus-visible:bg-accent disabled:cursor-not-allowed disabled:opacity-45",onClick:()=>{g.disabled||(r(g.value),l(!1))},children:[m.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center text-primary",children:_?m.jsx(Co,{className:"size-4","aria-hidden":"true"}):null}),m.jsx(sI,{label:g.label})]},g.value)})}):null,s?m.jsx("div",{className:"mt-2 text-xs leading-relaxed text-muted-foreground",children:s}):null]})}function sI({label:e,muted:t=!1}){const n=q4(e);return m.jsxs("span",{className:"min-w-0 flex-1",children:[m.jsx("span",{className:`block truncate text-base leading-6 md:text-sm ${t?"text-muted-foreground":"text-foreground"}`,children:n.title}),n.detail?m.jsx("span",{className:"mt-0.5 block truncate text-xs leading-4 text-muted-foreground",children:n.detail}):null]})}function ofe({scrollRef:e}={}){const[t,n]=b.useState(s0),[r,i]=b.useState(String(s0.turnIdleSeconds)),[s,o]=b.useState(()=>Wg()),[l,u]=b.useState(""),[d,f]=b.useState(!1),[p,y]=b.useState(!1),[g,_]=b.useState({kind:"idle"}),w=b.useRef(null),x=b.useRef(null),S=b.useRef(null),k=b.useRef(null),T=b.useRef(null),N=b.useRef(!1);b.useEffect(()=>{const Z=Ft;if(!Z){_({kind:"error",message:"请先连接 Relay 服务器"});return}let ae=!1;return _({kind:"loading"}),Z.requestVoiceConfig().then(le=>{if(!ae){if(le.error||!le.config){_({kind:"error",message:le.error??"读取语音设置失败"});return}n(le.config),i(String(le.config.turnIdleSeconds)),u(""),f(!1),y(!0),_({kind:"idle"})}}).catch(le=>{ae||_({kind:"error",message:le instanceof Error?le.message:"读取语音设置失败"})}),()=>{ae=!0}},[]),b.useEffect(()=>{const Z=Ft;if(!Z||!p)return;let ae=!1;return Z.requestVoiceCapabilities({region:t.region}).then(le=>{if(!ae){if(le.error||!le.capabilities){o(Wg());return}o(le.capabilities)}}).catch(()=>{ae||o(Wg())}),()=>{ae=!0}},[t.region,p]),b.useEffect(()=>(N.current=!0,()=>{N.current=!1,$(),re()}),[]);const P=b.useMemo(()=>g.kind==="loading"?"读取中...":g.kind==="saving"?"保存中...":g.kind==="testing"?"正在测试语音合成":g.kind==="playingTest"?"正在播放测试音频":g.kind==="testPassed"?"测试通过":g.kind==="saved"?"已保存":g.kind==="error"?g.message:null,[g]),R=g.kind==="saving"||g.kind==="loading"||g.kind==="testing"||g.kind==="playingTest",M=b.useMemo(()=>g1(s.ttsVoices,t.ttsModel),[s.ttsVoices,t.ttsModel]),X=M.some(Z=>Z.value===t.ttsVoice)?t.ttsVoice:"",U=M.length===0?"当前模型暂无可用音色":X?null:"请选择可用音色",V=b.useMemo(()=>ufe(r),[r]),j=V?null:"请输入正整数秒数",A=U??j,D=R||!!A,O=b.useMemo(()=>[{value:"cn",label:"中国大陆"},{value:"intl",label:"国际"}],[]),I=b.useMemo(()=>lI(s.asrModels,t.asrModel),[s.asrModels,t.asrModel]),B=b.useMemo(()=>dfe(s.ttsModels,s.ttsVoices,t.ttsModel),[s.ttsModels,s.ttsVoices,t.ttsModel]),F=b.useMemo(()=>lI(M,X),[M,X]);function Y(){return{...d?{clearApiKey:!0}:{},...!d&&l.trim()?{apiKey:l.trim()}:{},region:t.region,asrModel:t.asrModel.trim(),ttsModel:t.ttsModel.trim(),ttsVoice:t.ttsVoice.trim(),turnIdleSeconds:V??s0.turnIdleSeconds}}async function z(){if(R)return;if(A){_({kind:"error",message:A});return}const Z=Ft;if(!Z){_({kind:"error",message:"请先连接 Relay 服务器"});return}const ae=Y();re(),_({kind:"saving"});const le=performance.now();try{const me=await Z.updateVoiceConfig(ae);if(!N.current)return;const ke=performance.now()-le;if(ke<rI&&await cfe(rI-ke),!N.current)return;if(!me.success||me.error||!me.config){_({kind:"error",message:me.error??"保存语音设置失败"});return}n(me.config),i(String(me.config.turnIdleSeconds)),u(""),f(!1),_({kind:"saved"}),T.current=setTimeout(()=>{T.current=null,_($e=>$e.kind==="saved"?{kind:"idle"}:$e)},sfe),Z.requestVoiceCapabilities({region:me.config.region}).then($e=>{N.current&&$e.capabilities&&o($e.capabilities)}).catch(()=>{N.current&&o(Wg())})}catch(me){if(!N.current)return;_({kind:"error",message:me instanceof Error?me.message:"保存语音设置失败"})}}async function q(){if(R)return;if(A){_({kind:"error",message:A});return}const Z=Ft;if(!Z){_({kind:"error",message:"请先连接 Relay 服务器"});return}let ae;try{ae=K()}catch(le){_({kind:"error",message:aI(le)});return}_({kind:"testing"});try{const[le]=await Promise.all([Z.testVoiceConfig(Y()),ae.ready]);if(!le.success||le.error){$(),_({kind:"error",message:le.error??"语音配置测试失败"});return}const me=await Q(le,ae.context);_({kind:"playingTest",transcript:le.transcript}),k.current=setTimeout(()=>{k.current=null,$(),_({kind:"testPassed",transcript:le.transcript})},me)}catch(le){$(),_({kind:"error",message:aI(le)})}}function K(){$();const Z=hk.acquire("playback");x.current=Z;try{const ae=lfe();return w.current=ae,{context:ae,ready:oI(ae)}}catch(ae){throw Z.release(),x.current=null,ae}}function $(){var Z,ae,le;k.current&&(clearTimeout(k.current),k.current=null),(Z=S.current)==null||Z.stop(),S.current=null,(ae=w.current)==null||ae.close(),w.current=null,(le=x.current)==null||le.release(),x.current=null}function re(){T.current&&(clearTimeout(T.current),T.current=null)}async function Q(Z,ae){if(!Z.audioBase64)throw new Error("语音测试未返回可播放音频");if(Z.audioEncoding&&Z.audioEncoding!=="pcm_s16le")throw new Error("测试音频格式暂不支持");const le=Z.audioSampleRate??24e3,me=afe(Z.audioBase64);if(me.byteLength===0||me.byteLength%2!==0)throw new Error("测试音频数据无效");await oI(ae);const ke=new W4(ae,le);S.current=ke,ke.enqueue(me);const $e=Math.ceil(me.byteLength/2/le*1e3);return Math.max(ife,$e)}function G(Z){var ae;return((ae=g1(s.ttsVoices,Z)[0])==null?void 0:ae.value)??""}return m.jsxs("form",{className:"flex min-h-0 min-w-0 flex-1 flex-col","data-slot":"voice-settings-panel",autoComplete:"off",onSubmit:Z=>{Z.preventDefault(),z()},children:[m.jsx("div",{className:"flex min-h-0 flex-1 flex-col px-4 py-3 sm:px-5 sm:py-3.5","data-slot":"voice-settings-body-frame",children:m.jsx("div",{className:"dev-render-scroll min-h-0 flex-1 overflow-y-auto overscroll-contain pr-4 sm:pr-1","data-slot":"voice-settings-scroll",ref:e,children:m.jsxs("div",{className:"space-y-3","data-slot":"voice-settings-fields",children:[m.jsx("div",{className:"grid gap-2 rounded-lg border border-border/75 bg-card/55 p-3.5 sm:p-3",children:m.jsxs("div",{className:"flex items-center justify-between gap-3",children:[m.jsxs("div",{className:"min-w-0",children:[m.jsx("div",{className:"text-[13px] font-medium leading-none text-muted-foreground",children:"服务商"}),m.jsx("div",{className:"mt-2 truncate text-base font-medium text-foreground md:text-sm",children:"阿里云百炼"})]}),m.jsx("span",{className:"shrink-0 rounded-full border border-primary/35 bg-primary/10 px-2.5 py-1 text-xs font-medium text-primary",children:"Bailian"})]})}),m.jsx(iI,{label:"阿里云百炼 API Key",help:d?"保存后会清空已保存的 key":null,children:m.jsxs("div",{className:"flex min-w-0 gap-2",children:[m.jsxs("div",{className:"relative min-w-0 flex-1",children:[m.jsx(tz,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":"true"}),m.jsx("input",{"aria-label":"阿里云百炼 API Key",type:"password",name:"dev-anywhere-bailian-api-key",autoComplete:"off",value:l,onChange:Z=>{u(Z.target.value),f(!1)},placeholder:d?"保存后清空":t.configured?"••••••••••••••••":"输入 API Key",className:`${nI} w-full pl-9`})]}),t.configured&&m.jsxs(gt,{type:"button",variant:"outline",className:"min-h-11 shrink-0 px-3 md:h-9 md:min-h-0",onClick:()=>{u(""),f(!0)},children:[m.jsx(az,{className:"size-4","aria-hidden":"true"}),"清空"]})]})}),m.jsx(sv,{label:"地域",value:t.region,options:O,onChange:Z=>n(ae=>({...ae,region:Z==="intl"?"intl":"cn"}))}),m.jsx(sv,{label:"语音识别模型",value:t.asrModel,options:I,onChange:Z=>n(ae=>({...ae,asrModel:Z}))}),m.jsx(sv,{label:"语音合成模型",value:t.ttsModel,options:B,onChange:Z=>n(ae=>({...ae,ttsModel:Z,ttsVoice:G(Z)}))}),m.jsx(sv,{label:"语音音色",value:X,options:F,placeholder:M.length===0?"暂无可用音色":"请选择音色",onChange:Z=>n(ae=>({...ae,ttsVoice:Z})),help:U}),m.jsx(iI,{label:"结束停顿时间(秒)",help:j,children:m.jsx("input",{"aria-label":"结束停顿时间(秒)",type:"number",min:1,step:1,inputMode:"numeric",value:r,onChange:Z=>i(Z.target.value),className:`${nI} w-full`})})]})})}),m.jsxs("div",{className:"bg-background/95 px-4 pb-3.5 pt-0 backdrop-blur sm:px-5","data-slot":"voice-settings-footer",children:[m.jsx("div",{className:"mr-4 border-t border-border/70","data-slot":"voice-settings-footer-divider"}),m.jsxs("div",{className:"mt-3.5 flex items-center justify-end gap-2",children:[P?m.jsx("div",{role:g.kind==="error"?"alert":"status","aria-live":"polite",className:g.kind==="error"?"min-w-0 flex-1 text-sm text-destructive":"min-w-0 flex-1 text-sm text-muted-foreground",children:P}):null,m.jsxs(gt,{type:"button",variant:"outline",disabled:D,onClick:()=>void q(),children:[m.jsx(iz,{className:"size-4","aria-hidden":"true"}),"测试"]}),m.jsxs(gt,{type:"submit",disabled:D,children:[m.jsx(_Y,{className:"size-4","aria-hidden":"true"}),g.kind==="saving"?"保存中...":"保存"]})]})]})]})}function afe(e){const t=window.atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r+=1)n[r]=t.charCodeAt(r);return n}function lfe(){const e=window,t=e.AudioContext??e.webkitAudioContext;if(!t)throw new Error("当前浏览器不支持音频播放");return new t}async function oI(e){if(e.state!=="running")try{await e.resume()}catch{throw new Error("浏览器阻止了测试音频播放,请再次点击测试")}if(e.state!=="running")throw new Error("浏览器阻止了测试音频播放,请再次点击测试")}function aI(e){return e instanceof Error?e.message:"语音配置测试失败"}function cfe(e){return new Promise(t=>setTimeout(t,e))}function ufe(e){const t=e.trim();if(!/^[1-9]\d*$/.test(t))return null;const n=Number(t);return Number.isSafeInteger(n)?n:null}function lI(e,t){const n=e.map(r=>({value:r.value,label:V4(r)}));return!t||n.some(r=>r.value===t)?n:[{value:t,label:t},...n]}function dfe(e,t,n){const r=e.map(i=>{const s=g1(t,i.value).length===0;return{value:i.value,label:`${V4(i)}${s?" · 暂无音色":""}`,disabled:s}});return!n||r.some(i=>i.value===n)?r:[{value:n,label:`${n} · 暂无音色`,disabled:!0},...r]}function q4(e){const t=e.split(" · ").map(n=>n.trim()).filter(Boolean);return t.length<=1?{title:e,detail:null}:{title:t[0],detail:t.slice(1).join(" · ")}}function V4(e){if(!e.age)return e.label;const t=`年龄 ${e.age}`;if(e.label.includes(t))return e.label;const n=` · ${e.age}`;return e.label.endsWith(n)?`${e.label.slice(0,-n.length)} · ${t}`:`${e.label} · ${t}`}const ffe=[{value:"auto",label:"跟随系统"},{value:"light",label:"浅色"},{value:"dark",label:"深色"}],hfe=[{value:"auto",label:"自动"},{value:"touch",label:"触控优先"},{value:"hardware",label:"实体键盘优先"}],pk="dev-render-scroll min-h-0 space-y-3 overflow-y-auto overscroll-contain pr-4 sm:pr-1";function Y4(e){if(!Number.isFinite(e)||e<0)return"未知";if(e<60)return`${Math.floor(e)} 秒`;const t=Math.floor(e/60);if(t<60)return`${t} 分钟`;const n=Math.floor(t/60),r=t%60;if(n<24)return r>0?`${n} 小时 ${r} 分钟`:`${n} 小时`;const i=Math.floor(n/24),s=n%24;return s>0?`${i} 天 ${s} 小时`:`${i} 天`}function pfe(e){const t=e||window.location.origin;return new URL("/health",t).toString()}function mfe(e){return e==="version"?"版本":e==="relay-token"?"Relay Token":e==="clients"?"客户端管理":"设置 Voice Pilot"}function gfe(e){return e==="version"?"Web 与 Relay 服务器版本。":e==="relay-token"?"连接受保护的 Relay 服务器,保存后立即重连。":e==="clients"?"管理当前连接的 Web 客户端。":"连接语音服务后,即可以语音交互的形式驱动会话。"}function v1({open:e,onOpenChange:t}){const n=Ie(V=>V.relayUrl),r=Ie(V=>V.latencyMonitorEnabled),i=Ie(V=>V.setLatencyMonitorEnabled),s=Ie(V=>V.sessionIdleNotificationsEnabled),o=Ie(V=>V.setSessionIdleNotificationsEnabled),l=Ie(V=>V.inputModePreference),u=Ie(V=>V.setInputModePreference),d=Ie(V=>V.themePreference),f=Ie(V=>V.setThemePreference),p=Ie(V=>V.ptyScrollTraceEnabled),y=Ie(V=>V.setPtyScrollTraceEnabled),[g,_]=b.useState("menu"),[w,x]=b.useState(e),[S,k]=b.useState({kind:"idle"}),T=b.useRef(null),N=b.useRef(null),P=qie(),R=b.useMemo(()=>rf().osName==="iPad",[]);e!==w&&(x(e),e&&_("menu"));const M=b.useCallback(async V=>{if(!V){o(!1);return}const j=await gie();if(j==="granted"){o(!0);return}if(j==="denied"){We.error("浏览器未授予通知权限,请在浏览器设置中允许通知");return}if(j==="default"){We.info("未授予通知权限,会话通知保持关闭");return}We.error("当前浏览器不支持系统通知")},[o]),L=b.useCallback(async V=>{k({kind:"loading"});try{const j=await fetch(pfe(n),{cache:"no-store",signal:V});if(!j.ok)throw new Error(`HTTP ${j.status}`);const A=await j.json();if(A.status!=="ok")throw new Error("状态异常");k({kind:"ready",version:A.version??"未知",uptime:A.uptime??0})}catch(j){if(j instanceof DOMException&&j.name==="AbortError")return;k({kind:"error",message:j instanceof Error?"当前 Relay 服务器无法读取版本":"读取失败"})}},[n]);b.useEffect(()=>{if(!e||g!=="version")return;const V=new AbortController;return L(V.signal),()=>V.abort()},[L,e,g]),b.useEffect(()=>{if(!e||g!=="voice")return;const V=window.requestAnimationFrame(()=>{var j;(j=T.current)==null||j.focus({preventScroll:!0}),N.current&&(N.current.scrollTop=0)});return()=>window.cancelAnimationFrame(V)},[e,g]);const X=S.kind==="ready"?S.version:S.kind==="loading"?"读取中...":S.kind==="error"?"读取失败":"未读取",U=S.kind==="ready"?`运行 ${Y4(S.uptime)}`:S.kind==="error"?S.message:"从当前 Relay 服务器 /health 读取";return m.jsx(ss,{open:e,onOpenChange:t,children:m.jsxs(os,{className:Ye("grid max-h-[calc(100dvh-1rem)] grid-rows-[auto_minmax(0,1fr)] overflow-hidden p-4 sm:max-w-[440px] sm:p-6",g==="voice"&&"max-h-[min(760px,calc(100dvh-1rem))] !gap-0 !p-0 sm:max-w-[480px]",g==="voice"&&"max-sm:top-auto max-sm:bottom-0 max-sm:left-2 max-sm:right-2 max-sm:h-[calc(100dvh-1rem)] max-sm:w-auto max-sm:max-h-none max-sm:max-w-none max-sm:translate-x-0 max-sm:translate-y-0 max-sm:rounded-b-none max-sm:rounded-t-2xl max-sm:border-x max-sm:border-b-0"),"data-slot":"settings-dialog","data-view":g,focusSurfaceOnOpen:!0,ref:T,showCloseButton:g==="menu",children:[m.jsx(as,{className:Ye(g==="menu"&&"pr-12 text-left",g!=="menu"&&"text-left",g==="voice"&&"gap-0 px-4 pb-0 pt-3.5 text-left sm:px-5 sm:pt-4"),children:g!=="menu"?m.jsxs(m.Fragment,{children:[m.jsxs("div",{className:"flex items-start gap-2",children:[m.jsx(gt,{type:"button",variant:"ghost",size:"icon",className:"-ml-2 mt-0.5 size-11 sm:size-9","aria-label":"返回设置","data-slot":"voice-settings-back",onClick:()=>_("menu"),children:m.jsx(Qp,{className:"size-4","aria-hidden":"true"})}),m.jsxs("div",{className:"min-w-0 space-y-1.5 pt-0.5 text-left",children:[m.jsx(Yi,{children:mfe(g)}),m.jsx(_s,{className:"max-w-[28rem] leading-5",children:gfe(g)})]})]}),g==="voice"?m.jsx("div",{className:"mr-4 mt-3.5 border-t border-border/70","data-slot":"voice-settings-header-divider"}):null]}):m.jsxs(m.Fragment,{children:[m.jsx(Yi,{children:"设置"}),m.jsx(_s,{children:"连接、外观、通知和高级诊断选项。"})]})}),g==="version"?m.jsx(vfe,{relayVersion:X,relayDetail:U,relayMuted:S.kind==="error"}):g==="relay-token"?m.jsx(bfe,{saved:P}):g==="clients"?m.jsx(Efe,{}):g==="voice"?m.jsx(ofe,{scrollRef:N}):m.jsx(yfe,{relayTokenSaved:P,themePreference:d,onThemePreferenceChange:f,inputModePreference:l,onInputModePreferenceChange:u,showInputModeSetting:R,sessionIdleNotificationsEnabled:s,onSessionIdleNotificationsEnabledChange:M,ptyScrollTraceEnabled:p,onPtyScrollTraceEnabledChange:y,latencyMonitorEnabled:r,onLatencyMonitorEnabledChange:i,onOpenVoice:()=>_("voice"),onOpenRelayToken:()=>_("relay-token"),onOpenClients:()=>_("clients"),onOpenVersion:()=>_("version")})]})})}function vfe({relayVersion:e,relayDetail:t,relayMuted:n}){return m.jsxs("div",{className:pk,"data-slot":"settings-dialog-body",children:[m.jsx(uI,{icon:m.jsx(rz,{className:"size-4","aria-hidden":"true"}),label:"Web",value:Zde.version,detail:"当前浏览器加载的版本"}),m.jsx(uI,{icon:m.jsx(sz,{className:"size-4","aria-hidden":"true"}),label:"Relay 服务器",value:e,detail:t,muted:n})]})}function yfe({relayTokenSaved:e,themePreference:t,onThemePreferenceChange:n,inputModePreference:r,onInputModePreferenceChange:i,showInputModeSetting:s,sessionIdleNotificationsEnabled:o,onSessionIdleNotificationsEnabledChange:l,ptyScrollTraceEnabled:u,onPtyScrollTraceEnabledChange:d,latencyMonitorEnabled:f,onLatencyMonitorEnabledChange:p,onOpenVoice:y,onOpenRelayToken:g,onOpenClients:_,onOpenVersion:w}){return m.jsxs("div",{className:"dev-render-scroll min-h-0 space-y-4 overflow-y-auto overscroll-contain pr-4 sm:pr-1","data-slot":"settings-dialog-body",children:[m.jsxs(td,{title:"服务",children:[m.jsx(ov,{icon:m.jsx(K7,{className:"size-4","aria-hidden":"true"}),label:"Voice Pilot",detail:"用语音输入、听取回复和处理审批",onClick:y}),m.jsx(ov,{icon:m.jsx(tz,{className:"size-4","aria-hidden":"true"}),label:"Relay Token",detail:`${e?"已保存":"未设置"} · 受保护的 Relay 服务器`,onClick:g}),m.jsx(ov,{icon:m.jsx(HY,{className:"size-4","aria-hidden":"true"}),label:"客户端管理",detail:"已连接的浏览器页面和设备",onClick:_})]}),m.jsx(td,{title:"外观",children:m.jsx(cI,{icon:m.jsx(MY,{className:"size-4","aria-hidden":"true"}),label:"主题",value:t,options:ffe,onValueChange:n})}),m.jsx(td,{title:"通知",children:m.jsx(a0,{icon:m.jsx(X7,{className:"size-4","aria-hidden":"true"}),label:"会话空闲通知",detail:"会话从工作中转为空闲时发送浏览器通知",checked:o,onCheckedChange:l})}),s?m.jsx(td,{title:"交互",children:m.jsx(cI,{icon:m.jsx(nz,{className:"size-4","aria-hidden":"true"}),label:"输入方式",detail:"默认自动识别软键盘和实体键盘;必要时可强制一种方式",value:r,options:hfe,onValueChange:i})}):null,m.jsxs(td,{title:"高级诊断",children:[m.jsx(a0,{icon:m.jsx(Ep,{className:"size-4","aria-hidden":"true"}),label:"PTY 滚动追踪",detail:"记录终端滚动和视口同步现场,方便复制诊断报告",checked:u,onCheckedChange:d}),m.jsx(a0,{icon:m.jsx(YB,{className:"size-4","aria-hidden":"true"}),label:"延迟监控",detail:"显示可拖动的连接延迟浮窗",checked:f,onCheckedChange:p})]}),m.jsx(td,{title:"关于",children:m.jsx(ov,{icon:m.jsx(sz,{className:"size-4","aria-hidden":"true"}),label:"版本",onClick:w})})]})}function td({title:e,children:t}){return m.jsxs("section",{className:"space-y-2","data-slot":"settings-section",children:[m.jsx("h3",{className:"px-1 text-xs font-medium text-muted-foreground",children:e}),m.jsx("div",{className:"overflow-hidden rounded-lg border border-border bg-card/55 divide-y divide-border/70",children:t})]})}function cI({icon:e,label:t,detail:n,value:r,options:i,onValueChange:s}){const o=b.useId(),l=b.useId();return m.jsxs("div",{className:"flex w-full items-start gap-3 px-3 py-3 text-left","data-slot":"settings-choice-item",children:[m.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-md bg-background/55 text-muted-foreground",children:e}),m.jsxs("div",{className:"min-w-0 flex-1",children:[m.jsx("div",{id:o,className:"text-sm font-medium text-foreground",children:t}),n?m.jsx("div",{id:l,className:"mt-1 text-xs text-muted-foreground",children:n}):null,m.jsx("div",{role:"radiogroup","aria-labelledby":o,"aria-describedby":n?l:void 0,className:"mt-3 grid grid-cols-3 gap-1 rounded-md border border-border bg-muted/70 p-1","data-slot":"settings-segmented-choice",children:i.map(u=>{const d=u.value===r;return m.jsx("button",{type:"button",role:"radio","aria-checked":d,className:Ye("min-w-0 whitespace-nowrap rounded px-2 py-1.5 text-xs font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",d?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:bg-background/55 hover:text-foreground"),onClick:()=>s(u.value),children:u.label},u.value)})})]})]})}function bfe({saved:e}){const t=b.useId(),n=b.useId(),[r,i]=b.useState(""),[s,o]=b.useState(null),l=()=>{Yj().catch(f=>{o(f instanceof Error?f.message:"Relay 重连失败。")})},u=()=>{const f=r.trim();if(!f){o("请输入 token。");return}if(!qj(f)){const p="Relay Token 保存失败,请检查浏览器存储权限。";o(p),We.error(p);return}o(null),We.success("Relay Token 已保存,正在重新连接"),l()},d=()=>{Vj(),l()};return m.jsxs("form",{className:pk,"data-slot":"settings-dialog-body",onSubmit:f=>{f.preventDefault(),u()},children:[m.jsxs("div",{className:"rounded-md border border-border bg-card/70 p-3","data-slot":"relay-token-card",children:[m.jsx("label",{htmlFor:t,className:"text-sm font-medium text-foreground",children:"Token"}),m.jsx("input",{id:t,type:"password",value:r,onChange:f=>{i(f.currentTarget.value),s&&o(null)},autoComplete:"off",spellCheck:!1,"aria-describedby":s?n:void 0,className:"mt-2 h-10 w-full rounded-md border border-border bg-background px-3 font-mono text-sm text-foreground outline-none transition-colors placeholder:text-muted-foreground focus:border-ring focus:ring-2 focus:ring-ring/75",placeholder:"粘贴 token"}),s?m.jsx("p",{id:n,className:"mt-2 text-xs text-destructive",children:s}):null]}),m.jsxs("div",{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",children:[e?m.jsx(gt,{type:"button",variant:"outline",onClick:d,children:"清空"}):null,m.jsx(gt,{type:"submit",disabled:!r.trim(),children:"保存"})]})]})}function _fe(e){return e.length<=16?e:`${e.slice(0,8)}...${e.slice(-4)}`}function wfe(e,t){var r;return((r=t.get(e))==null?void 0:r.trim())||_fe(e)}function xfe(e){return ane(e)}function Sfe(e){const t=Math.max(0,Math.floor((Date.now()-e)/1e3));return Y4(t)}function o0({label:e,value:t,title:n}){return m.jsxs("div",{className:"grid grid-cols-[3.75rem_minmax(0,1fr)] items-baseline gap-2 text-xs leading-5",children:[m.jsx("span",{className:"shrink-0 text-muted-foreground/80",children:e}),m.jsx("span",{className:"min-w-0 truncate text-muted-foreground",title:n??t,children:t})]})}function Efe(){const e=Ie(y=>y.proxies),[t,n]=b.useState([]),[r,i]=b.useState(!0),[s,o]=b.useState(null),[l,u]=b.useState(null),d=b.useMemo(()=>new Map(e.map(y=>[y.proxyId,y.name]).filter(y=>typeof y[1]=="string")),[e]),f=b.useCallback(async()=>{const y=Ft;if(!y){n([]),o("Relay 未连接。"),i(!1);return}i(!0),o(null);try{n(await y.requestRelayClients())}catch(g){o(g instanceof Error?g.message:"读取客户端列表失败。")}finally{i(!1)}},[]);b.useEffect(()=>{f()},[f]);const p=b.useCallback(async y=>{const g=Ft;if(!g){o("Relay 未连接。");return}u(y),o(null);try{const _=await g.kickRelayClient(y);if(!_.success){o(_.error??"断开客户端失败。");return}n(w=>w.filter(x=>x.clientId!==y))}catch(_){o(_ instanceof Error?_.message:"断开客户端失败。")}finally{u(null)}},[]);return m.jsxs("div",{className:pk,"data-slot":"settings-dialog-body",children:[m.jsxs("div",{className:"flex min-h-9 items-center gap-2","data-slot":"relay-clients-toolbar",children:[m.jsx("div",{className:"text-sm font-medium text-foreground",children:r?"正在读取客户端":`${t.length} 个在线客户端`}),m.jsx(gt,{type:"button",variant:"ghost",size:"icon-sm","aria-label":"刷新客户端列表",title:"刷新",onClick:()=>void f(),disabled:r,"data-slot":"relay-clients-refresh",children:m.jsx(em,{className:Ye("size-3.5",r&&"animate-spin"),"aria-hidden":"true"})})]}),s?m.jsx("div",{className:"rounded-md border border-destructive/35 bg-destructive/10 px-3 py-2 text-xs text-destructive",children:s}):null,!r&&t.length===0?m.jsx("div",{className:"rounded-md border border-border bg-card/70 px-3 py-6 text-center text-sm text-muted-foreground",children:"当前没有在线客户端"}):null,t.map(y=>{const g=y.current===!0,_=l===y.clientId;return m.jsx("div",{className:"rounded-md border border-border bg-card/70 p-3","data-slot":"relay-client-row","data-client-id":y.clientId,title:`客户端 ${y.clientId}`,children:m.jsxs("div",{className:"grid gap-3 sm:grid-cols-[minmax(0,1fr)_7.5rem] sm:items-start",children:[m.jsxs("div",{className:"min-w-0 space-y-1.5",children:[m.jsx("div",{className:"min-w-0",children:m.jsx("div",{className:"truncate text-sm font-medium leading-5 text-foreground",children:xfe(y)})}),m.jsxs("div",{className:"space-y-1",children:[m.jsx(o0,{label:"已连接",value:Sfe(y.connectedAt)}),y.proxyId?m.jsx(o0,{label:"连接到",value:wfe(y.proxyId,d),title:y.proxyId}):null,y.remoteAddress?m.jsx(o0,{label:"来源 IP",value:y.remoteAddress}):null]})]}),g?m.jsx("div",{className:"inline-flex h-9 w-full items-center justify-center rounded-md border border-primary/30 bg-primary/10 px-3 text-sm font-normal text-primary","aria-label":"当前设备","data-slot":"relay-client-current-indicator",children:"当前设备"}):m.jsxs(gt,{type:"button",variant:"outline",size:"sm",className:"h-9 w-full justify-center",disabled:_,onClick:()=>void p(y.clientId),"data-slot":"relay-client-action",children:[m.jsx(GV,{className:"size-3.5","aria-hidden":"true"}),_?"断开中...":"断开"]})]})},y.clientId)})]})}function a0({icon:e,label:t,detail:n,checked:r,onCheckedChange:i}){const s=b.useId(),o=b.useId();return m.jsxs("button",{type:"button",role:"switch",className:"group flex w-full items-center gap-3 px-3 py-3 text-left transition-colors hover:bg-accent/55 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",onClick:()=>i(!r),"aria-checked":r,"aria-labelledby":s,"aria-describedby":o,"data-slot":"settings-toggle-item",children:[m.jsx("div",{className:Ye("flex size-8 shrink-0 items-center justify-center rounded-md bg-background/55 transition-colors",r?"text-primary":"text-muted-foreground"),children:e}),m.jsxs("div",{className:"min-w-0 flex-1",children:[m.jsx("div",{id:s,className:"text-sm font-medium text-foreground",children:t}),m.jsx("div",{id:o,className:"mt-1 text-xs text-muted-foreground",children:n})]}),m.jsx("span",{className:Ye("relative h-6 w-11 shrink-0 rounded-full border transition-colors",r?"border-primary/65 bg-primary/70":"border-border bg-muted/50"),"aria-hidden":"true","data-slot":"settings-toggle-switch",children:m.jsx("span",{className:Ye("absolute top-1/2 size-4 -translate-y-1/2 rounded-full bg-background shadow-sm transition-transform",r?"translate-x-[1.35rem]":"translate-x-1")})})]})}function ov({icon:e,label:t,detail:n,onClick:r}){const i=b.useId(),s=b.useId();return m.jsxs("button",{type:"button",className:"group flex w-full items-center gap-3 px-3 py-3 text-left transition-colors hover:bg-accent/55 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset",onClick:r,"aria-labelledby":i,"aria-describedby":n?s:void 0,"data-slot":"settings-menu-item",children:[m.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-md bg-background/55 text-muted-foreground transition-colors group-hover:text-foreground",children:e}),m.jsxs("div",{className:"min-w-0 flex-1",children:[m.jsx("div",{id:i,className:"text-sm font-medium text-foreground",children:t}),n?m.jsx("div",{id:s,className:"mt-1 text-xs text-muted-foreground",children:n}):null]}),m.jsx(dp,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"})]})}function uI({icon:e,label:t,value:n,detail:r,muted:i=!1}){return m.jsxs("div",{className:"flex gap-3 rounded-md border border-border bg-card/70 p-3",children:[m.jsx("div",{className:Ye("mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-md border",i?"border-border text-muted-foreground":"border-primary/35 bg-primary/10 text-primary"),children:e}),m.jsxs("div",{className:"min-w-0 flex-1",children:[m.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[m.jsx("div",{className:"text-sm text-muted-foreground",children:t}),m.jsx("div",{className:"min-w-0 truncate font-mono text-sm text-foreground",children:n})]}),m.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:r})]})]})}const Cfe="xterm-helper-textarea";function kfe(e=document.activeElement){return!(e instanceof HTMLElement)||!e.classList.contains(Cfe)?!1:(e.blur(),!0)}function dI(e,t,n){if(!e||Math.abs(n)<1)return!1;let r=e instanceof Element?e:null;for(;r&&t.contains(r);){if(r instanceof HTMLElement&&Tfe(r,n))return!0;if(r===t)break;r=r.parentElement}return!1}function Tfe(e,t){if(e.scrollHeight<=e.clientHeight+1)return!1;const n=window.getComputedStyle(e).overflowY;return n!=="auto"&&n!=="scroll"&&n!=="overlay"?!1:t<0?e.scrollTop>0:e.scrollTop+e.clientHeight<e.scrollHeight-1}function Rfe({releasePtyFocus:e=!0,containVerticalScroll:t=!0}={}){const n=b.useRef(null),r=b.useCallback(()=>{e&&kfe()},[e]),i=b.useCallback(l=>{var u;n.current=((u=l.touches[0])==null?void 0:u.clientY)??null,r()},[r]),s=b.useCallback(l=>{if(!t)return;const u=l.touches[0];if(!u)return;const f=(n.current??u.clientY)-u.clientY;n.current=u.clientY,dI(l.target,l.currentTarget,f)||l.preventDefault()},[t]),o=b.useCallback(l=>{r(),t&&(dI(l.target,l.currentTarget,l.deltaY)||l.preventDefault())},[t,r]);return{onPointerDownCapture:r,onTouchStartCapture:i,onTouchMoveCapture:s,onWheelCapture:o}}function Afe({className:e}){const t=Ie(o=>o.sidebarCollapsed),n=Ie(o=>o.toggleSidebarCollapsed),[r,i]=b.useState(!1),s=Rfe();return t?m.jsxs(m.Fragment,{children:[m.jsxs("nav",{className:Ye("dev-sidebar-shell dev-sidebar-rail relative flex-col items-center w-12 shrink-0 bg-card border-r border-border overflow-hidden px-1.5 pb-[calc(var(--dev-safe-area-bottom,env(safe-area-inset-bottom))+0.5rem)] pt-[max(0.5rem,env(safe-area-inset-top))]",e),"aria-label":"侧边栏","data-slot":"sidebar-rail","data-collapsed":"true",...s,children:[m.jsx(hI,{collapsed:!0,onClick:n}),m.jsx("div",{className:"mt-3 h-px w-5 bg-border/70","aria-hidden":"true"}),m.jsxs("div",{className:"mt-auto flex flex-col gap-2",children:[m.jsx(fI,{compact:!0,tooltipSide:"right",onClick:()=>i(!0)}),m.jsx(Q2,{compact:!0})]})]}),m.jsx(v1,{open:r,onOpenChange:i})]}):m.jsxs(m.Fragment,{children:[m.jsxs("nav",{className:Ye("dev-sidebar-shell group/sidebar relative flex-col w-[280px] shrink-0 bg-card border-r border-border overflow-visible pt-[env(safe-area-inset-top)]",e),"aria-label":"侧边栏","data-slot":"sidebar","data-collapsed":"false",...s,children:[m.jsx("div",{className:"dev-sidebar-fade p-2.5","data-slot":"sidebar-proxy-switcher",children:m.jsxs("div",{className:"dev-sidebar-chrome rounded-lg border p-3",children:[m.jsxs("div",{className:"flex items-center justify-between gap-3",children:[m.jsx(Cz,{className:"text-[13px]",slot:"sidebar-brand"}),m.jsx(hI,{collapsed:!1,onClick:n})]}),m.jsx("div",{className:"mt-2.5",children:m.jsx(R4,{layout:"dropdown",variant:"sidebarChrome"})})]})}),m.jsx("div",{className:"dev-sidebar-fade flex min-h-0 flex-1 flex-col overflow-hidden","data-slot":"sidebar-session-list",children:m.jsx("div",{className:"flex-1 min-h-0",children:m.jsx($4,{layout:"sidebar"})})}),m.jsxs("div",{className:"dev-sidebar-fade flex shrink-0 gap-2 px-2 pb-[calc(var(--dev-safe-area-bottom,env(safe-area-inset-bottom))+0.5rem)] pt-2","data-slot":"sidebar-new-session",children:[m.jsx("div",{className:"min-w-0 flex-1",children:m.jsx(Q2,{})}),m.jsx("div",{className:"min-w-0 flex-1",children:m.jsx(fI,{onClick:()=>i(!0)})})]})]}),m.jsx(v1,{open:r,onOpenChange:i})]})}function fI({compact:e=!1,tooltipSide:t="top",onClick:n}){return m.jsxs(hf,{delayDuration:500,children:[m.jsx(pf,{asChild:!0,children:m.jsxs("button",{type:"button","aria-label":"设置","data-slot":"sidebar-settings-trigger",onClick:n,className:Ye("inline-flex items-center justify-center shrink-0 border text-muted-foreground outline-none transition-[color,background-color,border-color,box-shadow]","focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",e?"h-11 w-11 rounded-md border-border bg-card/70 hover:border-primary/60 hover:bg-accent hover:text-foreground":"h-[46px] w-full gap-2 rounded-md border-border bg-background hover:border-primary/50 hover:bg-accent hover:text-foreground"),children:[m.jsx(oz,{className:"size-4","aria-hidden":"true"}),!e&&m.jsx("span",{className:"truncate text-sm font-medium",children:"设置"})]})}),m.jsx(mf,{side:t,sideOffset:10,hideArrow:!0,className:"border border-border/80 bg-card/95 px-2.5 py-1 text-muted-foreground shadow-sm backdrop-blur",children:"设置"})]})}function hI({collapsed:e,onClick:t}){const n=e?"展开侧边栏":"收起侧边栏",r=e?oY:iY;return m.jsxs(hf,{delayDuration:500,children:[m.jsx(pf,{asChild:!0,children:m.jsx("button",{type:"button","aria-label":n,"data-slot":e?"sidebar-expand-trigger":"sidebar-collapse-trigger",onClick:t,className:Ye("group inline-flex items-center justify-center text-muted-foreground outline-none transition-[opacity,color,background-color,border-color,box-shadow,transform]","outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background",e?"h-9 w-9 rounded-md border border-border/80 bg-card/70 hover:border-primary/60 hover:bg-accent hover:text-foreground":"h-9 w-9 rounded-full border border-primary/25 bg-primary/10 hover:border-primary/60 hover:bg-primary/15 hover:text-foreground"),children:m.jsx(r,{className:Ye("size-3.5 transition-transform",e&&"group-hover:translate-x-0.5",!e&&"group-hover:-translate-x-0.5"),"aria-hidden":"true"})})}),m.jsx(mf,{side:e?"right":"top",sideOffset:10,hideArrow:!0,className:"border border-border/80 bg-card/95 px-2.5 py-1 text-muted-foreground shadow-sm backdrop-blur",children:n})]})}const Nfe=1500,Mfe=300,pI=70,mI=35;function K4({texts:e,className:t}){const[n,r]=b.useState(""),[i,s]=b.useState(!0),o=b.useRef("typing"),l=b.useRef(0),u=b.useRef(0);b.useEffect(()=>{const f=setInterval(()=>s(p=>!p),530);return()=>clearInterval(f)},[]),b.useEffect(()=>{let f;const p=()=>e[u.current%e.length],y=()=>{const g=o.current;if(g==="typing"){const _=p();l.current<_.length?(l.current+=1,r(_.slice(0,l.current)),f=setTimeout(y,pI)):(o.current="paused",f=setTimeout(y,Nfe))}else g==="paused"?(o.current="deleting",f=setTimeout(y,mI)):g==="deleting"?l.current>0?(l.current-=1,r(p().slice(0,l.current)),f=setTimeout(y,mI)):(u.current+=1,o.current="waiting",f=setTimeout(y,Mfe)):(o.current="typing",f=setTimeout(y,pI))};return f=setTimeout(y,500),()=>clearTimeout(f)},[e]);const d=n.startsWith("DEV")?3:n.length<=3&&"DEV".startsWith(n)?n.length:0;return m.jsxs("div",{className:`font-mono leading-tight select-none ${t??""}`,"data-slot":"brand-typewriter",children:[m.jsx("span",{className:"text-green-500",children:"> "}),m.jsx("span",{className:"text-primary","data-slot":"brand-typewriter-dev",children:n.slice(0,d)}),m.jsx("span",{className:"text-foreground/90",children:n.slice(d)}),m.jsx("span",{className:`text-primary ${i?"opacity-100":"opacity-0"}`,children:"_"})]})}const G4=["DEV Anywhere","/unlimited @anytime"];function Pfe({subtitle:e,action:t}){return m.jsx("section",{className:"dev-mobile-brand-hero border-b border-border/80 px-4 pb-5 pt-[calc(env(safe-area-inset-top)+1.25rem)] md:hidden","data-slot":"mobile-brand-hero","aria-label":"DEV Anywhere",children:m.jsxs("div",{className:"dev-mobile-brand-content min-w-0 space-y-3 pr-12",children:[m.jsx(K4,{texts:G4,className:"dev-mobile-brand-typewriter max-w-full overflow-hidden text-ellipsis whitespace-nowrap font-bold tracking-normal"}),e?m.jsx("p",{className:"dev-mobile-brand-subtitle max-w-[34rem] text-sm leading-5 text-muted-foreground",children:e}):null,t?m.jsx("div",{className:"dev-mobile-brand-action flex max-w-full min-w-0 pt-1",children:t}):null]})})}const Ife=3e3,Ofe=1e4,av=12,Lfe=4,gI={webRelay:"浏览器 ↔ Relay 服务器",relayProxy:"Relay 服务器 ↔ 开发机",webProxy:"浏览器 ↔ 开发机"},Dfe={webRelay:{state:"idle"},relayProxy:{state:"idle"},webProxy:{state:"idle"}};function l0(e){if(!e.success||e.rttMs===void 0)return{state:"unavailable",error:e.error??"不可用",updatedAt:Date.now()};const t=e.rttMs;return{state:t<=120?"ok":t<=300?"warn":"bad",rttMs:t,updatedAt:Date.now()}}function nd(e){return{state:"unavailable",error:e,updatedAt:Date.now()}}function tp(e){return e===void 0||!Number.isFinite(e)?"--":`${Math.max(0,Math.round(e))}ms`}function vI(e){switch(e){case"bad":return 4;case"unavailable":return 3;case"warn":return 2;case"measuring":return 1;default:return 0}}function X4(e){return e==="bad"||e==="unavailable"?"bad":e==="warn"?"warn":e==="ok"?"ok":"neutral"}function Bfe(e){switch(e){case"ok":return"border-emerald-500/35 bg-emerald-500/10 text-emerald-300";case"warn":return"border-amber-500/40 bg-amber-500/10 text-amber-300";case"bad":return"border-destructive/55 bg-destructive/10 text-destructive";default:return"border-border bg-card/90 text-muted-foreground"}}function zfe(e){return e.state==="measuring"?"检测中":e.state==="unavailable"?e.error??"不可用":e.rttMs!==void 0?tp(e.rttMs):"等待检测"}function jfe(){const e=Si("local",wn.latencyMonitorPosition);if(!e)return null;try{const t=JSON.parse(e);return!Number.isFinite(t.x)||!Number.isFinite(t.y)?null:{x:Number(t.x),y:Number(t.y)}}catch{return null}}function yI(e){Tr("local",wn.latencyMonitorPosition,JSON.stringify(e))}function Ffe(){var e,t;return{width:((e=window.visualViewport)==null?void 0:e.width)??window.innerWidth??document.documentElement.clientWidth??0,height:((t=window.visualViewport)==null?void 0:t.height)??window.innerHeight??document.documentElement.clientHeight??0}}function c0(e,t){const n=Ffe(),r=av,i=av,s=Math.max(r,n.width-t.width-av),o=Math.max(i,n.height-t.height-av);return{x:Math.min(s,Math.max(r,Math.round(e.x))),y:Math.min(o,Math.max(i,Math.round(e.y)))}}function $fe(){const e=Ie(R=>R.latencyMonitorEnabled),t=Ie(R=>R.connected),n=Ie(R=>R.proxyOnline),r=Ie(R=>R.selectedProxyId),[i,s]=b.useState(Dfe),[o,l]=b.useState(()=>jfe()),u=b.useRef(!1),d=b.useRef(null),f=b.useRef(null),p=b.useRef(!1),y=b.useMemo(()=>(Object.values(i).sort((R,M)=>vI(M.state)-vI(R.state))[0]??{state:"idle"}).state,[i]),g=X4(y);async function _(){if(u.current)return;const R=Ft;if(!R||!t){const U=nd("Relay 服务器未连接");s({webRelay:U,relayProxy:U,webProxy:U});return}u.current=!0,s(U=>({webRelay:{...U.webRelay,state:"measuring"},relayProxy:n?{...U.relayProxy,state:"measuring"}:nd("未连接开发机"),webProxy:n?{...U.webProxy,state:"measuring"}:nd("未连接开发机")}));const[M,L,X]=await Promise.allSettled([R.measureWebRelayLatency(),n?R.measureRelayProxyLatency():Promise.resolve({success:!1}),n?R.measureWebProxyLatency():Promise.resolve({success:!1})]);s({webRelay:M.status==="fulfilled"?l0(M.value):nd(M.reason instanceof Error?M.reason.message:"测速失败"),relayProxy:L.status==="fulfilled"?l0(L.value):nd(L.reason instanceof Error?L.reason.message:"测速失败"),webProxy:X.status==="fulfilled"?l0(X.value):nd(X.reason instanceof Error?X.reason.message:"测速失败")}),u.current=!1}if(b.useEffect(()=>{if(!e)return;let R=!1,M=null;const L=async()=>{await _(),!R&&(M=setTimeout(L,document.hidden?Ofe:Ife))};return L(),()=>{R=!0,u.current=!1,M&&clearTimeout(M)}},[e,t,n,r]),b.useEffect(()=>{if(!e||!o)return;const R=d.current;if(!R)return;const M=R.getBoundingClientRect(),L=c0(o,{width:M.width,height:M.height});L.x===o.x&&L.y===o.y||(l(L),yI(L))},[e,o]),!e)return null;const w=i.webProxy.rttMs!==void 0?i.webProxy:i.relayProxy,x=o!==null?{left:`${o.x}px`,top:`${o.y}px`}:void 0;function S(R){var L,X;if(R.button!==0)return;const M=R.currentTarget.getBoundingClientRect();f.current={pointerId:R.pointerId,startX:R.clientX,startY:R.clientY,originX:M.left,originY:M.top,width:M.width,height:M.height,dragging:!1},(X=(L=R.currentTarget).setPointerCapture)==null||X.call(L,R.pointerId)}function k(R){const M=f.current;if(!M||M.pointerId!==R.pointerId)return;const L=R.clientX-M.startX,X=R.clientY-M.startY;if(!M.dragging&&Math.hypot(L,X)<Lfe)return;M.dragging=!0,R.preventDefault();const U=c0({x:M.originX+L,y:M.originY+X},{width:M.width,height:M.height});l(U)}function T(R){var V,j;const M=f.current;if(!M||M.pointerId!==R.pointerId||(f.current=null,(j=(V=R.currentTarget).releasePointerCapture)==null||j.call(V,R.pointerId),!M.dragging))return;R.preventDefault(),p.current=!0,window.setTimeout(()=>{p.current=!1},200);const L=R.clientX-M.startX,X=R.clientY-M.startY,U=c0({x:M.originX+L,y:M.originY+X},{width:M.width,height:M.height});l(U),yI(U)}function N(R){var L,X;const M=f.current;!M||M.pointerId!==R.pointerId||(f.current=null,(X=(L=R.currentTarget).releasePointerCapture)==null||X.call(L,R.pointerId))}function P(R){p.current&&(p.current=!1,R.preventDefault(),R.stopPropagation())}return m.jsxs(Rb,{children:[m.jsx(Ab,{asChild:!0,children:m.jsxs("button",{ref:d,type:"button",className:Ye("fixed z-40 flex max-w-[calc(100vw-1.5rem)] touch-none cursor-move select-none items-center gap-2 rounded-md border px-2.5 py-1.5 text-xs shadow-lg backdrop-blur transition-colors",o===null&&"right-[calc(env(safe-area-inset-right)+0.75rem)] top-[calc(env(safe-area-inset-top)+3.75rem)] md:right-4 md:top-4",Bfe(g)),style:x,"data-slot":"latency-monitor-trigger","aria-label":`延迟监控,Relay 服务器 ${tp(i.webRelay.rttMs)},开发机 ${tp(w.rttMs)}`,onPointerDown:S,onPointerMove:k,onPointerUp:T,onPointerCancel:N,onClickCapture:P,children:[m.jsx(YB,{className:"size-3.5","aria-hidden":"true"}),m.jsx("span",{className:"font-medium text-foreground",children:"延迟"}),m.jsxs("span",{className:"hidden text-muted-foreground sm:inline",children:["Relay ",tp(i.webRelay.rttMs)]}),m.jsxs("span",{className:"text-muted-foreground",children:["开发机 ",tp(w.rttMs)]}),m.jsx(Ql,{className:"size-3 text-muted-foreground","aria-hidden":"true"})]})}),m.jsxs(Nb,{align:"end",className:"w-[320px] p-3","data-slot":"latency-monitor-popover",children:[m.jsxs("div",{className:"flex items-start justify-between gap-3",children:[m.jsxs("div",{children:[m.jsx("div",{className:"text-sm font-medium text-foreground",children:"连接延迟"}),m.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:"数值越低,操作响应通常越快。"})]}),m.jsx(gt,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"立即测速",onClick:()=>void _(),children:m.jsx(em,{className:"size-3","aria-hidden":"true"})})]}),m.jsx("div",{className:"mt-3 space-y-2",children:Object.keys(gI).map(R=>m.jsx(Hfe,{label:gI[R],measurement:i[R]},R))})]})]})}function Hfe({label:e,measurement:t}){const n=X4(t.state);return m.jsxs("div",{className:"flex min-h-10 items-center justify-between gap-3 rounded-md border border-border/70 bg-card/60 px-3 py-2",children:[m.jsx("div",{className:"min-w-0 truncate text-xs font-medium text-foreground",children:e}),m.jsxs("div",{className:"flex items-center gap-2",children:[m.jsx("span",{className:Ye("size-1.5 rounded-full",n==="ok"?"bg-emerald-400":n==="warn"?"bg-amber-400":n==="bad"?"bg-destructive":"bg-muted-foreground/60"),"aria-hidden":"true"}),m.jsx("span",{className:"min-w-[4rem] text-right font-mono text-xs text-foreground",children:zfe(t)})]})]})}const Z4="/__dev_anywhere_debug/browser-state-dumps",Ufe=1500,Wfe=10,u0=80,mk=500,qfe=["id","class","data-slot","data-state","data-testid","role","aria-label","aria-hidden","name","type","autocomplete","autocorrect","autocapitalize","inputmode","enterkeyhint","virtualkeyboardpolicy","contenteditable","placeholder","href","src"],Vfe=["display","position","visibility","opacity","pointer-events","z-index","overflow","overflow-x","overflow-y","touch-action","transform","translate","color-scheme","background-color","color","font-size","line-height","padding-top","padding-right","padding-bottom","padding-left","margin-top","margin-right","margin-bottom","margin-left"];function bI(){if(typeof window>"u")return"off";const e=sF("debugDump");return e==="auto"?"auto":e!==null||the("debugInput")?"manual":"off"}function Yfe(e="manual"){const t={count:0,truncated:!1},n=window,r={schemaVersion:1,createdAt:new Date().toISOString(),trigger:e,url:{href:window.location.href,origin:window.location.origin,pathname:window.location.pathname,search:window.location.search,hash:window.location.hash},browser:{userAgent:navigator.userAgent,language:navigator.language,languages:Array.from(navigator.languages??[]),platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints??0,cookieEnabled:navigator.cookieEnabled,onLine:navigator.onLine},viewport:Zfe(),document:{title:document.title,readyState:document.readyState,visibilityState:document.visibilityState,activeElement:_I(document.activeElement),selection:Qfe(),focusedInputs:Array.from(document.querySelectorAll("input, textarea, select, [contenteditable]")).filter(i=>i===document.activeElement||i.matches(":focus")).map(i=>_I(i)).filter(i=>!!i),root:Q4(document.documentElement,0,t),truncated:t.truncated,nodeCount:t.count},devAnywhere:{ptyDebug:rd(()=>{var i;return((i=n.__devAnywherePtyDebug)==null?void 0:i.call(n))??null}),ptyInputDebugSnapshot:rd(()=>n.__devAnywherePtyInputDebugSnapshot??null),ptyInputDebugText:n.__devAnywherePtyInputDebugText??null,ptyInputDebugEvents:rd(()=>n.__devAnywherePtyInputDebugEvents??null),ptyScrollTraceTail:rd(()=>wI(n.__devAnywherePtyScrollTrace)),jsonScrollTraceTail:rd(()=>wI(n.__devAnywhereJsonScrollTrace)),voicePilotDiagnostics:rd(()=>{var i;return((i=n.__devAnywhereVoicePilotDiagnostics)==null?void 0:i.snapshot())??null})}};return window.__devAnywhereLastBrowserStateDump=r,r}async function Kfe(e="manual"){const t=Yfe(e);return Gfe(t)}async function Gfe(e){const t=JSON.stringify(e,null,2),n=new Blob([t]).size;try{const r=await Xfe(t);return{status:"saved",path:r.path,bytes:r.bytes,endpoint:Z4}}catch(r){const i=oF(r),s=Jfe(e.createdAt);return ehe(s,t,"application/json")?{status:"downloaded",filename:s,bytes:n,endpointError:i}:{status:"failed",error:"无法保存或下载诊断包",endpointError:i}}}async function Xfe(e){const t=await fetch(Z4,{method:"POST",headers:{"content-type":"application/json"},body:e});if(!t.ok)throw new Error(`${t.status} ${await t.text()}`);const n=await t.json();if(!n.ok||!n.path||typeof n.bytes!="number")throw new Error("debug endpoint returned an invalid response");return{path:n.path,bytes:n.bytes}}function Q4(e,t,n){if(n.count>=Ufe||t>Wfe)return n.truncated=!0,{kind:"truncated"};if(n.count+=1,e.nodeType===Node.TEXT_NODE){const u=xI(e.textContent??"");return u?{kind:"text",text:zb(u,mk)}:{kind:"text",text:""}}if(!(e instanceof HTMLElement))return{kind:"truncated"};const r=[];let i=0;const s=Array.from(e.childNodes);for(const u of s.slice(0,u0))u.nodeType===Node.TEXT_NODE&&!xI(u.textContent??"")||r.push(Q4(u,t+1,n));s.length>u0&&(i=s.length-u0,n.truncated=!0);const o={kind:"element",tag:e.tagName.toLowerCase(),path:iF(e),attrs:J4(e),rect:eF(e),scroll:tF(e),style:nF(e)},l=rF(e);return l&&(o.value=l),r.length>0&&(o.children=r),i>0&&(o.omittedChildren=i),o}function _I(e){if(!(e instanceof HTMLElement))return null;const t=rF(e);return{path:iF(e),tag:e.tagName.toLowerCase(),id:e.id||null,className:e.className||null,attrs:J4(e),rect:eF(e),scroll:tF(e),style:nF(e),...t?{value:t}:{}}}function Zfe(){var n;const e=window.visualViewport,t=((n=screen.orientation)==null?void 0:n.type)??null;return{window:{innerWidth:window.innerWidth,innerHeight:window.innerHeight,outerWidth:window.outerWidth,outerHeight:window.outerHeight,devicePixelRatio:window.devicePixelRatio,scrollX:window.scrollX,scrollY:window.scrollY},visualViewport:e?{width:e.width,height:e.height,offsetLeft:e.offsetLeft,offsetTop:e.offsetTop,pageLeft:e.pageLeft,pageTop:e.pageTop,scale:e.scale}:null,screen:{width:screen.width,height:screen.height,availWidth:screen.availWidth,availHeight:screen.availHeight,orientation:t}}}function J4(e){const t={};for(const n of qfe){const r=e.getAttribute(n);r!==null&&(t[n]=zb(r,500))}return t}function eF(e){const t=e.getBoundingClientRect();return{x:bs(t.x),y:bs(t.y),width:bs(t.width),height:bs(t.height),top:bs(t.top),right:bs(t.right),bottom:bs(t.bottom),left:bs(t.left)}}function tF(e){return{top:bs(e.scrollTop),left:bs(e.scrollLeft),height:bs(e.scrollHeight),width:bs(e.scrollWidth),clientHeight:bs(e.clientHeight),clientWidth:bs(e.clientWidth)}}function nF(e){const t=window.getComputedStyle(e),n={};for(const r of Vfe)n[r]=t.getPropertyValue(r);return n}function rF(e){if(!(!(e instanceof HTMLInputElement)&&!(e instanceof HTMLTextAreaElement)))return{length:e.value.length,preview:zb(e.value,mk),selectionStart:e.selectionStart,selectionEnd:e.selectionEnd}}function Qfe(){var e;try{return zb(((e=window.getSelection())==null?void 0:e.toString())??"",mk)}catch{return null}}function iF(e){const t=[];let n=e;for(;n&&n!==document.documentElement;){let r=n.tagName.toLowerCase();if(n.id){r+=`#${n.id}`,t.unshift(r);break}const i=n.getAttribute("data-slot");i?r+=`[data-slot="${i}"]`:n.classList.length>0&&(r+=`.${Array.from(n.classList).slice(0,3).join(".")}`);const s=n.parentElement;if(s){const o=n.tagName,l=Array.from(s.children).filter(u=>u instanceof HTMLElement&&u.tagName===o);l.length>1&&(r+=`:nth-of-type(${l.indexOf(n)+1})`)}t.unshift(r),n=s}return`html>${t.join(">")}`}function Jfe(e){return`dev-anywhere-browser-state-${e.replace(/[:.]/g,"-")}.json`}function ehe(e,t,n){if(typeof document>"u")return!1;const r=new Blob([t],{type:n}),i=URL.createObjectURL(r),s=document.createElement("a");return s.href=i,s.download=e,s.rel="noopener",document.body.append(s),s.click(),s.remove(),window.setTimeout(()=>URL.revokeObjectURL(i),1e3),!0}function the(e){return sF(e)!==null}function sF(e){const t=new URLSearchParams(window.location.search);if(t.has(e))return t.get(e)??"";const[,n=""]=window.location.hash.split("?"),r=new URLSearchParams(n);return r.has(e)?r.get(e)??"":null}function wI(e){return e?Ry(e.slice(-200)):null}function rd(e){try{return Ry(e())}catch(t){return{error:oF(t)}}}function Ry(e){if(e===null||typeof e=="string"||typeof e=="boolean")return e;if(typeof e=="number")return Number.isFinite(e)?e:String(e);if(Array.isArray(e))return e.map(Ry);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=Ry(r);return t}return String(e)}function xI(e){return e.replace(/\s+/g," ").trim()}function zb(e,t){return e.length>t?`${e.slice(0,t)}...`:e}function bs(e){return Math.round(e*100)/100}function oF(e){return e instanceof Error?e.message:String(e)}const nhe=500,rhe=1e3,ihe=60;function she(){const[e,t]=b.useState(()=>bI()),[n,r]=b.useState(!1),[i,s]=b.useState(null),o=b.useRef(null),l=b.useRef(!1),u=b.useRef(0),d=b.useRef(0),f=b.useRef(null);b.useEffect(()=>{const _=()=>t(bI());return window.addEventListener("hashchange",_),window.addEventListener("popstate",_),()=>{window.removeEventListener("hashchange",_),window.removeEventListener("popstate",_)}},[]);const p=b.useCallback(async(_="manual")=>{if(l.current)return o.current??{status:"failed",error:"dump already running"};l.current=!0,r(!0);try{const w=await Kfe(_);return o.current=w,s(w),(_==="manual"||w.status==="failed")&&ohe(w),w}finally{l.current=!1,r(!1)}},[]);if(b.useEffect(()=>(window.__devAnywhereDumpBrowserState=p,()=>{window.__devAnywhereDumpBrowserState===p&&delete window.__devAnywhereDumpBrowserState}),[p]),b.useEffect(()=>{var k,T;if(e!=="auto")return;const _=()=>{f.current!==null&&(window.clearTimeout(f.current),f.current=null)},w=N=>{d.current>=ihe||(_(),f.current=window.setTimeout(()=>{f.current=null;const P=Date.now(),R=rhe-(P-u.current);if(R>0){f.current=window.setTimeout(()=>w(N),R);return}u.current=Date.now(),d.current+=1,p(`auto:${d.current}:${N}`)},nhe))};w("initial");const x=["focusin","focusout","beforeinput","input","compositionstart","compositionupdate","compositionend","keydown","keyup","pointerdown","pointerup","resize","visibilitychange"],S=N=>w(N.type);return x.forEach(N=>window.addEventListener(N,S,!0)),(k=window.visualViewport)==null||k.addEventListener("resize",S),(T=window.visualViewport)==null||T.addEventListener("scroll",S),()=>{var N,P;_(),x.forEach(R=>window.removeEventListener(R,S,!0)),(N=window.visualViewport)==null||N.removeEventListener("resize",S),(P=window.visualViewport)==null||P.removeEventListener("scroll",S)}},[p,e]),e==="off")return null;const y=e==="auto"?"自动诊断中":"保存诊断",g=ahe(i);return m.jsxs("div",{className:"fixed bottom-3 right-3 z-[90] flex max-w-[min(360px,calc(100vw-24px))] flex-col items-end gap-1",children:[g?m.jsx("div",{className:"max-w-full truncate rounded-md border border-border/70 bg-popover/95 px-2 py-1 text-[10px] text-muted-foreground shadow",children:g}):null,m.jsxs(gt,{type:"button",size:"sm",variant:e==="auto"?"secondary":"outline",className:"h-9 rounded-md px-3 text-xs shadow-lg",onClick:()=>void p("manual"),disabled:n,"data-slot":"browser-state-dump",children:[n?m.jsx(ii,{className:"size-3.5 animate-spin","aria-hidden":"true"}):m.jsx(MV,{className:"size-3.5","aria-hidden":"true"}),m.jsx("span",{children:y})]})]})}function ohe(e){if(e.status==="saved"){We.success(`诊断已保存: ${e.path}`);return}if(e.status==="downloaded"){We.info(`诊断已下载: ${e.filename}`);return}We.error(e.endpointError?`${e.error}: ${e.endpointError}`:e.error)}function ahe(e){return e?e.status==="saved"?`已保存 ${e.path}`:e.status==="downloaded"?`已下载 ${e.filename}`:`失败 ${e.endpointError??e.error}`:null}function lhe({issue:e}){const t=e==="unreachable"?"暂时无法连接":e==="page_outdated"?"当前页面版本较旧,请刷新后重试":e==="service_outdated"?"服务端版本较旧,请更新服务后重试":e==="protocol_mismatch"?"页面与服务端版本不一致,请刷新后重试":"连接已断开",n=e==="page_outdated"||e==="protocol_mismatch"?"刷新页面":e==="service_outdated"?"重新检测":null;return m.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-3 px-6 text-center text-muted-foreground","data-slot":"relay-connection-state","data-state":"unavailable","data-issue":e,role:"status","aria-live":"polite",children:[e==="unreachable"?m.jsx(ii,{className:"size-5 animate-spin","aria-hidden":"true"}):null,m.jsx("p",{className:"text-sm",children:t}),n?m.jsx(gt,{type:"button",size:"sm",onClick:()=>window.location.reload(),children:n}):null]})}function che(e){if(typeof window>"u")return null;try{const t=window.localStorage;return!t||typeof t.getItem!="function"?null:t.getItem(e)}catch{return null}}function gk(e){const{windowKey:t,storageKey:n,maxEntries:r=5e3,dedupeKey:i}=e,s=new Map,o=()=>typeof window>"u"?!1:che(n)==="1",l=()=>typeof window>"u"?[]:window[t]??[],u=d=>{typeof window>"u"||(window[t]=d)};return{isEnabled:o,append(d){if(typeof window>"u")return;const f=l();if(i){const p=i(d);if(p!==null){const y=s.get(d.event);if(y&&i(y)===p&&f.includes(y)){y.t=d.t,y.repeat=(y.repeat??0)+1;const g=f.indexOf(y);g>=0&&g!==f.length-1&&(f.splice(g,1),f.push(y)),u(f);return}}}if(f.push(d),i&&s.set(d.event,d),f.length>r){const p=f.splice(0,f.length-r);if(i)for(const y of p)s.get(y.event)===y&&s.delete(y.event)}u(f)},getAll:l}}function Gn(e){return Math.round(e*10)/10}function Nl(e){return e.length===0?"":`${Gn(Math.min(...e))}..${Gn(Math.max(...e))}`}function kd(e){return[...new Set(e.filter(t=>t!==void 0).map(Gn))]}function aF(e){let t=0,n=0;for(let r=1;r<e.length;r+=1){const i=e[r]-e[r-1];if(Math.abs(i)<1)continue;const s=Math.sign(i);t!==0&&s!==t&&(n+=1),t=s}return n}const uhe="dev_anywhere_pty_input_latency_trace",SI=80,dhe=1e4,fhe=new TextDecoder;let hhe=0;const Zd=new Map,mu=gk({windowKey:"__devAnywherePtyInputLatencyTrace",storageKey:uhe,dedupeKey:e=>e.event.startsWith("input")?null:`${e.event}|${e.sessionId}|${e.outputSeq??""}|${e.pendingInputs??""}`});function phe(){typeof window>"u"||(window.__devAnywherePtyInputLatencyReport=yhe)}function mhe(e,t){if(!mu.isEnabled())return null;const n=`pty-in-${Date.now().toString(36)}-${++hhe}`,r=performance.now(),i={inputId:n,sessionId:e,data:t,kind:whe(t),dataLength:t.length,startedAt:r,sentAt:null,firstOutputAt:null,echoMatchedAt:null,xtermWriteAt:null,paintAt:null},s=Zd.get(e)??[];return s.push(i),yk(s,r),Zd.set(e,s),fm({t:r,event:"input:start",sessionId:e,inputId:n,inputKind:i.kind,dataLength:i.dataLength,pendingInputs:s.length}),{inputId:n,sessionId:e}}function EI(e,t){if(!e||!mu.isEnabled())return;const n=performance.now(),r=bhe(e.sessionId,e.inputId);r&&(r.sentAt=n),fm({t:n,event:"input:ws-send",sessionId:e.sessionId,inputId:e.inputId,inputKind:r==null?void 0:r.kind,dataLength:r==null?void 0:r.dataLength,sent:t.sent,queueWhenDisconnected:t.queueWhenDisconnected,deltaFromInputMs:r?n-r.startedAt:null,details:t.details})}function ghe(e,t,n){if(!mu.isEnabled())return;const r=performance.now(),i=vk(e,r),s=Ehe(t),o=[],l=[];for(const u of i)u.firstOutputAt===null&&(u.firstOutputAt=r,o.push(u.inputId)),u.echoMatchedAt===null&&She(u)&&s.includes(u.data)&&(u.echoMatchedAt=r,l.push(u.inputId));fm({t:r,event:"output:received",sessionId:e,outputSeq:n,bytes:t.byteLength,pendingInputs:i.length,deltaFromInputMs:bk(i,r),details:Che([o.length>0?`first=${o.length}`:"",l.length>0?`echo=${l.length}`:""])})}function vhe(e,t,n=1){if(!mu.isEnabled())return;const r=performance.now(),i=vk(e,r),s=[];for(const o of i)o.xtermWriteAt===null&&(o.xtermWriteAt=r,s.push(o.inputId));fm({t:r,event:"output:xterm-write",sessionId:e,bytes:t,chunkCount:n,pendingInputs:i.length,deltaFromInputMs:bk(i,r),details:s.length>0?`firstWrite=${s.length}`:""}),typeof requestAnimationFrame=="function"&&s.length>0&&requestAnimationFrame(()=>_he(e,s))}function yhe(){const e=mu.getAll(),t=e.slice(-200),n=[...Zd.values()].flat(),r=n.slice(-80).map(s=>[s.inputId,s.sessionId,s.kind,s.dataLength,s.sentAt===null?"":Gn(s.sentAt-s.startedAt),s.firstOutputAt===null?"":Gn(s.firstOutputAt-s.startedAt),s.echoMatchedAt===null?"":Gn(s.echoMatchedAt-s.startedAt),s.xtermWriteAt===null?"":Gn(s.xtermWriteAt-s.startedAt),s.paintAt===null?"":Gn(s.paintAt-s.startedAt)].join(" ")),i=t.map(s=>[Gn(s.t),s.repeat&&s.repeat>0?`${s.event} +${s.repeat}`:s.event,s.sessionId,s.inputId??"",s.inputKind??"",s.dataLength??"",s.sent===void 0?"":s.sent?"sent":"not-sent",s.queueWhenDisconnected?"queue-ok":"",s.outputSeq??"",s.bytes??"",s.chunkCount??"",s.pendingInputs??"",s.deltaFromInputMs===void 0||s.deltaFromInputMs===null?"":Gn(s.deltaFromInputMs),s.details??""].join(" "));return["DEV Anywhere PTY input latency trace",`events=${e.length}, included=${t.length}, pendingInputs=${n.length}`,"pending input summary:","inputId sessionId kind len wsSendMs firstOutputMs echoMatchMs xtermWriteMs paintMs",...r,"events:","t event sessionId inputId kind len sent queue outputSeq bytes chunks pending deltaMs details",...i].join(`
581
581
  `)}function fm(e){mu.append(e)}function vk(e,t){const n=Zd.get(e)??[];return yk(n,t),Zd.set(e,n),n}function yk(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n],i=r.paintAt!==null,s=t-r.startedAt>dhe;(i||s)&&e.splice(n,1)}e.length>SI&&e.splice(0,e.length-SI)}function bhe(e,t){return(Zd.get(e)??[]).find(n=>n.inputId===t)??null}function _he(e,t){if(!mu.isEnabled())return;const n=performance.now(),r=vk(e,n);let i=0;for(const s of t){const o=r.find(l=>l.inputId===s);!o||o.paintAt!==null||(o.paintAt=n,i+=1)}fm({t:n,event:"output:paint",sessionId:e,pendingInputs:r.length,deltaFromInputMs:bk(r,n),details:i>0?`paint=${i}`:""}),yk(r,n)}function bk(e,t){const n=e[0];return n?t-n.startedAt:null}function whe(e){return e==="\r"||e===`
582
582
  `?"enter":e.startsWith("\x1B")?"escape":xhe(e)?"control":e.length>16?"paste":/[\r\n]/.test(e)?"mixed":"printable"}function xhe(e){for(let t=0;t<e.length;t+=1){const n=e.charCodeAt(t);if(n>=0&&n<=8||n>=11&&n<=31||n===127)return!0}return!1}function She(e){return e.kind==="printable"&&e.data.length>0&&e.data.length<=16}function Ehe(e){try{return fhe.decode(e)}catch{return""}}function Che(e){return e.filter(Boolean).join(" ")}function So(e,t){if(!e||!t)return;const n=mhe(e,t),r=Da;if(!r){EI(n,{sent:!1,queueWhenDisconnected:!1,details:"no-ws-manager"});return}const i={type:"remote_input_raw",sessionId:e,data:t};n&&(i.traceId=n.inputId);const s=r.send(JSON.stringify(i),{queueWhenDisconnected:!0});EI(n,{sent:s,queueWhenDisconnected:!0,details:s?"sent-open-socket":"queued-or-dropped"})}const CI=-1;function khe({sessionId:e,enabled:t,waiting:n,approvalSeq:r,sendRawInput:i=So}){const s=b.useRef(void 0),o=b.useRef(e);b.useEffect(()=>{if(o.current!==e&&(o.current=e,s.current=void 0),!n){s.current=void 0;return}if(r===void 0){if(s.current!==void 0)return;s.current=CI,i(e,"\r");return}if(s.current===CI){s.current=r;return}s.current!==r&&(s.current=r,i(e,"\r"))},[r,t,i,e,n])}function The(e){var r,i,s;if(!e.connected||!e.proxyOnline||e.session.mode!=="pty"||e.session.kind==="terminal"||e.session.state==="idle"||e.session.state==="error"||e.session.state==="terminated")return null;const t=TC(e.proxyId,e.session.sessionId);return!t||!e.autoYesBySessionKey[t]||!(e.session.state==="waiting_approval"||((r=e.agentStatus)==null?void 0:r.phase)==="waiting_permission"||((i=e.ptyState)==null?void 0:i.state)==="approval_wait")?null:{key:t,sessionId:e.session.sessionId,waiting:!0,approvalSeq:((s=e.ptyState)==null?void 0:s.state)==="approval_wait"?e.ptyState.seq:void 0}}function Rhe({target:e,sendRawInput:t}){return khe({sessionId:e.sessionId,enabled:!0,waiting:e.waiting,approvalSeq:e.approvalSeq,sendRawInput:t}),null}function Ahe({sendRawInput:e=So}){const t=Ie(d=>d.connected),n=Ie(d=>d.proxyOnline),r=Ie(d=>d.selectedProxyId),i=Gt(d=>d.sessions),s=Gt(d=>d.ptyStateBySessionId),o=Gt(d=>d.agentStatusBySessionId),l=Gt(d=>d.ptyAutoYesBySessionKey),u=i.map(d=>The({proxyId:r,session:d,ptyState:s[d.sessionId],agentStatus:o[d.sessionId],autoYesBySessionKey:l,connected:t,proxyOnline:n})).filter(d=>d!==null);return m.jsx(m.Fragment,{children:u.map(d=>m.jsx(Rhe,{target:d,sendRawInput:e},d.key))})}function Nhe(e,t){return e.some(n=>n.sessionId===t)?e:[...e,{sessionId:t}]}var Fc=function(e,t){return Number(e.toFixed(t))},Mhe=function(e,t){return t},nr=function(e,t,n){n&&typeof n=="function"&&n(e,t)},Phe=function(e){return-Math.cos(e*Math.PI)/2+.5},Ihe=function(e){return e},Ohe=function(e){return e*e},Lhe=function(e){return e*(2-e)},Dhe=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},Bhe=function(e){return e*e*e},zhe=function(e){return--e*e*e+1},jhe=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},Fhe=function(e){return e*e*e*e},$he=function(e){return 1- --e*e*e*e},Hhe=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},Uhe=function(e){return e*e*e*e*e},Whe=function(e){return 1+--e*e*e*e*e},qhe=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},lF={easeOut:Phe,linear:Ihe,easeInQuad:Ohe,easeOutQuad:Lhe,easeInOutQuad:Dhe,easeInCubic:Bhe,easeOutCubic:zhe,easeInOutCubic:jhe,easeInQuart:Fhe,easeOutQuart:$he,easeInOutQuart:Hhe,easeInQuint:Uhe,easeOutQuint:Whe,easeInOutQuint:qhe},cF=function(e){typeof e=="number"&&cancelAnimationFrame(e)},xo=function(e){e.mounted&&(cF(e.animation),e.isAnimating=!1,e.animation=null,e.velocity=null)};function uF(e,t,n,r){if(e.mounted){var i=new Date().getTime(),s=1;xo(e),e.animation=function(){if(!e.mounted)return cF(e.animation);var o=new Date().getTime()-i,l=o/n,u=lF[t],d=u(l);o>=n?(r(s),e.animation=null):e.animation&&(r(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function Vhe(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function oc(e,t,n,r){var i=Vhe(t);if(!(!e.mounted||!i)){var s=e.setState,o=e.state,l=o.scale,u=o.positionX,d=o.positionY,f=t.scale-l,p=t.positionX-u,y=t.positionY-d;n===0?s(t.scale,t.positionX,t.positionY):uF(e,r,n,function(g){g!==1?e.isAnimating=!0:e.isAnimating=!1;var _=l+f*g,w=u+p*g,x=d+y*g;s(_,w,x)})}}function Yhe(e,t,n){var r=e.offsetWidth,i=e.offsetHeight,s=t.offsetWidth,o=t.offsetHeight,l=s*n,u=o*n,d=r-l,f=i-u;return{wrapperWidth:r,wrapperHeight:i,newContentWidth:l,newDiffWidth:d,newContentHeight:u,newDiffHeight:f}}var Khe=function(e,t,n,r,i,s,o){var l=e>t?n*(o?.5:1):0,u=r>i?s*(o?.5:1):0,d=e-t-l,f=l,p=r-i-u,y=u;return{minPositionX:d,maxPositionX:f,minPositionY:p,maxPositionY:y,scaleWidthFactor:l,scaleHeightFactor:u}},_k=function(e,t){var n=e.wrapperComponent,r=e.contentComponent,i=e.setup,s=i.centerZoomedOut,o=i.disablePadding;if(!n||!r)throw new Error("Components are not mounted");var l=Yhe(n,r,t),u=l.wrapperWidth,d=l.wrapperHeight,f=l.newContentWidth,p=l.newContentHeight,y=l.newDiffWidth,g=l.newDiffHeight,_=Khe(u,f,y,d,p,g,!!s),w=u>=f&&d>=p;o&&w&&!s&&(_.minPositionX=0,_.maxPositionX=0,_.minPositionY=0,_.maxPositionY=0);var x=e.setup,S=x.minPositionX,k=x.maxPositionX,T=x.minPositionY,N=x.maxPositionY;return S!=null&&(_.minPositionX=u*(1-t)+S*t),k!=null&&(_.maxPositionX=k*t),T!=null&&(_.minPositionY=d*(1-t)+T*t),N!=null&&(_.maxPositionY=N*t),_},Dp=function(e,t,n,r){return r?e<t?Fc(t,2):e>n?Fc(n,2):Fc(e,2):Fc(e,2)},Qd=function(e,t){var n=_k(e,t);return e.bounds=n,n};function hm(e,t,n,r,i,s,o){var l=n.minPositionX,u=n.minPositionY,d=n.maxPositionX,f=n.maxPositionY,p=0,y=0;o&&(p=i,y=s);var g=Dp(e,l-p,d+p,r),_=Dp(t,u-y,f+y,r);return{x:g,y:_}}function jb(e,t,n,r,i,s){var o=e.state,l=o.scale,u=o.positionX,d=o.positionY,f=r-l;if(typeof t!="number"||typeof n!="number")return console.error("Mouse X and Y position were not provided!"),{x:u,y:d};var p=u-t*f,y=d-n*f,g=hm(p,y,i,s,0,0,null);return g}var kI=1e-7;function pm(e,t,n,r,i){var s=i?r:0,o=Math.max(t-s,kI),l=n+s;return!Number.isNaN(n)&&e>=l?l:!Number.isNaN(t)&&e<=o?o:Math.max(e,kI)}var TI=function(e,t){var n=e.setup.panning.excluded,r=e.isInitialized,i=e.wrapperComponent,s=t.target,o="shadowRoot"in s&&"composedPath"in t,l=o?t.composedPath().some(function(f){return f instanceof Element?i==null?void 0:i.contains(f):!1}):i==null?void 0:i.contains(s),u=r&&s&&l;if(!u)return!1;var d=mm(s,n);return!(d||s.getAttribute("draggable")==="true"||s.getAttribute("contenteditable")==="true"||s.isContentEditable)},RI=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,i=r.panning.disabled,s=t&&n&&!i;return!!s},Ghe=function(e,t){var n=e.state,r=n.positionX,i=n.positionY;e.isPanning=!0;var s=t.clientX,o=t.clientY;e.startCoords={x:s-r,y:o-i}},Xhe=function(e,t){var n=t.touches,r=e.state,i=r.positionX,s=r.positionY;e.isPanning=!0;var o=n.length===1;if(o){var l=n[0].clientX,u=n[0].clientY;e.startCoords={x:l-i,y:u-s}}};function Zhe(e){var t=e.state,n=t.positionX,r=t.positionY,i=t.scale,s=e.setup,o=s.disabled,l=s.limitToBounds,u=s.centerZoomedOut,d=e.wrapperComponent;if(!(o||!d||!e.bounds)){var f=e.bounds,p=f.maxPositionX,y=f.minPositionX,g=f.maxPositionY,_=f.minPositionY,w=n>p||n<y,x=r>g||r<_,S=n>p?d.offsetWidth:e.setup.minPositionX||0,k=r>g?d.offsetHeight:e.setup.minPositionY||0,T=jb(e,S,k,i,e.bounds,l||u),N=T.x,P=T.y;return{scale:i,positionX:w?N:n,positionY:x?P:r}}}function dF(e,t,n,r,i){var s=e.setup.limitToBounds,o=e.wrapperComponent,l=e.bounds,u=e.state,d=u.scale,f=u.positionX,p=u.positionY;if(!(o===null||l===null||t===f&&n===p)){var y=hm(t,n,l,s,r,i,o),g=y.x,_=y.y;e.setState(d,g,_)}}var Qhe=function(e,t,n){var r=e.startCoords,i=e.state,s=e.setup.panning,o=s.lockAxisX,l=s.lockAxisY,u=i.positionX,d=i.positionY;if(!r)return{x:u,y:d};var f=t-r.x,p=n-r.y,y=o?u:f,g=l?d:p;return{x:y,y:g}},Gl=function(e,t,n){var r=e.setup,i=e.state,s=r.minScale,o=r.disablePadding,l=r.centerZoomedOut,u=n??i.scale;return t>0&&u>=s&&!o&&!l?t:0},zl;(function(e){e.TRACK_PAD="track_pad",e.MOUSE="mouse",e.TOUCH="touch"})(zl||(zl={}));var Jhe=function(e){var t=e.mounted,n=e.wrapperComponent,r=e.contentComponent,i=e.setup,s=i.disabled,o=i.velocityAnimation,l=i.limitToBounds,u=e.state.scale,d=o.disabled;if(d||s||!t||!n||!r)return!1;if(!l)return!0;var f=n.offsetWidth<r.offsetWidth*u||n.offsetHeight<r.offsetHeight*u;return f},epe=function(e){var t=e.mounted,n=e.velocity,r=e.bounds,i=e.setup,s=i.disabled,o=i.velocityAnimation,l=o.disabled,u=!l&&!s&&t;return!(!u||!n||!r)};function tpe(e,t){var n=e.setup.velocityAnimation,r=n.animationTime,i=n.maxAnimationTime,s=n.inertia;return Math.min(r*Math.max(1,Math.abs(t/s)),i)}function AI(e,t,n,r,i,s,o,l,u,d){if(i){if(t>o&&n>o){var f=o+(e-o)*d;return f>u?u:f<o?o:f}if(t<s&&n<s){var f=s+(e-s)*d;return f<l?l:f>s?s:f}}return r?t:Dp(e,s,o,i)}function npe(e){var t=1,n=e.offsetWidth/window.innerWidth;return Number.isNaN(n)?t:Math.min(t,n)}var d0=function(e,t,n){var r=0,i=e*n;return Number.isNaN(i)?r:e<0?Math.max(i,-t):Math.min(i,t)};function rpe(e,t,n){var r,i,s=Jhe(e);if(s){var o=e.lastMousePosition,l=e.velocityTime,u=e.setup,d=e.wrapperComponent,f=u.velocityAnimation,p=f.maxStrengthMouse,y=f.maxStrengthTouch,g=f.sensitivityTouch,_=f.sensitivityMouse,w=Date.now();if(o&&l&&d){var x=npe(d),S=(r={},r[zl.TOUCH]=g,r[zl.MOUSE]=_,r)[n],k=(i={},i[zl.TOUCH]=y,i[zl.MOUSE]=p,i)[n],T=t.x-o.x,N=t.y-o.y,P=d0(T/x,k,S),R=d0(N/x,k,S),M=w-l,L=T*T+N*N,X=d0(Math.sqrt(L)/M,k,S);e.velocity={velocityX:P,velocityY:R,total:X}}e.lastMousePosition=t,e.velocityTime=w}}function ipe(e){var t=e.velocity,n=e.bounds,r=e.setup,i=e.wrapperComponent,s=epe(e);if(!(!s||!t||!n||!i)){var o=t.velocityX,l=t.velocityY,u=t.total,d=n.maxPositionX,f=n.minPositionX,p=n.maxPositionY,y=n.minPositionY,g=r.limitToBounds,_=r.autoAlignment,w=r.zoomAnimation,x=r.panning,S=x.lockAxisY,k=x.lockAxisX,T=w.animationType,N=_.sizeX,P=_.sizeY,R=_.velocityAlignmentTime,M=R,L=tpe(e,u),X=Math.max(L,M),U=Gl(e,N),V=Gl(e,P),j=U*i.offsetWidth/100,A=V*i.offsetHeight/100,D=d+j,O=f-j,I=p+A,B=y-A,F=e.state,Y=new Date().getTime();uF(e,T,X,function(z){var q=e.state,K=q.scale,$=q.positionX,re=q.positionY,Q=new Date().getTime()-Y,G=Q/M,Z=lF[_.animationType],ae=1-Z(Math.min(1,G)),le=1-z,me=$+o*le,ke=re+l*le,$e=AI(me,F.positionX,$,k,g,f,d,O,D,ae),he=AI(ke,F.positionY,re,S,g,y,p,B,I,ae);if($!==me||re!==ke){e.setState(K,$e,he);var He=e.props.onPanning;He&&He(Xn(e),{})}})}}function NI(e,t){var n=e.state,r=n.scale,i=n.positionX,s=n.positionY;e.panStartPosition={x:i,y:s},xo(e),Qd(e,r),window.TouchEvent!==void 0&&t instanceof TouchEvent?Xhe(e,t):Ghe(e,t)}function fF(e,t){var n=e.state.scale,r=e.setup,i=r.minScale,s=r.autoAlignment,o=s.disabled,l=s.sizeX,u=s.sizeY,d=s.animationTime,f=s.animationType,p=o||n<i||!l&&!u;if(!p){var y=Zhe(e);y&&oc(e,y,d,f)}}function MI(e,t,n,r){var i=e.startCoords,s=e.setup,o=s.autoAlignment,l=o.sizeX,u=o.sizeY;if(i){var d=Qhe(e,t,n),f=d.x,p=d.y,y=Gl(e,l),g=Gl(e,u);rpe(e,{x:f,y:p},r),dF(e,f,p,y,g)}}function spe(e,t){if(e.isPanning){var n=e.velocity,r=e.wrapperComponent,i=e.contentComponent;e.isPanning=!1;var s=e.state,o=s.positionX,l=s.positionY,u=s.scale,d=e.panStartPosition;if(e.panStartPosition=null,d){var f=o-d.x,p=l-d.y;if(f*f+p*p<=25)return}e.isAnimating=!1,e.animation=null;var y=(r==null?void 0:r.offsetWidth)||0,g=(r==null?void 0:r.offsetHeight)||0,_=((i==null?void 0:i.offsetWidth)||0)*u,w=((i==null?void 0:i.offsetHeight)||0)*u,x=!e.setup.limitToBounds||y<_||g<w,S=!t&&n&&n.total>.1&&x;S?ipe(e):fF(e)}}function wk(e,t,n,r){var i=e.setup,s=i.minScale,o=i.maxScale,l=i.limitToBounds,u=pm(Fc(t,2),s,o,0,!1),d=Qd(e,u),f=jb(e,n,r,u,d,l),p=f.x,y=f.y;return{scale:u,positionX:p,positionY:y}}function xk(e,t,n){var r=e.state.scale,i=e.wrapperComponent,s=e.setup,o=s.minScale,l=s.maxScale,u=s.limitToBounds,d=s.zoomAnimation,f=d.disabled,p=d.animationTime,y=d.animationType,g=r>=o&&r<=l,_=f||g;if((r>=1||u)&&fF(e),!(_||!i||!e.mounted)){var w=t||i.offsetWidth/2,x=n||i.offsetHeight/2,S=r<o?o:l,k=wk(e,S,w,x);k&&oc(e,k,p,y)}}var io=function(){return io=Object.assign||function(t){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},io.apply(this,arguments)};function PI(e,t,n){for(var r=0,i=t.length,s;r<i;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}var f0={scale:1,positionX:0,positionY:0},zc={disabled:!1,minPositionX:null,maxPositionX:null,minPositionY:null,maxPositionY:null,minScale:1,maxScale:8,limitToBounds:!0,centerZoomedOut:!1,centerOnInit:!1,disablePadding:!1,smooth:!0,detached:!1,wheel:{step:.015,disabled:!1,wheelDisabled:!1,touchPadDisabled:!1,activationKeys:[],excluded:[]},trackPadPanning:{disabled:!0,velocityDisabled:!1,lockAxisX:!1,lockAxisY:!1,activationKeys:[],excluded:[]},panning:{disabled:!1,velocityDisabled:!1,lockAxisX:!1,lockAxisY:!1,allowLeftClickPan:!0,allowMiddleClickPan:!0,allowRightClickPan:!0,activationKeys:[],excluded:[]},pinch:{step:5,disabled:!1,allowPanning:!0,excluded:[]},doubleClick:{disabled:!1,step:.7,mode:"zoomIn",animationType:"easeOut",animationTime:200,excluded:[]},zoomAnimation:{disabled:!1,size:.4,animationTime:200,animationType:"easeOut"},autoAlignment:{disabled:!1,sizeX:100,sizeY:100,animationTime:200,velocityAlignmentTime:400,animationType:"easeOut"},velocityAnimation:{disabled:!1,sensitivityMouse:1,sensitivityTouch:1.2,maxStrengthMouse:20,maxStrengthTouch:40,inertia:1,animationTime:300,maxAnimationTime:800,animationType:"easeOut"}},y1={wrapperClass:"react-transform-wrapper",contentClass:"react-transform-component"},hF=function(e){var t,n,r,i,s,o,l,u,d,f=Math.max((t=e.minScale)!==null&&t!==void 0?t:zc.minScale,1e-7),p=(n=e.maxScale)!==null&&n!==void 0?n:zc.maxScale,y=(r=e.initialScale)!==null&&r!==void 0?r:f0.scale,g=Math.min(Math.max(y,f),p),_=Dp((i=e.initialPositionX)!==null&&i!==void 0?i:f0.positionX,(s=e.minPositionX)!==null&&s!==void 0?s:-1/0,(o=e.maxPositionX)!==null&&o!==void 0?o:1/0,e.minPositionX!=null||e.maxPositionX!=null),w=Dp((l=e.initialPositionY)!==null&&l!==void 0?l:f0.positionY,(u=e.minPositionY)!==null&&u!==void 0?u:-1/0,(d=e.maxPositionY)!==null&&d!==void 0?d:1/0,e.minPositionY!=null||e.maxPositionY!=null);return{previousScale:g,scale:g,positionX:_,positionY:w}},II=function(e){var t=io({},zc);return Object.keys(e).forEach(function(n){var r=n,i=typeof e[r]<"u",s=typeof zc[r]<"u";if(s&&i){var o=Object.prototype.toString.call(zc[r]),l=o==="[object Object]",u=o==="[object Array]";l?t[r]=io(io({},zc[r]),e[r]):u?t[r]=PI(PI([],zc[r],!0),e[r]):t[r]=e[r]}}),t.minScale<=0&&(t.minScale=1e-7),t},pF=function(e,t,n){var r=e.state.scale,i=e.wrapperComponent,s=e.setup,o=s.maxScale,l=s.minScale,u=s.zoomAnimation,d=s.smooth,f=u.size;if(!i)throw new Error("Wrapper is not mounted");var p=d?r*Math.exp(t*n):r+t*n,y=pm(Fc(p,3),l,o,f,!1);return y};function mF(e,t,n,r,i){var s,o,l=e.wrapperComponent,u=e.state,d=u.scale,f=u.positionX,p=u.positionY,y=e.setup.zoomAnimation;if(!l)return console.error("No WrapperComponent found");var g=y.disabled?0:r,_=l.offsetWidth,w=l.offsetHeight,x=(_/2-f)/d,S=(w/2-p)/d,k=pF(e,t,n),T=wk(e,k,x,S);if(!T)return console.error("Error during zoom event. New transformation state was not calculated.");var N=e.props,P=N.onZoomStart,R=N.onZoom,M=N.onZoomStop,L=new MouseEvent("mousemove",{bubbles:!0}),X=Xn(e);nr(X,L,P),nr(X,L,R),oc(e,T,g,i);var U=(o=(s=l.ownerDocument)===null||s===void 0?void 0:s.defaultView)!==null&&o!==void 0?o:typeof window<"u"?window:null;U&&U.setTimeout(function(){e.mounted&&nr(Xn(e),L,M)},g)}function gF(e,t,n,r){var i,s,o=e.setup,l=e.wrapperComponent,u=e.contentComponent,d=o.limitToBounds,f=o.centerOnInit,p=hF(e.props),y=e.state,g=y.scale,_=y.positionX,w=y.positionY;if(l){var x=p.positionX,S=p.positionY;if(f&&u){var k=Sk(p.scale,l,u);x=k.positionX,S=k.positionY}var T=_k(e,p.scale),N=hm(x,S,T,d,0,0,l),P={scale:p.scale,positionX:N.x,positionY:N.y};if(!(g===p.scale&&_===p.positionX&&w===p.positionY)){r==null||r();var R=e.props,M=R.onZoomStart,L=R.onZoom,X=R.onZoomStop,U=new MouseEvent("mousemove",{bubbles:!0}),V=Xn(e);nr(V,U,M),nr(V,U,L),oc(e,P,t,n);var j=(s=(i=l.ownerDocument)===null||i===void 0?void 0:i.defaultView)!==null&&s!==void 0?s:typeof window<"u"?window:null;j&&j.setTimeout(function(){e.mounted&&nr(Xn(e),U,X)},t)}}}function ope(e,t,n,r){var i=e.getBoundingClientRect(),s=t.getBoundingClientRect(),o=n.getBoundingClientRect(),l=s.x*r.scale,u=s.y*r.scale;return{x:(i.x-o.x+l)/r.scale,y:(i.y-o.y+u)/r.scale}}function ape(e,t,n,r,i){r===void 0&&(r=0),i===void 0&&(i=0);var s=e.wrapperComponent,o=e.contentComponent,l=e.state,u=e.setup,d=u.limitToBounds,f=u.minScale,p=u.maxScale;if(!s||!o)return l;var y=s.getBoundingClientRect(),g=t.getBoundingClientRect(),_=ope(t,s,o,l),w=_.x,x=_.y,S=g.width/l.scale,k=g.height/l.scale,T=s.offsetWidth/S,N=s.offsetHeight/k,P=pm(n||Math.min(T,N),f,p,0,!1),R=(y.width-S*P)/2,M=(y.height-k*P)/2,L=(y.left-w)*P+R+r,X=(y.top-x)*P+M+i,U=_k(e,P),V=hm(L,X,U,d,0,0,s),j=V.x,A=V.y;return{positionX:j,positionY:A,scale:P}}var lpe=function(e){return function(t,n,r){t===void 0&&(t=.5),n===void 0&&(n=300),r===void 0&&(r="easeOut"),mF(e,1,t,n,r)}},cpe=function(e){return function(t,n,r){t===void 0&&(t=.5),n===void 0&&(n=300),r===void 0&&(r="easeOut"),mF(e,-1,t,n,r)}},upe=function(e){return function(t,n,r,i,s){i===void 0&&(i=300),s===void 0&&(s="easeOut");var o=e.state,l=o.positionX,u=o.positionY,d=o.scale,f=e.wrapperComponent,p=e.contentComponent,y=e.setup.disabled;if(!(y||!f||!p)){var g={positionX:Number.isNaN(t)?l:t,positionY:Number.isNaN(n)?u:n,scale:Number.isNaN(r)?d:r};oc(e,g,i,s)}}},dpe=function(e){return function(t,n){t===void 0&&(t=200),n===void 0&&(n="easeOut"),gF(e,t,n)}},fpe=function(e){return function(t,n,r){n===void 0&&(n=200),r===void 0&&(r="easeOut");var i=e.state,s=e.wrapperComponent,o=e.contentComponent;if(s&&o){var l=Sk(t||i.scale,s,o);oc(e,l,n,r)}}},hpe=function(e){return function(t,n,r,i,s,o){r===void 0&&(r=600),i===void 0&&(i="easeOut"),s===void 0&&(s=0),o===void 0&&(o=0),xo(e);var l=e.wrapperComponent,u=typeof t=="string"?document.getElementById(t):t;if(l&&u&&l.contains(u)){var d=ape(e,u,n,s,o);oc(e,d,r,i)}}},b1=function(e){return{instance:e,state:e.state,zoomIn:lpe(e),zoomOut:cpe(e),setTransform:upe(e),resetTransform:dpe(e),centerView:fpe(e),zoomToElement:hpe(e)}},ppe=function(e){return{instance:e,state:e.state}},Xn=function(e){var t={};return Object.assign(t,ppe(e)),Object.assign(t,b1(e)),t},h0=!1;function p0(){try{var e={get passive(){return h0=!0,!1}};return e}catch{return h0=!1,h0}}var lv=".".concat(y1.wrapperClass),mm=function(e,t){return t.some(function(n){return e.matches("".concat(lv," ").concat(n,", ").concat(lv," .").concat(n,", ").concat(lv," ").concat(n," *, ").concat(lv," .").concat(n," *"))})},Bp=function(e){e&&clearTimeout(e)},mpe=function(e){return Number.parseFloat(e.toFixed(8))},vF=function(e,t,n){var r=mpe(n);return"translate(".concat(e,"px, ").concat(t,"px) scale(").concat(r,")")},Sk=function(e,t,n){var r=n.offsetWidth*e,i=n.offsetHeight*e,s=(t.offsetWidth-r)/2,o=(t.offsetHeight-i)/2;return{scale:e,positionX:s,positionY:o}};function gpe(e,t){e!=null&&(typeof e=="function"?e(t):e.current=t)}function vpe(e){return function(t){e.forEach(function(n){typeof n=="function"?n(t):n!=null&&(n.current=t)})}}var yF=function(e,t){var n=e.setup.wheel,r=n.disabled,i=n.wheelDisabled,s=n.touchPadDisabled,o=n.excluded,l=e.isInitialized,u=e.isPanning,d=t.target,f=l&&!u&&!r&&d;if(!f||i&&!t.ctrlKey||s&&t.ctrlKey)return!1;var p=mm(d,o);if(p)return!1;var y=e.isPressingKeys(e.setup.wheel.activationKeys);return!!y},ype=function(e,t){var n=e.setup,r=n.disabled,i=n.trackPadPanning,s=i.activationKeys,o=i.excluded;if(!e.wrapperComponent||!e.contentComponent||r||i.disabled||t.ctrlKey)return!1;var l=yF(e,t);if(l)return!1;var u=t.target,d=mm(u,o);if(d)return!1;var f=e.isPressingKeys(s);return!!f},bpe=function(e){return e?e.deltaY<0?1:-1:0};function _pe(e,t){var n=bpe(e),r=Mhe(t,n);return r}function bF(e,t,n){var r=t.getBoundingClientRect(),i=0,s=0;if("clientX"in e)i=(e.clientX-r.left)/n,s=(e.clientY-r.top)/n;else{var o=e.touches[0];i=(o.clientX-r.left)/n,s=(o.clientY-r.top)/n}return(Number.isNaN(i)||Number.isNaN(s))&&console.error("No mouse or touch offset found"),{x:i,y:s}}var wpe=function(e,t,n,r,i){var s=e.state.scale,o=e.wrapperComponent,l=e.setup,u=l.maxScale,d=l.minScale,f=l.zoomAnimation,p=l.disablePadding,y=f.size,g=f.disabled;if(!o)throw new Error("Wrapper is not mounted");var _=s+t*n,w=r?!1:!g,x=pm(_,d,u,y,w&&!p);return x},_F=function(e,t){var n=e.previousWheelEvent,r=e.state.scale,i=e.setup,s=i.maxScale,o=i.minScale;return n?r<s||r>o||Math.sign(n.deltaY)!==Math.sign(t.deltaY)||n.deltaY>0&&n.deltaY<t.deltaY||n.deltaY<0&&n.deltaY>t.deltaY||Math.sign(n.deltaY)!==Math.sign(t.deltaY):!1},xpe=function(e,t){var n=e.setup.pinch,r=n.disabled,i=n.excluded,s=e.isInitialized,o=t.target,l=s&&!r&&o;if(!l)return!1;var u=mm(o,i);return!u},Spe=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,i=n&&!t&&r!==null;return!!i},Epe=function(e,t,n){var r=n.getBoundingClientRect(),i=e.touches,s=i[0].clientX-r.left,o=i[0].clientY-r.top,l=i[1].clientX-r.left,u=i[1].clientY-r.top;return{x:(s+l)/2/t,y:(o+u)/2/t}},wF=function(e){return Math.sqrt(Math.pow(e.touches[0].pageX-e.touches[1].pageX,2)+Math.pow(e.touches[0].pageY-e.touches[1].pageY,2))},Cpe=5,kpe=function(e,t){var n=e.pinchStartScale,r=e.pinchStartDistance,i=e.setup,s=i.maxScale,o=i.minScale,l=i.zoomAnimation,u=i.disablePadding,d=i.pinch,f=l.size,p=l.disabled,y=d.step;if(!n||r===null)throw new Error("Pinch touches distance was not provided");if(t<0)return e.state.scale;var g=t/r,_=g*n,w=(_-n)*(y/Cpe),x=n+w,S=x===1/0?0:Fc(x,10);return pm(S,o,s,f,!p&&!u)},xF=160,SF=100,Tpe=function(e,t){var n=e.props,r=n.onWheelStart,i=n.onZoomStart;e.wheelStopEventTimer||(xo(e),nr(Xn(e),t,r),nr(Xn(e),t,i))},Rpe=function(e,t){var n=e.props,r=n.onWheel,i=n.onZoom,s=e.contentComponent,o=e.setup,l=e.state,u=l.scale,d=o.limitToBounds,f=o.centerZoomedOut,p=o.zoomAnimation,y=o.wheel,g=o.disablePadding,_=o.smooth,w=p.size,x=p.disabled,S=y.step;if(!s)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var k=_pe(t,null),T=_?S*Math.abs(t.deltaY):S,N=wpe(e,k,T,!t.ctrlKey);if(u!==N){var P=Qd(e,N),R=bF(t,s,u),M=x||w===0||f||g,L=d&&M,X=jb(e,R.x,R.y,N,P,L),U=X.x,V=X.y;e.previousWheelEvent=t,e.setState(N,U,V),nr(Xn(e),t,r),nr(Xn(e),t,i)}},Ape=function(e,t){var n=e.props,r=n.onWheelStop,i=n.onZoomStop;Bp(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(xk(e,t.x,t.y),e.wheelAnimationTimer=null)},SF);var s=_F(e,t);s&&(Bp(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,nr(Xn(e),t,r),nr(Xn(e),t,i))},xF))},Npe=function(e,t){var n=e.props,r=n.onWheelStart,i=n.onPanningStart;e.wheelStopEventTimer||(xo(e),nr(Xn(e),t,r),nr(Xn(e),t,i))},Mpe=function(e,t){var n=e.props,r=n.onWheelStop,i=n.onPanningStop;Bp(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(xk(e,t.x,t.y),e.wheelAnimationTimer=null)},SF);var s=_F(e,t);s&&(Bp(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,nr(Xn(e),t,r),nr(Xn(e),t,i))},xF))},EF=function(e){for(var t=0,n=0,r=0;r<2;r+=1)t+=e.touches[r].clientX,n+=e.touches[r].clientY;var i=t/2,s=n/2;return{x:i,y:s}},Ppe=function(e,t){var n=wF(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.state.scale,e.isPanning=!1,e.isPinching=!0,e.pinchPreviousCenter=EF(t),xo(e)},Ipe=function(e,t){var n=e.contentComponent,r=e.pinchStartDistance,i=e.wrapperComponent,s=e.pinchPreviousCenter,o=e.state.scale,l=e.setup,u=l.limitToBounds,d=l.centerZoomedOut,f=l.zoomAnimation,p=l.autoAlignment,y=l.pinch,g=l.panning,_=f.disabled,w=f.size,x=y.allowPanning;if(!(r===null||!n)){var S=Epe(t,o,n);if(!(!Number.isFinite(S.x)||!Number.isFinite(S.y))){var k=wF(t),T=kpe(e,k),N=EF(t),P=o/T,R=(N.x-((s==null?void 0:s.x)||0))*P,M=(N.y-((s==null?void 0:s.y)||0))*P;if(!(T===o&&R===0&&M===0)){e.pinchPreviousCenter=N;var L=Qd(e,T),X=_||w===0||d,U=u&&X,V=jb(e,S.x,S.y,T,L,U),j=V.x,A=V.y;if(e.pinchMidpoint=S,e.lastDistance=k,g.disabled||!x)e.setState(T,j,A);else{var D=p.sizeX,O=p.sizeY,I=Gl(e,D,T),B=Gl(e,O,T),F=j+R,Y=A+M,z=hm(F,Y,L,u,I,B,i),q=z.x,K=z.y;e.setState(T,q,K)}}}}},Ope=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,e.isPinching=!1,xk(e,t==null?void 0:t.x,t==null?void 0:t.y)},CF=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;Bp(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,nr(Xn(e),t,n)},r)},Lpe=function(e,t){var n=e.props,r=n.onZoomStart,i=n.onZoom,s=e.setup.doubleClick,o=s.animationTime,l=s.animationType;nr(Xn(e),t,r),gF(e,o,l,function(){return nr(Xn(e),t,i)}),CF(e,t)};function Dpe(e,t){return e==="toggle"?t===1?1:-1:e==="zoomOut"?-1:1}function Bpe(e,t){var n=e.setup,r=e.doubleClickStopEventTimer,i=e.state,s=e.contentComponent,o=i.scale,l=e.props,u=l.onZoomStart,d=l.onZoom,f=n.doubleClick,p=f.disabled,y=f.mode,g=f.step,_=f.animationTime,w=f.animationType;if(!p&&!r){if(y==="reset")return Lpe(e,t);if(!s)return console.error("No ContentComponent found");var x=Dpe(y,e.state.scale),S=pF(e,x,g);if(o!==S){nr(Xn(e),t,u);var k=bF(t,s,o),T=wk(e,S,k.x,k.y);if(!T)return console.error("Error during zoom event. New transformation state was not calculated.");nr(Xn(e),t,d),oc(e,T,_,w),CF(e,t)}}}var zpe=function(e,t){var n=e.isInitialized,r=e.setup,i=e.wrapperComponent,s=r.doubleClick,o=s.disabled,l=s.excluded,u=t.target,d=i==null?void 0:i.contains(u),f=n&&u&&d&&!o;if(!f)return!1;var p=mm(u,l);return!p},jpe=(function(){function e(t){var n=this;this.mounted=!0,this.onChangeCallbacks=new Set,this.onInitCallbacks=new Set,this.onTransformCallbacks=new Set,this.wrapperComponent=null,this.contentComponent=null,this.isInitialized=!1,this.bounds=null,this.previousWheelEvent=null,this.wheelStopEventTimer=null,this.wheelAnimationTimer=null,this.isPanning=!1,this.isWheelPanning=!1,this.startCoords=null,this.panStartPosition=null,this.lastTouch=null,this.isPinching=!1,this.distance=null,this.lastDistance=null,this.pinchStartDistance=null,this.pinchStartScale=null,this.pinchMidpoint=null,this.pinchPreviousCenter=null,this.doubleClickStopEventTimer=null,this.velocity=null,this.velocityTime=null,this.lastMousePosition=null,this.isAnimating=!1,this.animation=null,this.pressedKeys={},this.mount=function(){n.initializeWindowEvents()},this.unmount=function(){n.cleanupWindowEvents()},this.update=function(r){n.props=r,n.wrapperComponent&&n.contentComponent&&Qd(n,n.state.scale),n.setup=II(r)},this.initializeWindowEvents=function(){var r,i,s,o,l=p0(),u=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,d=u==null?void 0:u.defaultView;(i=n.wrapperComponent)===null||i===void 0||i.addEventListener("wheel",n.onWheelPanning,l),(s=n.wrapperComponent)===null||s===void 0||s.addEventListener("keyup",n.setKeyUnPressed,l),(o=n.wrapperComponent)===null||o===void 0||o.addEventListener("keydown",n.setKeyPressed,l),d==null||d.addEventListener("mousedown",n.onPanningStart,l),d==null||d.addEventListener("mousemove",n.onPanning,l),d==null||d.addEventListener("mouseup",n.onPanningStop,l),u==null||u.addEventListener("mouseleave",n.clearPanning,l),d==null||d.addEventListener("keyup",n.setKeyUnPressed,l),d==null||d.addEventListener("keydown",n.setKeyPressed,l),d==null||d.addEventListener("blur",n.handleWindowBlur)},this.cleanupWindowEvents=function(){var r,i,s,o,l,u=p0(),d=(r=n.wrapperComponent)===null||r===void 0?void 0:r.ownerDocument,f=d==null?void 0:d.defaultView;f==null||f.removeEventListener("mousedown",n.onPanningStart,u),f==null||f.removeEventListener("mousemove",n.onPanning,u),f==null||f.removeEventListener("mouseup",n.onPanningStop,u),d==null||d.removeEventListener("mouseleave",n.clearPanning,u),f==null||f.removeEventListener("keyup",n.setKeyUnPressed,u),f==null||f.removeEventListener("keydown",n.setKeyPressed,u),f==null||f.removeEventListener("blur",n.handleWindowBlur),document.removeEventListener("mouseleave",n.clearPanning,u),(i=n.wrapperComponent)===null||i===void 0||i.removeEventListener("wheel",n.onWheelPanning,u),(s=n.wrapperComponent)===null||s===void 0||s.removeEventListener("keyup",n.setKeyUnPressed,u),(o=n.wrapperComponent)===null||o===void 0||o.removeEventListener("keydown",n.setKeyPressed,u),xo(n),(l=n.observer)===null||l===void 0||l.disconnect()},this.handleInitializeWrapperEvents=function(r){var i=p0();r.addEventListener("wheel",n.onWheelZoom,i),r.addEventListener("dblclick",n.onDoubleClick,i),r.addEventListener("touchstart",n.onTouchPanningStart,i),r.addEventListener("touchmove",n.onTouchPanning,i),r.addEventListener("touchend",n.onTouchPanningStop,i)},this.handleInitialize=function(r){var i=n.setup.centerOnInit;n.applyTransformation(),n.onInitCallbacks.forEach(function(s){return s(Xn(n))}),i&&(n.setCenter(),n.observer=new ResizeObserver(function(){var s,o=r.offsetWidth,l=r.offsetHeight;(o>0||l>0)&&(n.onInitCallbacks.forEach(function(u){return u(Xn(n))}),n.setCenter(),(s=n.observer)===null||s===void 0||s.disconnect())}),setTimeout(function(){var s;(s=n.observer)===null||s===void 0||s.disconnect()},5e3),n.observer.observe(r))},this.onWheelZoom=function(r){var i=n.setup.disabled;if(!i){n.syncModifierKeys(r);var s=yF(n,r);s&&(Tpe(n,r),Rpe(n,r),Ape(n,r))}},this.onWheelPanning=function(r){var i=n.props.onPanning,s=n.setup.trackPadPanning,o=s.lockAxisX,l=s.lockAxisY;n.syncModifierKeys(r);var u=ype(n,r);if(u){r.preventDefault(),r.stopPropagation();var d=n.state,f=d.positionX,p=d.positionY,y=f-r.deltaX,g=p-r.deltaY,_=o?f:y,w=l?p:g,x=n.setup.autoAlignment,S=x.sizeX,k=x.sizeY,T=Gl(n,S),N=Gl(n,k);_===f&&w===p||(Npe(n,r),dF(n,_,w,T,N),nr(Xn(n),r,i),Mpe(n,r))}},this.onPanningStart=function(r){var i=n.setup.disabled,s=n.props.onPanningStart;if(!i){n.syncModifierKeys(r);var o=TI(n,r);if(o){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.button===0&&!n.setup.panning.allowLeftClickPan||r.button===1&&!n.setup.panning.allowMiddleClickPan||r.button===2&&!n.setup.panning.allowRightClickPan||(r.preventDefault(),r.stopPropagation(),xo(n),NI(n,r),nr(Xn(n),r,s)))}}},this.onPanning=function(r){var i=n.setup.disabled,s=n.props.onPanning;if(!i){if(n.syncModifierKeys(r),n.isPanning&&r.buttons===0){n.clearPanning(r);return}var o=RI(n);if(o){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),MI(n,r.clientX,r.clientY,zl.MOUSE),nr(Xn(n),r,s))}}},this.onPanningStop=function(r){var i=n.setup.panning.velocityDisabled,s=n.props.onPanningStop;n.isPanning&&(spe(n,i),nr(Xn(n),r,s))},this.onPinchStart=function(r){var i=n.setup.disabled,s=n.props.onPinchStart;if(!i){var o=xpe(n,r);o&&(Ppe(n,r),xo(n),nr(Xn(n),r,s))}},this.onPinch=function(r){var i=n.setup.disabled,s=n.props.onPinch;if(!i){var o=Spe(n);o&&(r.preventDefault(),r.stopPropagation(),Ipe(n,r),nr(Xn(n),r,s))}},this.onPinchStop=function(r){var i=n.props.onPinchStop;n.pinchStartScale&&(Ope(n),nr(Xn(n),r,i))},this.onTouchPanningStart=function(r){var i=n.setup,s=i.disabled,o=i.doubleClick,l=n.props.onPanningStart;if(!s){var u=!(o!=null&&o.disabled),d=n.lastTouch&&+new Date-n.lastTouch<200;if(u&&d&&r.touches.length===1)n.onDoubleClick(r);else{n.lastTouch=+new Date,xo(n);var f=r.touches,p=f.length===1,y=f.length===2,g=TI(n,r);if(p){if(!g)return;xo(n),NI(n,r),nr(Xn(n),r,l)}y&&n.onPinchStart(r)}}},this.onTouchPanning=function(r){var i=n.setup.disabled,s=n.props.onPanning;if(n.isPanning&&r.touches.length===1){if(i)return;var o=RI(n);if(!o)return;r.cancelable&&r.preventDefault(),r.stopPropagation();var l=r.touches[0];MI(n,l.clientX,l.clientY,zl.TOUCH),nr(Xn(n),r,s)}else r.touches.length>1&&n.onPinch(r)},this.onTouchPanningStop=function(r){n.onPanningStop(r),n.onPinchStop(r)},this.onDoubleClick=function(r){var i=n.setup.disabled;if(!i){var s=zpe(n,r);s&&Bpe(n,r)}},this.clearPanning=function(r){n.isPanning&&n.onPanningStop(r)},this.handleWindowBlur=function(){n.pressedKeys={},n.isPanning&&(n.isPanning=!1,n.startCoords=null)},this.syncModifierKeys=function(r){var i=r.ctrlKey,s=r.metaKey,o=r.shiftKey,l=r.altKey;typeof i=="boolean"&&(n.pressedKeys.Control=i),typeof s=="boolean"&&(n.pressedKeys.Meta=s),typeof o=="boolean"&&(n.pressedKeys.Shift=o),typeof l=="boolean"&&(n.pressedKeys.Alt=l)},this.setKeyPressed=function(r){n.pressedKeys[r.key]=!0},this.setKeyUnPressed=function(r){n.pressedKeys[r.key]=!1},this.isPressingKeys=function(r){return typeof r=="function"?r(Object.entries(n.pressedKeys).filter(function(i){var s=i[1];return s}).map(function(i){var s=i[0];return s})):r.length?!!r.every(function(i){return n.pressedKeys[i]}):!0},this.setCenter=function(){if(n.wrapperComponent&&n.contentComponent){var r=Sk(n.state.scale,n.wrapperComponent,n.contentComponent);n.setState(r.scale,r.positionX,r.positionY)}},this.handleTransformStyles=function(r,i,s){return n.props.customTransform?n.props.customTransform(r,i,s):vF(r,i,s)},this.getContext=function(){return Xn(n)},this.applyTransformation=function(){if(!(!n.mounted||!n.contentComponent)){var r=n.state,i=r.scale,s=r.positionX,o=r.positionY,l=n.handleTransformStyles(s,o,i);n.props.detached||(n.contentComponent.style.transform=l),n.onTransformCallbacks.forEach(function(u){return u({scale:i,positionX:s,positionY:o,previousScale:n.state.previousScale,ref:Xn(n)})})}},this.setState=function(r,i,s){var o=n.props.onTransform;if(!Number.isNaN(r)&&!Number.isNaN(i)&&!Number.isNaN(s)){var l=Math.max(r,1e-7);l!==n.state.scale&&(n.state.previousScale=n.state.scale,n.state.scale=l),n.state.positionX=i,n.state.positionY=s,n.applyTransformation();var u=Xn(n);n.onChangeCallbacks.forEach(function(d){return d(u)}),nr(u,{scale:n.state.scale,positionX:i,positionY:s},o)}else console.error("Detected NaN set state values")},this.onTransform=function(r){return n.onTransformCallbacks.has(r)||n.onTransformCallbacks.add(r),function(){n.onTransformCallbacks.delete(r)}},this.onChange=function(r){return n.onChangeCallbacks.has(r)||n.onChangeCallbacks.add(r),function(){n.onChangeCallbacks.delete(r)}},this.onInit=function(r){return n.onInitCallbacks.has(r)||n.onInitCallbacks.add(r),function(){n.onInitCallbacks.delete(r)}},this.init=function(r,i){n.cleanupWindowEvents(),n.wrapperComponent=r,n.contentComponent=i,Qd(n,n.state.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(i),n.initializeWindowEvents(),n.isInitialized=!0;var s=Xn(n);nr(s,void 0,n.props.onInit),gpe(n.props.ref,s)},this.props=t,this.setup=II(this.props),this.state=hF(this.props)}return e})(),Fb=ct.createContext(null),Fpe=function(e,t){return typeof e=="function"?e(t):e},$pe=ct.forwardRef(function(e,t){var n=b.useRef(new jpe(e)).current,r=Fpe(e.children,b1(n));return b.useImperativeHandle(t,function(){return b1(n)},[n]),b.useEffect(function(){n.update(e)},[n,e]),m.jsx(Fb.Provider,io({value:n},{children:r}))});ct.forwardRef(function(e,t){var n=b.useRef(null),r=b.useContext(Fb);return b.useEffect(function(){return r.onChange(function(i){if(n.current){var s=0,o=0;n.current.style.transform=r.handleTransformStyles(s,o,1/i.instance.state.scale)}})},[r]),m.jsx("div",io({},e,{ref:vpe([n,t])}))});function Hpe(e,t){t===void 0&&(t={});var n=t.insertAt;if(!(typeof document>"u")){var r=document.head||document.getElementsByTagName("head")[0],i=document.createElement("style");i.type="text/css",n==="top"&&r.firstChild?r.insertBefore(i,r.firstChild):r.appendChild(i),i.styleSheet?i.styleSheet.cssText=e:i.appendChild(document.createTextNode(e))}}var Upe=`.transform-component-module_wrapper__SPB86 {
583
583
  position: relative;
@@ -715,7 +715,7 @@ WARNING: This link could potentially be dangerous`)){let n=window.open();if(n){t
715
715
  `))return null;const n=q0e(t);return!n||/^[a-z][a-z0-9+.-]*:\/\//i.test(n)||Gk(n)||n.split("/").includes("...")?null:n}function Y0e(e){return e.includes("/")?!1:Qk(e)}function K0e(e){const t=e.split("/").pop()??e;if(/^\d+(?:\.\d+)+$/.test(t))return!1;if(e.includes("/"))return!0;const n=e.replace(P6,""),r=n.split("/").pop()??n;return/[A-Za-z_-]/.test(r)}function G0e(e){const t=V0e(e);return!t||Y0e(t)||!K0e(t)?null:W0e.test(t)?{kind:"image-preview",path:t}:P6.test(t)?{kind:"file-download",path:t}:null}const X0e=16,Z0e=24,Oh=6,Q0e=425,lp=-1;function ld(e,t){return e.pointerId===t||t===lp&&e.touchIdentifier!==null}function Ic(e,t){if(t===null)return null;for(let n=0;n<e.length;n+=1){const r=e[n];if((r==null?void 0:r.identifier)===t)return r}return null}function _v(e,t){let n=null,r=Number.POSITIVE_INFINITY;for(let i=0;i<e.length;i+=1){const s=e[i];if(!s)continue;const o=Math.hypot(s.clientX-t.clientX,s.clientY-t.clientY);o>=r||(n=s,r=o)}return n}function cd(e){return Math.hypot(e.lastX-e.startX,e.lastY-e.startY)}function Fi(e,t={}){const n=window.__ccTestPtyTouchGestureEvents;n&&(n.push({event:e,t:performance.now(),...t}),n.length>200&&n.splice(0,n.length-200))}function J0e({terminalRef:e,suppressPtyFocus:t,focusTerminal:n,isGestureTarget:r,onLongPressCandidateStart:i,onTap:s,isTapCandidate:o,onLongPressStart:l,onLongPressMove:u,onLongPressEnd:d,onGestureFinish:f,getScrollPosition:p}){const y=b.useRef(null),g=b.useRef(null);b.useEffect(()=>{const B=Y=>{const z=g.current;z&&(z.touchIdentifier!==null&&!Ic(Y.changedTouches,z.touchIdentifier)||(g.current=null,(z.kind==="longpress"||z.kind==="link")&&Y.cancelable&&Y.preventDefault()))},F=()=>{g.current=null};return document.addEventListener("touchend",B,{capture:!0,passive:!1}),document.addEventListener("touchcancel",F,{capture:!0}),()=>{document.removeEventListener("touchend",B,{capture:!0}),document.removeEventListener("touchcancel",F,{capture:!0})}},[]);const _=b.useCallback(B=>{B.longPressTimer!==null&&(window.clearTimeout(B.longPressTimer),B.longPressTimer=null)},[]),w=b.useCallback(B=>{B.longPressed||B.moved||(B.longPressed=!0,B.longPressArmed=!1,_(B),t(),l==null||l({clientX:B.startX,clientY:B.startY}))},[_,l,t]),x=b.useCallback(B=>{if(!(B.longPressed||B.longPressArmed||B.moved)){if(cd(B)>Oh){_(B),Fi("longpress:cancel-drift",{distance:cd(B),threshold:Oh});return}if(o!=null&&o({clientX:B.startX,clientY:B.startY})){B.longPressArmed=!0,_(B),Fi("longpress:arm-link",{clientX:B.startX,clientY:B.startY});return}w(B)}},[_,o,w]),S=b.useCallback((B,F=!0)=>{if(B.longPressDelivered||!B.longPressed||B.moved)return;B.longPressDelivered=!0;const Y={clientX:B.lastX,clientY:B.lastY};F?window.setTimeout(()=>d==null?void 0:d(Y),0):d==null||d(Y)},[d]),k=b.useCallback((B,F,Y,z=!1,q=null)=>{g.current=null;const K={pointerId:B,touchIdentifier:q,startX:F,startY:Y,lastX:F,lastY:Y,moved:!1,longPressArmed:!1,longPressed:!1,longPressDelivered:!1,touchEventStream:z,longPressTimer:null,scrollPositionAtStart:(p==null?void 0:p())??null};K.longPressTimer=window.setTimeout(()=>{y.current===K&&x(K)},Q0e),y.current=K,Fi("start",{pointerId:B,clientX:F,clientY:Y,touchEventStream:z}),i==null||i({clientX:F,clientY:Y})},[p,x,i]),T=b.useCallback(B=>{const F=B.scrollPositionAtStart,Y=(p==null?void 0:p())??null;return!F||!Y?!1:Math.abs(Y.scrollLeft-F.scrollLeft)>.5||Math.abs(Y.scrollTop-F.scrollTop)>.5},[p]),N=b.useCallback((B,F,Y)=>{const z=y.current;if(!z||!ld(z,B))return!1;z.lastX=F,z.lastY=Y;const q=cd(z);if(z.longPressArmed&&q>Oh&&(z.longPressArmed=!1,Fi("longpress:cancel-armed-drift",{pointerId:B,clientX:F,clientY:Y,distance:q,threshold:Oh})),z.longPressed)return Fi("move",{pointerId:B,clientX:F,clientY:Y,distance:q,moved:z.moved,longPressed:!0}),u==null||u({clientX:F,clientY:Y}),!0;const K=F-z.startX,$=Y-z.startY;return!z.moved&&q>=X0e&&(z.moved=!0,_(z)),Fi("move",{pointerId:B,clientX:F,clientY:Y,dx:K,dy:$,distance:q,moved:z.moved,longPressed:!1}),z.moved},[_,u]),P=b.useCallback((B,F)=>{var K;const Y=y.current;if(!Y||!ld(Y,B))return null;F&&(Y.lastX=F.clientX,Y.lastY=F.clientY),y.current=null,_(Y);const z=cd(Y);let q;if(Y.longPressArmed){if(z<=Oh)return w(Y),S(Y),q="longpress",Fi("finish",{pointerId:B,result:q,point:F,moved:Y.moved,distance:z,longPressed:!0,longPressArmed:!0}),f==null||f(q),q;Y.longPressArmed=!1}return Y.longPressed?(S(Y),q="longpress",Fi("finish",{pointerId:B,result:q,point:F,moved:Y.moved,longPressArmed:Y.longPressArmed,distance:z,longPressed:!0}),f==null||f(q),q):T(Y)?(t(),q="scroll",Fi("finish",{pointerId:B,result:q,point:F,moved:Y.moved,distance:z,longPressed:!1,containerScrolled:!0}),f==null||f(q),q):Y.moved?F&&cd(Y)<=Z0e&&(s!=null&&s(F))?(t(),q="link",Fi("finish",{pointerId:B,result:q,point:F,moved:!0,distance:z,longPressed:!1}),f==null||f(q),q):(t(),q="scroll",Fi("finish",{pointerId:B,result:q,point:F,moved:!0,distance:z,longPressed:!1}),f==null||f(q),q):F&&(s!=null&&s(F))?(t(),q="link",Fi("finish",{pointerId:B,result:q,point:F,moved:!1,distance:z,longPressed:!1}),f==null||f(q),q):(n?n():(K=e.current)==null||K.focus(),q="tap",Fi("finish",{pointerId:B,result:q,point:F,moved:!1,distance:z,longPressed:!1}),f==null||f(q),q)},[_,S,T,n,f,s,w,t,e]),R=b.useCallback((B,F={})=>{const Y=y.current;return!Y||!ld(Y,B)?null:(_(Y),y.current=null,Y.longPressed?(S(Y,F.immediateLongPressEnd!==!0),Fi("cancel",{pointerId:B,result:"longpress"}),f==null||f("longpress"),"longpress"):(Y.longPressArmed&&Fi("cancel",{pointerId:B,result:"armed"}),t(),Fi("cancel",{pointerId:B,result:"scroll",moved:Y.moved,distance:cd(Y)}),f==null||f("scroll"),"scroll"))},[_,S,f,t]),M=b.useRef(R);M.current=R,b.useEffect(()=>{const B=()=>{g.current=null;const Y=y.current;Y&&M.current(Y.pointerId,{immediateLongPressEnd:!0})},F=()=>{document.visibilityState==="hidden"&&B()};return window.addEventListener("blur",B),window.addEventListener("pagehide",B),document.addEventListener("visibilitychange",F),()=>{window.removeEventListener("blur",B),window.removeEventListener("pagehide",B),document.removeEventListener("visibilitychange",F);const Y=y.current;Y&&_(Y),y.current=null,g.current=null}},[_]);const L=b.useCallback(B=>{if(B.pointerType!=="touch")return;const F=B.target;if(!(F instanceof Element&&F.closest('[data-slot="pty-selection-handle"]'))&&!(!(F instanceof Element)||!F.closest(".xterm")&&!(r!=null&&r({clientX:B.clientX,clientY:B.clientY})))){if(y.current){B.stopPropagation();return}k(B.pointerId,B.clientX,B.clientY),B.stopPropagation()}},[r,k]),X=b.useCallback(B=>{if(B.pointerType!=="touch")return;const F=y.current;if(F&&!ld(F,B.pointerId)){B.stopPropagation();return}if(F!=null&&F.touchEventStream&&ld(F,B.pointerId)){B.stopPropagation();return}const Y=N(B.pointerId,B.clientX,B.clientY),z=y.current;z&&Y&&(B.stopPropagation(),z.longPressed&&B.preventDefault())},[N]),U=b.useCallback(B=>{const F=y.current,Y=P(B.pointerId,{clientX:B.clientX,clientY:B.clientY});Y&&(B.pointerType==="touch"&&(g.current={kind:Y,touchIdentifier:(F==null?void 0:F.touchIdentifier)??null}),B.stopPropagation(),Y==="link"&&B.cancelable&&B.preventDefault())},[P]),V=b.useCallback(B=>{const F=y.current;if(B.pointerType==="touch"&&F&&ld(F,B.pointerId)&&F.touchEventStream&&!F.longPressed){B.stopPropagation();return}const Y=R(B.pointerId);Y&&(B.pointerType==="touch"&&(g.current={kind:Y,touchIdentifier:(F==null?void 0:F.touchIdentifier)??null}),B.stopPropagation())},[R]),j=b.useCallback(B=>{const F=B.target;if(!(F instanceof Element)||F.closest('[data-slot="pty-selection-handle"]'))return;const Y=B.changedTouches[0]??B.touches[0];if(Y&&!(!F.closest(".xterm")&&!(r!=null&&r({clientX:Y.clientX,clientY:Y.clientY})))){if(y.current){if(y.current.touchIdentifier===null){const z=_v(B.changedTouches,{clientX:y.current.lastX,clientY:y.current.lastY});if(!z)return;y.current.touchIdentifier=z.identifier,y.current.touchEventStream=!0}return}k(lp,Y.clientX,Y.clientY,!0,Y.identifier)}},[r,k]),A=b.useCallback(B=>{const F=y.current;if(!F)return;if(F.touchIdentifier===null){const $=_v(B.changedTouches.length>0?B.changedTouches:B.touches,{clientX:F.lastX,clientY:F.lastY});if(!$)return;F.touchIdentifier=$.identifier,F.touchEventStream=!0}const Y=Ic(B.changedTouches,F.touchIdentifier);if(!Y&&B.changedTouches.length>0)return;const z=Y??Ic(B.touches,F.touchIdentifier);if(!z)return;const q=N(lp,z.clientX,z.clientY),K=y.current;K&&q&&K.longPressed&&(B.stopPropagation(),B.preventDefault())},[N]),D=b.useCallback(B=>{var K;const F=y.current;if((F==null?void 0:F.touchIdentifier)===null&&B.changedTouches.length>0){const $=_v(B.changedTouches,{clientX:F.lastX,clientY:F.lastY});$&&(F.touchIdentifier=$.identifier)}const Y=F?Ic(B.changedTouches,F.touchIdentifier):null;if(F&&!Y&&Ic(B.touches,F.touchIdentifier))return;const z=Y?{clientX:Y.clientX,clientY:Y.clientY}:F?{clientX:F.lastX,clientY:F.lastY}:void 0,q=P(lp,z)??((K=g.current)==null?void 0:K.kind);g.current=null,(q==="longpress"||q==="link")&&(B.stopPropagation(),B.cancelable&&B.preventDefault())},[P]),O=b.useCallback(B=>{var z;const F=y.current;if((F==null?void 0:F.touchIdentifier)===null&&B.changedTouches.length>0){const q=_v(B.changedTouches,{clientX:F.lastX,clientY:F.lastY});q&&(F.touchIdentifier=q.identifier)}if(F&&!Ic(B.changedTouches,F.touchIdentifier)&&Ic(B.touches,F.touchIdentifier))return;const Y=R(lp)??((z=g.current)==null?void 0:z.kind);g.current=null,Y==="longpress"&&B.stopPropagation()},[R]),I=b.useCallback(B=>{const F=y.current;F&&(B.preventDefault(),B.stopPropagation(),x(F))},[x]);return{onPointerDownCapture:L,onPointerMoveCapture:X,onPointerUpCapture:U,onPointerCancelCapture:V,onTouchStartCapture:j,onTouchMoveCapture:A,onTouchEndCapture:D,onTouchCancelCapture:O,onContextMenuCapture:I}}function eSe({terminalRef:e,containerEl:t,suppressPtyFocus:n,focusPtyInput:r,isSelectionActive:i,isGestureTarget:s,onTap:o,isTapCandidate:l,onLongPressCandidateStart:u,onLongPressStart:d,onLongPressMove:f,onLongPressEnd:p,onGestureFinish:y,getTouchScrollPosition:g,onVerticalScrollIntent:_,onHorizontalScrollIntent:w,onSelectionAutoscroll:x,onHandleDragStart:S,onHandleDragMove:k,onHandleDragEnd:T,onHandleDragCancel:N}){const P=b.useRef(null),R=b.useRef(null),M=b.useRef(null),L=b.useRef(!1),X=b.useRef(!1),U=b.useRef(null),V=b.useRef(null),j=b.useCallback(()=>{R.current=null,M.current=null,L.current=!1,P.current!==null&&(cancelAnimationFrame(P.current),P.current=null)},[]),A=b.useCallback(()=>{var K;(K=U.current)==null||K.call(U),U.current=null,V.current=null,X.current=!1,j()},[j]),D=b.useCallback(()=>{var G;P.current=null;const K=R.current;if(!K||!t||!i())return;const $=t.getBoundingClientRect(),{dx:re,dy:Q}=A6({pointerX:K.clientX,pointerY:K.clientY,rect:$,scrollLeft:t.scrollLeft,scrollTop:t.scrollTop,scrollWidth:t.scrollWidth,scrollHeight:t.scrollHeight,clientWidth:t.clientWidth,clientHeight:t.clientHeight,edgePx:44,maxSpeedPx:18});re!==0&&(w==null||w(`selectionGestureAutoscroll dx=${Math.round(re)}`),t.scrollLeft+=re),Q!==0&&(L.current||(_==null||_(`selectionGestureAutoscroll dy=${Math.round(Q)}`),L.current=!0),t.scrollTop+=Q),(re!==0||Q!==0)&&(x==null||x({scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}),(G=M.current)==null||G.call(M,K)),P.current=requestAnimationFrame(D)},[t,i,w,x,_]),O=b.useCallback((K,$)=>{R.current=K,M.current=$,P.current===null&&(P.current=requestAnimationFrame(D))},[D]);b.useEffect(()=>A,[A]),b.useEffect(()=>{const K=()=>{const re=V.current;re?re():A()},$=()=>{document.visibilityState==="hidden"&&K()};return window.addEventListener("blur",K),window.addEventListener("pagehide",K),document.addEventListener("visibilitychange",$),()=>{window.removeEventListener("blur",K),window.removeEventListener("pagehide",K),document.removeEventListener("visibilitychange",$)}},[A]),b.useEffect(()=>{if(!t)return;const K=$=>{X.current&&$.preventDefault()};return t.addEventListener("touchmove",K,{capture:!0,passive:!1}),document.addEventListener("touchmove",K,{capture:!0,passive:!1}),()=>{t.removeEventListener("touchmove",K,{capture:!0}),document.removeEventListener("touchmove",K,{capture:!0})}},[t]);const I=b.useCallback(K=>{A(),X.current=!0,d(K)},[d,A]),B=b.useCallback(K=>{if(!f(K)){j();return}O(K,f)},[f,j,O]),F=b.useCallback(K=>{A(),p(K)},[p,A]),Y=J0e({terminalRef:e,suppressPtyFocus:n,focusTerminal:r,isGestureTarget:s,onTap:o,isTapCandidate:l,onLongPressCandidateStart:u,onLongPressStart:I,onLongPressMove:B,onLongPressEnd:F,onGestureFinish:y,getScrollPosition:g}),z=b.useCallback((K,$)=>{if($.preventDefault(),$.stopPropagation(),U.current)return;A(),X.current=!0,S(K);const re=$.pointerId,Q=$.currentTarget.getBoundingClientRect(),G={x:$.clientX-(Q.left+Q.width/2),y:$.clientY-(Q.top+Q.height/2)},Z=($e,he)=>({clientX:$e-G.x,clientY:he-G.y});let ae=()=>{};const le=$e=>{if($e.pointerId!==re)return;$e.cancelable&&$e.preventDefault();const he=Z($e.clientX,$e.clientY);k(K,he),O(he,He=>k(K,He))},me=$e=>{if($e.pointerId!==re)return;const he=Z($e.clientX,$e.clientY);ae(),U.current=null,A(),T(K,he)},ke=$e=>{$e.pointerId===re&&(ae(),U.current=null,A(),N(K))};ae=()=>{window.removeEventListener("pointermove",le),window.removeEventListener("pointerup",me),window.removeEventListener("pointercancel",ke)},U.current=ae,V.current=()=>{A(),N(K)},window.addEventListener("pointermove",le,{passive:!1}),window.addEventListener("pointerup",me),window.addEventListener("pointercancel",ke)},[N,T,k,S,A,O]),q=b.useCallback((K,$)=>{if(U.current)return;const re=$.touches[0]??$.changedTouches[0];if(!re)return;$.preventDefault(),$.stopPropagation(),X.current=!0,L.current=!1,S(K);const Q=re.identifier,G=$.currentTarget.getBoundingClientRect(),Z={x:re.clientX-(G.left+G.width/2),y:re.clientY-(G.top+G.height/2)},ae=He=>{for(let Nt=0;Nt<He.length;Nt+=1){const ye=He[Nt];if((ye==null?void 0:ye.identifier)===Q)return ye}return null},le=(He,Nt)=>({clientX:He-Z.x,clientY:Nt-Z.y});let me=()=>{};const ke=He=>{const Nt=ae(He.touches)??ae(He.changedTouches);if(!Nt)return;He.cancelable&&He.preventDefault();const ye=le(Nt.clientX,Nt.clientY);k(K,ye),O(ye,Ze=>k(K,Ze))},$e=He=>{const Nt=ae(He.changedTouches);if(!Nt)return;const ye=Nt?le(Nt.clientX,Nt.clientY):R.current;me(),U.current=null,A(),T(K,ye)},he=He=>{ae(He.changedTouches)&&(me(),U.current=null,A(),N(K))};me=()=>{window.removeEventListener("touchmove",ke),window.removeEventListener("touchend",$e),window.removeEventListener("touchcancel",he)},U.current=me,V.current=()=>{A(),N(K)},window.addEventListener("touchmove",ke,{passive:!1}),window.addEventListener("touchend",$e),window.addEventListener("touchcancel",he)},[N,T,k,S,A,O]);return{pointerHandlers:Y,stopPtySelectionGesture:A,handlePtySelectionHandlePointerDown:z,handlePtySelectionHandleTouchStart:q}}const tSe=2,vL=600,nSe=160;function tT(){return/^(Macintosh|MacIntel|MacPPC|Mac68K)$/u.test(navigator.platform)}function I6(e,t){return tT()?t.altKey&&e.options.macOptionClickForcesSelection===!0:t.shiftKey}function rSe(e,t){return e.modes.mouseTrackingMode==="none"||I6(e,t)}function iSe(e,t){return t.altKey&&!(tT()&&e.options.macOptionClickForcesSelection===!0)}function Hc(e,t){return e.row===t.row?e.column-t.column:e.row-t.row}function iy(e){const t=Os(e.anchor),n=Os(e.focus);return Hc(t,n)<=0?{start:t,end:n}:{start:n,end:t}}function sSe(e,t){if(e.columnMode)return t.row>=Math.min(e.anchor.row,e.focus.row)&&t.row<=Math.max(e.anchor.row,e.focus.row)&&t.column>=Math.min(e.anchor.column,e.focus.column)&&t.column<=Math.max(e.anchor.column,e.focus.column);const{start:n,end:r}=iy(e);return Hc(t,n)>=0&&Hc(t,r)<=0}function oSe(e){return e.key.toLowerCase()==="c"&&(tT()?e.metaKey:e.ctrlKey)}function Os(e){return{row:e.row,column:e.column}}function K0(e,t){const n=e.buffer.active;if(n.type!=="normal"||!Number.isInteger(t)||t<0||t>=n.length||!n.getLine(t))return null;let r;try{r=e.registerMarker(t-(n.baseY+n.cursorY))}catch{return null}return!r||r.isDisposed||r.line!==t?(r==null||r.dispose(),null):r}function aSe(e){const{terminalRef:t,xtermHostRef:n,selectionHandleLayerRef:r,scrollControllerRef:i,containerEl:s,keyboardOffset:o,ptyFontSize:l,suppressPtyFocus:u,focusPtyInput:d,onTap:f,isTapCandidate:p,onDownloadPath:y,onPreviewPath:g}=e,_=b.useRef(O0e()),w=b.useRef(null),x=b.useRef(null),S=b.useRef(new Map),k=b.useRef(null),T=b.useRef(null),N=b.useRef(""),P=b.useRef(!1),R=b.useRef(null),M=b.useRef(null),L=b.useRef(null),X=b.useRef(null),U=b.useRef("hide"),V=b.useRef(!1),j=b.useRef(0),A=b.useRef(0),D=b.useRef(null),O=b.useRef(null),I=b.useRef(0),B=b.useRef(o),[F,Y]=b.useState(null),[z,q]=b.useState(null),[K,$]=b.useState(null),re=b.useMemo(()=>$0e(l),[l]),Q=b.useCallback(W=>{U.current=W,V.current=!1,j.current+=1,window.clearTimeout(A.current),A.current=0},[]),G=b.useCallback((W,ie)=>{const J=window.visualViewport;return M6({clientX:W,clientY:ie,viewportWidth:(J==null?void 0:J.width)??window.innerWidth,viewportHeight:(J==null?void 0:J.height)??window.innerHeight,viewportOffsetLeft:(J==null?void 0:J.offsetLeft)??0,viewportOffsetTop:(J==null?void 0:J.offsetTop)??0})},[]),Z=b.useCallback(W=>{const ie=r.current;if(!ie||!s)return null;const J=ie.getBoundingClientRect(),ce=s.getBoundingClientRect(),Te=window.visualViewport,te=Math.max(ce.left+s.clientLeft,(Te==null?void 0:Te.offsetLeft)??0),se=Math.max(ce.top+s.clientTop,(Te==null?void 0:Te.offsetTop)??0),ue=Math.min(ce.left+s.clientLeft+s.clientWidth,((Te==null?void 0:Te.offsetLeft)??0)+((Te==null?void 0:Te.width)??window.innerWidth)),ge=Math.min(ce.top+s.clientTop+s.clientHeight,((Te==null?void 0:Te.offsetTop)??0)+((Te==null?void 0:Te.height)??window.innerHeight)),ee={anchor:{left:W.anchor.left+J.left,top:W.anchor.top+J.top},focus:{left:W.focus.left+J.left,top:W.focus.top+J.top}},oe=de=>de.left>=te&&de.left<=ue&&de.top>=se&&de.top<=ge;return{clientHandles:ee,visible:{anchor:oe(ee.anchor),focus:oe(ee.focus)}}},[s,r]),ae=b.useCallback(W=>{const ie=Z(W);if(!ie)return null;const J=["anchor","focus"].filter(se=>ie.visible[se]);if(J.length===0)return null;const ce=ie.clientHandles[J[0]],Te=ie.clientHandles[J[1]??J[0]],te=window.visualViewport;return U0e({handles:{anchor:ce,focus:Te},viewportWidth:(te==null?void 0:te.width)??window.innerWidth,viewportHeight:(te==null?void 0:te.height)??window.innerHeight,viewportOffsetLeft:(te==null?void 0:te.offsetLeft)??0,viewportOffsetTop:(te==null?void 0:te.offsetTop)??0})},[Z]),le=b.useCallback(W=>{const ie=t.current,J=n.current;return!ie||!J?null:By(J,W)??S.current.get(W)??ie.buffer.active.getLine(W)},[t,n]),me=b.useCallback(W=>{const ie=t.current,J=n.current,ce=r.current;return!ie||!J||!ce?null:H0e({terminal:ie,host:J,coordinateSpace:ce,anchor:Os(W.anchor),focus:Os(W.focus),columnMode:W.columnMode,getLine:le})},[le,r,t,n]),ke=b.useCallback(()=>{var ie;const W=t.current;return!W||!s||!W.element?null:(w.current&&x.current===W||((ie=w.current)==null||ie.dispose(),w.current=l6({terminal:W,container:s,getLine:le}),x.current=W),w.current)},[s,le,t]),$e=b.useCallback((W,ie=!1)=>{const J=t.current,ce=n.current;if(!J||!ce)return;ie&&(S.current=new Map);const Te=Math.min(W.anchor.row,W.focus.row),te=Math.max(W.anchor.row,W.focus.row),se=o6(ce);for(const[ee,oe]of se)ee>=Te&&ee<=te&&S.current.set(ee,r6(oe,J.cols));const ue=Math.max(Te,J.buffer.active.viewportY),ge=Math.min(te,J.buffer.active.viewportY+J.rows-1);for(let ee=ue;ee<=ge;ee+=1)se.has(ee)||S.current.delete(ee)},[t,n]),he=b.useCallback(W=>{const ie=Math.min(W.anchor.row,W.focus.row),J=Math.max(W.anchor.row,W.focus.row);S.current=new Map(Array.from(S.current).filter(([ce])=>ce>=ie&&ce<=J))},[]),He=b.useCallback(()=>{const W=t.current,ie=n.current;if(!W||!ie)return null;const J=W.buffer.active,ce=new Proxy(J,{get(te,se){if(se==="getLine")return ue=>S.current.get(ue)??By(ie,ue)??te.getLine(ue);if(se==="length"){let ue=0;for(const ge of S.current.keys())ue=Math.max(ue,ge+1);return Math.max(te.length,ue)}return Reflect.get(te,se,te)}}),Te=new Proxy(W.buffer,{get(te,se){return se==="active"?ce:Reflect.get(te,se,te)}});return new Proxy(W,{get(te,se){return se==="buffer"?Te:Reflect.get(te,se,te)}})},[t,n]),Nt=b.useCallback((W,ie)=>{const J=ie??G0e(W);return T.current=J,$(J),J},[]),ye=b.useCallback((W,ie)=>{$e(W);const J=He();if(!J)return null;const ce=Vb({terminal:J,anchor:Os(W.anchor),focus:Os(W.focus),columnMode:W.columnMode});return ce?(N.current=ce.text,Nt(ce.text,ie),ce):null},[$e,He,Nt]),Ze=b.useCallback(()=>{const W=ji(_.current);return W?ye(W):null},[ye]),Oe=b.useCallback((W,ie)=>{var Te;ie.toolbar==="hide"&&Q("hide");let J=null;if(ie.toolbar==="hide"){$e(W);const te=He();if(!te||W.anchor.column>=te.cols||W.focus.column>=te.cols||!te.buffer.active.getLine(W.anchor.row)||!te.buffer.active.getLine(W.focus.row))return!1;N.current="",T.current=null,$(null)}else{if(!ye(W,ie.explicitPathAction))return!1;J=T.current}(Te=ke())==null||Te.render(W),P.current=ie.handles;const ce=ie.handles?me(W):null;return q(ce),ie.toolbar==="hide"?Y(null):ie.toolbar==="path-only"&&!J?(Q("hide"),Y(null)):ce?(Q(ie.toolbar),Y(ae(ce))):ie.clientPoint?(Q(ie.toolbar),Y(G(ie.clientPoint.clientX,ie.clientPoint.clientY))):(Q("hide"),Y(null)),!0},[ke,$e,He,me,G,ae,ye,Q]),ze=b.useCallback(()=>{var ie,J;const W=k.current;if(W){k.current=null;for(const ce of W.subscriptions)ce.dispose();(ie=W.anchor)==null||ie.dispose(),(J=W.focus)==null||J.dispose()}},[]),et=b.useCallback(()=>{var W;(W=w.current)==null||W.render(null),P.current=!1,T.current=null,N.current="",Q("hide"),Y(null),q(null),$(null)},[Q]),Ct=b.useCallback(()=>{var W,ie,J;(W=O.current)==null||W.call(O),(ie=D.current)==null||ie.call(D),_.current=Ra(_.current,{type:"clear-selection"}),S.current=new Map,ze(),R.current=null,M.current=null,L.current=null,X.current=null,(J=w.current)==null||J.dispose(),w.current=null,x.current=null,et()},[et,ze]),tt=b.useCallback(()=>{var W;Ct(),(W=t.current)==null||W.clearSelection()},[Ct,t]),Le=b.useCallback((W,ie,J=!1)=>{const ce=t.current,Te=n.current;return!ce||!Te?null:P0e({terminal:ce,host:Te,clientX:W,clientY:ie,clampToBuffer:J})},[t,n]),it=b.useCallback(()=>{var ce;if(!P.current)return;const W=ji(_.current);if(!W){q(null),Y(null);return}$e(W),(ce=ke())==null||ce.render(W);const ie=me(W);if(q(ie),!ie){Y(null);return}const J=U.current;Y(J!=="hide"&&!V.current&&(J!=="path-only"||T.current)?ae(ie):null)},[$e,ke,me,ae]),dt=b.useCallback(W=>{ze();const ie=t.current;if(!ie)return!1;const J=ie.buffer.active,ce=ie.cols,Te=ie.rows;if(J.type==="alternate"){const ee={terminal:ie,buffer:J,cols:ce,rows:Te,anchor:null,focus:null,subscriptions:[],sync:()=>{}},oe=()=>{k.current===ee&&(ze(),tt())};return ee.sync=()=>{k.current===ee&&(t.current!==ie||ie.buffer.active!==J||ie.cols!==ce||ie.rows!==Te)&&oe()},k.current=ee,ee.subscriptions.push(ie.onResize(ee.sync),ie.buffer.onBufferChange(oe)),!0}const te=K0(ie,W.anchor.row);if(!te)return!1;const se=K0(ie,W.focus.row);if(!se||ie.buffer.active!==J||te.isDisposed||te.line!==W.anchor.row||se.isDisposed||se.line!==W.focus.row)return te.dispose(),se==null||se.dispose(),!1;const ue={terminal:ie,buffer:J,cols:ce,rows:Te,anchor:te,focus:se,subscriptions:[],sync:()=>{}},ge=()=>{k.current===ue&&(ze(),tt())};return ue.sync=()=>{var Ke;if(k.current!==ue)return;if(t.current!==ie||ie.buffer.active!==J||ie.cols!==ce||te.isDisposed||se.isDisposed||te.line<0||se.line<0){ge();return}const ee=_.current;if(ee.phase!=="selected"||ee.range.anchor.row===te.line&&ee.range.focus.row===se.line)return;const oe=te.line-ee.range.anchor.row,de=se.line-ee.range.focus.row;if(oe!==de){ge();return}const De={...ee.range,anchor:{...ee.range.anchor,row:te.line},focus:{...ee.range.focus,row:se.line}};if(_.current=Ra(ee,{type:"set-selection",range:De}),S.current=Mh(S.current,oe),M.current&&(M.current={...M.current,row:M.current.row+oe}),L.current){const at=Ma(L.current.range,oe);if(!at){ge();return}L.current={range:at,lines:Mh(L.current.lines,oe)}}(Ke=ke())==null||Ke.render(De),it()},k.current=ue,ue.subscriptions.push(te.onDispose(ge),se.onDispose(ge),ie.onWriteParsed(ue.sync),ie.onResize(ue.sync),ie.buffer.onBufferChange(ge)),!0},[tt,ke,it,ze,t]),be=b.useCallback(()=>{if(!P.current)return;const W=ji(_.current),ie=r.current,J=W?me(W):null;if(!ie)return;const ce=J?Z(J):null;for(const Te of["anchor","focus"]){const te=ie.querySelector(`[data-slot="pty-selection-handle"][data-kind="${Te}"]`);if(!te)continue;const se=J==null?void 0:J[Te];if(!se){te.style.visibility!=="hidden"&&(te.style.visibility="hidden"),te.style.pointerEvents!=="none"&&(te.style.pointerEvents="none");continue}const ue=(ce==null?void 0:ce.visible[Te])===!0||X.current===Te,ge=`translate3d(${se.left}px, ${se.top}px, 0) translate(-50%, -50%)`,ee=ue?"visible":"hidden",oe=ue?"auto":"none";te.style.transform!==ge&&(te.style.transform=ge),te.style.visibility!==ee&&(te.style.visibility=ee),te.style.pointerEvents!==oe&&(te.style.pointerEvents=oe)}},[Z,me,r]),Ve=b.useCallback((W,ie,J=!1)=>{const ce={anchor:Os(W.anchor),focus:Os(W.focus),columnMode:W.columnMode};return _.current=Ra(_.current,{type:"set-selection",range:ce}),J&&(S.current=new Map),!Oe(ce,ie)||!dt(ce)?(tt(),null):ce},[dt,tt,Oe]);b.useEffect(()=>()=>{ze()},[ze]),b.useEffect(()=>{var W;return(W=w.current)==null||W.dispose(),w.current=null,x.current=null,()=>{var ie;(ie=w.current)==null||ie.dispose(),w.current=null,x.current=null}},[s]),b.useEffect(()=>{if(!s)return;const W=s.ownerDocument,ie=t.current;let J=null,ce=1,Te=null,te=!1,se=null,ue=()=>{};const ge=()=>{var Rt;const Fe=se;if(Fe){se=null;for(const It of Fe.subscriptions)It.dispose();(Rt=Fe.marker)==null||Rt.dispose()}},ee=()=>{Te!==null&&(cancelAnimationFrame(Te),Te=null)},oe=()=>{J=null,ee(),ge()};O.current=oe;const de=(Fe,Rt)=>{const It=ji(_.current);It&&(J&&(S.current=J.selectionLines),Oe(It,{handles:!1,toolbar:"hide",clientPoint:{clientX:Fe,clientY:Rt}}))},De=(Fe,Rt)=>{ge();const It=Fe.buffer.active,Ne=It.type==="normal"?K0(Fe,Rt):null;if(It.type==="normal"&&!Ne)return!1;const ut={terminal:Fe,buffer:It,cols:Fe.cols,rows:Fe.rows,marker:Ne,markerLine:(Ne==null?void 0:Ne.line)??Rt,subscriptions:[]},Pt=()=>{se===ut&&(ge(),ue())},en=()=>{if(se!==ut||!J)return;if(t.current!==Fe||Fe.buffer.active!==It||Fe.cols!==ut.cols||It.type==="alternate"&&Fe.rows!==ut.rows||Ne!=null&&Ne.isDisposed||Ne!==null&&Ne.line<0){Pt();return}if(!Ne)return;const pn=Ne.line-ut.markerLine;if(pn!==0){if(ut.markerLine=Ne.line,_.current=D0e(_.current,pn),J.initialRange=J.initialRange?Ma(J.initialRange,pn):null,J.selectionLines=Mh(J.selectionLines,pn),J.selectionLinesBeforePress=Mh(J.selectionLinesBeforePress,pn),S.current=Mh(S.current,pn),_.current.phase!=="pressed"&&_.current.phase!=="selecting"){Pt();return}de(J.lastX,J.lastY)}};return se=ut,ut.subscriptions.push(Fe.onWriteParsed(en),Fe.onResize(en),Fe.buffer.onBufferChange(Pt)),Ne&&ut.subscriptions.push(Ne.onDispose(Pt)),!0},Ke=(Fe,Rt)=>{const It=He();return It?Rt==="line"?I0e({terminal:It,point:Fe}):Rt==="word"?q0({terminal:It,point:Fe})??W0({terminal:It,point:Fe}):null:null},at=Fe=>{if(!J||!Fe||J.unit==="cell"||!J.initialRange)return null;const Rt=Ke(Fe,J.unit);if(!Rt)return J.initialRange;const It=iy(J.initialRange),Ne=iy({anchor:Rt.anchor,focus:Rt.focus});return Hc(Ne.end,It.start)<0?{anchor:It.end,focus:Ne.start}:Hc(Ne.start,It.end)>0?{anchor:It.start,focus:Ne.end}:J.initialRange},st=()=>{if(!J)return;const Fe=Le(J.lastX,J.lastY,!0);_.current=Ra(_.current,{type:"selection-autoscroll",pointerId:J.id,bufferPoint:Fe,range:at(Fe)}),de(J.lastX,J.lastY)},Et=()=>{var Pt,en;if(Te=null,!J||!xE(_.current))return;const Fe=s.getBoundingClientRect(),{dx:Rt,dy:It}=A6({pointerX:J.lastX,pointerY:J.lastY,rect:Fe,scrollLeft:s.scrollLeft,scrollTop:s.scrollTop,scrollWidth:s.scrollWidth,scrollHeight:s.scrollHeight,clientWidth:s.clientWidth,clientHeight:s.clientHeight}),Ne=s.scrollLeft,ut=s.scrollTop;Rt!==0&&((Pt=i.current)==null||Pt.markHorizontalScrollIntent(`managedSelectionAutoscroll dx=${Math.round(Rt)}`),s.scrollLeft+=Rt),It!==0&&((en=i.current)==null||en.markSelectionAutoscrollIntent(`managedSelectionAutoscroll dy=${Math.round(It)}`),s.scrollTop+=It),(s.scrollLeft!==Ne||s.scrollTop!==ut)&&st(),Te=requestAnimationFrame(Et)},kt=()=>{Te===null&&xE(_.current)&&(Te=requestAnimationFrame(Et))},lt=(Fe,Rt,It)=>{var Vt;if(!J)return;const Ne=J,ut=_.current,Pt=Fe==="cancel"?"preserve-selection":ut.phase==="pressed"?Ne.shiftExtend||Ne.unit!=="cell"?"commit-selection":"clear-on-click":"commit-selection";_.current=Ra(ut,{type:"gesture-finish",pointerId:Ne.id,result:Pt}),S.current=Pt==="preserve-selection"?Ne.selectionLinesBeforePress:Pt==="commit-selection"?Ne.selectionLines:new Map,oe(),Pt==="preserve-selection"&&((Vt=k.current)==null||Vt.sync());const en=ji(_.current);if(!en){S.current=new Map,ze(),et();return}if(he(en),!Oe(en,{handles:!1,toolbar:"path-only",clientPoint:{clientX:Rt,clientY:It}})){tt();return}Pt==="commit-selection"&&!dt(en)&&tt()};ue=()=>{var Fe;J&&((Fe=t.current)==null||Fe.clearSelection(),lt("cancel",J.lastX,J.lastY))};const Ht=Fe=>{if(Fe.button!==0)return;const Rt=t.current,It=Fe.target;if(!Rt||!(It instanceof Element))return;const Ne=Le(Fe.clientX,Fe.clientY,!1);if(!It.closest(".xterm")&&!Ne)return;const ut=I6(Rt,Fe),Pt=qxe(Rt,Fe),en=Rt.modes.mouseTrackingMode!=="none"&&!ut&&(Fe.metaKey||Fe.ctrlKey)&&Pt!==null;if(!rSe(Rt,Fe)&&!en)return;J&&lt("cancel",J.lastX,J.lastY),Fe.preventDefault(),Fe.stopImmediatePropagation(),Rt.focus(),Rt.clearSelection();const pn=ji(_.current),Vt=new Map(S.current),fe=ce++,Ee=Fe.shiftKey&&pn!==null&&Ne!==null,_e=pn&&Ee?pn.columnMode:iSe(Rt,Fe),Me=Ee?"cell":Fe.detail===3?"line":Fe.detail===2?"word":"cell",mt=Ee?new Map(Vt):new Map;S.current=mt;const Ot=Ne?Ke(Ne,Me):null,bt=Ee?{anchor:pn.anchor,focus:Ne,columnMode:pn.columnMode}:Ot?{anchor:Os(Ot.anchor),focus:Os(Ot.focus)}:null;if(_.current=Ra(_.current,{type:"pointer-press",candidate:{pointerId:fe,client:{x:Fe.clientX,y:Fe.clientY},bufferPoint:Ne,columnMode:_e}}),bt&&(_.current=Ra(_.current,{type:"resolve-press-range",pointerId:fe,range:bt}),de(Fe.clientX,Fe.clientY)),J={id:fe,startX:Fe.clientX,startY:Fe.clientY,lastX:Fe.clientX,lastY:Fe.clientY,shiftExtend:Ee,unit:Me,initialRange:bt,linkCandidate:Fe.detail===1&&!Ee&&!ut&&!_e?Pt:null,selectionLinesBeforePress:Vt,selectionLines:mt},Ne&&!De(Rt,Ne.row)){ue();return}(Ee||Me!=="cell")&&queueMicrotask(()=>{t.current===Rt&&Rt.clearSelection()})},Mt=Fe=>{var Ne,ut;if(!J)return;if(Fe.buttons===0){(Ne=t.current)==null||Ne.clearSelection(),lt("release",Fe.clientX,Fe.clientY);return}Fe.preventDefault(),Fe.stopImmediatePropagation(),J.lastX=Fe.clientX,J.lastY=Fe.clientY;const Rt=_.current;if(Rt.phase==="pressed"&&Math.hypot(Fe.clientX-J.startX,Fe.clientY-J.startY)<tSe)return;(ut=t.current)==null||ut.clearSelection(),J.linkCandidate=null;const It=Le(Fe.clientX,Fe.clientY,!0);_.current=Ra(Rt,{type:"pointer-move",pointerId:J.id,client:{x:Fe.clientX,y:Fe.clientY},bufferPoint:It,range:at(It)}),_.current.phase==="selecting"&&(de(Fe.clientX,Fe.clientY),kt())},ln=Fe=>{var ut,Pt;if(!J||Fe.button!==0)return;const Rt=_.current.phase==="pressed"&&J.unit==="cell"&&!J.shiftExtend,It=Rt?J.linkCandidate:null;Fe.preventDefault(),Fe.stopImmediatePropagation(),(ut=t.current)==null||ut.clearSelection(),lt("release",Fe.clientX,Fe.clientY),!((It==null?void 0:It.activateOnMouseUp(Fe))===!0)&&Rt&&It===null&&(f==null||f({clientX:Fe.clientX,clientY:Fe.clientY,pointerType:"mouse",altKey:Fe.altKey,ctrlKey:Fe.ctrlKey,metaKey:Fe.metaKey,shiftKey:Fe.shiftKey})),(Pt=t.current)==null||Pt.focus()},hn=()=>{var Fe;J&&((Fe=t.current)==null||Fe.clearSelection(),lt("cancel",J.lastX,J.lastY))},Ae=Fe=>{var Rt;!J||Fe.pointerType!=="mouse"||((Rt=t.current)==null||Rt.clearSelection(),lt("cancel",Fe.clientX,Fe.clientY))},Ge=()=>{var Fe;!J||W.visibilityState!=="hidden"||((Fe=t.current)==null||Fe.clearSelection(),lt("cancel",J.lastX,J.lastY))},ot=()=>{var Fe;J&&((Fe=t.current)==null||Fe.clearSelection(),lt("cancel",J.lastX,J.lastY))},pt=Fe=>{var It;const Rt=((It=Ze())==null?void 0:It.text)??"";!Rt||!Fe.clipboardData||(te=!0,Fe.clipboardData.setData("text/plain",Rt),Fe.preventDefault(),Fe.stopImmediatePropagation())},jt=Fe=>{var Rt;if(ji(_.current)){if(oSe(Fe)){const It=((Rt=Ze())==null?void 0:Rt.text)??"";if(!It)return;Fe.preventDefault(),Fe.stopImmediatePropagation(),te=!1;try{W.execCommand("copy")}catch{}if(!te){const Ne=W.activeElement instanceof HTMLElement?W.activeElement:null;Ap(It,{allowUserGestureFallback:!0}).finally(()=>{Ne!=null&&Ne.isConnected&&(W.activeElement===W.body||W.activeElement===null)&&Ne.focus({preventScroll:!0})})}return}Fe.key==="Shift"||Fe.key==="Control"||Fe.key==="Meta"||Fe.key==="Alt"||tt()}},sn=Fe=>{var Ee,_e,Me;const Rt=t.current,It=Fe.target,Ne=Le(Fe.clientX,Fe.clientY,!1);if(!Rt||!(It instanceof Element)||!It.closest(".xterm")&&!Ne)return;const ut=ji(_.current);if(Ne&&(!ut||!sSe(ut,Ne))){const mt=S.current;S.current=new Map;const Ot=He();if(!Ot){S.current=mt;return}const bt=q0({terminal:Ot,point:Ne}),An=bt??W0({terminal:Ot,point:Ne});An?Ve(An,{handles:!1,toolbar:"hide",clientPoint:{clientX:Fe.clientX,clientY:Fe.clientY},explicitPathAction:bt==null?void 0:bt.pathAction},!0):S.current=mt}if(!ji(_.current))return;const en=((Ee=Ze())==null?void 0:Ee.text)??"",pn=(_e=Rt.element)==null?void 0:_e.querySelector(".xterm-helper-textarea"),Vt=(Me=Rt.element)==null?void 0:Me.querySelector(".xterm-screen");if(!pn||!Vt)return;Fe.stopImmediatePropagation();const fe=Vt.getBoundingClientRect();Object.assign(pn.style,{width:"20px",height:"20px",left:`${Fe.clientX-fe.left-10}px`,top:`${Fe.clientY-fe.top-10}px`,zIndex:"1000"}),pn.value=en,pn.focus({preventScroll:!0}),pn.select()};return s.addEventListener("mousedown",Ht,!0),s.addEventListener("copy",pt,!0),s.addEventListener("keydown",jt,!0),s.addEventListener("contextmenu",sn,!0),W.addEventListener("mousemove",Mt,!0),W.addEventListener("mouseup",ln,!0),W.addEventListener("pointercancel",Ae,!0),W.addEventListener("visibilitychange",Ge),window.addEventListener("blur",hn),window.addEventListener("pagehide",ot),()=>{J?(ie==null||ie.clearSelection(),lt("cancel",J.lastX,J.lastY)):oe(),O.current===oe&&(O.current=null),s.removeEventListener("mousedown",Ht,!0),s.removeEventListener("copy",pt,!0),s.removeEventListener("keydown",jt,!0),s.removeEventListener("contextmenu",sn,!0),W.removeEventListener("mousemove",Mt,!0),W.removeEventListener("mouseup",ln,!0),W.removeEventListener("pointercancel",Ae,!0),W.removeEventListener("visibilitychange",Ge),window.removeEventListener("blur",hn),window.removeEventListener("pagehide",ot)}},[dt,tt,et,s,Le,He,f,Oe,he,Ze,ze,i,Ve,t]),b.useLayoutEffect(()=>{if(!F&&!z&&!K)return;const W=ie=>{const J=ie.target;if(J instanceof Element&&J.closest('[data-slot="pty-selection-toolbar"], [data-slot="pty-selection-handle"]'))return;const ce="pointerType"in ie&&typeof ie.pointerType=="string"?ie.pointerType:null,Te=J instanceof Element&&J.closest(".xterm")!==null,te=Te||J instanceof Element&&J.closest('[data-slot="pty-spacer"], [data-slot="pty-host"]')!==null,se=!Te&&te&&"clientX"in ie&&typeof ie.clientX=="number"&&"clientY"in ie&&typeof ie.clientY=="number"&&Le(ie.clientX,ie.clientY,!1)!==null,ue=J instanceof Element&&J.closest('[data-slot="pty-scrollbar"], [data-slot="pty-horizontal-scrollbar"]')!==null;j0e({hasManagedSelection:ji(_.current)!==null,eventType:ie.type,pointerType:ce,targetIsScrollSurface:ue||te&&(ie.type==="touchstart"||ce==="touch")})||ce==="mouse"&&(Te||se)||tt()};return document.addEventListener("pointerdown",W,!0),document.addEventListener("touchstart",W,!0),()=>{document.removeEventListener("pointerdown",W,!0),document.removeEventListener("touchstart",W,!0)}},[tt,Le,z,K,F]);const ft=z!==null;b.useLayoutEffect(()=>{ft&&be()},[ft,z,be]),b.useLayoutEffect(()=>{if(!ft||!s)return;const W=t.current;be(),s.addEventListener("scroll",be,{passive:!0});const ie=W==null?void 0:W.onScroll(be),J=W==null?void 0:W.onRender(be),ce=W==null?void 0:W.onResize(be),Te=new ResizeObserver(be);Te.observe(s);const te=r.current;te&&Te.observe(te);const se=n.current;return se&&Te.observe(se),()=>{s.removeEventListener("scroll",be),ie==null||ie.dispose(),J==null||J.dispose(),ce==null||ce.dispose(),Te.disconnect()}},[s,ft,r,be,t,n]),b.useLayoutEffect(()=>{var ie;const W=B.current!==o;B.current=o,W&&(I.current=performance.now()+vL),ft&&((ie=i.current)==null||ie.relayout(),it(),be())},[ft,o,it,i,be]),b.useEffect(()=>{if(!ft)return;const W=window.visualViewport;let ie=0,J=0;const ce=()=>{I.current=performance.now()+vL,cancelAnimationFrame(ie),window.clearTimeout(J),ie=requestAnimationFrame(()=>{it(),be(),J=window.setTimeout(()=>{ie=requestAnimationFrame(()=>{it(),be()})},160)})};return it(),be(),window.addEventListener("resize",ce),W==null||W.addEventListener("resize",ce),W==null||W.addEventListener("scroll",ce),()=>{cancelAnimationFrame(ie),window.clearTimeout(J),window.removeEventListener("resize",ce),W==null||W.removeEventListener("resize",ce),W==null||W.removeEventListener("scroll",ce)}},[ft,it,be]);const St=b.useCallback(({clientX:W,clientY:ie})=>{u({blur:!1}),R.current=Le(W,ie,!1)},[Le,u]),wt=b.useCallback(({clientX:W,clientY:ie})=>{const J=t.current;if(!J)return;const ce=Le(W,ie,!1)??R.current;if(J.clearSelection(),!ce){tt();return}S.current=new Map;const Te=He();if(!Te)return;const te=q0({terminal:Te,point:ce}),se=te??W0({terminal:Te,point:ce});if(!se){tt();return}M.current=null,Ve(se,{handles:!0,toolbar:"hide",clientPoint:{clientX:W,clientY:ie},explicitPathAction:te==null?void 0:te.pathAction},!0)},[tt,Le,He,Ve,t]),fn=b.useCallback(({clientX:W,clientY:ie})=>{const J=Le(W,ie,!0),ce=ji(_.current);if(!J||!ce)return!1;if(!M.current){const{start:te,end:se}=iy(ce),ue=Hc(J,te),ge=Hc(J,se);if(ue>=0&&ge<=0)return!1;M.current=Os(ue<0?se:te)}const Te={anchor:M.current,focus:J,text:""};return Ve(Te,{handles:!0,toolbar:"hide",clientPoint:{clientX:W,clientY:ie}})!==null},[Le,Ve]),Xt=b.useCallback(W=>{const ie=ji(_.current);ie&&(he(ie),Oe(ie,{handles:!0,toolbar:"show",clientPoint:W}))},[Oe,he]),Jt=b.useCallback(()=>{const W=U.current;if(W==="hide"||X.current!==null)return;const ie=ji(_.current);if(!ie||!Ze()||W==="path-only"&&!T.current)return;const J=me(ie);Y(J?ae(J):null)},[me,ae,Ze]);b.useLayoutEffect(()=>{if(!s)return;const W=s.ownerDocument,ie=W.defaultView??window;let J=!1;const ce=()=>{window.clearTimeout(A.current),A.current=0},Te=()=>{if(ce(),J||!V.current||U.current==="hide"||W.visibilityState==="hidden")return;const de=++j.current;A.current=window.setTimeout(()=>{A.current=0,!(de!==j.current||J||U.current==="hide"||W.visibilityState==="hidden")&&(V.current=!1,Jt())},nSe)},te=()=>{U.current!=="hide"&&(V.current=!0,Y(null),Te())},se=de=>{de.touches.length!==0&&(J=!0,j.current+=1,ce())},ue=de=>{de.touches.length>0||(J=!1,Te())},ge=()=>{J=!1,j.current+=1,ce()},ee=()=>{W.visibilityState==="hidden"?ge():Te()},oe=()=>Te();return s.addEventListener("scroll",te,{passive:!0}),s.addEventListener("touchstart",se,{passive:!0,capture:!0}),W.addEventListener("touchend",ue,{passive:!0,capture:!0}),W.addEventListener("touchcancel",ue,{passive:!0,capture:!0}),W.addEventListener("visibilitychange",ee),ie.addEventListener("blur",ge),ie.addEventListener("focus",oe),ie.addEventListener("pagehide",ge),ie.addEventListener("pageshow",oe),()=>{j.current+=1,V.current=!1,ce(),s.removeEventListener("scroll",te),s.removeEventListener("touchstart",se,!0),W.removeEventListener("touchend",ue,!0),W.removeEventListener("touchcancel",ue,!0),W.removeEventListener("visibilitychange",ee),ie.removeEventListener("blur",ge),ie.removeEventListener("focus",oe),ie.removeEventListener("pagehide",ge),ie.removeEventListener("pageshow",oe)}},[s,Jt]);const xn=b.useCallback(({clientX:W,clientY:ie})=>{R.current=null,M.current=null,Xt({clientX:W,clientY:ie})},[Xt]),mn=b.useCallback(()=>{var ie;const W=((ie=Ze())==null?void 0:ie.text)??"";W&&Ap(W,{allowUserGestureFallback:!0}).then(J=>{tt(),J==="failed"?We.error("复制失败"):We.success("已复制")})},[tt,Ze]),yt=b.useCallback(()=>{if(!Ze())return;const W=T.current;W&&(W.kind==="image-preview"?g(W.path):y(W.path),tt())},[tt,y,g,Ze]),Zt=b.useCallback(()=>ji(_.current)!==null,[]),zt=b.useCallback(()=>!s||performance.now()<=I.current?null:{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop},[s]),yn=b.useCallback(W=>{X.current=W;const ie=ji(_.current);L.current=ie?{range:{...ie,anchor:{...ie.anchor},focus:{...ie.focus}},lines:new Map(S.current)}:null,Q("hide"),Y(null)},[Q]),$n=b.useCallback((W,{clientX:ie,clientY:J})=>{const ce=Le(ie,J,!0),Te=ji(_.current);if(!ce||!Te)return;const te={anchor:W==="anchor"?ce:Os(Te.anchor),focus:W==="focus"?ce:Os(Te.focus),columnMode:Te.columnMode,text:""};Ve(te,{handles:!0,toolbar:"hide",clientPoint:{clientX:ie,clientY:J}})},[Le,Ve]),Zn=b.useCallback((W,ie)=>{X.current=null,L.current=null,Xt(ie??void 0)},[Xt]),Jn=b.useCallback(()=>{X.current=null;const W=L.current;if(L.current=null,!W){Xt();return}if(S.current=W.lines,_.current=Ra(_.current,{type:"set-selection",range:W.range}),!Oe(W.range,{handles:!0,toolbar:"show"})){tt();return}dt(W.range)||tt()},[dt,tt,Oe,Xt]),gn=eSe({terminalRef:t,containerEl:s,suppressPtyFocus:u,focusPtyInput:d,isSelectionActive:Zt,isGestureTarget:({clientX:W,clientY:ie})=>Le(W,ie,!1)!==null,onTap:f,isTapCandidate:p,onLongPressCandidateStart:St,onLongPressStart:wt,onLongPressMove:fn,onLongPressEnd:xn,getTouchScrollPosition:zt,onGestureFinish:W=>{F0e(W)&&tt()},onVerticalScrollIntent:W=>{var ie;return(ie=i.current)==null?void 0:ie.markSelectionAutoscrollIntent(W)},onHorizontalScrollIntent:W=>{var ie;return(ie=i.current)==null?void 0:ie.markHorizontalScrollIntent(W)},onHandleDragStart:yn,onHandleDragMove:$n,onHandleDragEnd:Zn,onHandleDragCancel:Jn});return D.current=gn.stopPtySelectionGesture,{pointerHandlers:gn.pointerHandlers,ptySelectionToolbar:F,ptySelectionHandles:z,ptySelectionPathAction:K,ptySelectionHandleMetrics:re,hasPtySelection:Zt,clearManagedPtySelection:Ct,clearPtySelection:tt,copyPtySelection:mn,openPtySelectionPathAction:yt,handlePtySelectionHandlePointerDown:gn.handlePtySelectionHandlePointerDown,handlePtySelectionHandleTouchStart:gn.handlePtySelectionHandleTouchStart}}function lSe(){return Ie(e=>e.ptyScrollTraceEnabled)}const cSe=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function yL(e){return cSe.has(e)}function nT(e){if(!e)return null;const t=Array.from(e.items??[]);for(const r of t){if(r.kind!=="file"||!yL(r.type))continue;const i=r.getAsFile();if(i)return i}return Array.from(e.files??[]).find(r=>yL(r.type))??null}function uSe(e){return`${e.startsWith("@")?e:`@${e}`} `}async function O6(e){const t=nT(e.clipboardData);if(!t)return null;if(!e.relay)throw new Error("请先连接开发机");const n=await T6(t),r=await e.relay.uploadClipboardImage(e.sessionId,n);if(!r.success||!r.path)throw new Error(r.error??"剪贴板图片上传失败");return{path:r.path,pathMention:uSe(r.path)}}function dSe(e){if(!(e!=null&&e.files)||e.files.length===0)return null;for(const t of e.files)if(!t.type.startsWith("image/"))return t;return null}function fSe({sessionId:e,terminalRef:t,onAfterPaste:n}){return b.useCallback(async r=>{var u;const i=r.clipboardData,s=!!nT(i),o=s?null:dSe(i);if(!s&&!o)return;r.preventDefault(),r.stopPropagation();const l=Ft;if(!l){We.error("请先连接开发机");return}if(s){const d=We.loading("图片上传中...");try{const f=await O6({clipboardData:i,relay:l,sessionId:e});if(We.dismiss(d),!f)return;So(e,f.pathMention)}catch(f){We.error(f instanceof Error?f.message:String(f),{id:d});return}}else if(o){const d=await Up({relay:l,sessionId:e,file:o});if(!d)return;So(e,`@${d} `)}n==null||n(),(u=t.current)==null||u.focus()},[e,t,n])}const hSe=new Set(["Enter","Backspace","Tab","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Delete","Home","End"]),bL={caseSensitive:!1,regex:!1,wholeWord:!1,decorations:vE};function pSe({softKeyboardEditingSurface:e,ptyInputFocused:t,keyboardOpen:n}){return e&&t&&n}function mSe({controlsVisible:e,keyboardOpen:t,previous:n}){return e?!n.controlsVisible||t&&!n.keyboardOpen:!1}function gSe({touchEditingSurface:e,inputModePreference:t,detectedPhysicalKeyboard:n,softKeyboardDetected:r}){return!e||t==="hardware"?!0:t==="touch"?!1:n&&!r}function vSe({active:e,touchEditingSurface:t,key:n,code:r,altKey:i=!1,ctrlKey:s=!1,metaKey:o=!1,isComposing:l=!1,targetAcceptsPtyInput:u=!0}){return!e||!t||!u||l||i||s||o||!r||r==="Unidentified"?!1:n.length===1?!0:n==="Unidentified"||n==="Process"||n==="Dead"?!1:hSe.has(n)}const _L=8,ySe=32;function bSe({showMobilePtyControls:e,horizontalScrollable:t,mobileControlsHeight:n}){return e?Math.ceil(Math.max(0,n))+_L:t?ySe:_L}function _Se(e,t){return e.isComposing||e.altKey||e.ctrlKey||e.metaKey?null:e.key.length===1?e.key:e.key==="Enter"?"\r":e.key==="Backspace"?"":e.key==="Tab"?e.shiftKey?"\x1B[Z":" ":e.key==="Escape"?"\x1B":e.key==="ArrowUp"?ap("\x1B[A",t):e.key==="ArrowDown"?ap("\x1B[B",t):e.key==="ArrowRight"?ap("\x1B[C",t):e.key==="ArrowLeft"?ap("\x1B[D",t):e.key==="Delete"?"\x1B[3~":e.key==="Home"?"\x1B[H":e.key==="End"?"\x1B[F":null}function wSe(e){const{sessionId:t,active:n=!0,containerEl:r,spacerRef:i,xtermHostRef:s,selectionHandleLayerRef:o,mobileControlsHeight:l}=e,u=v0e(),d=u.markDisconnected,f=w0e(),p=lSe(),{openImagePreview:y}=Ck(),g=b.useRef(null),_=b.useRef(null),w=b.useRef(null),x=b.useRef(!1),S=b.useRef([]),k=b.useRef(null),T=b.useRef(null),N=b.useRef(n),P=b.useRef(n),R=b.useRef(!1),M=b.useRef(!1),L=b.useRef(!1),X=b.useRef(!1),U=b.useRef(null),V=b.useRef(null),j=b.useRef(null),A=b.useRef(null),D=b.useRef({keyboardOpen:!1,controlsVisible:!1}),O=b.useRef(!1),I=b.useRef(!1),B=b.useRef(!1),F=b.useRef({keyboardOffset:0,hasSeenSoftKeyboard:!1,showMobilePtyControls:!1,touchEditingSurface:!1,ptyInputFocused:!1,containerPaddingBottom:0,mobileControlsBottomInset:0}),[Y,z]=b.useState({scrollTop:0,scrollLeft:0,scrollHeight:0,scrollWidth:0,clientHeight:0,clientWidth:0,scrollable:!1,horizontalScrollable:!1}),[q,K]=b.useState(!1),[$,re]=b.useState(!1),[Q,G]=b.useState({resultIndex:-1,resultCount:0}),Z=Ie(Ae=>Ae.connected),ae=Ie(Ae=>Ae.proxyOnline),le=Ie(Ae=>Ae.ptyFontSize),me=Ie(Ae=>Ae.inputModePreference),ke=Ie(Ae=>Ae.adaptiveInputModality),$e=Ie(Ae=>Ae.setAdaptiveInputModality),he=ke==="hardware",He=co("(pointer: coarse), (hover: none)"),{bottomOffset:Nt,layoutBottomInset:ye}=eT(),Ze=me==="hardware",Oe=gSe({touchEditingSurface:He,inputModePreference:me,detectedPhysicalKeyboard:he,softKeyboardDetected:Nt>0}),ze=He&&!Oe,et=Oe?0:Nt,Ct=et>0,tt=Oe?0:ye,[Le,it]=b.useState(()=>Z&&ae);O.current=Oe,N.current=n,R.current=u.ready,M.current=Z&&ae;const dt=b.useCallback(()=>N.current&&R.current&&M.current,[]);b.useEffect(()=>{Z&&ae&&it(!0)},[Z,ae]),b.useEffect(()=>{et>0&&K(!0)},[et]);const be=_0e({containerEl:r,xtermHostRef:s,terminalRef:g}),{ptyInputFocused:Ve,suppressPtyFocus:ft,focusPtyInput:St,handleFocusCapture:wt,handleBlurCapture:fn}=be,Xt=pSe({softKeyboardEditingSurface:ze,ptyInputFocused:Ve,keyboardOpen:Ct});F.current={keyboardOffset:et,hasSeenSoftKeyboard:q,showMobilePtyControls:Xt,touchEditingSurface:He,ptyInputFocused:Ve,containerPaddingBottom:F.current.containerPaddingBottom,mobileControlsBottomInset:tt};const Jt=f.clearNewFramesWhileAway;V.current||(V.current=sL(()=>{var Ae;(Ae=T.current)==null||Ae.relayout()}));const xn=b.useCallback(()=>{B.current=!1},[]);j.current||(j.current=sL(()=>{var Ge,ot;const Ae=A.current??{reason:"rawInput",force:!1};A.current=null,Ae.force&&xn(),(Ge=T.current)==null||Ge.traceRawInputFollowFire(),(ot=T.current)==null||ot.scrollToBottom(Ae.reason,Ae.force?{force:!0}:void 0),Jt()}));const mn=b.useCallback(()=>{if(B.current)return;const Ae=T.current;Ae&&Ae.preparePageResumeRestore(),B.current=!0},[]),yt=b.useCallback(()=>{if(!B.current||document.visibilityState==="hidden"||!N.current||!R.current)return;const Ae=T.current;Ae&&(Ae.restorePageResume(),Jt(),B.current=!1)},[Jt]);b.useEffect(()=>()=>{var Ae,Ge;(Ae=V.current)==null||Ae.dispose(),(Ge=j.current)==null||Ge.dispose(),V.current=null,j.current=null},[]),b.useEffect(()=>{const Ae=()=>{mn()},Ge=()=>{if(document.visibilityState==="hidden"){Ae();return}yt()};return document.addEventListener("visibilitychange",Ge),window.addEventListener("pagehide",Ae),window.addEventListener("pageshow",yt),window.addEventListener("focus",yt),()=>{document.removeEventListener("visibilitychange",Ge),window.removeEventListener("pagehide",Ae),window.removeEventListener("pageshow",yt),window.removeEventListener("focus",yt)}},[mn,yt]),b.useLayoutEffect(()=>{const Ae=P.current;if(P.current=n,!n){Ae&&mn();return}(!Ae||B.current)&&u.ready&&yt()},[n,u.ready,mn,yt]);const Zt=b.useCallback((Ae="rawInput",Ge)=>{var jt,sn;const ot=A.current,pt=(ot==null?void 0:ot.force)===!0||(Ge==null?void 0:Ge.force)===!0;A.current={reason:(Ge==null?void 0:Ge.force)===!0||!ot?Ae:ot.reason,force:pt},(jt=T.current)==null||jt.traceRawInputFollowScheduled(Ae),(sn=j.current)==null||sn.schedule()},[]),zt=b.useCallback((Ae,Ge)=>{var ot;!Ae.includes("\r")&&!Ae.includes(`
716
716
  `)||(ot=T.current)==null||ot.resetHorizontalScroll(Ge,{holdUntilCursorVisible:!0})},[]),yn=b.useCallback(()=>O.current?"submit":"linefeed",[]),$n=b.useCallback(()=>O.current,[]);b.useEffect(()=>{if(!n||me!=="auto"||!He)return;const Ae=ot=>{const pt=s.current,jt=r;return ot instanceof Node?pt!=null&&pt.contains(ot)||ot===document.body||ot===document.documentElement?!0:jt!=null&&jt.contains(ot)?ot instanceof HTMLElement?ot.closest('a,button,input,textarea,select,[contenteditable="true"],[role="button"],[role="textbox"]')===null:!0:!1:ot===window},Ge=ot=>{var sn,Fe;if(!vSe({active:N.current,touchEditingSurface:He,key:ot.key,code:ot.code,altKey:ot.altKey,ctrlKey:ot.ctrlKey,metaKey:ot.metaKey,isComposing:ot.isComposing,targetAcceptsPtyInput:Ae(ot.target)}))return;$e("hardware"),O.current=!0,(sn=g.current)==null||sn.focus();const pt=s.current;if(ot.target instanceof Node&&(pt!=null&&pt.contains(ot.target)))return;const jt=_Se(ot,(Fe=g.current)==null?void 0:Fe.modes);!jt||!dt()||(ot.preventDefault(),ot.stopPropagation(),So(t,jt),Zt("physicalKeyboard"),zt(jt,"physicalKeyboardEnter"))};return window.addEventListener("keydown",Ge,!0),()=>window.removeEventListener("keydown",Ge,!0)},[n,dt,r,me,zt,Zt,t,$e,He,s]);const Zn=b.useCallback(Ae=>{const Ge=Ft;if(!Ge){We.error("请先连接开发机");return}const ot=We.loading(`下载 ${Ae} ...`);Ek({relay:Ge,sessionId:t,path:Ae}).then(pt=>{pt.ok?We.success(`已开始下载 ${Ae}`,{id:ot}):We.error(pt.error,{id:ot})}).catch(pt=>{We.error(pt instanceof Error?pt.message:String(pt),{id:ot})})},[t]),Jn=b.useCallback(Ae=>{const Ge=g.current;return Ge?Kxe(Ge,S.current,Ae):!1},[]),gn=b.useCallback(Ae=>{const Ge=g.current;return Ge?Yxe(Ge,S.current,Ae):!1},[]),W=aSe({terminalRef:g,xtermHostRef:s,selectionHandleLayerRef:o,scrollControllerRef:T,containerEl:r,keyboardOffset:et,ptyFontSize:le,suppressPtyFocus:ft,focusPtyInput:St,onTap:Jn,isTapCandidate:gn,onDownloadPath:Zn,onPreviewPath:y}),ie=W.clearManagedPtySelection,J=W.clearPtySelection;I.current=W.hasPtySelection();const ce=b.useCallback(()=>{const Ae=g.current,Ge=w.current,ot=x.current&&Ae?YO(Ae.getSelectionPosition(),Ae.cols):null;Ge==null||Ge.render(ot)},[]),Te=fSe({sessionId:t,terminalRef:g,onAfterPaste:()=>Zt("paste")}),te=b.useCallback(Ae=>{if(!dt()){Ae.preventDefault();return}Te(Ae)},[dt,Te]),[se,ue]=b.useState(!1),ge=b.useCallback(Ae=>{Ae.dataTransfer.types.includes("Files")&&(Ae.preventDefault(),ue(Ge=>Ge||!0))},[]),ee=b.useCallback(Ae=>{Ae.currentTarget.contains(Ae.relatedTarget)||ue(!1)},[]),oe=b.useCallback(async Ae=>{var jt;const Ge=(jt=Ae.dataTransfer.files)==null?void 0:jt[0];if(!Ge||(Ae.preventDefault(),ue(!1),!dt()))return;const ot=Ft;if(!ot){We.error("请先连接开发机");return}const pt=await Up({relay:ot,sessionId:t,file:Ge});pt&&(So(t,`@${pt} `),Zt("dropUpload"))},[dt,Zt,t]),de=b.useCallback(Ae=>{var ot;if(!dt()){Ae.preventDefault();return}const Ge=Ae.target;Ge instanceof Element&&Ge.closest(".xterm")||(Ae.preventDefault(),(ot=g.current)==null||ot.focus())},[dt]);b.useEffect(()=>{if(!Le)return;const Ae=s.current,Ge=Da,ot=Ft,pt=r,jt=i.current;if(!Ae||!Ge||!ot||!pt||!jt)return;let sn=null,Fe=null,Rt=null,It=null,Ne=null,ut=null,Pt=null,en=null;const Ee=lxe({host:Ae,sessionId:t,ws:Ge,relay:ot,scheduleAutoFocus:ze?()=>{}:_e=>{requestAnimationFrame(()=>{uL(s.current)&&_e()})},createTerminal:async _e=>{const Me=await n6(_e,{fontSize:Ie.getState().ptyFontSize});return en=Me.serializeAddon,Me},attachRawInput:(_e,Me,mt)=>pwe(_e,Me,{...mt,getPlainEnterBehavior:yn,isPhysicalKeyboardMode:$n,physicalKeyboardMode:Ze}),isInputEnabled:dt,canFocus:dt,onTerminalReady:_e=>{J();const Me=_e;g.current=Me;const mt=new cge({highlightLimit:1e3});Me.loadAddon(mt),_.current=mt,Ne=mt.onDidChangeResults(Hn=>{G(Hn),ce()}),re(!0);const Ot=kxe(Me,y);sn=Ot.dispose;const bt=Fxe(Me,Zn);Fe=bt.dispose,S.current=[Ot.provider,bt.provider],d0e(()=>g.current);const An=z_e(Me),vr=V_e(Ae,{serializeRangeAsHtml:(Hn,Mr)=>(en==null?void 0:en.serializeAsHTML({range:{startLine:Hn,endLine:Math.min(Mr,Math.max(0,Me.buffer.active.length-1)),startCol:0},includeGlobalBackground:!0,onlySelection:!1,scrollback:0}))??"",getSerializedCell:(Hn,Mr)=>{var Ci;const Bn=(Ci=Me.buffer.active.getLine(Hn))==null?void 0:Ci.getCell(Mr);return Bn?{text:Bn.getWidth()===0?"":Bn.getChars()||" ",isDim:!!Bn.isDim(),isRenderedFgRGB:Bn.isInverse()?Bn.isBgRGB():Bn.isFgRGB()}:null},getSelectionLine:Hn=>Me.buffer.active.getLine(Hn)??null,getBufferRowIdentityOffset:An.getOffset});It=()=>{vr.dispose(),An.dispose()};const or=B.current;or&&(X.current=!1);const hi=Jwe({container:pt,spacer:jt,host:Ae,term:Me,hasNewFrame:()=>L.current,consumeNewFrame:()=>{L.current=!1},hasNewFramesWhileAway:()=>f.hasNewFramesWhileAwayRef.current,setNewFramesWhileAway:f.setHasNewFramesWhileAway,onAtBottomChange:f.handleAtBottomChange,onScrollStateChange:z,initialUserHasVerticalScrollIntent:or?!1:X.current,onUserVerticalScrollIntentChange:Hn=>{X.current=Hn},onTouchReviewStart:ft,onHistoryProjectionChange:Hn=>{const Mr=vr.render(Hn);return Mr&&ce(),Mr},getBufferRowIdentityOffset:An.getOffset});T.current=hi,Rt=hi.dispose,Pt=l6({terminal:Me,container:pt,getLine:Hn=>By(Ae,Hn)??Me.buffer.active.getLine(Hn)??null,resolveRange:()=>x.current?YO(Me.getSelectionPosition(),Me.cols):null,projectionOnly:!0,overlaySlot:"pty-search-selection-overlay",segmentSlot:"pty-search-selection-segment",selectionBackground:vE.activeMatchBackground,borderColor:vE.activeMatchBorder,opacity:"0.62"}),w.current=Pt,ut=Me.onSelectionChange(ce),ce(),or&&(hi.restorePageResume(),Jt(),B.current=!1),h0e(()=>{var lc;const Hn=Pr=>{if(!Pr)return null;const Un=Pr.getBoundingClientRect();return{top:Un.top,bottom:Un.bottom,height:Un.height,left:Un.left,right:Un.right,width:Un.width}},Mr=document.querySelector('[data-slot="pty-mobile-controls"]'),Bn=document.querySelector("[data-keyboard-offset]"),Ci=window.visualViewport,No=Hn(Mr),cn=(Ci==null?void 0:Ci.height)??window.innerHeight;return{...m0e(hi.getDebugProbe,{container:pt,spacer:jt,host:Ae,term:Me}),mobileLayout:{...F.current,window:{innerHeight:window.innerHeight,outerHeight:window.outerHeight,documentClientHeight:document.documentElement.clientHeight},visualViewport:Ci?{height:Ci.height,width:Ci.width,offsetTop:Ci.offsetTop,pageTop:Ci.pageTop,scale:Ci.scale}:null,chatRoot:{dataKeyboardOffset:(Bn==null?void 0:Bn.getAttribute("data-keyboard-offset"))??null,rect:Hn(Bn)},ptyViewRect:Hn(pt.parentElement),containerRect:Hn(pt),controlsRect:No,controlsOverflowBelowVisualViewport:No===null?null:No.bottom-cn,activeElement:document.activeElement instanceof HTMLElement?{tag:document.activeElement.tagName,ariaLabel:document.activeElement.getAttribute("aria-label"),slot:(lc=document.activeElement.closest("[data-slot]"))==null?void 0:lc.getAttribute("data-slot")}:null},frame:{lastWriteAt:U.current,pendingNewFrame:L.current}}})},onFramePending:()=>{var _e;L.current=!0,(_e=T.current)==null||_e.markHorizontalLiveFramePending(),X.current&&!f.hasNewFramesWhileAwayRef.current&&f.setHasNewFramesWhileAway(!0)},onFrameWritten:()=>{var _e;U.current=performance.now(),(_e=V.current)==null||_e.schedule()},onRawInput:_e=>{mwe(_e)||(Zt("rawInput",{force:!0}),zt(_e,"rawInputEnter"))},onError:_e=>{const Me=_e instanceof Error?_e.message:String(_e);We.error(`终端初始化失败:${Me}`)},connectTransportInitially:Z&&ae,...u.transport});return k.current=Ee,()=>{x.current=!1,ut==null||ut.dispose(),Pt==null||Pt.dispose(),w.current===Pt&&(w.current=null),J(),Rt==null||Rt(),It==null||It(),Ne==null||Ne.dispose(),p0e(),sn==null||sn(),Fe==null||Fe(),S.current=[],f0e(),_.current=null,re(!1),G({resultIndex:-1,resultCount:0}),Ee.dispose(),g.current=null,T.current=null,k.current=null}},[t,Le,r,i,s,u.transport,f.handleAtBottomChange,f.hasNewFramesWhileAwayRef,f.setHasNewFramesWhileAway,dt,Ze,yn,$n,Zn,y,ft,Zt,zt,J,ce]),b.useEffect(()=>{if(!Le)return;const Ae=k.current;if(Ae){if(!Z||!ae){d(),Ae.setTransportActive(!1);return}return uxe(t,n?"active":"background",()=>{var Ge;(Ge=k.current)==null||Ge.setTransportActive(!0)})}},[n,Z,d,ae,t,Le]),b.useEffect(()=>{const Ae=g.current,Ge=T.current;!Ae||!Ge||B_e(Ae,le,Ge.relayout)},[le]),b.useEffect(()=>{if(!n||!u.ready||ze)return;const Ae=requestAnimationFrame(()=>{var Ge;uL(s.current)&&((Ge=g.current)==null||Ge.focus())});return()=>cancelAnimationFrame(Ae)},[n,u.ready,ze,s]);const De=b.useCallback((Ae="viewExternal",Ge)=>{var ot;Ge!=null&&Ge.force&&xn(),(ot=T.current)==null||ot.scrollToBottom(Ae,Ge)},[xn]),Ke=b.useCallback(Ae=>{var Ge;(Ge=T.current)==null||Ge.scrollToRatio(Ae)},[]),at=b.useCallback(Ae=>{var Ge;(Ge=T.current)==null||Ge.scrollToXRatio(Ae)},[]),st=b.useCallback(Ae=>{var Fe;const Ge=g.current,ot=Ge==null?void 0:Ge.getSelectionPosition();if(!Ge||!ot)return;const pt=ot.start.y;if(pt>=Ae&&pt<Ae+Ge.rows)return;const jt=Math.max(0,Ge.buffer.active.length-Ge.rows);if(jt===0)return;const sn=Math.max(0,Math.min(jt,pt-Math.floor(Ge.rows/2)));(Fe=T.current)==null||Fe.scrollToRatio(sn/jt)},[]),Et=b.useCallback((Ae,Ge=!1)=>{const ot=g.current,pt=_.current;if(!ot||!pt||!Ae)return Ae||(x.current=!1,pt==null||pt.clearDecorations(),ot==null||ot.clearSelection(),ie(),ce(),G({resultIndex:-1,resultCount:0})),!1;ie(),x.current=!0;const jt=ot.buffer.active.viewportY,sn=pt.findNext(Ae,{...bL,incremental:Ge});return sn&&st(jt),ce(),sn},[ie,ce,st]),kt=b.useCallback(Ae=>{const Ge=g.current,ot=_.current;if(!Ge||!ot||!Ae)return!1;ie(),x.current=!0;const pt=Ge.buffer.active.viewportY,jt=ot.findPrevious(Ae,bL);return jt&&st(pt),ce(),jt},[ie,ce,st]),lt=b.useCallback(()=>{var Ae,Ge;x.current=!1,(Ae=_.current)==null||Ae.clearDecorations(),(Ge=g.current)==null||Ge.clearSelection(),ie(),ce(),G({resultIndex:-1,resultCount:0})},[ie,ce]),Ht=b.useCallback(Ae=>{var ot,pt;if(!dt())return;const Ge=ap(Ae,(ot=g.current)==null?void 0:ot.modes);So(t,Ge),Zt("mobileControl",{force:!0}),zt(Ae,"mobileControlEnter"),(pt=g.current)==null||pt.focus()},[dt,zt,Zt,t]),Mt=b.useCallback(()=>{var Ge,ot,pt;if(!dt())return;const Ae=(ot=(Ge=navigator.clipboard)==null?void 0:Ge.readText)==null?void 0:ot.bind(navigator.clipboard);if(!window.isSecureContext||!Ae){We.error("无法读取剪贴板"),(pt=g.current)==null||pt.focus();return}Ae().then(jt=>{if(!jt)return;const sn=g.current;if(sn){sn.paste(jt);return}So(t,jt),Zt("paste"),zt(jt,"pasteEnter")}).catch(jt=>{const sn=jt instanceof Error&&jt.message?jt.message:"无法读取剪贴板";We.error(sn)}).finally(()=>{var jt;return(jt=g.current)==null?void 0:jt.focus()})},[dt,zt,Zt,t]),ln=bSe({showMobilePtyControls:Xt,horizontalScrollable:Y.horizontalScrollable,mobileControlsHeight:l});F.current.containerPaddingBottom=ln,b.useEffect(()=>{var ot,pt;I.current?(ot=T.current)==null||ot.relayout():(pt=V.current)==null||pt.schedule();const Ae=D.current,Ge=mSe({controlsVisible:Xt,keyboardOpen:Ct,previous:Ae});D.current={keyboardOpen:Ct,controlsVisible:Xt},Xt&&(I.current?Jt():Ge&&Zt("keyboardOffset",{force:!0}))},[et,Ct,Xt,ln,Jt,Zt]);const hn=b.useMemo(()=>({onFocusCapture:wt,onBlurCapture:fn}),[wt,fn]);return{scrollState:Y,isAtBottom:f.isAtBottom,hasNewFramesWhileAway:f.hasNewFramesWhileAway,ptyInputFocused:Ve,showMobilePtyControls:Xt,touchEditingSurface:He,keyboardOffset:et,physicalKeyboardMode:Oe,softKeyboardEditingSurface:ze,mobileControlsBottomInset:tt,connectionReady:u.ready,connectionOverlay:u.overlay,containerPaddingBottom:ln,traceEnabled:p,findReady:$,findResultIndex:Q.resultIndex,findResultCount:Q.resultCount,findNext:Et,findPrevious:kt,clearFind:lt,scrollToBottom:De,scrollToRatio:Ke,scrollToXRatio:at,clearNewFramesWhileAway:Jt,sendMobileInput:Ht,pasteMobileClipboard:Mt,handleTerminalContainerMouseDown:de,handlePasteCapture:te,pointerHandlers:W.pointerHandlers,focusHandlers:hn,ptySelectionToolbar:W.ptySelectionToolbar,ptySelectionHandles:W.ptySelectionHandles,ptySelectionPathAction:W.ptySelectionPathAction,ptySelectionHandleMetrics:W.ptySelectionHandleMetrics,copyPtySelection:W.copyPtySelection,openPtySelectionPathAction:W.openPtySelectionPathAction,handlePtySelectionHandlePointerDown:W.handlePtySelectionHandlePointerDown,handlePtySelectionHandleTouchStart:W.handlePtySelectionHandleTouchStart,isPtyDragOver:se,handlePtyDragOver:ge,handlePtyDragLeave:ee,handlePtyDrop:oe}}function xSe({sessionId:e,sessionKind:t,provider:n,active:r=!0,findRequest:i}){const[s,o]=b.useState(null),[l,u]=b.useState(0),[d,f]=b.useState(!1),[p,y]=b.useState(""),g=b.useRef(null),_=b.useRef(null),w=b.useRef(null),x=wSe({sessionId:e,active:r,containerEl:s,spacerRef:g,xtermHostRef:_,selectionHandleLayerRef:w,mobileControlsHeight:l}),S=x.ptySelectionHandleMetrics,{clearFind:k,findNext:T,findPrevious:N,findReady:P,findResultCount:R,findResultIndex:M}=x,L=b.useCallback(()=>{N(p)},[N,p]),X=b.useCallback(()=>{T(p)},[T,p]),U=b.useCallback(()=>f(!0),[]),V=b.useCallback(()=>{f(!1),k()},[k]),j=PF({enabled:r,open:d,openRequest:i,onOpen:U,onClose:V,onPrevious:L,onNext:X});return b.useEffect(()=>{!d||!P||(p?T(p,!0):k())},[k,T,d,p,P]),m.jsxs("div",{className:"flex flex-col h-full relative","data-slot":"chat-pty-view","data-connection-ready":x.connectionReady?"true":"false","aria-busy":!x.connectionReady,children:[d?m.jsx(_1,{query:p,resultIndex:M,resultCount:R,focusRequest:j.focusRequest,loading:!!p&&!P,onQueryChange:y,onPrevious:L,onNext:X,onClose:j.closeFind}):null,m.jsxs("div",{ref:o,className:"relative flex-1 min-h-0 overflow-auto overscroll-contain bg-background px-3 pt-2",style:{paddingBottom:`calc(env(safe-area-inset-bottom) + ${x.containerPaddingBottom}px)`,touchAction:"pan-x pan-y",overflowAnchor:"none"},onMouseDownCapture:x.handleTerminalContainerMouseDown,onPointerDownCapture:A=>{x.pointerHandlers.onPointerDownCapture(A)},onPointerMoveCapture:x.pointerHandlers.onPointerMoveCapture,onPointerUpCapture:x.pointerHandlers.onPointerUpCapture,onPointerCancelCapture:x.pointerHandlers.onPointerCancelCapture,onTouchStartCapture:x.pointerHandlers.onTouchStartCapture,onTouchMoveCapture:x.pointerHandlers.onTouchMoveCapture,onTouchEndCapture:x.pointerHandlers.onTouchEndCapture,onTouchCancelCapture:x.pointerHandlers.onTouchCancelCapture,onContextMenuCapture:x.pointerHandlers.onContextMenuCapture,onPasteCapture:x.handlePasteCapture,onDragOver:x.handlePtyDragOver,onDragLeave:x.handlePtyDragLeave,onDrop:x.handlePtyDrop,onFocusCapture:x.focusHandlers.onFocusCapture,onBlurCapture:x.focusHandlers.onBlurCapture,"data-slot":"pty-terminal","data-drag-over":x.isPtyDragOver?"true":void 0,children:[m.jsx("div",{ref:g,style:{position:"relative",overflowAnchor:"none"},"data-slot":"pty-spacer",children:m.jsx("div",{ref:_,style:{position:"absolute",left:0,top:0,overflow:"hidden",overflowAnchor:"none",boxSizing:"border-box"},"data-slot":"pty-host"})}),m.jsx("div",{ref:w,"data-slot":"pty-selection-handle-layer",style:{position:"absolute",left:0,top:0,width:0,height:0,contain:"layout size",overflow:"visible",pointerEvents:"none",zIndex:11}})]}),m.jsx(AF,{visible:!x.isAtBottom,hasNewMessages:x.hasNewFramesWhileAway,className:d?"top-14":"top-10",onClick:()=>{x.scrollToBottom("backToBottomBtn",{force:!0}),x.clearNewFramesWhileAway()}}),x.showMobilePtyControls?m.jsx(wme,{sessionKind:t,provider:n,bottomInset:x.mobileControlsBottomInset,onInput:x.sendMobileInput,onPaste:x.pasteMobileClipboard,onHeightChange:u}):null,x.ptySelectionHandles&&w.current?cu.createPortal(m.jsxs(m.Fragment,{children:[m.jsx(wL,{kind:"anchor",metrics:S,"aria-label":"调整选区起点",onPointerDown:A=>x.handlePtySelectionHandlePointerDown("anchor",A),onTouchStart:A=>x.handlePtySelectionHandleTouchStart("anchor",A)}),m.jsx(wL,{kind:"focus",metrics:S,"aria-label":"调整选区终点",onPointerDown:A=>x.handlePtySelectionHandlePointerDown("focus",A),onTouchStart:A=>x.handlePtySelectionHandleTouchStart("focus",A)})]}),w.current):null,x.ptySelectionToolbar?m.jsxs("div",{className:"fixed z-50 flex -translate-x-1/2 gap-1 rounded-md border border-border bg-popover p-1 text-popover-foreground shadow-lg",style:{left:x.ptySelectionToolbar.left,top:x.ptySelectionToolbar.top},"data-slot":"pty-selection-toolbar",children:[m.jsx("button",{type:"button",className:"min-w-14 whitespace-nowrap rounded px-3 py-1.5 text-center text-sm font-medium leading-none hover:bg-accent active:bg-accent/80",onPointerDown:A=>A.preventDefault(),onClick:x.copyPtySelection,"aria-label":"复制终端选区",children:"复制"}),x.ptySelectionPathAction?m.jsx("button",{type:"button",className:"min-w-14 whitespace-nowrap rounded px-3 py-1.5 text-center text-sm font-medium leading-none hover:bg-accent active:bg-accent/80",onPointerDown:A=>A.preventDefault(),onClick:x.openPtySelectionPathAction,"aria-label":x.ptySelectionPathAction.kind==="image-preview"?"预览终端选区图片":"下载终端选区文件",children:x.ptySelectionPathAction.kind==="image-preview"?"预览":"下载"}):null]}):null,m.jsx(Ame,{state:x.scrollState,onScrollRatio:x.scrollToRatio}),m.jsx(Nme,{state:x.scrollState,onScrollRatio:x.scrollToXRatio}),m.jsx(lme,{...x.connectionOverlay}),m.jsx(ume,{ptyInputFocused:x.ptyInputFocused,touchEditingSurface:x.touchEditingSurface,softKeyboardEditingSurface:x.softKeyboardEditingSurface,physicalKeyboardMode:x.physicalKeyboardMode,keyboardOffset:x.keyboardOffset,showMobilePtyControls:x.showMobilePtyControls,mobileControlsBottomInset:x.mobileControlsBottomInset}),x.traceEnabled?m.jsx(SSe,{}):null]})}function wL({kind:e,metrics:t,"aria-label":n,onPointerDown:r,onTouchStart:i}){const s=t.touchSize/2,o=2,l=t.visualSize,u=Math.max(t.stemSize+2,l+1),d=s-o/2,f=s,p=e==="anchor"?d-l+o:d,y=f+u-l+o,g=e==="anchor"?{borderTopLeftRadius:l,borderBottomLeftRadius:l,borderTopRightRadius:2,borderBottomRightRadius:l}:{borderTopLeftRadius:2,borderBottomLeftRadius:l,borderTopRightRadius:l,borderBottomRightRadius:l};return m.jsxs("button",{type:"button",className:"absolute z-50 touch-none rounded-full bg-transparent p-0 pointer-events-auto focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring",style:{left:0,top:0,width:t.touchSize,height:t.touchSize,transform:"translate3d(0, 0, 0) translate(-50%, -50%)",visibility:"hidden",willChange:"transform"},"data-slot":"pty-selection-handle","data-kind":e,"aria-label":n,onPointerDown:r,onTouchStart:i,children:[m.jsx("span",{className:"pointer-events-none absolute rounded-full bg-primary",style:{left:d,top:f,width:o,height:u},"data-slot":"pty-selection-handle-stem"}),m.jsx("span",{className:"pointer-events-none absolute border-2 border-primary bg-background shadow-sm shadow-black/30",style:{left:p,top:y,width:l,height:l,...g},"data-slot":"pty-selection-handle-dot"})]})}function SSe(){const[e,t]=b.useState(!1);async function n(){const r=ome();try{await navigator.clipboard.writeText(r),t(!0),window.setTimeout(()=>t(!1),1200)}catch{window.prompt("Copy PTY scroll trace",r)}}return m.jsx("button",{type:"button",className:"absolute left-3 top-3 z-30 rounded border border-border bg-popover/90 px-2 py-1 text-[11px] text-muted-foreground",onPointerDown:r=>r.preventDefault(),onClick:n,"data-slot":"pty-scroll-trace-copy",children:e?"Copied":"Trace"})}const ESe=1024,CSe=720,wv=.5,L6=b.createContext(null);function kSe({children:e}){const[t,n]=b.useState([]),[r,i]=b.useState(null),[s,o]=b.useState(null),l=Ie(k=>k.selectedProxyId),u=Gt(k=>k.sessions),d=Gt(k=>k.sessionListLoaded),f=b.useRef(l),p=b.useRef(null),y=b.useMemo(()=>u.filter(k=>k.mode==="pty").map(k=>k.sessionId).sort().join(`
717
717
  `),[u]),g=b.useCallback(k=>{p.current=k.sessionId,i(k),n(T=>Nhe(T,k.sessionId).map(P=>P.sessionId===k.sessionId?{...P,sessionKind:k.sessionKind,provider:k.provider}:P))},[]),_=b.useCallback(k=>{p.current===k&&(p.current=null),i(T=>(T==null?void 0:T.sessionId)===k?null:T),o(T=>p.current===null?null:T)},[]),w=b.useCallback((k,T)=>{p.current===k&&o(N=>!T||N&&ASe(N,T)?N:T)},[]),x=b.useCallback((k,T)=>{T!==void 0&&n(N=>N.map(P=>P.sessionId===k?{...P,findRequest:T}:P))},[]);b.useEffect(()=>{if(!d)return;const k=new Set(y?y.split(`
718
- `):[]);n(T=>T.filter(N=>k.has(N.sessionId))),i(T=>T&&k.has(T.sessionId)?T:null),p.current&&!k.has(p.current)&&(p.current=null,o(null))},[y,d]),b.useEffect(()=>{const k=f.current;f.current=l,!(!k||k===l)&&(p.current=null,n([]),i(null),o(null))},[l]);const S=b.useMemo(()=>({activate:g,deactivate:_,updateFindRequest:x,updateViewportRect:w}),[g,_,x,w]);return m.jsxs(L6.Provider,{value:S,children:[e,m.jsx(RSe,{entries:t,activeView:r,viewportRect:s})]})}function TSe({sessionId:e,sessionKind:t,provider:n,findRequest:r}){const i=b.useContext(L6),s=b.useRef(null);if(!i)throw new Error("PtyKeepAliveViewport must be used within PtyKeepAliveProvider");const{activate:o,deactivate:l,updateFindRequest:u,updateViewportRect:d}=i;return b.useLayoutEffect(()=>(o({sessionId:e,sessionKind:t,provider:n}),()=>l(e)),[o,l,e,t,n]),b.useLayoutEffect(()=>{u(e,r)},[r,e,u]),b.useLayoutEffect(()=>{const f=s.current;if(!f)return;const p=()=>{const g=f.getBoundingClientRect();d(e,{top:g.top,left:g.left,width:g.width,height:g.height})};p();const y=new ResizeObserver(p);return y.observe(f),window.addEventListener("resize",p),()=>{y.disconnect(),window.removeEventListener("resize",p)}},[e,d]),m.jsx("div",{ref:s,className:"h-full w-full bg-background","data-slot":"pty-keepalive-viewport","data-session-id":e})}function RSe({entries:e,activeView:t,viewportRect:n}){return e.length===0?null:m.jsx("div",{className:"fixed inset-0 z-10 pointer-events-none","data-slot":"pty-keepalive-layer",children:e.map(r=>{const i=(t==null?void 0:t.sessionId)===r.sessionId&&n!==null,s=i?n:{top:-1e5,left:0,width:(n==null?void 0:n.width)??ESe,height:(n==null?void 0:n.height)??CSe};return m.jsx("div",{className:"absolute overflow-hidden bg-background","data-slot":"pty-keepalive-entry","data-session-id":r.sessionId,"data-active":i?"true":"false","aria-hidden":!i,style:{top:s.top,left:s.left,width:s.width,height:s.height,pointerEvents:i?"auto":"none",visibility:i?"visible":"hidden"},children:m.jsx(RF,{sessionId:r.sessionId,children:m.jsx(xSe,{sessionId:r.sessionId,sessionKind:r.sessionKind,provider:r.provider,active:i,findRequest:r.findRequest})})},r.sessionId)})})}function ASe(e,t){return Math.abs(e.top-t.top)<=wv&&Math.abs(e.left-t.left)<=wv&&Math.abs(e.width-t.width)<=wv&&Math.abs(e.height-t.height)<=wv}function NSe(){const e=Gt(r=>r.codexActiveWriterConflict),t=Gt(r=>r.setCodexActiveWriterConflict),n=()=>t(null);return m.jsx(ss,{open:e!==null,onOpenChange:r=>!r&&n(),children:m.jsxs(os,{focusSurfaceOnOpen:!0,className:"min-w-0 sm:max-w-md",children:[m.jsxs(as,{children:[m.jsx(Yi,{children:"该 Codex 会话仍在运行"}),m.jsxs(_s,{className:"space-y-2 text-left leading-6",children:[m.jsxs("span",{className:"block",children:["另一个 Codex 进程正在使用此会话",e!=null&&e.activeWriterPid?m.jsxs(m.Fragment,{children:["(PID"," ",m.jsx("span",{className:"font-mono text-foreground",children:e.activeWriterPid}),")"]}):null,"。"]}),m.jsx("span",{className:"block",children:"它可能来自本机终端、Codex App 或另一条 DEV Anywhere 会话。请先回到或结束原会话后再重试。"}),m.jsx("span",{className:"block text-muted-foreground/80",children:"DEV Anywhere 不会自动终止该进程。"})]})]}),m.jsx(Fs,{children:m.jsx(gt,{type:"button",onClick:n,autoFocus:!0,children:"知道了"})})]})})}function rT({route:e,surface:t,proxiesLength:n,proxyListLoaded:r,hasProxy:i,relayClientAuthIssue:s=null}){return s==="missing_client_token"?"Relay 需要 client token,请在设置中填写":s==="invalid_client_token"?"client token 无效或已过期,请在设置中更新":r?n===0?"在开发机上启动 DEV Anywhere,本页会显示可连接的开发机":t==="mobile"&&e==="proxy-select"||!i?"选择要连接的开发机":null:null}function MSe(e){const t=Rj(e);return t.osName!=="iPad"?{supported:!0}:e.standalone||t.browserName==="Safari"?{supported:!0}:{supported:!1,reason:"ipad-safari-required",browserName:t.browserName}}function sy(){if(typeof window>"u"||typeof navigator>"u")return!1;const e=typeof window.matchMedia=="function"&&(window.matchMedia("(display-mode: standalone)").matches||window.matchMedia("(display-mode: fullscreen)").matches),t=!!navigator.standalone;return e||t}function PSe(){return typeof navigator>"u"?{supported:!0}:MSe({userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints,standalone:sy()})}function ISe(){s0e(),o0e();const e=rs(),t=ws(),n=e.pathname.startsWith("/chat/"),r=e.pathname.startsWith("/preview/device/"),i=n||r,s=e.pathname==="/"||e.pathname==="/sessions",[o,l]=b.useState(!1),[u,d]=b.useState(()=>sy()),f=Ie(V=>V.proxies.length),p=Ie(V=>V.proxyListLoaded),y=Ie(V=>V.relayClientAuthIssue),g=Ie(V=>V.relayConnectionIssue),_=Ie(V=>!!V.selectedProxyId),w=Ie(V=>V.selectedProxyId),x=Ie(V=>V.selectedProxyName);Gt(V=>V.sessions.length);const S=Ie(V=>V.pendingToast),k=Ie(V=>V.setPendingToast),T=e.pathname==="/"?"proxy-select":"sessions",N=g!==null&&y===null,P=rT({route:T,surface:"mobile",proxiesLength:f,proxyListLoaded:p,hasProxy:_,relayClientAuthIssue:y}),R=x??w,L=e.pathname==="/sessions"&&p&&f>0?m.jsxs(gt,{variant:"ghost",size:"sm",className:"h-auto min-h-11 max-w-full justify-start rounded-md border border-border/70 bg-background/35 px-3 py-2 text-left text-muted-foreground hover:border-primary/45 hover:bg-accent/70 hover:text-foreground","data-slot":"mobile-switch-proxy","aria-label":R?`切换开发机,当前 ${R}`:"切换开发机",onClick:()=>t("/"),children:[m.jsx(rz,{className:"size-4 text-primary","aria-hidden":"true"}),m.jsxs("span",{className:"min-w-0 truncate",children:[m.jsx("span",{className:"text-foreground",children:"切换开发机"}),R?m.jsxs("span",{className:"ml-1 text-muted-foreground/75",children:["· ",R]}):null]})]}):null;b.useEffect(()=>{if(!S)return;({error:We.error,info:We.info,success:We.success})[S.kind](S.message),k(null)},[S,k]),b.useEffect(()=>{if(typeof window.matchMedia!="function"){d(sy());return}const V=window.matchMedia("(display-mode: standalone)"),j=window.matchMedia("(display-mode: fullscreen)"),A=()=>d(sy());return A(),V.addEventListener("change",A),j.addEventListener("change",A),()=>{V.removeEventListener("change",A),j.removeEventListener("change",A)}},[]);const X=b.useRef(!1);b.useEffect(()=>{if(X.current)return;X.current=!0;const V=Ore({pathname:e.pathname,alreadyRestored:Bre(),lastRoute:Lre()});zre(),V&&(jre(V),t(V,{replace:!0}))},[]);const U=b.useRef(!1);return b.useEffect(()=>{n?(U.current=!0,Dre(`${e.pathname}${e.search}`)):U.current&&(U.current=!1,by())},[n,e.pathname,e.search]),m.jsxs(Oue,{blocked:N,children:[m.jsxs("div",{className:"flex flex-col bg-background text-foreground",style:{height:"var(--dev-app-shell-height, max(100dvh, var(--dev-visual-viewport-height, 100dvh)))"},"data-slot":"app-shell","data-standalone-display":u?"true":void 0,inert:N?!0:void 0,"aria-hidden":N?!0:void 0,children:[!i&&m.jsx(gt,{variant:"ghost",size:"icon",className:"dev-mobile-settings-trigger group fixed right-4 z-30 size-11 rounded-full border-0 bg-transparent p-0 text-muted-foreground shadow-none hover:bg-transparent hover:text-foreground md:hidden","aria-label":"设置","data-slot":"mobile-settings-trigger",onClick:()=>l(!0),children:m.jsx("span",{"data-slot":"mobile-settings-trigger-visual",className:"flex size-7 items-center justify-center rounded-full border border-border/80 bg-card/90 shadow-lg backdrop-blur transition-colors group-hover:border-primary/45 group-hover:bg-accent",children:m.jsx(oz,{className:"size-4","aria-hidden":"true"})})}),!i&&m.jsx(Pfe,{subtitle:P,action:L}),m.jsx(Ahe,{}),m.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[m.jsx(Afe,{className:"hidden md:flex"}),m.jsx("main",{className:"relative flex-1 overflow-hidden",role:"main",children:m.jsx(kSe,{children:m.jsx("div",{className:Ye("h-full",!s&&"animate-in fade-in-0 duration-200 motion-reduce:animate-none"),"data-slot":"route-content",children:m.jsx(Yq,{})},s?"top-level":e.pathname)})})]}),m.jsx(v1,{open:o,onOpenChange:l}),m.jsx(NSe,{}),m.jsx(she,{}),m.jsx($fe,{}),m.jsx(ore,{})]}),N&&g?m.jsx("div",{className:"fixed inset-0 z-[60] bg-background",children:m.jsx(lhe,{issue:g})}):null]})}function D6({subtitle:e,action:t}){return m.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-6 px-6 text-center",children:[m.jsx(K4,{texts:G4,className:"text-2xl md:text-3xl font-bold"}),e?m.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:e}):null,t&&m.jsx("div",{children:t})]})}function OSe(){const e=Ie(o=>o.proxies),t=Ie(o=>o.proxyListLoaded),n=Ie(o=>!!o.selectedProxyId),r=Ie(o=>o.relayClientAuthIssue);Gt(o=>o.sessions.length);const i=rT({route:"proxy-select",surface:"desktop",proxiesLength:e.length,proxyListLoaded:t,hasProxy:n,relayClientAuthIssue:r}),s=r==="missing_client_token"?"client-token-missing":r==="invalid_client_token"?"client-token-invalid":null;return m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"h-full md:hidden",children:m.jsx(R4,{layout:"page"})}),m.jsx("div",{className:"hidden md:block h-full",children:s?m.jsx(Uc,{variant:s}):m.jsx(D6,{subtitle:i})})]})}function LSe(){const e=Ie(o=>o.proxies),t=Ie(o=>o.proxyListLoaded),n=Ie(o=>!!o.selectedProxyId),r=Ie(o=>o.relayClientAuthIssue);Gt(o=>o.sessions.length);const i=Si("local",wn.proxyId)!==null;if(!n&&!i)return m.jsx(Vq,{to:"/",replace:!0});const s=rT({route:"sessions",surface:"desktop",proxiesLength:e.length,proxyListLoaded:t,hasProxy:n,relayClientAuthIssue:r});return m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"h-full md:hidden",children:m.jsx($4,{layout:"page"})}),m.jsx("div",{className:"hidden md:block h-full",children:m.jsx(D6,{subtitle:s})})]})}function B6(){if(!(typeof navigator>"u"))return navigator.wakeLock}function DSe(e,t){return e===!1?"insecure-context":t?null:"unsupported"}function z6(){var t;const e=typeof window>"u"?void 0:window.isSecureContext;return DSe(e,typeof((t=B6())==null?void 0:t.request)=="function")}function BSe(e){return e==="insecure-context"?"屏幕常亮需要 HTTPS":"当前浏览器不支持屏幕常亮"}function zSe(){const e=B6();if(typeof(e==null?void 0:e.request)!="function")throw new Error(BSe(z6()));return e.request("screen")}function jSe(e){return e instanceof Error&&e.message.trim()?e.message:"无法开启屏幕常亮"}class FSe{constructor(t={}){je(this,"activeScopes",new Set);je(this,"pendingScopes",new Set);je(this,"listeners",new Map);je(this,"sentinel",null);je(this,"requestInFlight",null);je(this,"requestWakeLock");je(this,"documentRef");je(this,"windowRef");je(this,"unavailableReason");je(this,"handleVisibilityChange",()=>{var t,n;if(((t=this.documentRef)==null?void 0:t.visibilityState)==="hidden"){this.releaseSentinel().catch(()=>{});return}((n=this.documentRef)==null?void 0:n.visibilityState)==="visible"&&this.ensureWakeLock().catch(()=>{})});je(this,"handlePageHide",()=>{this.releaseSentinel().catch(()=>{})});var n,r;this.requestWakeLock=t.request??zSe,this.unavailableReason=typeof t.request=="function"?null:z6(),this.documentRef=t.document??(typeof document>"u"?void 0:document),this.windowRef=t.window??(typeof window>"u"?void 0:window),(n=this.documentRef)==null||n.addEventListener("visibilitychange",this.handleVisibilityChange),(r=this.windowRef)==null||r.addEventListener("pagehide",this.handlePageHide)}isSupported(){return this.unavailableReason===null}getSnapshot(t){return{active:this.activeScopes.has(t),pending:this.pendingScopes.has(t),supported:this.isSupported(),unavailableReason:this.unavailableReason}}subscribe(t,n){const r=this.listeners.get(t)??new Set;return r.add(n),this.listeners.set(t,r),n(this.getSnapshot(t)),()=>{r.delete(n),r.size===0&&this.listeners.delete(t)}}async enable(t){this.activeScopes.add(t),this.pendingScopes.add(t),this.notify(t);try{await this.ensureWakeLock()}catch(n){throw this.activeScopes.delete(t),new Error(jSe(n),{cause:n})}finally{this.pendingScopes.delete(t),this.notify(t)}}async disable(t){const n=this.activeScopes.delete(t);this.pendingScopes.delete(t),this.notify(t),!(!n||this.activeScopes.size>0)&&await this.releaseSentinel()}async toggle(t){this.activeScopes.has(t)?await this.disable(t):await this.enable(t)}dispose(){var t,n;(t=this.documentRef)==null||t.removeEventListener("visibilitychange",this.handleVisibilityChange),(n=this.windowRef)==null||n.removeEventListener("pagehide",this.handlePageHide),this.activeScopes.clear(),this.pendingScopes.clear(),this.releaseSentinel().catch(()=>{});for(const r of this.listeners.keys())this.notify(r)}async ensureWakeLock(){var t;if(this.activeScopes.size!==0&&((t=this.documentRef)==null?void 0:t.visibilityState)!=="hidden"&&!(this.sentinel&&!this.sentinel.released))return this.requestInFlight?this.requestInFlight:(this.requestInFlight=this.requestWakeLock().then(async n=>{var r;if(this.activeScopes.size===0||((r=this.documentRef)==null?void 0:r.visibilityState)==="hidden"){n.released||await n.release();return}this.sentinel=n,n.addEventListener("release",()=>{var i;this.sentinel===n&&(this.sentinel=null),this.activeScopes.size>0&&((i=this.documentRef)==null?void 0:i.visibilityState)!=="hidden"&&this.ensureWakeLock().catch(()=>{})},{once:!0})}).finally(()=>{this.requestInFlight=null}),this.requestInFlight)}async releaseSentinel(){const t=this.sentinel;this.sentinel=null,!(!t||t.released)&&await t.release()}notify(t){var r;const n=this.getSnapshot(t);(r=this.listeners.get(t))==null||r.forEach(i=>i(n))}}const Pl=new FSe;function j6(e){const[t,n]=b.useState(()=>Pl.getSnapshot(e));b.useEffect(()=>Pl.subscribe(e,n),[e]),b.useEffect(()=>()=>{Pl.disable(e).catch(()=>{})},[e]);const r=b.useCallback(()=>Pl.enable(e),[e]),i=b.useCallback(()=>Pl.disable(e),[e]),s=b.useCallback(()=>Pl.toggle(e),[e]);return{...t,enable:r,disable:i,toggle:s}}function $Se(){return new AudioContext}class HSe{constructor(t=$Se){je(this,"context",null);this.createContext=t}get(){return this.context??(this.context=this.createContext()),this.context}async prepare(){const t=this.get();if(t.state!=="running"&&t.state!=="closed"&&await t.resume(),t.state!=="running")throw new Error("浏览器未允许播放 Voice Pilot 提示音");return t}async reactivateAfterCapture(){const t=this.get();if(t.state==="closed")throw new Error("Voice Pilot 播放上下文已关闭");if(t.state==="running"&&await t.suspend(),t.state!=="running"&&await t.resume(),t.state!=="running")throw new Error("浏览器未能恢复 Voice Pilot 音频输出");return t}}const oy=new HSe,xL=400,Ad=[];let F6=1;function USe(){return typeof performance>"u"?0:Math.round(performance.now()*10)/10}function cp(e){const t={sequence:F6++,timestamp:new Date().toISOString(),monotonicMs:USe(),sessionId:e.sessionId,scope:e.scope,event:e.event,...e.attemptId?{attemptId:e.attemptId}:{},...e.requestId?{requestId:e.requestId}:{},...e.details?{details:{...e.details}}:{}};Ad.push(t),Ad.length>xL&&Ad.splice(0,Ad.length-xL)}function WSe(){return Ad.map(e=>({...e,...e.details?{details:{...e.details}}:{}}))}function qSe(){Ad.length=0,F6=1}typeof window<"u"&&(window.__devAnywhereVoicePilotDiagnostics={snapshot:WSe,clear:qSe});function $6(e){return`voice-pilot:${e}`}function VSe(e){const t=new Int16Array(e.length);for(let n=0;n<e.length;n+=1){const r=Math.max(-1,Math.min(1,e[n]??0));t[n]=r<0?Math.round(r*32768):Math.floor(r*32767)}return new Uint8Array(t.buffer)}const YSe="modulepreload",KSe=function(e){return"/"+e},SL={},H6=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){let o=function(d){return Promise.all(d.map(f=>Promise.resolve(f).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),u=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));i=o(n.map(d=>{if(d=KSe(d),d in SL)return;SL[d]=!0;const f=d.endsWith(".css"),p=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const y=document.createElement("link");if(y.rel=f?"stylesheet":YSe,f||(y.as="script"),y.crossOrigin="",y.href=d,u&&y.setAttribute("nonce",u),document.head.appendChild(y),f)return new Promise((g,_)=>{y.addEventListener("load",g),y.addEventListener("error",()=>_(new Error(`Unable to preload CSS for ${d}`)))})}))}function s(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return i.then(o=>{for(const l of o||[])l.status==="rejected"&&s(l.reason);return t().catch(s)})},GSe="/assets/fvad-DYxbW2my.wasm",ef=16e3,XSe=20,Il=ef*XSe/1e3,G0=Il*Int16Array.BYTES_PER_ELEMENT;let EL=null;async function ZSe(){return EL??(EL=H6(async()=>{const{default:e}=await import("./fvad-oSUTPVOe.js");return{default:e}},[]).then(({default:e})=>e({locateFile:t=>t.endsWith(".wasm")?GSe:t}))),EL}class iT{constructor(t,n,r){je(this,"destroyed",!1);this.module=t,this.handle=n,this.framePointer=r}static async create(t=3){const n=await ZSe(),r=n._fvad_new();if(!r)throw new Error("无法初始化浏览器语音活动检测器");const i=n._malloc(G0);if(!i)throw n._fvad_free(r),new Error("无法分配浏览器语音活动检测缓冲区");if(n._fvad_set_sample_rate(r,ef)!==0)throw n._free(i),n._fvad_free(r),new Error("浏览器语音活动检测器不支持 16 kHz 音频");if(n._fvad_set_mode(r,t)!==0)throw n._free(i),n._fvad_free(r),new Error("无法配置浏览器语音活动检测器");return new iT(n,r,i)}process(t){if(this.destroyed)throw new Error("浏览器语音活动检测器已释放");if(t.byteLength!==G0)throw new Error(`语音活动检测帧必须为 ${G0} 字节`);this.module.HEAPU8.set(t,this.framePointer);const n=this.module._fvad_process(this.handle,this.framePointer,Il);if(n<0)throw new Error("浏览器语音活动检测失败");return n===1}reset(){this.destroyed||this.module._fvad_reset(this.handle)}destroy(){this.destroyed||(this.destroyed=!0,this.module._free(this.framePointer),this.module._fvad_free(this.handle))}}class QSe{constructor(t={}){je(this,"startSpeechFrames");je(this,"endSilenceFrames");je(this,"active",!1);je(this,"speechFrames",0);je(this,"silenceFrames",0);if(this.startSpeechFrames=t.startSpeechFrames??10,this.endSilenceFrames=t.endSilenceFrames??30,this.startSpeechFrames<1||this.endSilenceFrames<1)throw new Error("Invalid voice activity gate configuration")}push(t){return this.active?t?(this.silenceFrames=0,"none"):(this.silenceFrames+=1,this.silenceFrames<this.endSilenceFrames?"none":(this.active=!1,this.silenceFrames=0,"speech-end")):(this.speechFrames=t?this.speechFrames+1:0,this.speechFrames>=this.startSpeechFrames?(this.active=!0,this.speechFrames=0,this.silenceFrames=0,"speech-start"):"none")}reset(){this.active=!1,this.speechFrames=0,this.silenceFrames=0}}class JSe{constructor(){je(this,"pending",new Float32Array(Il));je(this,"pendingLength",0)}push(t,n){let r=0;if(this.pendingLength>0){const i=Il-this.pendingLength,s=Math.min(i,t.length);this.pending.set(t.subarray(0,s),this.pendingLength),this.pendingLength+=s,r+=s,this.pendingLength===Il&&(n(this.pending.slice()),this.pendingLength=0)}for(;r+Il<=t.length;)n(t.slice(r,r+Il)),r+=Il;if(r<t.length){const i=t.subarray(r);this.pending.set(i,0),this.pendingLength=i.length}}reset(){this.pendingLength=0}}const e1e="/__dev_anywhere_debug/voice-fixture",t1e=ef*U4/1e3;function n1e(){return iT.create(3)}const r1e={createVad:n1e,getUserMedia:e=>navigator.mediaDevices.getUserMedia(e),createAudioContext:e=>new AudioContext(e),fetch:e=>fetch(e)};function i1e(e){if(e.length===0)return 0;let t=0;for(const n of e)t+=n*n;return Math.min(1,Math.sqrt(t/e.length)*10)}function s1e(e){for(const t of e.getTracks())t.stop()}function U6(e){const t=e.createAudioContext({sampleRate:ef});if(t.sampleRate!==ef)throw t.close().catch(()=>{}),new Error("浏览器无法提供 Voice Pilot 所需的 16 kHz 音频输入");return t}async function o1e(e){const t=U6(e);let n;try{n=await e.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:ef}})}catch(i){throw await t.close().catch(()=>{}),i}const r=t.createMediaStreamSource(n);return{context:t,input:r,async start(){t.state==="suspended"&&await t.resume()},async stop(){r.disconnect(),s1e(n),t.state!=="closed"&&await t.close()}}}async function a1e(e,t){const n=U6(t);try{const r=await t.fetch(e);if(!r.ok)throw new Error(`测试录音读取失败 (${r.status})`);const i=await n.decodeAudioData(await r.arrayBuffer()),s=n.createBufferSource();s.buffer=i;let o=!1,l=!1;return{context:n,input:s,async start(){o||l||(o=!0,n.state==="suspended"&&await n.resume(),s.start())},async stop(){if(!l){if(l=!0,o)try{s.stop()}catch{}s.disconnect(),n.state!=="closed"&&await n.close()}}}}catch(r){throw await n.close().catch(()=>{}),r}}function W6(e=window.location.search,t=!1){return t&&new URLSearchParams(e).get("voice-fixture")==="default"?{kind:"fixture",url:e1e}:{kind:"microphone"}}async function l1e(e,t=r1e){const n=await t.createVad();let r;try{r=e.source.kind==="fixture"?await a1e(e.source.url,t):await o1e(t)}catch(f){throw n.destroy(),f}const i=new QSe,s=new JSe,o=r.context.createScriptProcessor(t1e,1,1);let l=!1,u=null,d=null;return o.onaudioprocess=f=>{l&&s.push(f.inputBuffer.getChannelData(0),p=>{const y=VSe(p),g=n.process(y);e.onFrame({pcm:y,speechProbability:g?1:0,activityLevel:i1e(p)});const _=i.push(g);_==="speech-start"&&e.onSpeechStart(),_==="speech-end"&&e.onSpeechEnd()})},r.input.connect(o),o.connect(r.context.destination),{source:e.source.kind,start(){return d?Promise.reject(new Error("语音采集已停止")):(u??(u=(async()=>{l=!0,await r.start()})()),u)},stop(){return d??(d=(async()=>{l=!1,o.onaudioprocess=null,o.disconnect(),i.reset(),s.reset(),n.reset(),n.destroy(),await r.stop()})()),d}}}function q6(e=rf().osName){return{mediaAccept:"image/*,video/*",fileAccept:e==="Android"?"application/*,text/*":void 0}}function c1e(e){const[t,n,...r]=Array.from(e);return t&&n===" "&&r.length>0?{indicator:t,label:r.join("")}:{label:e}}function u1e({title:e,isPtyTitle:t}){if(!t)return m.jsx(m.Fragment,{children:e});const{indicator:n,label:r}=c1e(e);return m.jsxs("span",{className:"inline-flex items-center justify-center max-w-full min-w-0 font-mono font-normal",children:[n&&m.jsx("span",{className:"inline-block w-[1.25ch] shrink-0 text-center","aria-hidden":"true",children:n}),m.jsx("span",{className:"truncate",children:n?` ${r}`:r})]})}function d1e(e){const t=e instanceof Error?e.name:"";return t==="NotAllowedError"||t==="SecurityError"?"没有麦克风权限,请在浏览器里允许访问麦克风。":t==="NotFoundError"||t==="DevicesNotFoundError"?"未检测到可用麦克风。":t==="NotReadableError"||t==="TrackStartError"?"麦克风正在被其他应用占用。":e instanceof Error?e.message:"无法访问麦克风。"}async function f1e(){var t;if(!((t=navigator.mediaDevices)!=null&&t.getUserMedia))throw new Error("当前浏览器不支持麦克风访问。");let e=null;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(n){throw new Error(d1e(n),{cause:n})}finally{e==null||e.getTracks().forEach(n=>n.stop())}}const ud="min-h-9 gap-2.5",xv="px-2 pb-1 pt-2 text-xs font-semibold text-muted-foreground";function Uo({children:e,className:t}){return m.jsx("span",{"aria-hidden":"true","data-slot":"chat-menu-icon",className:Ye("inline-flex size-5 shrink-0 items-center justify-center text-muted-foreground [&_svg]:size-4",t),children:e})}function h1e({label:e}){return m.jsxs(Uo,{className:"relative",children:[m.jsx(nz,{className:"size-4","aria-hidden":"true"}),m.jsx("span",{className:"absolute -right-1.5 -top-1 flex h-3 min-w-4 items-center justify-center rounded-[3px] border border-border bg-popover px-0.5 font-mono text-[7px] leading-none text-muted-foreground shadow-sm",children:e})]})}function p1e({sessionId:e,mode:t,onFind:n}){const r=q6(),i=ws(),s=Gt(ye=>ye.sessions.find(Ze=>Ze.sessionId===e)),o=Gt(ye=>ye.ptyTitles[e]),l=Ie(ye=>ye.ptyFontSize),u=Ie(ye=>ye.chatContentFontSize),d=Ie(ye=>ye.selectedProxyId),f=Ie(ye=>ye.adjustPtyFontSize),p=Ie(ye=>ye.adjustChatContentFontSize),y=Ie(ye=>ye.setChatContentFontSize),g=Ie(ye=>ye.resetPtyFontSize),_=Ie(ye=>ye.resetChatContentFontSize),w=Ie(ye=>ye.inputModePreference==="hardware"),x=Gt(ye=>ye.renameSession),S=TC(d,e),k=Gt(ye=>S?!!ye.ptyAutoYesBySessionKey[S]:!1),T=Gt(ye=>ye.setPtyAutoYes),P=co("(pointer: coarse), (hover: none)")&&!w,R=t==="pty"||(s==null?void 0:s.mode)==="pty",M=(s==null?void 0:s.kind)==="terminal",L=j6(e),X=Rn(ye=>ye.bySessionId[e]??qb),U=Rn(ye=>ye.enable),V=Rn(ye=>ye.disable),j=!!(s!=null&&s.nameLocked&&(s!=null&&s.name)),A=LC(s),D=j&&(s==null?void 0:s.name)||A||R&&o||(s==null?void 0:s.name)||e.slice(0,8),O=!!(R&&!M&&o&&!j),I=R?l:uC(u,P),B=!R&&P?Rz:kz,F=R?g:_,[Y,z]=b.useState(!1),[q,K]=b.useState(!1),$=X.enabled,re=L.active||$,Q=L.pending||!L.supported||$;function G(ye){if(R){f(ye);return}if(P){y(I+ye);return}p(ye)}function Z(){L.toggle().catch(ye=>{We.error(ye instanceof Error?ye.message:String(ye))})}async function ae(ye){var Oe;if(R||M){We.info("Voice Pilot 目前适用于聊天会话。");return}if(ye!==!0){V(e);return}const Ze=Ft;if(!Ze){We.error("请先连接开发机");return}try{if(!((Oe=(await Ze.requestVoiceConfig()).config)!=null&&Oe.configured)){We.info("请先在设置里配置 Voice Pilot。");return}z(!0)}catch(ze){We.error(ze instanceof Error?ze.message:String(ze))}}async function le(){var ze;K(!0);let ye=null,Ze=!1;const Oe=$6(e);try{cp({sessionId:e,scope:"runtime",event:"wake-lock-requested",details:{userActivationActive:((ze=navigator.userActivation)==null?void 0:ze.isActive)??!1,visibilityState:document.visibilityState,secureContext:window.isSecureContext}});const et=Pl.enable(Oe).then(()=>{cp({sessionId:e,scope:"runtime",event:"wake-lock-acquired"})},it=>{throw cp({sessionId:e,scope:"runtime",event:"wake-lock-failed",details:{error:it instanceof Error?it.message:String(it)}}),new Error("屏幕常亮请求被浏览器拒绝,Voice Pilot 未开启。",{cause:it})});ye=hk.acquire("capture");const Ct=oy.prepare(),Le=W6().kind==="microphone"?f1e():Promise.resolve();await Promise.all([et,Ct,Le]),U(e),Ze=!0,z(!1)}catch(et){cp({sessionId:e,scope:"runtime",event:"startup-failed",details:{error:et instanceof Error?et.message:String(et)}}),We.error(et instanceof Error?et.message:String(et))}finally{ye==null||ye.release(),Ze||await Pl.disable(Oe).catch(()=>{}),K(!1)}}const me=b.useRef(null),ke=b.useRef(null),[$e,he]=b.useState(!1);async function He(ye){var et;const Ze=(et=ye.target.files)==null?void 0:et[0];if(ye.target.value="",!Ze)return;const Oe=Ft;if(!Oe){We.error("请先连接开发机");return}const ze=await Up({relay:Oe,sessionId:e,file:Ze});ze&&So(e,`@${ze} `)}async function Nt(ye,Ze){const Oe=Ft;if(!Oe)throw new Error("请先连接开发机");const ze=await Oe.renameSession(ye,Ze);if(!ze.success)throw new Error(ze.error??"重命名失败");x(ye,ze.name??Ze),We.success("已重命名会话")}return m.jsxs("div",{className:"border-b border-border bg-card pt-[env(safe-area-inset-top)] shrink-0","data-slot":"chat-header",children:[m.jsx("div",{className:"dev-chat-shell-rail-inset","data-slot":"chat-header-rail-inset",children:m.jsxs("div",{className:"grid min-h-12 w-full grid-cols-[2.25rem_minmax(0,1fr)_2.25rem] items-center","data-slot":"chat-header-rail",children:[m.jsx("div",{className:"flex justify-start",children:m.jsx(gt,{variant:"ghost",size:"icon-sm",className:"md:hidden",onClick:()=>i("/sessions"),"aria-label":"返回会话列表","data-slot":"chat-back-button",children:m.jsx(Qp,{"aria-hidden":"true"})})}),m.jsx("span",{className:"text-sm font-semibold truncate text-center px-2","data-slot":"chat-session-title",children:m.jsx(u1e,{title:D,isPtyTitle:O})}),m.jsxs(uf,{modal:!1,children:[m.jsx(df,{asChild:!0,children:m.jsx(gt,{variant:"ghost",size:"icon-sm",className:"justify-self-end","aria-label":"会话操作","data-slot":"chat-overflow-trigger",children:m.jsx(wV,{"aria-hidden":"true"})})}),m.jsxs(ff,{align:"end",className:"w-max min-w-44 max-w-[calc(100vw-1rem)]","data-slot":"chat-overflow-menu",children:[m.jsx(nv,{className:xv,children:"会话"}),m.jsxs(ni,{className:ud,"data-slot":"chat-menu-find",onSelect:n,children:[m.jsx(Uo,{children:m.jsx(cy,{"aria-hidden":"true"})}),"在会话中查找"]}),m.jsxs(ni,{className:ud,"data-slot":"chat-menu-rename",onSelect:()=>he(!0),children:[m.jsx(Uo,{children:m.jsx(uY,{"aria-hidden":"true"})}),"重命名"]}),m.jsxs(t0,{checked:re,className:"min-h-9 justify-start gap-2.5 pl-2 pr-8 [&>span:first-child]:left-auto [&>span:first-child]:right-2",disabled:Q,"data-slot":"chat-menu-screen-wake-lock-item",onCheckedChange:Z,children:[m.jsx(Uo,{children:m.jsx(VV,{"aria-hidden":"true"})}),m.jsx("span",{className:"min-w-0 flex-1",children:L.supported?$?"屏幕常亮(Voice Pilot 控制)":"屏幕常亮":L.unavailableReason==="insecure-context"?"屏幕常亮(需要 HTTPS)":"屏幕常亮(浏览器不支持)"})]}),R&&!M&&m.jsxs(t0,{checked:k,className:"min-h-9 justify-start gap-2.5 pl-2 pr-8 [&>span:first-child]:left-auto [&>span:first-child]:right-2",disabled:!S,"data-slot":"chat-menu-pty-auto-yes-item",onCheckedChange:ye=>{S&&T(S,ye===!0)},children:[m.jsx(Uo,{children:m.jsx(Co,{"aria-hidden":"true"})}),m.jsx("span",{className:"min-w-0 flex-1",children:"Always yes"})]}),!R&&!M&&m.jsxs(t0,{checked:X.enabled,className:"min-h-9 justify-start gap-2.5 pl-2 pr-8 [&>span:first-child]:left-auto [&>span:first-child]:right-2","data-slot":"chat-menu-voice-pilot-item",onCheckedChange:ae,children:[m.jsx(Uo,{children:m.jsx(QV,{"aria-hidden":"true"})}),m.jsx("span",{className:"min-w-0 flex-1",children:"Voice Pilot"})]}),m.jsx(Ld,{}),R&&!M?m.jsxs(m.Fragment,{children:[m.jsx(nv,{className:xv,children:"快捷键"}),m.jsxs(ni,{className:ud,"data-slot":"chat-menu-send-ctrl-o",onClick:()=>So(e,""),children:[m.jsx(h1e,{label:"^O"}),"发送 Ctrl+O"]}),m.jsx(Ld,{}),m.jsx(nv,{className:xv,children:"文件"}),m.jsxs(ni,{className:ud,"data-slot":"chat-menu-upload-image",onClick:()=>{var ye;return(ye=ke.current)==null?void 0:ye.click()},children:[m.jsx(Uo,{children:m.jsx(Jp,{"aria-hidden":"true"})}),"上传照片或视频"]}),m.jsxs(ni,{className:ud,"data-slot":"chat-menu-upload-file",onClick:()=>{var ye;return(ye=me.current)==null?void 0:ye.click()},children:[m.jsx(Uo,{children:m.jsx(lz,{"aria-hidden":"true"})}),"上传文件"]}),m.jsx(Ld,{})]}):null,m.jsx(nv,{className:xv,children:"字号"}),m.jsx("div",{className:"px-2 pb-1","data-slot":"chat-menu-font-control",children:m.jsxs("div",{className:"inline-grid min-h-9 grid-cols-[1.25rem_auto] items-center gap-x-2.5 py-1","data-slot":"chat-menu-font-row",children:[m.jsx(Uo,{children:m.jsx(BY,{"aria-hidden":"true"})}),m.jsxs("div",{className:"col-start-2 inline-flex w-fit shrink-0 items-center gap-2","data-slot":"chat-menu-font-stepper",children:[m.jsx(gt,{variant:"ghost",size:"icon-sm",className:"size-[22px] rounded-[5px] bg-muted/45 text-muted-foreground hover:bg-accent hover:text-accent-foreground",disabled:I<=B,"aria-label":"字号变小","data-slot":"chat-menu-font-smaller",onClick:ye=>{ye.stopPropagation(),G(-1)},children:m.jsx(eY,{"aria-hidden":"true"})}),m.jsxs("span",{className:"flex h-[22px] min-w-11 items-center justify-center px-1 text-sm font-medium leading-none tabular-nums text-foreground","data-slot":"chat-menu-font-size",children:[I,"px"]}),m.jsx(gt,{variant:"ghost",size:"icon-sm",className:"size-[22px] rounded-[5px] bg-muted/45 text-muted-foreground hover:bg-accent hover:text-accent-foreground",disabled:I>=Tz,"aria-label":"字号变大","data-slot":"chat-menu-font-larger",onClick:ye=>{ye.stopPropagation(),G(1)},children:m.jsx(hY,{"aria-hidden":"true"})})]})]})}),m.jsxs(ni,{className:ud,"data-slot":"chat-menu-font-reset",onClick:F,children:[m.jsx(Uo,{children:m.jsx(gY,{"aria-hidden":"true"})}),m.jsx("span",{"data-slot":"chat-menu-font-reset-label",children:"恢复默认"})]})]})]})]})}),m.jsx(Jh,{open:$e,sessionId:e,initialName:s==null?void 0:s.name,onOpenChange:he,onRename:Nt}),m.jsx(ss,{open:Y&&!X.enabled,onOpenChange:ye=>{q||z(ye)},children:m.jsxs(os,{className:"sm:max-w-md","data-slot":"voice-pilot-wake-lock-dialog",focusSurfaceOnOpen:!0,children:[m.jsxs(as,{children:[m.jsx(Yi,{children:"开启 Voice Pilot?"}),m.jsx(_s,{children:"开启后会持续聆听并保持屏幕常亮,停止后自动恢复。"})]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"outline",disabled:q,onClick:()=>z(!1),children:"取消"}),m.jsx(gt,{type:"button","data-slot":"voice-pilot-confirm-start",disabled:q,onClick:()=>{le()},children:q?"正在开启...":"开启 Voice Pilot"})]})]})}),R?m.jsxs(m.Fragment,{children:[m.jsx("input",{ref:ke,type:"file",accept:r.mediaAccept,className:"hidden","data-slot":"chat-menu-upload-image-input",onChange:ye=>{He(ye)}}),m.jsx("input",{ref:me,type:"file",accept:r.fileAccept,className:"hidden","data-slot":"chat-menu-upload-file-input",onChange:ye=>{He(ye)}})]}):null]})}function dd(e,t,n){let r=n.initialDeps??[],i,s=!0;function o(){var l,u,d;let f;n.key&&((l=n.debug)!=null&&l.call(n))&&(f=Date.now());const p=e();if(!(p.length!==r.length||p.some((_,w)=>r[w]!==_)))return i;r=p;let g;if(n.key&&((u=n.debug)!=null&&u.call(n))&&(g=Date.now()),i=t(...p),n.key&&((d=n.debug)!=null&&d.call(n))){const _=Math.round((Date.now()-f)*100)/100,w=Math.round((Date.now()-g)*100)/100,x=w/16,S=(k,T)=>{for(k=String(k);k.length<T;)k=" "+k;return k};console.info(`%c⏱ ${S(w,5)} /${S(_,5)} ms`,`
718
+ `):[]);n(T=>T.filter(N=>k.has(N.sessionId))),i(T=>T&&k.has(T.sessionId)?T:null),p.current&&!k.has(p.current)&&(p.current=null,o(null))},[y,d]),b.useEffect(()=>{const k=f.current;f.current=l,!(!k||k===l)&&(p.current=null,n([]),i(null),o(null))},[l]);const S=b.useMemo(()=>({activate:g,deactivate:_,updateFindRequest:x,updateViewportRect:w}),[g,_,x,w]);return m.jsxs(L6.Provider,{value:S,children:[e,m.jsx(RSe,{entries:t,activeView:r,viewportRect:s})]})}function TSe({sessionId:e,sessionKind:t,provider:n,findRequest:r}){const i=b.useContext(L6),s=b.useRef(null);if(!i)throw new Error("PtyKeepAliveViewport must be used within PtyKeepAliveProvider");const{activate:o,deactivate:l,updateFindRequest:u,updateViewportRect:d}=i;return b.useLayoutEffect(()=>(o({sessionId:e,sessionKind:t,provider:n}),()=>l(e)),[o,l,e,t,n]),b.useLayoutEffect(()=>{u(e,r)},[r,e,u]),b.useLayoutEffect(()=>{const f=s.current;if(!f)return;const p=()=>{const g=f.getBoundingClientRect();d(e,{top:g.top,left:g.left,width:g.width,height:g.height})};p();const y=new ResizeObserver(p);return y.observe(f),window.addEventListener("resize",p),()=>{y.disconnect(),window.removeEventListener("resize",p)}},[e,d]),m.jsx("div",{ref:s,className:"h-full w-full bg-background","data-slot":"pty-keepalive-viewport","data-session-id":e})}function RSe({entries:e,activeView:t,viewportRect:n}){return e.length===0?null:m.jsx("div",{className:"fixed inset-0 z-10 pointer-events-none","data-slot":"pty-keepalive-layer",children:e.map(r=>{const i=(t==null?void 0:t.sessionId)===r.sessionId&&n!==null,s=i?n:{top:-1e5,left:0,width:(n==null?void 0:n.width)??ESe,height:(n==null?void 0:n.height)??CSe};return m.jsx("div",{className:"absolute overflow-hidden bg-background","data-slot":"pty-keepalive-entry","data-session-id":r.sessionId,"data-active":i?"true":"false","aria-hidden":!i,style:{top:s.top,left:s.left,width:s.width,height:s.height,pointerEvents:i?"auto":"none",visibility:i?"visible":"hidden"},children:m.jsx(RF,{sessionId:r.sessionId,children:m.jsx(xSe,{sessionId:r.sessionId,sessionKind:r.sessionKind,provider:r.provider,active:i,findRequest:r.findRequest})})},r.sessionId)})})}function ASe(e,t){return Math.abs(e.top-t.top)<=wv&&Math.abs(e.left-t.left)<=wv&&Math.abs(e.width-t.width)<=wv&&Math.abs(e.height-t.height)<=wv}function NSe(){const e=Gt(r=>r.codexActiveWriterConflict),t=Gt(r=>r.setCodexActiveWriterConflict),n=()=>t(null);return m.jsx(ss,{open:e!==null,onOpenChange:r=>!r&&n(),children:m.jsxs(os,{focusSurfaceOnOpen:!0,className:"min-w-0 sm:max-w-md",children:[m.jsxs(as,{children:[m.jsx(Yi,{children:"该 Codex 会话仍在运行"}),m.jsxs(_s,{className:"space-y-2 text-left leading-6",children:[m.jsxs("span",{className:"block",children:["另一个 Codex 进程正在使用此会话",e!=null&&e.activeWriterPid?m.jsxs(m.Fragment,{children:["(PID"," ",m.jsx("span",{className:"font-mono text-foreground",children:e.activeWriterPid}),")"]}):null,"。"]}),m.jsx("span",{className:"block",children:"它可能来自本机终端、Codex App 或另一条 DEV Anywhere 会话。请先回到或结束原会话后再重试。"}),m.jsx("span",{className:"block text-muted-foreground/80",children:"DEV Anywhere 不会自动终止该进程。"})]})]}),m.jsx(Fs,{children:m.jsx(gt,{type:"button",onClick:n,autoFocus:!0,children:"知道了"})})]})})}function rT({route:e,surface:t,proxiesLength:n,proxyListLoaded:r,hasProxy:i,relayClientAuthIssue:s=null}){return s==="missing_client_token"?"Relay 需要 client token,请在设置中填写":s==="invalid_client_token"?"client token 无效或已过期,请在设置中更新":r?n===0?"在开发机上启动 DEV Anywhere,本页会显示可连接的开发机":t==="mobile"&&e==="proxy-select"||!i?"选择要连接的开发机":null:null}function MSe(e){const t=Rj(e);return t.osName!=="iPad"?{supported:!0}:e.standalone||t.browserName==="Safari"?{supported:!0}:{supported:!1,reason:"ipad-safari-required",browserName:t.browserName}}function sy(){if(typeof window>"u"||typeof navigator>"u")return!1;const e=typeof window.matchMedia=="function"&&(window.matchMedia("(display-mode: standalone)").matches||window.matchMedia("(display-mode: fullscreen)").matches),t=!!navigator.standalone;return e||t}function PSe(){return typeof navigator>"u"?{supported:!0}:MSe({userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints,standalone:sy()})}function ISe(){s0e(),o0e();const e=rs(),t=ws(),n=e.pathname.startsWith("/chat/"),r=e.pathname.startsWith("/preview/device/"),i=n||r,s=e.pathname==="/"||e.pathname==="/sessions",[o,l]=b.useState(!1),[u,d]=b.useState(()=>sy()),f=Ie(V=>V.proxies.length),p=Ie(V=>V.proxyListLoaded),y=Ie(V=>V.relayClientAuthIssue),g=Ie(V=>V.relayConnectionIssue),_=Ie(V=>!!V.selectedProxyId),w=Ie(V=>V.selectedProxyId),x=Ie(V=>V.selectedProxyName);Gt(V=>V.sessions.length);const S=Ie(V=>V.pendingToast),k=Ie(V=>V.setPendingToast),T=e.pathname==="/"?"proxy-select":"sessions",N=g!==null&&y===null,P=rT({route:T,surface:"mobile",proxiesLength:f,proxyListLoaded:p,hasProxy:_,relayClientAuthIssue:y}),R=x??w,L=e.pathname==="/sessions"&&p&&f>0?m.jsxs(gt,{variant:"ghost",size:"sm",className:"h-auto min-h-11 max-w-full justify-start rounded-md border border-border/70 bg-background/35 px-3 py-2 text-left text-muted-foreground hover:border-primary/45 hover:bg-accent/70 hover:text-foreground","data-slot":"mobile-switch-proxy","aria-label":R?`切换开发机,当前 ${R}`:"切换开发机",onClick:()=>t("/"),children:[m.jsx(rz,{className:"size-4 text-primary","aria-hidden":"true"}),m.jsxs("span",{className:"min-w-0 truncate",children:[m.jsx("span",{className:"text-foreground",children:"切换开发机"}),R?m.jsxs("span",{className:"ml-1 text-muted-foreground/75",children:["· ",R]}):null]})]}):null;b.useEffect(()=>{if(!S)return;({error:We.error,info:We.info,success:We.success})[S.kind](S.message),k(null)},[S,k]),b.useEffect(()=>{if(typeof window.matchMedia!="function"){d(sy());return}const V=window.matchMedia("(display-mode: standalone)"),j=window.matchMedia("(display-mode: fullscreen)"),A=()=>d(sy());return A(),V.addEventListener("change",A),j.addEventListener("change",A),()=>{V.removeEventListener("change",A),j.removeEventListener("change",A)}},[]);const X=b.useRef(!1);b.useEffect(()=>{if(X.current)return;X.current=!0;const V=Ore({pathname:e.pathname,alreadyRestored:Bre(),lastRoute:Lre()});zre(),V&&(jre(V),t(V,{replace:!0}))},[]);const U=b.useRef(!1);return b.useEffect(()=>{n?(U.current=!0,Dre(`${e.pathname}${e.search}`)):U.current&&(U.current=!1,by())},[n,e.pathname,e.search]),m.jsxs(Oue,{blocked:N,children:[m.jsxs("div",{className:"flex flex-col bg-background text-foreground",style:{height:"var(--dev-app-shell-height, max(100dvh, var(--dev-visual-viewport-height, 100dvh)))"},"data-slot":"app-shell","data-standalone-display":u?"true":void 0,inert:N?!0:void 0,"aria-hidden":N?!0:void 0,children:[!i&&m.jsx(gt,{variant:"ghost",size:"icon",className:"dev-mobile-settings-trigger group fixed right-4 z-30 size-11 rounded-full border-0 bg-transparent p-0 text-muted-foreground shadow-none hover:bg-transparent hover:text-foreground md:hidden","aria-label":"设置","data-slot":"mobile-settings-trigger",onClick:()=>l(!0),children:m.jsx("span",{"data-slot":"mobile-settings-trigger-visual",className:"flex size-7 items-center justify-center rounded-full border border-border/80 bg-card/90 shadow-lg backdrop-blur transition-colors group-hover:border-primary/45 group-hover:bg-accent",children:m.jsx(oz,{className:"size-4","aria-hidden":"true"})})}),!i&&m.jsx(Pfe,{subtitle:P,action:L}),m.jsx(Ahe,{}),m.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[m.jsx(Afe,{className:"hidden md:flex"}),m.jsx("main",{className:"relative flex-1 overflow-hidden",role:"main",children:m.jsx(kSe,{children:m.jsx("div",{className:Ye("h-full",!s&&"animate-in fade-in-0 duration-200 motion-reduce:animate-none"),"data-slot":"route-content",children:m.jsx(Yq,{})},s?"top-level":e.pathname)})})]}),m.jsx(v1,{open:o,onOpenChange:l}),m.jsx(NSe,{}),m.jsx(she,{}),m.jsx($fe,{}),m.jsx(ore,{})]}),N&&g?m.jsx("div",{className:"fixed inset-0 z-[60] bg-background",children:m.jsx(lhe,{issue:g})}):null]})}function D6({subtitle:e,action:t}){return m.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-6 px-6 text-center",children:[m.jsx(K4,{texts:G4,className:"text-2xl md:text-3xl font-bold"}),e?m.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:e}):null,t&&m.jsx("div",{children:t})]})}function OSe(){const e=Ie(o=>o.proxies),t=Ie(o=>o.proxyListLoaded),n=Ie(o=>!!o.selectedProxyId),r=Ie(o=>o.relayClientAuthIssue);Gt(o=>o.sessions.length);const i=rT({route:"proxy-select",surface:"desktop",proxiesLength:e.length,proxyListLoaded:t,hasProxy:n,relayClientAuthIssue:r}),s=r==="missing_client_token"?"client-token-missing":r==="invalid_client_token"?"client-token-invalid":null;return m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"h-full md:hidden",children:m.jsx(R4,{layout:"page"})}),m.jsx("div",{className:"hidden md:block h-full",children:s?m.jsx(Uc,{variant:s}):m.jsx(D6,{subtitle:i})})]})}function LSe(){const e=Ie(o=>o.proxies),t=Ie(o=>o.proxyListLoaded),n=Ie(o=>!!o.selectedProxyId),r=Ie(o=>o.relayClientAuthIssue);Gt(o=>o.sessions.length);const i=Si("local",wn.proxyId)!==null;if(!n&&!i)return m.jsx(Vq,{to:"/",replace:!0});const s=rT({route:"sessions",surface:"desktop",proxiesLength:e.length,proxyListLoaded:t,hasProxy:n,relayClientAuthIssue:r});return m.jsxs(m.Fragment,{children:[m.jsx("div",{className:"h-full md:hidden",children:m.jsx($4,{layout:"page"})}),m.jsx("div",{className:"hidden md:block h-full",children:m.jsx(D6,{subtitle:s})})]})}function B6(){if(!(typeof navigator>"u"))return navigator.wakeLock}function DSe(e,t){return e===!1?"insecure-context":t?null:"unsupported"}function z6(){var t;const e=typeof window>"u"?void 0:window.isSecureContext;return DSe(e,typeof((t=B6())==null?void 0:t.request)=="function")}function BSe(e){return e==="insecure-context"?"屏幕常亮需要 HTTPS":"当前浏览器不支持屏幕常亮"}function zSe(){const e=B6();if(typeof(e==null?void 0:e.request)!="function")throw new Error(BSe(z6()));return e.request("screen")}function jSe(e){return e instanceof Error&&e.message.trim()?e.message:"无法开启屏幕常亮"}class FSe{constructor(t={}){je(this,"activeScopes",new Set);je(this,"pendingScopes",new Set);je(this,"listeners",new Map);je(this,"sentinel",null);je(this,"requestInFlight",null);je(this,"requestWakeLock");je(this,"documentRef");je(this,"windowRef");je(this,"unavailableReason");je(this,"handleVisibilityChange",()=>{var t,n;if(((t=this.documentRef)==null?void 0:t.visibilityState)==="hidden"){this.releaseSentinel().catch(()=>{});return}((n=this.documentRef)==null?void 0:n.visibilityState)==="visible"&&this.ensureWakeLock().catch(()=>{})});je(this,"handlePageHide",()=>{this.releaseSentinel().catch(()=>{})});var n,r;this.requestWakeLock=t.request??zSe,this.unavailableReason=typeof t.request=="function"?null:z6(),this.documentRef=t.document??(typeof document>"u"?void 0:document),this.windowRef=t.window??(typeof window>"u"?void 0:window),(n=this.documentRef)==null||n.addEventListener("visibilitychange",this.handleVisibilityChange),(r=this.windowRef)==null||r.addEventListener("pagehide",this.handlePageHide)}isSupported(){return this.unavailableReason===null}getSnapshot(t){return{active:this.activeScopes.has(t),pending:this.pendingScopes.has(t),supported:this.isSupported(),unavailableReason:this.unavailableReason}}subscribe(t,n){const r=this.listeners.get(t)??new Set;return r.add(n),this.listeners.set(t,r),n(this.getSnapshot(t)),()=>{r.delete(n),r.size===0&&this.listeners.delete(t)}}async enable(t){this.activeScopes.add(t),this.pendingScopes.add(t),this.notify(t);try{await this.ensureWakeLock()}catch(n){throw this.activeScopes.delete(t),new Error(jSe(n),{cause:n})}finally{this.pendingScopes.delete(t),this.notify(t)}}async disable(t){const n=this.activeScopes.delete(t);this.pendingScopes.delete(t),this.notify(t),!(!n||this.activeScopes.size>0)&&await this.releaseSentinel()}async toggle(t){this.activeScopes.has(t)?await this.disable(t):await this.enable(t)}dispose(){var t,n;(t=this.documentRef)==null||t.removeEventListener("visibilitychange",this.handleVisibilityChange),(n=this.windowRef)==null||n.removeEventListener("pagehide",this.handlePageHide),this.activeScopes.clear(),this.pendingScopes.clear(),this.releaseSentinel().catch(()=>{});for(const r of this.listeners.keys())this.notify(r)}async ensureWakeLock(){var t;if(this.activeScopes.size!==0&&((t=this.documentRef)==null?void 0:t.visibilityState)!=="hidden"&&!(this.sentinel&&!this.sentinel.released))return this.requestInFlight?this.requestInFlight:(this.requestInFlight=this.requestWakeLock().then(async n=>{var r;if(this.activeScopes.size===0||((r=this.documentRef)==null?void 0:r.visibilityState)==="hidden"){n.released||await n.release();return}this.sentinel=n,n.addEventListener("release",()=>{var i;this.sentinel===n&&(this.sentinel=null),this.activeScopes.size>0&&((i=this.documentRef)==null?void 0:i.visibilityState)!=="hidden"&&this.ensureWakeLock().catch(()=>{})},{once:!0})}).finally(()=>{this.requestInFlight=null}),this.requestInFlight)}async releaseSentinel(){const t=this.sentinel;this.sentinel=null,!(!t||t.released)&&await t.release()}notify(t){var r;const n=this.getSnapshot(t);(r=this.listeners.get(t))==null||r.forEach(i=>i(n))}}const Pl=new FSe;function j6(e){const[t,n]=b.useState(()=>Pl.getSnapshot(e));b.useEffect(()=>Pl.subscribe(e,n),[e]),b.useEffect(()=>()=>{Pl.disable(e).catch(()=>{})},[e]);const r=b.useCallback(()=>Pl.enable(e),[e]),i=b.useCallback(()=>Pl.disable(e),[e]),s=b.useCallback(()=>Pl.toggle(e),[e]);return{...t,enable:r,disable:i,toggle:s}}function $Se(){return new AudioContext}class HSe{constructor(t=$Se){je(this,"context",null);this.createContext=t}get(){return this.context??(this.context=this.createContext()),this.context}async prepare(){const t=this.get();if(t.state!=="running"&&t.state!=="closed"&&await t.resume(),t.state!=="running")throw new Error("浏览器未允许播放 Voice Pilot 提示音");return t}async reactivateAfterCapture(){const t=this.get();if(t.state==="closed")throw new Error("Voice Pilot 播放上下文已关闭");if(t.state==="running"&&await t.suspend(),t.state!=="running"&&await t.resume(),t.state!=="running")throw new Error("浏览器未能恢复 Voice Pilot 音频输出");return t}}const oy=new HSe,xL=400,Ad=[];let F6=1;function USe(){return typeof performance>"u"?0:Math.round(performance.now()*10)/10}function cp(e){const t={sequence:F6++,timestamp:new Date().toISOString(),monotonicMs:USe(),sessionId:e.sessionId,scope:e.scope,event:e.event,...e.attemptId?{attemptId:e.attemptId}:{},...e.requestId?{requestId:e.requestId}:{},...e.details?{details:{...e.details}}:{}};Ad.push(t),Ad.length>xL&&Ad.splice(0,Ad.length-xL)}function WSe(){return Ad.map(e=>({...e,...e.details?{details:{...e.details}}:{}}))}function qSe(){Ad.length=0,F6=1}typeof window<"u"&&(window.__devAnywhereVoicePilotDiagnostics={snapshot:WSe,clear:qSe});function $6(e){return`voice-pilot:${e}`}function VSe(e){const t=new Int16Array(e.length);for(let n=0;n<e.length;n+=1){const r=Math.max(-1,Math.min(1,e[n]??0));t[n]=r<0?Math.round(r*32768):Math.floor(r*32767)}return new Uint8Array(t.buffer)}const YSe="modulepreload",KSe=function(e){return"/"+e},SL={},H6=function(t,n,r){let i=Promise.resolve();if(n&&n.length>0){let o=function(d){return Promise.all(d.map(f=>Promise.resolve(f).then(p=>({status:"fulfilled",value:p}),p=>({status:"rejected",reason:p}))))};document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),u=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));i=o(n.map(d=>{if(d=KSe(d),d in SL)return;SL[d]=!0;const f=d.endsWith(".css"),p=f?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${p}`))return;const y=document.createElement("link");if(y.rel=f?"stylesheet":YSe,f||(y.as="script"),y.crossOrigin="",y.href=d,u&&y.setAttribute("nonce",u),document.head.appendChild(y),f)return new Promise((g,_)=>{y.addEventListener("load",g),y.addEventListener("error",()=>_(new Error(`Unable to preload CSS for ${d}`)))})}))}function s(o){const l=new Event("vite:preloadError",{cancelable:!0});if(l.payload=o,window.dispatchEvent(l),!l.defaultPrevented)throw o}return i.then(o=>{for(const l of o||[])l.status==="rejected"&&s(l.reason);return t().catch(s)})},GSe="/assets/fvad-DYxbW2my.wasm",ef=16e3,XSe=20,Il=ef*XSe/1e3,G0=Il*Int16Array.BYTES_PER_ELEMENT;let EL=null;async function ZSe(){return EL??(EL=H6(async()=>{const{default:e}=await import("./fvad-okuu-1HD.js");return{default:e}},[]).then(({default:e})=>e({locateFile:t=>t.endsWith(".wasm")?GSe:t}))),EL}class iT{constructor(t,n,r){je(this,"destroyed",!1);this.module=t,this.handle=n,this.framePointer=r}static async create(t=3){const n=await ZSe(),r=n._fvad_new();if(!r)throw new Error("无法初始化浏览器语音活动检测器");const i=n._malloc(G0);if(!i)throw n._fvad_free(r),new Error("无法分配浏览器语音活动检测缓冲区");if(n._fvad_set_sample_rate(r,ef)!==0)throw n._free(i),n._fvad_free(r),new Error("浏览器语音活动检测器不支持 16 kHz 音频");if(n._fvad_set_mode(r,t)!==0)throw n._free(i),n._fvad_free(r),new Error("无法配置浏览器语音活动检测器");return new iT(n,r,i)}process(t){if(this.destroyed)throw new Error("浏览器语音活动检测器已释放");if(t.byteLength!==G0)throw new Error(`语音活动检测帧必须为 ${G0} 字节`);this.module.HEAPU8.set(t,this.framePointer);const n=this.module._fvad_process(this.handle,this.framePointer,Il);if(n<0)throw new Error("浏览器语音活动检测失败");return n===1}reset(){this.destroyed||this.module._fvad_reset(this.handle)}destroy(){this.destroyed||(this.destroyed=!0,this.module._free(this.framePointer),this.module._fvad_free(this.handle))}}class QSe{constructor(t={}){je(this,"startSpeechFrames");je(this,"endSilenceFrames");je(this,"active",!1);je(this,"speechFrames",0);je(this,"silenceFrames",0);if(this.startSpeechFrames=t.startSpeechFrames??10,this.endSilenceFrames=t.endSilenceFrames??30,this.startSpeechFrames<1||this.endSilenceFrames<1)throw new Error("Invalid voice activity gate configuration")}push(t){return this.active?t?(this.silenceFrames=0,"none"):(this.silenceFrames+=1,this.silenceFrames<this.endSilenceFrames?"none":(this.active=!1,this.silenceFrames=0,"speech-end")):(this.speechFrames=t?this.speechFrames+1:0,this.speechFrames>=this.startSpeechFrames?(this.active=!0,this.speechFrames=0,this.silenceFrames=0,"speech-start"):"none")}reset(){this.active=!1,this.speechFrames=0,this.silenceFrames=0}}class JSe{constructor(){je(this,"pending",new Float32Array(Il));je(this,"pendingLength",0)}push(t,n){let r=0;if(this.pendingLength>0){const i=Il-this.pendingLength,s=Math.min(i,t.length);this.pending.set(t.subarray(0,s),this.pendingLength),this.pendingLength+=s,r+=s,this.pendingLength===Il&&(n(this.pending.slice()),this.pendingLength=0)}for(;r+Il<=t.length;)n(t.slice(r,r+Il)),r+=Il;if(r<t.length){const i=t.subarray(r);this.pending.set(i,0),this.pendingLength=i.length}}reset(){this.pendingLength=0}}const e1e="/__dev_anywhere_debug/voice-fixture",t1e=ef*U4/1e3;function n1e(){return iT.create(3)}const r1e={createVad:n1e,getUserMedia:e=>navigator.mediaDevices.getUserMedia(e),createAudioContext:e=>new AudioContext(e),fetch:e=>fetch(e)};function i1e(e){if(e.length===0)return 0;let t=0;for(const n of e)t+=n*n;return Math.min(1,Math.sqrt(t/e.length)*10)}function s1e(e){for(const t of e.getTracks())t.stop()}function U6(e){const t=e.createAudioContext({sampleRate:ef});if(t.sampleRate!==ef)throw t.close().catch(()=>{}),new Error("浏览器无法提供 Voice Pilot 所需的 16 kHz 音频输入");return t}async function o1e(e){const t=U6(e);let n;try{n=await e.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:ef}})}catch(i){throw await t.close().catch(()=>{}),i}const r=t.createMediaStreamSource(n);return{context:t,input:r,async start(){t.state==="suspended"&&await t.resume()},async stop(){r.disconnect(),s1e(n),t.state!=="closed"&&await t.close()}}}async function a1e(e,t){const n=U6(t);try{const r=await t.fetch(e);if(!r.ok)throw new Error(`测试录音读取失败 (${r.status})`);const i=await n.decodeAudioData(await r.arrayBuffer()),s=n.createBufferSource();s.buffer=i;let o=!1,l=!1;return{context:n,input:s,async start(){o||l||(o=!0,n.state==="suspended"&&await n.resume(),s.start())},async stop(){if(!l){if(l=!0,o)try{s.stop()}catch{}s.disconnect(),n.state!=="closed"&&await n.close()}}}}catch(r){throw await n.close().catch(()=>{}),r}}function W6(e=window.location.search,t=!1){return t&&new URLSearchParams(e).get("voice-fixture")==="default"?{kind:"fixture",url:e1e}:{kind:"microphone"}}async function l1e(e,t=r1e){const n=await t.createVad();let r;try{r=e.source.kind==="fixture"?await a1e(e.source.url,t):await o1e(t)}catch(f){throw n.destroy(),f}const i=new QSe,s=new JSe,o=r.context.createScriptProcessor(t1e,1,1);let l=!1,u=null,d=null;return o.onaudioprocess=f=>{l&&s.push(f.inputBuffer.getChannelData(0),p=>{const y=VSe(p),g=n.process(y);e.onFrame({pcm:y,speechProbability:g?1:0,activityLevel:i1e(p)});const _=i.push(g);_==="speech-start"&&e.onSpeechStart(),_==="speech-end"&&e.onSpeechEnd()})},r.input.connect(o),o.connect(r.context.destination),{source:e.source.kind,start(){return d?Promise.reject(new Error("语音采集已停止")):(u??(u=(async()=>{l=!0,await r.start()})()),u)},stop(){return d??(d=(async()=>{l=!1,o.onaudioprocess=null,o.disconnect(),i.reset(),s.reset(),n.reset(),n.destroy(),await r.stop()})()),d}}}function q6(e=rf().osName){return{mediaAccept:"image/*,video/*",fileAccept:e==="Android"?"application/*,text/*":void 0}}function c1e(e){const[t,n,...r]=Array.from(e);return t&&n===" "&&r.length>0?{indicator:t,label:r.join("")}:{label:e}}function u1e({title:e,isPtyTitle:t}){if(!t)return m.jsx(m.Fragment,{children:e});const{indicator:n,label:r}=c1e(e);return m.jsxs("span",{className:"inline-flex items-center justify-center max-w-full min-w-0 font-mono font-normal",children:[n&&m.jsx("span",{className:"inline-block w-[1.25ch] shrink-0 text-center","aria-hidden":"true",children:n}),m.jsx("span",{className:"truncate",children:n?` ${r}`:r})]})}function d1e(e){const t=e instanceof Error?e.name:"";return t==="NotAllowedError"||t==="SecurityError"?"没有麦克风权限,请在浏览器里允许访问麦克风。":t==="NotFoundError"||t==="DevicesNotFoundError"?"未检测到可用麦克风。":t==="NotReadableError"||t==="TrackStartError"?"麦克风正在被其他应用占用。":e instanceof Error?e.message:"无法访问麦克风。"}async function f1e(){var t;if(!((t=navigator.mediaDevices)!=null&&t.getUserMedia))throw new Error("当前浏览器不支持麦克风访问。");let e=null;try{e=await navigator.mediaDevices.getUserMedia({audio:!0})}catch(n){throw new Error(d1e(n),{cause:n})}finally{e==null||e.getTracks().forEach(n=>n.stop())}}const ud="min-h-9 gap-2.5",xv="px-2 pb-1 pt-2 text-xs font-semibold text-muted-foreground";function Uo({children:e,className:t}){return m.jsx("span",{"aria-hidden":"true","data-slot":"chat-menu-icon",className:Ye("inline-flex size-5 shrink-0 items-center justify-center text-muted-foreground [&_svg]:size-4",t),children:e})}function h1e({label:e}){return m.jsxs(Uo,{className:"relative",children:[m.jsx(nz,{className:"size-4","aria-hidden":"true"}),m.jsx("span",{className:"absolute -right-1.5 -top-1 flex h-3 min-w-4 items-center justify-center rounded-[3px] border border-border bg-popover px-0.5 font-mono text-[7px] leading-none text-muted-foreground shadow-sm",children:e})]})}function p1e({sessionId:e,mode:t,onFind:n}){const r=q6(),i=ws(),s=Gt(ye=>ye.sessions.find(Ze=>Ze.sessionId===e)),o=Gt(ye=>ye.ptyTitles[e]),l=Ie(ye=>ye.ptyFontSize),u=Ie(ye=>ye.chatContentFontSize),d=Ie(ye=>ye.selectedProxyId),f=Ie(ye=>ye.adjustPtyFontSize),p=Ie(ye=>ye.adjustChatContentFontSize),y=Ie(ye=>ye.setChatContentFontSize),g=Ie(ye=>ye.resetPtyFontSize),_=Ie(ye=>ye.resetChatContentFontSize),w=Ie(ye=>ye.inputModePreference==="hardware"),x=Gt(ye=>ye.renameSession),S=TC(d,e),k=Gt(ye=>S?!!ye.ptyAutoYesBySessionKey[S]:!1),T=Gt(ye=>ye.setPtyAutoYes),P=co("(pointer: coarse), (hover: none)")&&!w,R=t==="pty"||(s==null?void 0:s.mode)==="pty",M=(s==null?void 0:s.kind)==="terminal",L=j6(e),X=Rn(ye=>ye.bySessionId[e]??qb),U=Rn(ye=>ye.enable),V=Rn(ye=>ye.disable),j=!!(s!=null&&s.nameLocked&&(s!=null&&s.name)),A=LC(s),D=j&&(s==null?void 0:s.name)||A||R&&o||(s==null?void 0:s.name)||e.slice(0,8),O=!!(R&&!M&&o&&!j),I=R?l:uC(u,P),B=!R&&P?Rz:kz,F=R?g:_,[Y,z]=b.useState(!1),[q,K]=b.useState(!1),$=X.enabled,re=L.active||$,Q=L.pending||!L.supported||$;function G(ye){if(R){f(ye);return}if(P){y(I+ye);return}p(ye)}function Z(){L.toggle().catch(ye=>{We.error(ye instanceof Error?ye.message:String(ye))})}async function ae(ye){var Oe;if(R||M){We.info("Voice Pilot 目前适用于聊天会话。");return}if(ye!==!0){V(e);return}const Ze=Ft;if(!Ze){We.error("请先连接开发机");return}try{if(!((Oe=(await Ze.requestVoiceConfig()).config)!=null&&Oe.configured)){We.info("请先在设置里配置 Voice Pilot。");return}z(!0)}catch(ze){We.error(ze instanceof Error?ze.message:String(ze))}}async function le(){var ze;K(!0);let ye=null,Ze=!1;const Oe=$6(e);try{cp({sessionId:e,scope:"runtime",event:"wake-lock-requested",details:{userActivationActive:((ze=navigator.userActivation)==null?void 0:ze.isActive)??!1,visibilityState:document.visibilityState,secureContext:window.isSecureContext}});const et=Pl.enable(Oe).then(()=>{cp({sessionId:e,scope:"runtime",event:"wake-lock-acquired"})},it=>{throw cp({sessionId:e,scope:"runtime",event:"wake-lock-failed",details:{error:it instanceof Error?it.message:String(it)}}),new Error("屏幕常亮请求被浏览器拒绝,Voice Pilot 未开启。",{cause:it})});ye=hk.acquire("capture");const Ct=oy.prepare(),Le=W6().kind==="microphone"?f1e():Promise.resolve();await Promise.all([et,Ct,Le]),U(e),Ze=!0,z(!1)}catch(et){cp({sessionId:e,scope:"runtime",event:"startup-failed",details:{error:et instanceof Error?et.message:String(et)}}),We.error(et instanceof Error?et.message:String(et))}finally{ye==null||ye.release(),Ze||await Pl.disable(Oe).catch(()=>{}),K(!1)}}const me=b.useRef(null),ke=b.useRef(null),[$e,he]=b.useState(!1);async function He(ye){var et;const Ze=(et=ye.target.files)==null?void 0:et[0];if(ye.target.value="",!Ze)return;const Oe=Ft;if(!Oe){We.error("请先连接开发机");return}const ze=await Up({relay:Oe,sessionId:e,file:Ze});ze&&So(e,`@${ze} `)}async function Nt(ye,Ze){const Oe=Ft;if(!Oe)throw new Error("请先连接开发机");const ze=await Oe.renameSession(ye,Ze);if(!ze.success)throw new Error(ze.error??"重命名失败");x(ye,ze.name??Ze),We.success("已重命名会话")}return m.jsxs("div",{className:"border-b border-border bg-card pt-[env(safe-area-inset-top)] shrink-0","data-slot":"chat-header",children:[m.jsx("div",{className:"dev-chat-shell-rail-inset","data-slot":"chat-header-rail-inset",children:m.jsxs("div",{className:"grid min-h-12 w-full grid-cols-[2.25rem_minmax(0,1fr)_2.25rem] items-center","data-slot":"chat-header-rail",children:[m.jsx("div",{className:"flex justify-start",children:m.jsx(gt,{variant:"ghost",size:"icon-sm",className:"md:hidden",onClick:()=>i("/sessions"),"aria-label":"返回会话列表","data-slot":"chat-back-button",children:m.jsx(Qp,{"aria-hidden":"true"})})}),m.jsx("span",{className:"text-sm font-semibold truncate text-center px-2","data-slot":"chat-session-title",children:m.jsx(u1e,{title:D,isPtyTitle:O})}),m.jsxs(uf,{modal:!1,children:[m.jsx(df,{asChild:!0,children:m.jsx(gt,{variant:"ghost",size:"icon-sm",className:"justify-self-end","aria-label":"会话操作","data-slot":"chat-overflow-trigger",children:m.jsx(wV,{"aria-hidden":"true"})})}),m.jsxs(ff,{align:"end",className:"w-max min-w-44 max-w-[calc(100vw-1rem)]","data-slot":"chat-overflow-menu",children:[m.jsx(nv,{className:xv,children:"会话"}),m.jsxs(ni,{className:ud,"data-slot":"chat-menu-find",onSelect:n,children:[m.jsx(Uo,{children:m.jsx(cy,{"aria-hidden":"true"})}),"在会话中查找"]}),m.jsxs(ni,{className:ud,"data-slot":"chat-menu-rename",onSelect:()=>he(!0),children:[m.jsx(Uo,{children:m.jsx(uY,{"aria-hidden":"true"})}),"重命名"]}),m.jsxs(t0,{checked:re,className:"min-h-9 justify-start gap-2.5 pl-2 pr-8 [&>span:first-child]:left-auto [&>span:first-child]:right-2",disabled:Q,"data-slot":"chat-menu-screen-wake-lock-item",onCheckedChange:Z,children:[m.jsx(Uo,{children:m.jsx(VV,{"aria-hidden":"true"})}),m.jsx("span",{className:"min-w-0 flex-1",children:L.supported?$?"屏幕常亮(Voice Pilot 控制)":"屏幕常亮":L.unavailableReason==="insecure-context"?"屏幕常亮(需要 HTTPS)":"屏幕常亮(浏览器不支持)"})]}),R&&!M&&m.jsxs(t0,{checked:k,className:"min-h-9 justify-start gap-2.5 pl-2 pr-8 [&>span:first-child]:left-auto [&>span:first-child]:right-2",disabled:!S,"data-slot":"chat-menu-pty-auto-yes-item",onCheckedChange:ye=>{S&&T(S,ye===!0)},children:[m.jsx(Uo,{children:m.jsx(Co,{"aria-hidden":"true"})}),m.jsx("span",{className:"min-w-0 flex-1",children:"Always yes"})]}),!R&&!M&&m.jsxs(t0,{checked:X.enabled,className:"min-h-9 justify-start gap-2.5 pl-2 pr-8 [&>span:first-child]:left-auto [&>span:first-child]:right-2","data-slot":"chat-menu-voice-pilot-item",onCheckedChange:ae,children:[m.jsx(Uo,{children:m.jsx(QV,{"aria-hidden":"true"})}),m.jsx("span",{className:"min-w-0 flex-1",children:"Voice Pilot"})]}),m.jsx(Ld,{}),R&&!M?m.jsxs(m.Fragment,{children:[m.jsx(nv,{className:xv,children:"快捷键"}),m.jsxs(ni,{className:ud,"data-slot":"chat-menu-send-ctrl-o",onClick:()=>So(e,""),children:[m.jsx(h1e,{label:"^O"}),"发送 Ctrl+O"]}),m.jsx(Ld,{}),m.jsx(nv,{className:xv,children:"文件"}),m.jsxs(ni,{className:ud,"data-slot":"chat-menu-upload-image",onClick:()=>{var ye;return(ye=ke.current)==null?void 0:ye.click()},children:[m.jsx(Uo,{children:m.jsx(Jp,{"aria-hidden":"true"})}),"上传照片或视频"]}),m.jsxs(ni,{className:ud,"data-slot":"chat-menu-upload-file",onClick:()=>{var ye;return(ye=me.current)==null?void 0:ye.click()},children:[m.jsx(Uo,{children:m.jsx(lz,{"aria-hidden":"true"})}),"上传文件"]}),m.jsx(Ld,{})]}):null,m.jsx(nv,{className:xv,children:"字号"}),m.jsx("div",{className:"px-2 pb-1","data-slot":"chat-menu-font-control",children:m.jsxs("div",{className:"inline-grid min-h-9 grid-cols-[1.25rem_auto] items-center gap-x-2.5 py-1","data-slot":"chat-menu-font-row",children:[m.jsx(Uo,{children:m.jsx(BY,{"aria-hidden":"true"})}),m.jsxs("div",{className:"col-start-2 inline-flex w-fit shrink-0 items-center gap-2","data-slot":"chat-menu-font-stepper",children:[m.jsx(gt,{variant:"ghost",size:"icon-sm",className:"size-[22px] rounded-[5px] bg-muted/45 text-muted-foreground hover:bg-accent hover:text-accent-foreground",disabled:I<=B,"aria-label":"字号变小","data-slot":"chat-menu-font-smaller",onClick:ye=>{ye.stopPropagation(),G(-1)},children:m.jsx(eY,{"aria-hidden":"true"})}),m.jsxs("span",{className:"flex h-[22px] min-w-11 items-center justify-center px-1 text-sm font-medium leading-none tabular-nums text-foreground","data-slot":"chat-menu-font-size",children:[I,"px"]}),m.jsx(gt,{variant:"ghost",size:"icon-sm",className:"size-[22px] rounded-[5px] bg-muted/45 text-muted-foreground hover:bg-accent hover:text-accent-foreground",disabled:I>=Tz,"aria-label":"字号变大","data-slot":"chat-menu-font-larger",onClick:ye=>{ye.stopPropagation(),G(1)},children:m.jsx(hY,{"aria-hidden":"true"})})]})]})}),m.jsxs(ni,{className:ud,"data-slot":"chat-menu-font-reset",onClick:F,children:[m.jsx(Uo,{children:m.jsx(gY,{"aria-hidden":"true"})}),m.jsx("span",{"data-slot":"chat-menu-font-reset-label",children:"恢复默认"})]})]})]})]})}),m.jsx(Jh,{open:$e,sessionId:e,initialName:s==null?void 0:s.name,onOpenChange:he,onRename:Nt}),m.jsx(ss,{open:Y&&!X.enabled,onOpenChange:ye=>{q||z(ye)},children:m.jsxs(os,{className:"sm:max-w-md","data-slot":"voice-pilot-wake-lock-dialog",focusSurfaceOnOpen:!0,children:[m.jsxs(as,{children:[m.jsx(Yi,{children:"开启 Voice Pilot?"}),m.jsx(_s,{children:"开启后会持续聆听并保持屏幕常亮,停止后自动恢复。"})]}),m.jsxs(Fs,{children:[m.jsx(gt,{type:"button",variant:"outline",disabled:q,onClick:()=>z(!1),children:"取消"}),m.jsx(gt,{type:"button","data-slot":"voice-pilot-confirm-start",disabled:q,onClick:()=>{le()},children:q?"正在开启...":"开启 Voice Pilot"})]})]})}),R?m.jsxs(m.Fragment,{children:[m.jsx("input",{ref:ke,type:"file",accept:r.mediaAccept,className:"hidden","data-slot":"chat-menu-upload-image-input",onChange:ye=>{He(ye)}}),m.jsx("input",{ref:me,type:"file",accept:r.fileAccept,className:"hidden","data-slot":"chat-menu-upload-file-input",onChange:ye=>{He(ye)}})]}):null]})}function dd(e,t,n){let r=n.initialDeps??[],i,s=!0;function o(){var l,u,d;let f;n.key&&((l=n.debug)!=null&&l.call(n))&&(f=Date.now());const p=e();if(!(p.length!==r.length||p.some((_,w)=>r[w]!==_)))return i;r=p;let g;if(n.key&&((u=n.debug)!=null&&u.call(n))&&(g=Date.now()),i=t(...p),n.key&&((d=n.debug)!=null&&d.call(n))){const _=Math.round((Date.now()-f)*100)/100,w=Math.round((Date.now()-g)*100)/100,x=w/16,S=(k,T)=>{for(k=String(k);k.length<T;)k=" "+k;return k};console.info(`%c⏱ ${S(w,5)} /${S(_,5)} ms`,`
719
719
  font-size: .6rem;
720
720
  font-weight: bold;
721
721
  color: hsl(${Math.max(0,Math.min(120-120*x,120))}deg 100% 31%);`,n==null?void 0:n.key)}return n!=null&&n.onChange&&!(s&&n.skipInitialOnChange)&&n.onChange(i),s=!1,i}return o.updateDeps=l=>{r=l},o}function CL(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const m1e=(e,t)=>Math.abs(e-t)<1.01,g1e=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},kL=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},v1e=e=>e,y1e=e=>{const t=Math.max(e.startIndex-e.overscan,0),n=Math.min(e.endIndex+e.overscan,e.count-1),r=[];for(let i=t;i<=n;i++)r.push(i);return r},b1e=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;const i=o=>{const{width:l,height:u}=o;t({width:Math.round(l),height:Math.round(u)})};if(i(kL(n)),!r.ResizeObserver)return()=>{};const s=new r.ResizeObserver(o=>{const l=()=>{const u=o[0];if(u!=null&&u.borderBoxSize){const d=u.borderBoxSize[0];if(d){i({width:d.inlineSize,height:d.blockSize});return}}i(kL(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return s.observe(n,{box:"border-box"}),()=>{s.unobserve(n)}},TL={passive:!0},RL=typeof window>"u"?!0:"onscrollend"in window,_1e=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let i=0;const s=e.options.useScrollendEvent&&RL?()=>{}:g1e(r,()=>{t(i,!1)},e.options.isScrollingResetDelay),o=f=>()=>{const{horizontal:p,isRtl:y}=e.options;i=p?n.scrollLeft*(y&&-1||1):n.scrollTop,s(),t(i,f)},l=o(!0),u=o(!1);n.addEventListener("scroll",l,TL);const d=e.options.useScrollendEvent&&RL;return d&&n.addEventListener("scrollend",u,TL),()=>{n.removeEventListener("scroll",l),d&&n.removeEventListener("scrollend",u)}},w1e=(e,t,n)=>{if(t!=null&&t.borderBoxSize){const r=t.borderBoxSize[0];if(r)return Math.round(r[n.options.horizontal?"inlineSize":"blockSize"])}return e[n.options.horizontal?"offsetWidth":"offsetHeight"]},x1e=(e,{adjustments:t=0,behavior:n},r)=>{var i,s;const o=e+t;(s=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||s.call(i,{[r.options.horizontal?"left":"top"]:o,behavior:n})};class S1e{constructor(t){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var n,r,i;return((i=(r=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let n=null;const r=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(i=>{i.forEach(s=>{const o=()=>{const l=s.target,u=this.indexFromElement(l);if(!l.isConnected){this.observer.unobserve(l);return}this.shouldMeasureDuringScroll(u)&&this.resizeItem(u,this.options.measureElement(l,s,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),n=null},observe:i=>{var s;return(s=r())==null?void 0:s.observe(i,{box:"border-box"})},unobserve:i=>{var s;return(s=r())==null?void 0:s.unobserve(i)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([r,i])=>{typeof i>"u"&&delete n[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:v1e,rangeExtractor:y1e,onChange:()=>{},measureElement:w1e,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",...n}},this.notify=n=>{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,n)},this.maybeNotify=dd(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(n=>n()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var n;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.window)??null,this.elementsCache.forEach(i=>{this.observer.observe(i)}),this.unsubs.push(this.options.observeElementRect(this,i=>{this.scrollRect=i,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(i,s)=>{this.scrollAdjustments=0,this.scrollDirection=s?this.getScrollOffset()<i?"forward":"backward":null,this.scrollOffset=i,this.isScrolling=s,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(n,r)=>{const i=new Map,s=new Map;for(let o=r-1;o>=0;o--){const l=n[o];if(i.has(l.lane))continue;const u=s.get(l.lane);if(u==null||l.end>u.end?s.set(l.lane,l):l.end<u.end&&i.set(l.lane,!0),i.size===this.options.lanes)break}return s.size===this.options.lanes?Array.from(s.values()).sort((o,l)=>o.end===l.end?o.index-l.index:o.end-l.end)[0]:void 0},this.getMeasurementOptions=dd(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(n,r,i,s,o,l,u)=>(this.prevLanes!==void 0&&this.prevLanes!==l&&(this.lanesChangedFlag=!0),this.prevLanes=l,this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:r,scrollMargin:i,getItemKey:s,enabled:o,lanes:l,laneAssignmentMode:u}),{key:!1}),this.getMeasurements=dd(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:r,scrollMargin:i,getItemKey:s,enabled:o,lanes:l,laneAssignmentMode:u},d)=>{if(!o)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const g of this.laneAssignments.keys())g>=n&&this.laneAssignments.delete(g);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(g=>{this.itemSizeCache.set(g.key,g.size)}));const f=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1);const p=this.measurementsCache.slice(0,f),y=new Array(l).fill(void 0);for(let g=0;g<f;g++){const _=p[g];_&&(y[_.lane]=g)}for(let g=f;g<n;g++){const _=s(g),w=this.laneAssignments.get(g);let x,S;const k=u==="estimate"||d.has(_);if(w!==void 0&&this.options.lanes>1){x=w;const R=y[x],M=R!==void 0?p[R]:void 0;S=M?M.end+this.options.gap:r+i}else{const R=this.options.lanes===1?p[g-1]:this.getFurthestMeasurement(p,g);S=R?R.end+this.options.gap:r+i,x=R?R.lane:g%this.options.lanes,this.options.lanes>1&&k&&this.laneAssignments.set(g,x)}const T=d.get(_),N=typeof T=="number"?T:this.options.estimateSize(g),P=S+N;p[g]={index:g,start:S,size:N,end:P,key:_,lane:x},y[x]=g}return this.measurementsCache=p,p},{key:!1,debug:()=>this.options.debug}),this.calculateRange=dd(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,s)=>this.range=n.length>0&&r>0?E1e({measurements:n,outerSize:r,scrollOffset:i,lanes:s}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=dd(()=>{let n=null,r=null;const i=this.calculateRange();return i&&(n=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,r]},(n,r,i,s,o)=>s===null||o===null?[]:n({startIndex:s,endIndex:o,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const r=this.options.indexAttribute,i=n.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const s=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),o=Math.max(0,i-s),l=Math.min(this.options.count-1,i+s);return n>=o&&n<=l}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((o,l)=>{o.isConnected||(this.observer.unobserve(o),this.elementsCache.delete(l))});return}const r=this.indexFromElement(n),i=this.options.getItemKey(r),s=this.elementsCache.get(i);s!==n&&(s&&this.observer.unobserve(s),this.observer.observe(n),this.elementsCache.set(i,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,r)=>{var i;const s=this.measurementsCache[n];if(!s)return;const o=this.itemSizeCache.get(s.key)??s.size,l=r-o;l!==0&&(((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(s,l,this):s.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=l,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(s.index),this.itemSizeCache=new Map(this.itemSizeCache.set(s.key,r)),this.notify(!1))},this.getVirtualItems=dd(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,r)=>{const i=[];for(let s=0,o=n.length;s<o;s++){const l=n[s],u=r[l];i.push(u)}return i},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const r=this.getMeasurements();if(r.length!==0)return CL(r[V6(0,r.length-1,i=>CL(r[i]).start,n)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(n,r,i=0)=>{if(!this.scrollElement)return 0;const s=this.getSize(),o=this.getScrollOffset();r==="auto"&&(r=n>=o+s?"end":"start"),r==="center"?n+=(i-s)/2:r==="end"&&(n-=s);const l=this.getMaxScrollOffset();return Math.max(Math.min(l,n),0)},this.getOffsetForIndex=(n,r="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const i=this.getSize(),s=this.getScrollOffset(),o=this.measurementsCache[n];if(!o)return;if(r==="auto")if(o.end>=s+i-this.options.scrollPaddingEnd)r="end";else if(o.start<=s+this.options.scrollPaddingStart)r="start";else return[s,r];if(r==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),r];const l=r==="end"?o.end+this.options.scrollPaddingEnd:o.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(l,r,o.size),r]},this.scrollToOffset=(n,{align:r="start",behavior:i="auto"}={})=>{const s=this.getOffsetForAlignment(n,r),o=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:o,lastTargetOffset:s,stableFrames:0},this._scrollToOffset(s,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:r="auto",behavior:i="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const s=this.getOffsetForIndex(n,r);if(!s)return;const[o,l]=s,u=this.now();this.scrollState={index:n,align:l,behavior:i,startedAt:u,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+n,s=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:s,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var n;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1)i=((n=r[r.length-1])==null?void 0:n.end)??0;else{const s=Array(this.options.lanes).fill(null);let o=r.length-1;for(;o>=0&&s.some(l=>l===null);){const l=r[o];s[l.lane]===null&&(s[l.lane]=l.end),o--}i=Math.max(...s.filter(l=>l!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(n,{adjustments:r,behavior:i})=>{this.options.scrollToFn(n,{behavior:i,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(t)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,s=1,o=i!==this.scrollState.lastTargetOffset;if(!o&&m1e(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=s){this.scrollState=null;return}}else this.scrollState.stableFrames=0,o&&(this.scrollState.lastTargetOffset=i,this.scrollState.behavior="auto",this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const V6=(e,t,n,r)=>{for(;e<=t;){const i=(e+t)/2|0,s=n(i);if(s<r)e=i+1;else if(s>r)t=i-1;else return i}return e>0?e-1:0};function E1e({measurements:e,outerSize:t,scrollOffset:n,lanes:r}){const i=e.length-1,s=u=>e[u].start;if(e.length<=r)return{startIndex:0,endIndex:i};let o=V6(0,i,s,n),l=o;if(r===1)for(;l<i&&e[l].end<n+t;)l++;else if(r>1){const u=Array(r).fill(0);for(;l<i&&u.some(f=>f<n+t);){const f=e[l];u[f.lane]=f.end,l++}const d=Array(r).fill(n+t);for(;o>=0&&d.some(f=>f>=n);){const f=e[o];d[f.lane]=f.start,o--}o=Math.max(0,o-o%r),l=Math.min(i,l+(r-1-l%r))}return{startIndex:o,endIndex:l}}const AL=typeof document<"u"?b.useLayoutEffect:b.useEffect;function C1e({useFlushSync:e=!0,...t}){const n=b.useReducer(()=>({}),{})[1],r={...t,onChange:(s,o)=>{var l;e&&o?cu.flushSync(n):n(),(l=t.onChange)==null||l.call(t,s,o)}},[i]=b.useState(()=>new S1e(r));return i.setOptions(r),AL(()=>i._didMount(),[]),AL(()=>i._willUpdate()),i}function k1e(e){return C1e({observeElementRect:b1e,observeElementOffset:_1e,scrollToFn:x1e,...e})}function T1e(e){var n;const t=[];for(const r of e.matchAll(new RegExp("(?<!\\S)@(.+?)(?=\\s+@|\\s*$)","gu"))){const i=r[1]??"",s=r.index??-1;if(s<0||!i)continue;const o=Xk(i)?"image":Jk(i,{allowBare:!0})?"file":null;o&&t.push({kind:o,path:i,start:s,end:s+(((n=r[0])==null?void 0:n.length)??0)})}return t}function R1e(e){const t=T1e(e),n=[];let r=e.trimEnd().length;for(let i=t.length-1;i>=0;i-=1){const s=t[i];if(s){if(!/^\s*$/u.test(e.slice(s.end,r))||e[s.start]!=="@")break;n.unshift({kind:s.kind,path:s.path}),r=s.start}}return n.length===0?{bodyText:e,attachments:[]}:{bodyText:e.slice(0,r).trimEnd(),attachments:n}}function A1e(e){return e.kind==="diff"}const N1e=12e4;function NL(e){return e?e.replace(/\r\n?/gu,`
@@ -840,4 +840,4 @@ fn main() {
840
840
  ---
841
841
 
842
842
  _End of sample._
843
- `;function yOe(){return m.jsx("div",{className:"min-h-dvh bg-background text-foreground p-6",children:m.jsxs("div",{className:"mx-auto max-w-[720px] space-y-6",children:[m.jsxs("header",{children:[m.jsx("h1",{className:"text-lg font-semibold",children:"Markdown 渲染走查"}),m.jsx("p",{className:"text-sm text-muted-foreground",children:"下方模拟 assistant 气泡容器 (max-w 约束), 验证所有 markdown 元素在气泡内的实际渲染。"})]}),m.jsx("article",{className:"flex justify-start",children:m.jsx("div",{className:"max-w-[80%] rounded-md bg-card text-foreground px-4 py-2 text-sm",children:m.jsx(BE,{text:vOe})})})]})})}function UU(e){if([e.left,e.top,e.width,e.height,e.frameWidth,e.frameHeight].some(l=>!Number.isFinite(l))||e.width<=0||e.height<=0||e.frameWidth<=0||e.frameHeight<=0)return null;const n=Math.min(e.width/e.frameWidth,e.height/e.frameHeight),r=e.frameWidth*n,i=e.frameHeight*n,s=e.left+(e.width-r)/2,o=e.top+(e.height-i)/2;return{left:s,top:o,right:s+r,bottom:o+i,width:r,height:i}}function WU(e,t,n){return{x:Math.min(1,Math.max(0,(e-n.left)/n.width)),y:Math.min(1,Math.max(0,(t-n.top)/n.height))}}function bOe(e,t,n){if(!Number.isFinite(e)||!Number.isFinite(t))return null;const r=UU(n);return!r||e<r.left||e>r.right||t<r.top||t>r.bottom?null:WU(e,t,r)}function _Oe(e,t,n){if(!Number.isFinite(e)||!Number.isFinite(t))return null;const r=UU(n);return r?WU(e,t,r):null}async function wOe(e){const t=e.slice();return createImageBitmap(new Blob([t.buffer],{type:"image/jpeg"}))}class xOe{constructor(t,n,r=wOe){je(this,"latest",null);je(this,"painting",!1);je(this,"disposed",!1);je(this,"generation",0);je(this,"lastSequence",-1);je(this,"sizeReportedGeneration",-1);this.canvas=t,this.onSize=n,this.decoder=r}enqueue(t,n){var r;this.disposed||t<=this.lastSequence||((r=this.latest)==null?void 0:r.generation)===this.generation&&t<=this.latest.sequence||(this.latest={generation:this.generation,sequence:t,jpeg:n.slice()},this.painting||this.paintLoop())}reset(t=!1){var n;this.disposed||(this.generation+=1,this.latest=null,this.lastSequence=-1,t&&((n=this.canvas.getContext("2d",{alpha:!1}))==null||n.clearRect(0,0,this.canvas.width,this.canvas.height)))}dispose(){this.disposed=!0,this.generation+=1,this.latest=null}async paintLoop(){var t;this.painting=!0;try{for(;!this.disposed&&this.latest;){const n=this.latest;this.latest=null;let r;try{r=await this.decoder(n.jpeg)}catch(i){!this.disposed&&n.generation===this.generation&&console.warn("Failed to decode device preview frame",i);continue}try{if(this.disposed||n.generation!==this.generation||n.sequence<=this.lastSequence)continue;const i=this.canvas.width!==r.width||this.canvas.height!==r.height;i&&(this.canvas.width=r.width,this.canvas.height=r.height),(i||this.sizeReportedGeneration!==n.generation)&&(this.sizeReportedGeneration=n.generation,this.onSize({width:r.width,height:r.height})),(t=this.canvas.getContext("2d",{alpha:!1}))==null||t.drawImage(r,0,0),this.lastSequence=n.sequence}finally{r.close()}}}finally{this.painting=!1,!this.disposed&&this.latest&&this.paintLoop()}}}const SOe=120,EOe=8*1024*1024,COe=1e3/30,kOe=.15,TOe=100,ROe=.001;function AOe(e,t){if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n+=1)if(e[n]!==t[n])return!1;return!0}function Lc(e,t){if(e instanceof Error)return e;if(typeof e=="string"&&e.length>0)return new Error(e);if(e&&typeof e=="object"){const n=e,r=[n.name,n.message,n.error].filter(i=>typeof i=="string"&&i.length>0).join(": ");if(r.length>0)return new Error(r)}return new Error(t)}function NOe(e){const t=e.error;if(!t)return new Error("H.264 video playback failed");const n=t.message||`media error ${t.code}`;return new Error(`H.264 video playback failed: ${n}`)}class MOe{constructor(t,n={}){je(this,"muxer",null);je(this,"initialSources");je(this,"initialVideoState");je(this,"configuration",null);je(this,"configurationApplied",!1);je(this,"muxerReady",!1);je(this,"awaitingKeyframe",!0);je(this,"pendingFrames",[]);je(this,"fedFramesAwaitingPlayback",[]);je(this,"bufferedPacketCount",0);je(this,"bufferedBytes",0);je(this,"maxBufferedPackets");je(this,"maxBufferedBytes");je(this,"lastObservedMediaTime",null);je(this,"resyncRequired",!1);je(this,"playPending",!1);je(this,"playRequested",!1);je(this,"started",!1);je(this,"destroyed",!1);je(this,"generation",0);je(this,"playbackDelayTimer",null);je(this,"handlePlaying",()=>{this.destroyed||(this.observePlaybackProgress(),this.playRequested=!0,this.markStarted())});je(this,"handleTimeUpdate",()=>{this.observePlaybackProgress()});je(this,"handleVideoError",()=>{this.destroyed||this.reportError(NOe(this.video))});this.video=t,this.options=n,this.maxBufferedPackets=rB(n.maxBufferedPackets,SOe),this.maxBufferedBytes=rB(n.maxBufferedBytes,EOe),this.initialSources=new Set(t.querySelectorAll("source")),this.initialVideoState={autoplay:t.autoplay,disableRemotePlayback:t.disableRemotePlayback,muted:t.muted,playsInline:t.playsInline,src:t.getAttribute("src"),srcObject:t.srcObject},t.srcObject=null,t.muted=!0,t.autoplay=!0,t.playsInline=!0,t.disableRemotePlayback=!0,t.addEventListener("playing",this.handlePlaying),t.addEventListener("error",this.handleVideoError),t.addEventListener("timeupdate",this.handleTimeUpdate);const r={node:t,mode:"video",flushingTime:0,maxDelay:150,clearBuffer:!0,onReady:()=>this.handleMuxerReady(),onError:i=>this.handleMuxerError(i),onUnsupportedCodec:i=>{this.reportError(new Error(`Browser does not support the H.264 codec ${i}`))}};this.initializeMuxer(r)}feed(t){if(!(this.destroyed||t.data.byteLength===0)){if(this.observePlaybackProgress(),t.kind==="configuration"){this.feedConfiguration(t.data);return}this.feedFrame(t)}}destroy(){var n;if(this.destroyed)return;this.destroyed=!0,this.generation+=1,this.clearBufferedGeneration(),this.video.removeEventListener("playing",this.handlePlaying),this.video.removeEventListener("error",this.handleVideoError),this.video.removeEventListener("timeupdate",this.handleTimeUpdate),this.stopPlaybackDelayChecks();const t=this.generatedObjectUrls();try{(n=this.muxer)==null||n.destroy()}catch{}this.muxer=null;try{this.video.pause()}catch{}this.removeGeneratedSources(),this.video.removeAttribute("src"),this.initialVideoState.src!==null&&this.video.setAttribute("src",this.initialVideoState.src),this.video.srcObject=this.initialVideoState.srcObject,this.video.autoplay=this.initialVideoState.autoplay,this.video.disableRemotePlayback=this.initialVideoState.disableRemotePlayback,this.video.muted=this.initialVideoState.muted,this.video.playsInline=this.initialVideoState.playsInline;for(const r of t)this.revokeObjectUrl(r);try{this.video.load()}catch{}}async initializeMuxer(t){try{const{default:n}=await H6(async()=>{const{default:r}=await import("./jmuxer.min-BcaOPF7j.js").then(i=>i.j);return{default:r}},__vite__mapDeps([0,1]));if(this.destroyed)return;this.muxer=new n(t)}catch(n){if(this.destroyed)return;this.reportError(Lc(n,"Failed to initialize H.264 video playback")),this.destroy()}}feedConfiguration(t){if(this.configuration&&AOe(this.configuration,t))return;const n=this.configuration!==null&&this.configurationApplied;if(this.clearBufferedGeneration(),this.wouldOverflow(t.byteLength)){this.requireResync();return}if(this.configuration=t.slice(),this.addBufferedPacket(t.byteLength),this.awaitingKeyframe=!0,n){this.resetMuxer();return}this.applyConfigurationIfReady()}feedFrame(t){if(!this.configuration)return;if(this.awaitingKeyframe){if(!t.keyframe)return;this.awaitingKeyframe=!1,this.resyncRequired=!1}const n={data:t.data.slice(),durationMs:Number.isFinite(t.durationMs)&&t.durationMs>0?t.durationMs:COe,keyframe:t.keyframe};if(n.keyframe&&this.clearPendingFrames(),this.wouldOverflow(n.data.byteLength)){this.requireResync();return}if(this.addBufferedPacket(n.data.byteLength),!this.muxerReady||!this.configurationApplied){this.pendingFrames.push(n);return}this.applyFrame(n)||this.removeBufferedPacket(n.data.byteLength)}resetMuxer(){var r;const t=this.generatedSources(),n=this.generatedObjectUrls();this.generation+=1,this.muxerReady=!1,this.configurationApplied=!1,this.awaitingKeyframe=!0,this.playPending=!1,this.playRequested=!1,this.stopPlaybackDelayChecks();try{(r=this.muxer)==null||r.reset()}catch(i){this.reportError(Lc(i,"Failed to reset H.264 video playback"))}for(const i of t)i.remove();for(const i of n)this.revokeObjectUrl(i)}handleMuxerReady(){this.destroyed||(this.muxerReady=!0,this.startPlaybackDelayChecks(),this.applyConfigurationIfReady(),this.flushPendingFrames())}startPlaybackDelayChecks(){this.playbackDelayTimer===null&&(this.playbackDelayTimer=setInterval(()=>{this.catchUpToLiveEdge()},TOe))}stopPlaybackDelayChecks(){this.playbackDelayTimer!==null&&(clearInterval(this.playbackDelayTimer),this.playbackDelayTimer=null)}catchUpToLiveEdge(){if(this.destroyed||this.video.seeking)return;const t=this.video.buffered;if(t.length!==0)try{const n=t.end(t.length-1),r=this.video.currentTime;if(!Number.isFinite(n)||!Number.isFinite(r)||n-r<=kOe)return;this.video.currentTime=Math.max(0,n-ROe),this.observePlaybackProgress()}catch{}}applyConfigurationIfReady(){if(!(this.destroyed||!this.muxerReady||this.configurationApplied||!this.configuration||!this.muxer))try{this.muxer.feed({video:this.configuration,duration:0,isLastVideoFrameComplete:!0}),this.configurationApplied=!0,this.flushPendingFrames()}catch(t){this.reportError(Lc(t,"Failed to apply H.264 decoder configuration"))}}applyFrame(t){if(this.destroyed||!this.muxer)return!1;try{return this.muxer.feed({video:t.data,duration:t.durationMs,isLastVideoFrameComplete:!0}),this.fedFramesAwaitingPlayback.push({byteLength:t.data.byteLength,remainingDurationMs:t.durationMs}),this.attemptPlayback(),!0}catch(n){return this.reportError(Lc(n,"Failed to feed an H.264 video frame")),!1}}flushPendingFrames(){if(this.destroyed||!this.muxerReady||!this.configurationApplied||!this.muxer)return;this.observePlaybackProgress();const t=this.pendingFrames;this.pendingFrames=[];for(const n of t){if(this.destroyed)return;this.applyFrame(n)||this.removeBufferedPacket(n.data.byteLength)}}attemptPlayback(){if(this.destroyed||this.playPending||this.playRequested)return;this.playPending=!0,this.playRequested=!0;const t=this.generation;let n;try{n=this.video.play()}catch(r){this.playPending=!1,this.playRequested=!1,this.reportError(Lc(r,"Browser blocked H.264 video playback"));return}n.then(()=>{this.destroyed||t!==this.generation||(this.playPending=!1,this.markStarted())},r=>{this.destroyed||t!==this.generation||(this.playPending=!1,this.playRequested=!1,this.reportError(Lc(r,"Browser blocked H.264 video playback")))})}handleMuxerError(t){this.destroyed||(t.name==="InvalidStateError"&&(this.generation+=1,this.muxerReady=!1,this.configurationApplied=!1,this.awaitingKeyframe=!0,this.clearBufferedGeneration(),this.playPending=!1,this.playRequested=!1,this.stopPlaybackDelayChecks()),this.reportError(Lc(t,"H.264 video buffer failed")))}markStarted(){var t,n;this.started||(this.started=!0,(n=(t=this.options).onStart)==null||n.call(t))}reportError(t){var n,r;this.destroyed||(r=(n=this.options).onError)==null||r.call(n,t)}observePlaybackProgress(){const t=this.video.currentTime;if(!Number.isFinite(t)||t<0)return;if(this.lastObservedMediaTime===null||t<this.lastObservedMediaTime){this.lastObservedMediaTime=t;return}let n=(t-this.lastObservedMediaTime)*1e3;if(this.lastObservedMediaTime=t,!(n<=0))for(;n>0;){const r=this.fedFramesAwaitingPlayback[0];if(!r)return;if(n+Number.EPSILON<r.remainingDurationMs){r.remainingDurationMs-=n;return}n-=r.remainingDurationMs,this.fedFramesAwaitingPlayback.shift(),this.removeBufferedPacket(r.byteLength)}}wouldOverflow(t){return this.bufferedPacketCount+1>this.maxBufferedPackets||this.bufferedBytes+t>this.maxBufferedBytes}addBufferedPacket(t){this.bufferedPacketCount+=1,this.bufferedBytes+=t}removeBufferedPacket(t){this.bufferedPacketCount=Math.max(0,this.bufferedPacketCount-1),this.bufferedBytes=Math.max(0,this.bufferedBytes-t)}clearPendingFrames(){for(const t of this.pendingFrames)this.removeBufferedPacket(t.data.byteLength);this.pendingFrames=[]}clearBufferedGeneration(){this.pendingFrames=[],this.fedFramesAwaitingPlayback=[],this.configuration=null,this.configurationApplied=!1,this.bufferedPacketCount=0,this.bufferedBytes=0,this.lastObservedMediaTime=null}requireResync(){var n,r;const t=!this.resyncRequired;this.resyncRequired=!0,this.clearBufferedGeneration(),this.awaitingKeyframe=!0,this.resetMuxer(),t&&!this.destroyed&&((r=(n=this.options).onResyncRequired)==null||r.call(n,new Error("H.264 playback buffer overflowed; reconnecting for a fresh keyframe")))}generatedSources(){return Array.from(this.video.querySelectorAll("source")).filter(t=>!this.initialSources.has(t))}removeGeneratedSources(){for(const t of this.generatedSources())t.remove()}generatedObjectUrls(){const t=new Set,n=this.video.getAttribute("src");n!==this.initialVideoState.src&&(n!=null&&n.startsWith("blob:"))&&t.add(n);for(const r of this.generatedSources()){const i=r.getAttribute("src");i!=null&&i.startsWith("blob:")&&t.add(i)}return[...t]}revokeObjectUrl(t){if(typeof URL.revokeObjectURL=="function")try{URL.revokeObjectURL(t)}catch{}}}function rB(e,t){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:t}class POe{constructor(){je(this,"buffer",new Uint8Array(0))}push(t){if(t.byteLength===0)return[];const n=new Uint8Array(this.buffer.byteLength+t.byteLength);n.set(this.buffer),n.set(t,this.buffer.byteLength),this.buffer=n;const r=[];let i=0;for(;this.buffer.byteLength-i>=_h;){const s=new DataView(this.buffer.buffer,this.buffer.byteOffset+i,_h),o=s.getUint32(0,!0),l=s.getUint32(4,!0);if(o===0||o>vy)throw this.buffer=new Uint8Array(0),new RangeError(`Invalid device preview frame length: ${o}`);const u=_h+o;if(this.buffer.byteLength-i<u)break;r.push({sequence:l,jpeg:this.buffer.slice(i+_h,i+u)}),i+=u}if(i>0&&(this.buffer=this.buffer.slice(i)),this.buffer.byteLength>_h+vy)throw this.buffer=new Uint8Array(0),new RangeError("Device preview stream buffer exceeded its limit");return r}finish(){if(this.buffer.byteLength!==0)throw this.buffer=new Uint8Array(0),new Error("Device preview stream ended with a truncated frame")}}class IOe{constructor(){je(this,"buffer",new Uint8Array(0))}push(t){if(t.byteLength===0)return[];const n=new Uint8Array(this.buffer.byteLength+t.byteLength);n.set(this.buffer),n.set(t,this.buffer.byteLength),this.buffer=n;const r=[];let i=0;for(;this.buffer.byteLength-i>=Yh;){const s=this.buffer.subarray(i),o=Gte(s);if(!o)throw this.buffer=new Uint8Array(0),new RangeError("Invalid H.264 device preview packet header");const l=Yh+o.annexBLength;if(this.buffer.byteLength-i<l)break;r.push({sequence:o.packetSequence,kind:o.configuration?"configuration":"frame",keyframe:o.keyframe,durationMs:o.durationMs,data:this.buffer.slice(i+Yh,i+l)}),i+=l}if(i>0&&(this.buffer=this.buffer.slice(i)),this.buffer.byteLength>Yh+vy)throw this.buffer=new Uint8Array(0),new RangeError("H.264 device preview stream buffer exceeded its limit");return r}finish(){if(this.buffer.byteLength!==0)throw this.buffer=new Uint8Array(0),new Error("H.264 device preview stream ended with a truncated packet")}}function OOe(e){let t;try{t=new URL(e,globalThis.location.href)}catch{throw new Error("无效的模拟器画面地址")}if(t.origin!==globalThis.location.origin||t.username!==""||t.password!==""||!/^\/api\/device-preview-streams\/[A-Za-z0-9_-]{1,256}$/u.test(t.pathname)||t.search!==""||t.hash!=="")throw new Error("拒绝连接不受信任的模拟器画面地址")}function LOe(e){const t=Number(e.headers.get("X-Device-Width")),n=Number(e.headers.get("X-Device-Height"));return!Number.isSafeInteger(t)||t<=0||!Number.isSafeInteger(n)||n<=0?null:{width:t,height:n}}async function qU(e,t,n){OOe(e);const r=ob(),i=await n(e,{method:"GET",cache:"no-store",credentials:"same-origin",...r?{headers:{Authorization:`Bearer ${r}`}}:{},signal:t});if(!i.ok||!i.body)throw new Error(`无法打开模拟器画面(${i.status})`);return i}async function DOe(e,t){const n=t.fetch??globalThis.fetch,r=await qU(e,t.signal,n);if(r.headers.get("X-Device-Preview-Format")!=="jpeg")throw new Error("开发机返回了错误的模拟器画面格式");const i=new POe,s=r.body.getReader();try{for(;;){const{done:o,value:l}=await s.read();if(o)break;const d=i.push(l).at(-1);d&&await t.onFrame(d)}i.finish()}finally{s.releaseLock()}}async function BOe(e,t){var l;const n=t.fetch??globalThis.fetch,r=await qU(e,t.signal,n);if(r.headers.get("X-Device-Preview-Format")!=="h264_annex_b")throw new Error("开发机没有返回 H.264 模拟器画面");const i=LOe(r);i&&((l=t.onSize)==null||l.call(t,i));const s=new IOe,o=r.body.getReader();try{for(;;){const{done:u,value:d}=await o.read();if(u)break;for(const f of s.push(d))await t.onPacket(f)}s.finish()}finally{o.releaseLock()}}const zOe=16,jOe=16;class FOe{constructor(t){je(this,"send");je(this,"onFailure");je(this,"now");je(this,"moveFlushMs");je(this,"maxInFlightMoves");je(this,"active",null);je(this,"inFlightMoves",0);je(this,"disposed",!1);je(this,"failed",!1);this.send=t.send,this.onFailure=t.onFailure,this.now=t.now??(()=>performance.now()),this.moveFlushMs=t.moveFlushMs??zOe,this.maxInFlightMoves=t.maxInFlightMoves??jOe}begin(t,n){if(this.disposed||this.failed||this.active)return!1;const r={pointerId:t,lastPoint:n,lastMoveAt:Number.NEGATIVE_INFINITY,pendingMove:null,moveFlushTimer:null};return this.active=r,this.dispatch(this.input("down",n)),!0}move(t,n){const r=this.matchingActive(t);if(!r)return!1;r.lastPoint=n,r.pendingMove=n;const i=this.now(),s=this.moveFlushMs-(i-r.lastMoveAt);return s>0?(r.moveFlushTimer===null&&(r.moveFlushTimer=setTimeout(()=>{r.moveFlushTimer=null,!(this.active!==r||this.disposed||this.failed)&&(r.lastMoveAt=this.now(),this.flushLatestMove())},s)),!0):(this.clearMoveTimer(r),r.lastMoveAt=i,this.flushLatestMove(),!0)}end(t,n){const r=this.matchingActive(t);return r?(r.lastPoint=n,this.finish(r),this.dispatch(this.input("up",n)),!0):!1}cancel(t){const n=this.active;if(!n||t!==void 0&&n.pointerId!==t)return!1;const r=n.lastPoint;return this.finish(n),this.dispatch(this.input("up",r)),!0}dispose(){if(this.disposed)return;const t=this.active;if(t&&this.finish(t),this.disposed=!0,!(!t||this.failed))try{Promise.resolve(this.send(this.input("up",t.lastPoint))).catch(()=>{})}catch{}}matchingActive(t){var n;return this.disposed||this.failed||((n=this.active)==null?void 0:n.pointerId)!==t?null:this.active}finish(t){this.active===t&&(this.active=null),this.clearMoveTimer(t),t.pendingMove=null}clearMoveTimer(t){t.moveFlushTimer!==null&&clearTimeout(t.moveFlushTimer),t.moveFlushTimer=null}flushLatestMove(){const t=this.active;if(!t||this.disposed||this.failed||!t.pendingMove||t.moveFlushTimer!==null||this.inFlightMoves>=this.maxInFlightMoves)return;const n=t.pendingMove;t.pendingMove=null,this.inFlightMoves+=1,this.dispatch(this.input("move",n),()=>{this.inFlightMoves=Math.max(0,this.inFlightMoves-1),this.flushLatestMove()})}dispatch(t,n){let r;try{r=Promise.resolve(this.send(t))}catch(i){this.fail(i),n==null||n();return}r.then(()=>n==null?void 0:n(),i=>{this.fail(i),n==null||n()})}fail(t){if(this.disposed||this.failed)return;this.failed=!0;const n=this.active;n&&this.finish(n),this.onFailure(t)}input(t,n){return{kind:"touch",phase:t,x:n.x,y:n.y}}}const $Oe=15e3,HOe=1e4,UOe={ios:40,android:28},WOe={ios:{width:390,height:844},android:{width:412,height:915}};function qOe(){const{id:e=""}=FB(),t=ws(),n=gr(Oe=>Dj(Oe).find(ze=>ze.previewId===e)),r=gr(Oe=>Oe.listLoaded),i=gr(Oe=>{var ze;return((ze=Oe.authoritative)==null?void 0:ze.scope)??null}),s=qo(Oe=>_re(Oe,i,"device",e,"reconnect")),o=b.useRef(null),l=b.useRef(null),u=b.useRef(null),d=b.useRef(null),f=b.useRef(null),p=b.useRef(()=>{}),y=b.useRef(null),g=b.useRef(null),[_,w]=b.useState(0),[x,S]=b.useState("waiting"),[k,T]=b.useState(null),[N,P]=b.useState(null),[R,M]=b.useState(null),[L,X]=b.useState(""),[U,V]=b.useState(!1),[j,A]=b.useState(!1),[D,O]=b.useState(!1),I=n==null?void 0:n.previewId,B=n==null?void 0:n.state,F=n==null?void 0:n.platform,Y=b.useCallback(()=>{const Oe=f.current;f.current=null,Oe==null||Oe.dispose()},[]);b.useEffect(()=>{if(F!=="ios"){d.current=null,M(null);return}const Oe=o.current;if(!Oe)return;const ze=new xOe(Oe,M);return ze.reset(!0),M(null),d.current=ze,()=>{ze.dispose(),d.current=null}},[I,F]),b.useEffect(()=>{if(Y(),p.current=()=>{},y.current=null,g.current=null,P(null),A(!1),O(!1),!I||B!=="ready"){B==="disconnected"?(S("error"),T("模拟器已断开")):(S("waiting"),T(null));return}const Oe=Ft,ze=i;if(!Oe||!ze||!Tt.isActive(Oe,ze)){S("error"),T("开发机连接已断开");return}let et=!1,Ct=null,tt=null,Le=null,it=null,dt=null,be=0,Ve=!1;const ft=()=>{dt=null,Le==null||Le.abort(),Le=null,it==null||it.destroy(),it=null,Ct&&clearTimeout(Ct),Ct=null,tt&&clearTimeout(tt),tt=null},St=yt=>{S("streaming"),tt&&clearTimeout(tt),tt=setTimeout(()=>{tt=null,!(et||yt.signal.aborted||dt!==yt.leaseId||!Tt.isActive(Oe,ze))&&(be=0)},HOe)},wt=()=>{if(et||document.visibilityState==="hidden"||!Tt.isActive(Oe,ze))return;const yt=Math.min(5e3,500*2**be);be+=1,Ct=setTimeout(()=>void fn(),yt)},fn=async()=>{var Zt;if(Y(),ft(),et||document.visibilityState==="hidden"||!Tt.isActive(Oe,ze))return;Ve=!1,(Zt=d.current)==null||Zt.reset(),M(null),S("connecting"),T(null),P(null);const yt=new AbortController;Le=yt;try{const zt=await Tt.requestDevicePreviewStream(ze,I,F==="android"?{format:"h264_annex_b"}:{format:"jpeg",maxFps:15},{signal:yt.signal});if(et||yt.signal.aborted||!Tt.isActive(Oe,ze)||!zt)return;if(!zt.success)throw new Error(zt.error);const yn=zt;if(dt=yn.leaseId,P(yn),F==="android"){const Zn=l.current;if(!Zn)throw new Error("无法初始化 Android 模拟器播放器");let Jn;const gn=new Promise((ce,Te)=>{Jn=Te}),W=setTimeout(()=>{Jn(new Error("Android 模拟器画面启动超时"))},$Oe),ie=ce=>{Jn(ce instanceof Error?ce:new Error(String(ce)))},J=new MOe(Zn,{onStart:()=>{clearTimeout(W),!(et||yn.signal.aborted||!Tt.isActive(Oe,ze))&&St(yn)},onError:ie,onResyncRequired:ie});it=J;try{await Promise.race([BOe(yn.url,{signal:yn.signal,onSize:ce=>{!et&&!yn.signal.aborted&&Tt.isActive(Oe,ze)&&M(ce)},onPacket:ce=>{!et&&!yn.signal.aborted&&Tt.isActive(Oe,ze)&&J.feed(ce)}}),gn])}finally{clearTimeout(W)}if(!et&&!yn.signal.aborted&&Tt.isActive(Oe,ze))throw new Error("模拟器画面已断开");return}let $n=!1;if(await DOe(yn.url,{signal:yn.signal,onFrame:Zn=>{if(et||yn.signal.aborted||!Tt.isActive(Oe,ze))return;const Jn=d.current;Jn&&(Jn.enqueue(Zn.sequence,Zn.jpeg),$n||($n=!0,St(yn)))}}),!et&&!yn.signal.aborted&&Tt.isActive(Oe,ze))throw new Error("模拟器画面已断开")}catch(zt){if(et||yt.signal.aborted||!Tt.isActive(Oe,ze))return;Xt(zt,!1)}},Xt=(yt,Zt)=>{if(et||Ve||!Tt.isActive(Oe,ze))return;Ve=!0;const zt=yt instanceof Error?yt.message:"模拟器画面已断开";Y(),ft(),y.current=null,g.current=null,P(null),A(!1),O(!1),S("error"),T(zt),Zt&&We.error(zt),wt()},Jt=(yt,Zt,zt=!0)=>{yt===dt&&Xt(Zt,zt)};p.current=Jt;const xn=Oe.onMessage(yt=>{if(yt.type!=="device_preview_control_revoked_push"||!tn(yt.scope,ze)||yt.leaseId!==dt||!Tt.isActive(Oe,ze))return;if(g.current=null,O(!1),yt.reason==="taken_over"){y.current=null,A(!1),Y(),P(zt=>(zt==null?void 0:zt.leaseId)===yt.leaseId?{...zt,controlMode:"view_only"}:zt),We.info("控制权已由其他页面接管");return}const Zt=new Error(yt.reason==="proxy_offline"?"开发机连接已断开":yt.reason==="lease_expired"?"模拟器画面连接已过期":"模拟器画面已断开");Jt(yt.leaseId,Zt,!1)}),mn=()=>{if(document.visibilityState==="hidden"){Y(),ft(),y.current=null,g.current=null,P(null),A(!1),O(!1),S("waiting");return}be=0,fn()};return document.addEventListener("visibilitychange",mn),fn(),()=>{et=!0,p.current===Jt&&(p.current=()=>{}),xn(),document.removeEventListener("visibilitychange",mn),Y(),ft()}},[Y,I,F,i,B,_]),b.useEffect(()=>{var Oe;(Oe=f.current)==null||Oe.cancel()},[R==null?void 0:R.height,R==null?void 0:R.width]);const z=(n==null?void 0:n.state)==="ready"&&(N==null?void 0:N.previewId)===n.previewId&&i&&tn(N.scope,i)?N:null,q=(n==null?void 0:n.interactive)===!0&&x==="streaming"&&(z==null?void 0:z.controlMode)==="controller";b.useEffect(()=>{Y();const Oe=Ft,ze=z;if(!Oe||!ze||!q)return;const et=new FOe({send:async Ct=>{const tt=await Tt.sendDevicePreviewInput(ze,Ct);if(!tt)throw new Error("模拟器控制连接已失效");if(!tt.success)throw new Error(tt.error)},onFailure:Ct=>{f.current===et&&p.current(ze.leaseId,Ct)}});return f.current=et,()=>{f.current===et&&(f.current=null),et.dispose()}},[q,z,Y]);const K=R??WOe[(n==null?void 0:n.platform)==="android"?"android":"ios"],$=UOe[(n==null?void 0:n.platform)==="android"?"android":"ios"],re=K.width/K.height,Q=K.width>K.height?"landscape":"portrait",G=Q==="landscape"?`, ${K.width}px`:"",Z={aspectRatio:`${K.width} / ${K.height}`,width:`max(1px, min(calc(100cqw - ${$}px), calc(${(re*100).toFixed(6)}cqh - ${(re*$).toFixed(6)}px)${G}))`};b.useEffect(()=>{q||V(!1)},[q]);const ae=b.useCallback(async(Oe,ze=!0)=>{const et=Ft,Ct=z;if(!et||!Ct||!q)return!1;try{const tt=await Tt.sendDevicePreviewInput(Ct,Oe);return!tt||!Tt.isActive(et,Ct.scope)?!1:tt.success?!0:(ze&&We.error(tt.error),!1)}catch(tt){return Ct.signal.aborted||!Tt.isActive(et,Ct.scope)||ze&&We.error(tt instanceof Error?tt.message:"模拟器操作失败"),!1}},[q,z]);function le(Oe,ze){const et=u.current;if(!et||!R)return null;const Ct=et.getBoundingClientRect(),tt={left:Ct.left,top:Ct.top,width:Ct.width,height:Ct.height,frameWidth:R.width,frameHeight:R.height};return ze==="start"?bOe(Oe.clientX,Oe.clientY,tt):_Oe(Oe.clientX,Oe.clientY,tt)}function me(Oe){var Ct,tt;if(!q||Oe.button!==0)return;const ze=le(Oe,"start");if(!ze)return;const et=f.current;et!=null&&et.begin(Oe.pointerId,ze)&&(Oe.preventDefault(),(tt=(Ct=Oe.currentTarget).setPointerCapture)==null||tt.call(Ct,Oe.pointerId))}function ke(Oe){var et;const ze=le(Oe,"captured");ze&&(et=f.current)!=null&&et.move(Oe.pointerId,ze)&&Oe.preventDefault()}function $e(Oe){var et;const ze=le(Oe,"captured");ze&&((et=f.current)!=null&&et.end(Oe.pointerId,ze))&&Oe.preventDefault()}function he(Oe){var ze;(ze=f.current)==null||ze.cancel(Oe.pointerId)}async function He(){const Oe=Ft,ze=z;if(!Oe||!ze||D||x!=="streaming")return;const et=Symbol("device-preview-control-claim");g.current=et,O(!0);try{const Ct=await Tt.claimDevicePreviewControl(ze);if(g.current!==et||!Ct||!Tt.isActive(Oe,ze.scope))return;if(!Ct.success){We.error(Ct.error);return}P(tt=>(tt==null?void 0:tt.leaseId)===ze.leaseId?{...tt,controlMode:"controller"}:tt)}catch(Ct){if(g.current!==et||ze.signal.aborted||!Tt.isActive(Oe,ze.scope))return;We.error(Ct instanceof Error?Ct.message:"暂时无法取得控制权")}finally{g.current===et&&(g.current=null,O(!1))}}async function Nt(Oe){Oe.preventDefault();const ze=L;if(!ze||j)return;const et=Symbol("device-preview-text-input");y.current=et,A(!0);const Ct=await ae({kind:"text",text:ze});y.current===et&&(Ct&&(X(""),V(!1)),y.current=null,A(!1))}function ye(){var Oe;(Oe=f.current)==null||Oe.cancel(),ae({kind:"orientation",orientation:R&&R.width>R.height?"portrait":"landscape_right"})}async function Ze(){if((n==null?void 0:n.state)!=="disconnected"){w(et=>et+1);return}const Oe=Ft,ze=Tt.getActiveScope();if(!Oe||!ze){We.error("请先连接开发机");return}try{const et=await Tt.reconnectDevicePreview(ze,n.previewId);et.success||We.error(et.error)}catch(et){if(!Tt.isActive(Oe,ze))return;We.error(et instanceof Error?et.message:"无法重新连接模拟器预览")}}return n?m.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background","data-slot":"device-preview-page","data-preview-id":n.previewId,"data-stream-status":x,"data-control-mode":n.interactive?(z==null?void 0:z.controlMode)??"none":"unavailable",children:[m.jsxs("header",{className:"flex min-h-14 shrink-0 items-center gap-2 border-b px-3 md:px-4",children:[m.jsx(gt,{variant:"ghost",size:"icon",className:"md:hidden","aria-label":"返回",onClick:()=>t("/sessions"),children:m.jsx(Qp,{"aria-hidden":"true"})}),m.jsx(oC,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),m.jsxs("div",{className:"min-w-0 flex-1",children:[m.jsx("p",{className:"truncate text-sm font-medium",children:n.name}),m.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[n.model," · ",n.platform==="ios"?"iOS":"Android"," ",n.osVersion]})]}),n.interactive&&x==="streaming"&&(z==null?void 0:z.controlMode)==="view_only"?m.jsx(gt,{size:"sm",variant:"outline",disabled:D,onClick:()=>void He(),"data-slot":"device-preview-claim-control",children:"接管控制"}):m.jsx("span",{className:"text-xs text-muted-foreground",children:q?"可操控":x==="streaming"?"仅查看":"连接中"})]}),m.jsx("div",{className:"min-h-0 flex-1 overflow-hidden bg-muted/30",children:m.jsxs("div",{className:Ye("grid h-full min-h-0 min-w-0 gap-3 p-3 md:gap-4 md:p-6",Q==="portrait"?"grid-rows-[minmax(0,1fr)_auto] md:grid-cols-[minmax(0,1fr)_auto] md:grid-rows-1":"grid-rows-[minmax(0,1fr)_auto]"),"data-slot":"device-preview-stage","data-orientation":Q,children:[m.jsxs("div",{className:"relative flex min-h-0 min-w-0 items-center justify-center overflow-hidden [container-type:size]","data-slot":"device-preview-viewport",children:[m.jsxs("div",{className:Ye("relative isolate shrink-0 transition-[width,aspect-ratio] duration-300 ease-out motion-reduce:transition-none [container-type:size]",n.platform==="ios"?"[--device-screen-radius:clamp(22px,14cqmin,56px)] [--ios-rail:clamp(10px,4cqmin,16px)]":"[--device-screen-radius:clamp(14px,6.5cqw,38px)]"),style:Z,"data-slot":"device-preview-device-shell","data-platform":n.platform,"data-orientation":Q,children:[m.jsx(VOe,{platform:n.platform,orientation:Q}),m.jsx("div",{ref:u,className:Ye("relative z-10 flex h-full w-full min-h-0 min-w-0 items-center justify-center overflow-hidden rounded-[var(--device-screen-radius)] bg-black ring-1 ring-black",q&&"cursor-pointer"),"data-slot":"device-preview-surface","data-control-enabled":q?"true":"false",children:n.platform==="android"?m.jsx("video",{ref:l,className:"pointer-events-none h-full w-full object-contain","data-slot":"device-preview-video",muted:!0,autoPlay:!0,playsInline:!0,disableRemotePlayback:!0,onLoadedMetadata:Oe=>{const ze=Oe.currentTarget;ze.videoWidth>0&&ze.videoHeight>0&&M({width:ze.videoWidth,height:ze.videoHeight})},onResize:Oe=>{const ze=Oe.currentTarget;ze.videoWidth>0&&ze.videoHeight>0&&M({width:ze.videoWidth,height:ze.videoHeight})}}):m.jsx("canvas",{ref:o,className:"pointer-events-none h-full w-full object-contain","data-slot":"device-preview-canvas"})}),m.jsx("div",{className:Ye("absolute inset-0 z-20 select-none rounded-[var(--device-screen-radius)]",q?"touch-none cursor-pointer":"pointer-events-none"),onPointerDown:me,onPointerMove:ke,onPointerUp:$e,onPointerCancel:he,onLostPointerCapture:he,onContextMenu:Oe=>{q&&Oe.preventDefault()},"data-slot":"device-preview-input-surface","data-control-enabled":q?"true":"false","aria-hidden":"true"})]}),x!=="streaming"?m.jsx("div",{className:"absolute inset-0 z-30 flex items-center justify-center bg-background/55 p-6 backdrop-blur-[1px]","data-slot":"device-preview-stream-overlay","data-stream-status":x,children:m.jsx("div",{className:"grid max-w-sm justify-items-center gap-3 text-center",children:x==="error"?m.jsxs(m.Fragment,{children:[m.jsx("p",{className:"text-sm text-muted-foreground",children:k}),m.jsxs(gt,{variant:"outline",size:"sm",disabled:s,onClick:()=>void Ze(),"data-slot":"device-preview-retry",children:[s?m.jsx(ii,{className:"size-4 animate-spin","aria-hidden":!0}):null,s?"正在重新连接":"重新连接"]})]}):m.jsxs(m.Fragment,{children:[m.jsx(ii,{className:"size-5 animate-spin text-muted-foreground","aria-hidden":!0}),m.jsx("p",{className:"text-sm text-muted-foreground",children:"正在连接画面..."})]})})}):null]}),m.jsx("div",{className:"relative z-20 flex min-w-0 items-center justify-center pb-[max(0px,env(safe-area-inset-bottom))] md:pb-0","data-slot":"device-preview-control-dock","data-orientation":Q,role:"group","aria-label":"模拟器控制",children:m.jsxs("div",{className:Ye("flex max-w-full items-center gap-1 rounded-full border border-border/70 bg-card/85 p-1.5 shadow-xl ring-1 ring-black/5 backdrop-blur-xl",Q==="portrait"&&"md:flex-col"),children:[m.jsx(xS,{control:"home",label:"主屏幕",disabled:!q,icon:m.jsx(jV,{"aria-hidden":"true"}),tooltipSide:Q==="portrait"?"left":"top",onClick:()=>void ae({kind:"button",button:"home"})}),n.platform==="android"?m.jsx(xS,{control:"back",label:"返回",disabled:!q,icon:m.jsx(jY,{"aria-hidden":"true"}),tooltipSide:Q==="portrait"?"left":"top",onClick:()=>void ae({kind:"button",button:"back"})}):null,m.jsx(xS,{control:"orientation",label:"旋转",disabled:!q||!R,icon:m.jsx(yY,{"aria-hidden":"true"}),tooltipSide:Q==="portrait"?"left":"top",onClick:ye}),m.jsx("span",{className:Ye("mx-0.5 h-6 w-px shrink-0 bg-border/80",Q==="portrait"&&"md:mx-0 md:h-px md:w-6"),"aria-hidden":"true"}),m.jsxs(Rb,{open:U,onOpenChange:Oe=>{(!Oe||q)&&V(Oe)},children:[m.jsxs(hf,{children:[m.jsx(pf,{asChild:!0,children:m.jsx(Ab,{asChild:!0,children:m.jsx(gt,{type:"button",variant:"ghost",size:"icon",className:Ye("size-11 rounded-full text-muted-foreground hover:text-foreground",U&&"bg-accent text-foreground"),disabled:!q,"aria-label":"粘贴文字","aria-expanded":U,"aria-controls":"device-preview-text-form","data-slot":"device-preview-text-toggle",children:m.jsx(TS,{"aria-hidden":"true"})})})}),m.jsx(mf,{side:Q==="portrait"?"left":"top",sideOffset:10,hideArrow:!0,children:"粘贴文字"})]}),m.jsx(Nb,{side:Q==="portrait"?"left":"top",align:"center",sideOffset:12,className:"w-[min(20rem,calc(100vw-1.5rem))] rounded-2xl bg-card/95 p-2 shadow-2xl backdrop-blur-xl",children:m.jsxs("form",{id:"device-preview-text-form",className:"flex items-end gap-2","data-slot":"device-preview-text-form",onSubmit:Oe=>void Nt(Oe),children:[m.jsx("textarea",{value:L,onChange:Oe=>X(Oe.target.value),disabled:!q||j,maxLength:4096,rows:3,placeholder:"粘贴文字","aria-label":"粘贴文字","data-slot":"device-preview-text-input",className:"min-h-20 min-w-0 flex-1 resize-none rounded-xl border bg-background px-3 py-2 text-base outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50 md:text-sm"}),m.jsx(gt,{type:"submit",size:"icon",className:"size-10 rounded-xl",disabled:!q||!L||j,"aria-label":"粘贴","data-slot":"device-preview-send-text",children:j?m.jsx(ii,{className:"animate-spin","aria-hidden":"true"}):m.jsx(TS,{"aria-hidden":"true"})})]})})]})]})})]})})]}):m.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center",children:r?m.jsxs("div",{className:"grid gap-3",children:[m.jsx("p",{className:"text-sm text-muted-foreground",children:"无法找到该预览"}),m.jsx(gt,{variant:"outline",onClick:()=>t("/sessions"),children:"返回"})]}):m.jsx(ii,{className:"size-5 animate-spin text-muted-foreground","aria-label":"加载中"})})}function xS({control:e,label:t,icon:n,disabled:r,tooltipSide:i,onClick:s}){return m.jsxs(hf,{children:[m.jsx(pf,{asChild:!0,children:m.jsx(gt,{type:"button",variant:"ghost",size:"icon",className:"size-11 rounded-full text-muted-foreground hover:text-foreground","aria-label":t,disabled:r,onClick:s,"data-slot":"device-preview-control","data-control":e,children:n})}),m.jsx(mf,{side:i,sideOffset:10,hideArrow:!0,className:"border border-border/80 bg-card/95 px-2.5 py-1 text-muted-foreground shadow-sm backdrop-blur",children:t})]})}function VOe({platform:e,orientation:t}){const n=t==="portrait";return e==="ios"?m.jsxs("div",{"aria-hidden":"true","data-slot":"device-preview-device-chrome","data-platform":"ios","data-orientation":t,className:Ye("pointer-events-none absolute -inset-[var(--ios-rail)] z-0 select-none rounded-[calc(var(--device-screen-radius)+var(--ios-rail))] border border-black/85 bg-[#202024] ring-1 ring-black/30","shadow-[inset_1px_1px_0_rgba(255,255,255,0.16),inset_-1px_-1px_0_rgba(0,0,0,0.72)]"),children:[m.jsx("span",{className:"absolute inset-[2px] rounded-[calc(var(--device-screen-radius)+var(--ios-rail)-2px)] ring-1 ring-inset ring-white/[0.05]"}),n?m.jsxs(m.Fragment,{children:[m.jsx("span",{className:"absolute -left-[4px] top-[16%] h-[clamp(12px,4%,22px)] w-[4px] rounded-l-[3px] border border-r-0 border-black/70 bg-[#343439] shadow-[inset_1px_0_0_rgba(255,255,255,0.14)]"}),m.jsx("span",{className:"absolute -left-[4px] top-[23%] h-[clamp(24px,7%,42px)] w-[4px] rounded-l-[3px] border border-r-0 border-black/70 bg-[#343439] shadow-[inset_1px_0_0_rgba(255,255,255,0.14)]"}),m.jsx("span",{className:"absolute -left-[4px] top-[32%] h-[clamp(24px,7%,42px)] w-[4px] rounded-l-[3px] border border-r-0 border-black/70 bg-[#343439] shadow-[inset_1px_0_0_rgba(255,255,255,0.14)]"}),m.jsx("span",{className:"absolute -right-[4px] top-[28%] h-[clamp(36px,12%,64px)] w-[4px] rounded-r-[3px] border border-l-0 border-black/70 bg-[#343439] shadow-[inset_-1px_0_0_rgba(255,255,255,0.14)]"})]}):m.jsxs(m.Fragment,{children:[m.jsx("span",{className:"absolute -top-[4px] left-[16%] h-[4px] w-[clamp(12px,4%,22px)] rounded-t-[3px] border border-b-0 border-black/70 bg-[#343439] shadow-[inset_0_1px_0_rgba(255,255,255,0.14)]"}),m.jsx("span",{className:"absolute -top-[4px] left-[23%] h-[4px] w-[clamp(24px,7%,42px)] rounded-t-[3px] border border-b-0 border-black/70 bg-[#343439] shadow-[inset_0_1px_0_rgba(255,255,255,0.14)]"}),m.jsx("span",{className:"absolute -top-[4px] left-[32%] h-[4px] w-[clamp(24px,7%,42px)] rounded-t-[3px] border border-b-0 border-black/70 bg-[#343439] shadow-[inset_0_1px_0_rgba(255,255,255,0.14)]"}),m.jsx("span",{className:"absolute -bottom-[4px] left-[28%] h-[4px] w-[clamp(36px,12%,64px)] rounded-b-[3px] border border-t-0 border-black/70 bg-[#343439] shadow-[inset_0_-1px_0_rgba(255,255,255,0.14)]"})]})]}):m.jsxs("div",{"aria-hidden":"true","data-slot":"device-preview-device-chrome","data-platform":"android","data-orientation":t,className:Ye("pointer-events-none absolute -inset-[9px] z-0 select-none rounded-[calc(var(--device-screen-radius)+9px)] border border-black/70 bg-[linear-gradient(145deg,#68717a_0%,#22272d_22%,#08090b_58%,#454c55_100%)] ring-1 ring-white/15"),children:[m.jsx("span",{className:Ye("absolute rounded-full bg-white/25 shadow-sm",n?"left-1/2 top-[3px] h-px w-[14%] -translate-x-1/2":"left-[3px] top-1/2 h-[14%] w-px -translate-y-1/2")}),n?m.jsxs(m.Fragment,{children:[m.jsx("span",{className:"absolute -right-[4px] top-[20%] h-[14%] min-h-7 w-[3px] rounded-r-sm bg-slate-500 shadow-sm"}),m.jsx("span",{className:"absolute -right-[4px] top-[38%] h-[9%] min-h-4 w-[3px] rounded-r-sm bg-slate-400 shadow-sm"})]}):m.jsxs(m.Fragment,{children:[m.jsx("span",{className:"absolute -top-[4px] left-[20%] h-[3px] w-[14%] min-w-7 rounded-t-sm bg-slate-500 shadow-sm"}),m.jsx("span",{className:"absolute -top-[4px] left-[38%] h-[3px] w-[9%] min-w-4 rounded-t-sm bg-slate-400 shadow-sm"})]})]})}const zd=b7([{path:"/",element:m.jsx(ISe,{}),children:[{index:!0,element:m.jsx(OSe,{})},{path:"sessions",element:m.jsx(LSe,{})},{path:"chat/:id",element:m.jsx(sOe,{})},{path:"preview/device/:id",element:m.jsx(qOe,{})}]},{path:"/pty-test",element:m.jsx(uOe,{})},{path:"/tokens",element:m.jsx(gOe,{})},{path:"/markdown-test",element:m.jsx(yOe,{})}]);function YOe({browserName:e}){const[t,n]=b.useState("idle"),r=async()=>{const i=await Ap(window.location.href,{allowUserGestureFallback:!0});n(i==="failed"?"failed":"copied")};return m.jsxs("div",{className:"flex min-h-[100dvh] flex-col overflow-hidden bg-background text-foreground","data-slot":"unsupported-ipad-browser",children:[m.jsx("header",{className:"mx-auto flex w-full max-w-5xl items-center px-6 py-5 sm:px-10",children:m.jsx(Cz,{className:"text-sm",slot:"unsupported-browser-brand"})}),m.jsx("main",{className:"mx-auto flex w-full max-w-5xl flex-1 items-center px-6 pb-20 sm:px-10 sm:pb-24",children:m.jsxs("section",{className:"max-w-xl","aria-labelledby":"unsupported-browser-title",children:[m.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[m.jsx(pV,{className:"size-4 text-primary","aria-hidden":"true"}),m.jsx("span",{children:"iPad 浏览器支持"})]}),m.jsx("h1",{id:"unsupported-browser-title",className:"mt-4 text-3xl font-semibold tracking-normal sm:text-4xl",children:"请使用 Safari 打开"}),m.jsxs("p",{className:"mt-4 max-w-lg text-base leading-7 text-muted-foreground",children:["DEV Anywhere 暂不支持 iPad 上的 ",e,"。当前版本仅支持 Safari,以保证终端输入和实体键盘行为稳定。"]}),m.jsxs("div",{className:"mt-7 flex flex-wrap items-center gap-3",children:[m.jsxs(gt,{className:"h-11 px-4",onClick:r,children:[t==="copied"?m.jsx(Co,{className:"size-4","aria-hidden":"true"}):m.jsx(QB,{className:"size-4","aria-hidden":"true"}),t==="copied"?"链接已复制":"复制当前链接"]}),m.jsx("span",{className:"text-sm text-muted-foreground","aria-live":"polite",children:t==="copied"?"请切换到 Safari 后粘贴打开":t==="failed"?"复制失败,请从地址栏复制":"复制后在 Safari 中打开"})]})]})})]})}function KOe({children:e}){const t=PSe();return t.supported?e:m.jsx(YOe,{browserName:t.browserName})}function GOe(){return m.jsx(KOe,{children:m.jsx(XOe,{})})}function XOe(){return Zie(),m.jsx(Kue,{delayDuration:200,children:m.jsx(Uq,{router:zd})})}function ZOe(e=window.history){e.scrollRestoration="manual"}ZOe();QK();phe();sW.createRoot(document.getElementById("root")).render(m.jsx(b.StrictMode,{children:m.jsx(GOe,{})}));export{H6 as _,Vp as a,JOe as g};
843
+ `;function yOe(){return m.jsx("div",{className:"min-h-dvh bg-background text-foreground p-6",children:m.jsxs("div",{className:"mx-auto max-w-[720px] space-y-6",children:[m.jsxs("header",{children:[m.jsx("h1",{className:"text-lg font-semibold",children:"Markdown 渲染走查"}),m.jsx("p",{className:"text-sm text-muted-foreground",children:"下方模拟 assistant 气泡容器 (max-w 约束), 验证所有 markdown 元素在气泡内的实际渲染。"})]}),m.jsx("article",{className:"flex justify-start",children:m.jsx("div",{className:"max-w-[80%] rounded-md bg-card text-foreground px-4 py-2 text-sm",children:m.jsx(BE,{text:vOe})})})]})})}function UU(e){if([e.left,e.top,e.width,e.height,e.frameWidth,e.frameHeight].some(l=>!Number.isFinite(l))||e.width<=0||e.height<=0||e.frameWidth<=0||e.frameHeight<=0)return null;const n=Math.min(e.width/e.frameWidth,e.height/e.frameHeight),r=e.frameWidth*n,i=e.frameHeight*n,s=e.left+(e.width-r)/2,o=e.top+(e.height-i)/2;return{left:s,top:o,right:s+r,bottom:o+i,width:r,height:i}}function WU(e,t,n){return{x:Math.min(1,Math.max(0,(e-n.left)/n.width)),y:Math.min(1,Math.max(0,(t-n.top)/n.height))}}function bOe(e,t,n){if(!Number.isFinite(e)||!Number.isFinite(t))return null;const r=UU(n);return!r||e<r.left||e>r.right||t<r.top||t>r.bottom?null:WU(e,t,r)}function _Oe(e,t,n){if(!Number.isFinite(e)||!Number.isFinite(t))return null;const r=UU(n);return r?WU(e,t,r):null}async function wOe(e){const t=e.slice();return createImageBitmap(new Blob([t.buffer],{type:"image/jpeg"}))}class xOe{constructor(t,n,r=wOe){je(this,"latest",null);je(this,"painting",!1);je(this,"disposed",!1);je(this,"generation",0);je(this,"lastSequence",-1);je(this,"sizeReportedGeneration",-1);this.canvas=t,this.onSize=n,this.decoder=r}enqueue(t,n){var r;this.disposed||t<=this.lastSequence||((r=this.latest)==null?void 0:r.generation)===this.generation&&t<=this.latest.sequence||(this.latest={generation:this.generation,sequence:t,jpeg:n.slice()},this.painting||this.paintLoop())}reset(t=!1){var n;this.disposed||(this.generation+=1,this.latest=null,this.lastSequence=-1,t&&((n=this.canvas.getContext("2d",{alpha:!1}))==null||n.clearRect(0,0,this.canvas.width,this.canvas.height)))}dispose(){this.disposed=!0,this.generation+=1,this.latest=null}async paintLoop(){var t;this.painting=!0;try{for(;!this.disposed&&this.latest;){const n=this.latest;this.latest=null;let r;try{r=await this.decoder(n.jpeg)}catch(i){!this.disposed&&n.generation===this.generation&&console.warn("Failed to decode device preview frame",i);continue}try{if(this.disposed||n.generation!==this.generation||n.sequence<=this.lastSequence)continue;const i=this.canvas.width!==r.width||this.canvas.height!==r.height;i&&(this.canvas.width=r.width,this.canvas.height=r.height),(i||this.sizeReportedGeneration!==n.generation)&&(this.sizeReportedGeneration=n.generation,this.onSize({width:r.width,height:r.height})),(t=this.canvas.getContext("2d",{alpha:!1}))==null||t.drawImage(r,0,0),this.lastSequence=n.sequence}finally{r.close()}}}finally{this.painting=!1,!this.disposed&&this.latest&&this.paintLoop()}}}const SOe=120,EOe=8*1024*1024,COe=1e3/30,kOe=.15,TOe=100,ROe=.001;function AOe(e,t){if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n+=1)if(e[n]!==t[n])return!1;return!0}function Lc(e,t){if(e instanceof Error)return e;if(typeof e=="string"&&e.length>0)return new Error(e);if(e&&typeof e=="object"){const n=e,r=[n.name,n.message,n.error].filter(i=>typeof i=="string"&&i.length>0).join(": ");if(r.length>0)return new Error(r)}return new Error(t)}function NOe(e){const t=e.error;if(!t)return new Error("H.264 video playback failed");const n=t.message||`media error ${t.code}`;return new Error(`H.264 video playback failed: ${n}`)}class MOe{constructor(t,n={}){je(this,"muxer",null);je(this,"initialSources");je(this,"initialVideoState");je(this,"configuration",null);je(this,"configurationApplied",!1);je(this,"muxerReady",!1);je(this,"awaitingKeyframe",!0);je(this,"pendingFrames",[]);je(this,"fedFramesAwaitingPlayback",[]);je(this,"bufferedPacketCount",0);je(this,"bufferedBytes",0);je(this,"maxBufferedPackets");je(this,"maxBufferedBytes");je(this,"lastObservedMediaTime",null);je(this,"resyncRequired",!1);je(this,"playPending",!1);je(this,"playRequested",!1);je(this,"started",!1);je(this,"destroyed",!1);je(this,"generation",0);je(this,"playbackDelayTimer",null);je(this,"handlePlaying",()=>{this.destroyed||(this.observePlaybackProgress(),this.playRequested=!0,this.markStarted())});je(this,"handleTimeUpdate",()=>{this.observePlaybackProgress()});je(this,"handleVideoError",()=>{this.destroyed||this.reportError(NOe(this.video))});this.video=t,this.options=n,this.maxBufferedPackets=rB(n.maxBufferedPackets,SOe),this.maxBufferedBytes=rB(n.maxBufferedBytes,EOe),this.initialSources=new Set(t.querySelectorAll("source")),this.initialVideoState={autoplay:t.autoplay,disableRemotePlayback:t.disableRemotePlayback,muted:t.muted,playsInline:t.playsInline,src:t.getAttribute("src"),srcObject:t.srcObject},t.srcObject=null,t.muted=!0,t.autoplay=!0,t.playsInline=!0,t.disableRemotePlayback=!0,t.addEventListener("playing",this.handlePlaying),t.addEventListener("error",this.handleVideoError),t.addEventListener("timeupdate",this.handleTimeUpdate);const r={node:t,mode:"video",flushingTime:0,maxDelay:150,clearBuffer:!0,onReady:()=>this.handleMuxerReady(),onError:i=>this.handleMuxerError(i),onUnsupportedCodec:i=>{this.reportError(new Error(`Browser does not support the H.264 codec ${i}`))}};this.initializeMuxer(r)}feed(t){if(!(this.destroyed||t.data.byteLength===0)){if(this.observePlaybackProgress(),t.kind==="configuration"){this.feedConfiguration(t.data);return}this.feedFrame(t)}}destroy(){var n;if(this.destroyed)return;this.destroyed=!0,this.generation+=1,this.clearBufferedGeneration(),this.video.removeEventListener("playing",this.handlePlaying),this.video.removeEventListener("error",this.handleVideoError),this.video.removeEventListener("timeupdate",this.handleTimeUpdate),this.stopPlaybackDelayChecks();const t=this.generatedObjectUrls();try{(n=this.muxer)==null||n.destroy()}catch{}this.muxer=null;try{this.video.pause()}catch{}this.removeGeneratedSources(),this.video.removeAttribute("src"),this.initialVideoState.src!==null&&this.video.setAttribute("src",this.initialVideoState.src),this.video.srcObject=this.initialVideoState.srcObject,this.video.autoplay=this.initialVideoState.autoplay,this.video.disableRemotePlayback=this.initialVideoState.disableRemotePlayback,this.video.muted=this.initialVideoState.muted,this.video.playsInline=this.initialVideoState.playsInline;for(const r of t)this.revokeObjectUrl(r);try{this.video.load()}catch{}}async initializeMuxer(t){try{const{default:n}=await H6(async()=>{const{default:r}=await import("./jmuxer.min-CqkQ8MXd.js").then(i=>i.j);return{default:r}},__vite__mapDeps([0,1]));if(this.destroyed)return;this.muxer=new n(t)}catch(n){if(this.destroyed)return;this.reportError(Lc(n,"Failed to initialize H.264 video playback")),this.destroy()}}feedConfiguration(t){if(this.configuration&&AOe(this.configuration,t))return;const n=this.configuration!==null&&this.configurationApplied;if(this.clearBufferedGeneration(),this.wouldOverflow(t.byteLength)){this.requireResync();return}if(this.configuration=t.slice(),this.addBufferedPacket(t.byteLength),this.awaitingKeyframe=!0,n){this.resetMuxer();return}this.applyConfigurationIfReady()}feedFrame(t){if(!this.configuration)return;if(this.awaitingKeyframe){if(!t.keyframe)return;this.awaitingKeyframe=!1,this.resyncRequired=!1}const n={data:t.data.slice(),durationMs:Number.isFinite(t.durationMs)&&t.durationMs>0?t.durationMs:COe,keyframe:t.keyframe};if(n.keyframe&&this.clearPendingFrames(),this.wouldOverflow(n.data.byteLength)){this.requireResync();return}if(this.addBufferedPacket(n.data.byteLength),!this.muxerReady||!this.configurationApplied){this.pendingFrames.push(n);return}this.applyFrame(n)||this.removeBufferedPacket(n.data.byteLength)}resetMuxer(){var r;const t=this.generatedSources(),n=this.generatedObjectUrls();this.generation+=1,this.muxerReady=!1,this.configurationApplied=!1,this.awaitingKeyframe=!0,this.playPending=!1,this.playRequested=!1,this.stopPlaybackDelayChecks();try{(r=this.muxer)==null||r.reset()}catch(i){this.reportError(Lc(i,"Failed to reset H.264 video playback"))}for(const i of t)i.remove();for(const i of n)this.revokeObjectUrl(i)}handleMuxerReady(){this.destroyed||(this.muxerReady=!0,this.startPlaybackDelayChecks(),this.applyConfigurationIfReady(),this.flushPendingFrames())}startPlaybackDelayChecks(){this.playbackDelayTimer===null&&(this.playbackDelayTimer=setInterval(()=>{this.catchUpToLiveEdge()},TOe))}stopPlaybackDelayChecks(){this.playbackDelayTimer!==null&&(clearInterval(this.playbackDelayTimer),this.playbackDelayTimer=null)}catchUpToLiveEdge(){if(this.destroyed||this.video.seeking)return;const t=this.video.buffered;if(t.length!==0)try{const n=t.end(t.length-1),r=this.video.currentTime;if(!Number.isFinite(n)||!Number.isFinite(r)||n-r<=kOe)return;this.video.currentTime=Math.max(0,n-ROe),this.observePlaybackProgress()}catch{}}applyConfigurationIfReady(){if(!(this.destroyed||!this.muxerReady||this.configurationApplied||!this.configuration||!this.muxer))try{this.muxer.feed({video:this.configuration,duration:0,isLastVideoFrameComplete:!0}),this.configurationApplied=!0,this.flushPendingFrames()}catch(t){this.reportError(Lc(t,"Failed to apply H.264 decoder configuration"))}}applyFrame(t){if(this.destroyed||!this.muxer)return!1;try{return this.muxer.feed({video:t.data,duration:t.durationMs,isLastVideoFrameComplete:!0}),this.fedFramesAwaitingPlayback.push({byteLength:t.data.byteLength,remainingDurationMs:t.durationMs}),this.attemptPlayback(),!0}catch(n){return this.reportError(Lc(n,"Failed to feed an H.264 video frame")),!1}}flushPendingFrames(){if(this.destroyed||!this.muxerReady||!this.configurationApplied||!this.muxer)return;this.observePlaybackProgress();const t=this.pendingFrames;this.pendingFrames=[];for(const n of t){if(this.destroyed)return;this.applyFrame(n)||this.removeBufferedPacket(n.data.byteLength)}}attemptPlayback(){if(this.destroyed||this.playPending||this.playRequested)return;this.playPending=!0,this.playRequested=!0;const t=this.generation;let n;try{n=this.video.play()}catch(r){this.playPending=!1,this.playRequested=!1,this.reportError(Lc(r,"Browser blocked H.264 video playback"));return}n.then(()=>{this.destroyed||t!==this.generation||(this.playPending=!1,this.markStarted())},r=>{this.destroyed||t!==this.generation||(this.playPending=!1,this.playRequested=!1,this.reportError(Lc(r,"Browser blocked H.264 video playback")))})}handleMuxerError(t){this.destroyed||(t.name==="InvalidStateError"&&(this.generation+=1,this.muxerReady=!1,this.configurationApplied=!1,this.awaitingKeyframe=!0,this.clearBufferedGeneration(),this.playPending=!1,this.playRequested=!1,this.stopPlaybackDelayChecks()),this.reportError(Lc(t,"H.264 video buffer failed")))}markStarted(){var t,n;this.started||(this.started=!0,(n=(t=this.options).onStart)==null||n.call(t))}reportError(t){var n,r;this.destroyed||(r=(n=this.options).onError)==null||r.call(n,t)}observePlaybackProgress(){const t=this.video.currentTime;if(!Number.isFinite(t)||t<0)return;if(this.lastObservedMediaTime===null||t<this.lastObservedMediaTime){this.lastObservedMediaTime=t;return}let n=(t-this.lastObservedMediaTime)*1e3;if(this.lastObservedMediaTime=t,!(n<=0))for(;n>0;){const r=this.fedFramesAwaitingPlayback[0];if(!r)return;if(n+Number.EPSILON<r.remainingDurationMs){r.remainingDurationMs-=n;return}n-=r.remainingDurationMs,this.fedFramesAwaitingPlayback.shift(),this.removeBufferedPacket(r.byteLength)}}wouldOverflow(t){return this.bufferedPacketCount+1>this.maxBufferedPackets||this.bufferedBytes+t>this.maxBufferedBytes}addBufferedPacket(t){this.bufferedPacketCount+=1,this.bufferedBytes+=t}removeBufferedPacket(t){this.bufferedPacketCount=Math.max(0,this.bufferedPacketCount-1),this.bufferedBytes=Math.max(0,this.bufferedBytes-t)}clearPendingFrames(){for(const t of this.pendingFrames)this.removeBufferedPacket(t.data.byteLength);this.pendingFrames=[]}clearBufferedGeneration(){this.pendingFrames=[],this.fedFramesAwaitingPlayback=[],this.configuration=null,this.configurationApplied=!1,this.bufferedPacketCount=0,this.bufferedBytes=0,this.lastObservedMediaTime=null}requireResync(){var n,r;const t=!this.resyncRequired;this.resyncRequired=!0,this.clearBufferedGeneration(),this.awaitingKeyframe=!0,this.resetMuxer(),t&&!this.destroyed&&((r=(n=this.options).onResyncRequired)==null||r.call(n,new Error("H.264 playback buffer overflowed; reconnecting for a fresh keyframe")))}generatedSources(){return Array.from(this.video.querySelectorAll("source")).filter(t=>!this.initialSources.has(t))}removeGeneratedSources(){for(const t of this.generatedSources())t.remove()}generatedObjectUrls(){const t=new Set,n=this.video.getAttribute("src");n!==this.initialVideoState.src&&(n!=null&&n.startsWith("blob:"))&&t.add(n);for(const r of this.generatedSources()){const i=r.getAttribute("src");i!=null&&i.startsWith("blob:")&&t.add(i)}return[...t]}revokeObjectUrl(t){if(typeof URL.revokeObjectURL=="function")try{URL.revokeObjectURL(t)}catch{}}}function rB(e,t){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0?e:t}class POe{constructor(){je(this,"buffer",new Uint8Array(0))}push(t){if(t.byteLength===0)return[];const n=new Uint8Array(this.buffer.byteLength+t.byteLength);n.set(this.buffer),n.set(t,this.buffer.byteLength),this.buffer=n;const r=[];let i=0;for(;this.buffer.byteLength-i>=_h;){const s=new DataView(this.buffer.buffer,this.buffer.byteOffset+i,_h),o=s.getUint32(0,!0),l=s.getUint32(4,!0);if(o===0||o>vy)throw this.buffer=new Uint8Array(0),new RangeError(`Invalid device preview frame length: ${o}`);const u=_h+o;if(this.buffer.byteLength-i<u)break;r.push({sequence:l,jpeg:this.buffer.slice(i+_h,i+u)}),i+=u}if(i>0&&(this.buffer=this.buffer.slice(i)),this.buffer.byteLength>_h+vy)throw this.buffer=new Uint8Array(0),new RangeError("Device preview stream buffer exceeded its limit");return r}finish(){if(this.buffer.byteLength!==0)throw this.buffer=new Uint8Array(0),new Error("Device preview stream ended with a truncated frame")}}class IOe{constructor(){je(this,"buffer",new Uint8Array(0))}push(t){if(t.byteLength===0)return[];const n=new Uint8Array(this.buffer.byteLength+t.byteLength);n.set(this.buffer),n.set(t,this.buffer.byteLength),this.buffer=n;const r=[];let i=0;for(;this.buffer.byteLength-i>=Yh;){const s=this.buffer.subarray(i),o=Gte(s);if(!o)throw this.buffer=new Uint8Array(0),new RangeError("Invalid H.264 device preview packet header");const l=Yh+o.annexBLength;if(this.buffer.byteLength-i<l)break;r.push({sequence:o.packetSequence,kind:o.configuration?"configuration":"frame",keyframe:o.keyframe,durationMs:o.durationMs,data:this.buffer.slice(i+Yh,i+l)}),i+=l}if(i>0&&(this.buffer=this.buffer.slice(i)),this.buffer.byteLength>Yh+vy)throw this.buffer=new Uint8Array(0),new RangeError("H.264 device preview stream buffer exceeded its limit");return r}finish(){if(this.buffer.byteLength!==0)throw this.buffer=new Uint8Array(0),new Error("H.264 device preview stream ended with a truncated packet")}}function OOe(e){let t;try{t=new URL(e,globalThis.location.href)}catch{throw new Error("无效的模拟器画面地址")}if(t.origin!==globalThis.location.origin||t.username!==""||t.password!==""||!/^\/api\/device-preview-streams\/[A-Za-z0-9_-]{1,256}$/u.test(t.pathname)||t.search!==""||t.hash!=="")throw new Error("拒绝连接不受信任的模拟器画面地址")}function LOe(e){const t=Number(e.headers.get("X-Device-Width")),n=Number(e.headers.get("X-Device-Height"));return!Number.isSafeInteger(t)||t<=0||!Number.isSafeInteger(n)||n<=0?null:{width:t,height:n}}async function qU(e,t,n){OOe(e);const r=ob(),i=await n(e,{method:"GET",cache:"no-store",credentials:"same-origin",...r?{headers:{Authorization:`Bearer ${r}`}}:{},signal:t});if(!i.ok||!i.body)throw new Error(`无法打开模拟器画面(${i.status})`);return i}async function DOe(e,t){const n=t.fetch??globalThis.fetch,r=await qU(e,t.signal,n);if(r.headers.get("X-Device-Preview-Format")!=="jpeg")throw new Error("开发机返回了错误的模拟器画面格式");const i=new POe,s=r.body.getReader();try{for(;;){const{done:o,value:l}=await s.read();if(o)break;const d=i.push(l).at(-1);d&&await t.onFrame(d)}i.finish()}finally{s.releaseLock()}}async function BOe(e,t){var l;const n=t.fetch??globalThis.fetch,r=await qU(e,t.signal,n);if(r.headers.get("X-Device-Preview-Format")!=="h264_annex_b")throw new Error("开发机没有返回 H.264 模拟器画面");const i=LOe(r);i&&((l=t.onSize)==null||l.call(t,i));const s=new IOe,o=r.body.getReader();try{for(;;){const{done:u,value:d}=await o.read();if(u)break;for(const f of s.push(d))await t.onPacket(f)}s.finish()}finally{o.releaseLock()}}const zOe=16,jOe=16;class FOe{constructor(t){je(this,"send");je(this,"onFailure");je(this,"now");je(this,"moveFlushMs");je(this,"maxInFlightMoves");je(this,"active",null);je(this,"inFlightMoves",0);je(this,"disposed",!1);je(this,"failed",!1);this.send=t.send,this.onFailure=t.onFailure,this.now=t.now??(()=>performance.now()),this.moveFlushMs=t.moveFlushMs??zOe,this.maxInFlightMoves=t.maxInFlightMoves??jOe}begin(t,n){if(this.disposed||this.failed||this.active)return!1;const r={pointerId:t,lastPoint:n,lastMoveAt:Number.NEGATIVE_INFINITY,pendingMove:null,moveFlushTimer:null};return this.active=r,this.dispatch(this.input("down",n)),!0}move(t,n){const r=this.matchingActive(t);if(!r)return!1;r.lastPoint=n,r.pendingMove=n;const i=this.now(),s=this.moveFlushMs-(i-r.lastMoveAt);return s>0?(r.moveFlushTimer===null&&(r.moveFlushTimer=setTimeout(()=>{r.moveFlushTimer=null,!(this.active!==r||this.disposed||this.failed)&&(r.lastMoveAt=this.now(),this.flushLatestMove())},s)),!0):(this.clearMoveTimer(r),r.lastMoveAt=i,this.flushLatestMove(),!0)}end(t,n){const r=this.matchingActive(t);return r?(r.lastPoint=n,this.finish(r),this.dispatch(this.input("up",n)),!0):!1}cancel(t){const n=this.active;if(!n||t!==void 0&&n.pointerId!==t)return!1;const r=n.lastPoint;return this.finish(n),this.dispatch(this.input("up",r)),!0}dispose(){if(this.disposed)return;const t=this.active;if(t&&this.finish(t),this.disposed=!0,!(!t||this.failed))try{Promise.resolve(this.send(this.input("up",t.lastPoint))).catch(()=>{})}catch{}}matchingActive(t){var n;return this.disposed||this.failed||((n=this.active)==null?void 0:n.pointerId)!==t?null:this.active}finish(t){this.active===t&&(this.active=null),this.clearMoveTimer(t),t.pendingMove=null}clearMoveTimer(t){t.moveFlushTimer!==null&&clearTimeout(t.moveFlushTimer),t.moveFlushTimer=null}flushLatestMove(){const t=this.active;if(!t||this.disposed||this.failed||!t.pendingMove||t.moveFlushTimer!==null||this.inFlightMoves>=this.maxInFlightMoves)return;const n=t.pendingMove;t.pendingMove=null,this.inFlightMoves+=1,this.dispatch(this.input("move",n),()=>{this.inFlightMoves=Math.max(0,this.inFlightMoves-1),this.flushLatestMove()})}dispatch(t,n){let r;try{r=Promise.resolve(this.send(t))}catch(i){this.fail(i),n==null||n();return}r.then(()=>n==null?void 0:n(),i=>{this.fail(i),n==null||n()})}fail(t){if(this.disposed||this.failed)return;this.failed=!0;const n=this.active;n&&this.finish(n),this.onFailure(t)}input(t,n){return{kind:"touch",phase:t,x:n.x,y:n.y}}}const $Oe=15e3,HOe=1e4,UOe={ios:40,android:28},WOe={ios:{width:390,height:844},android:{width:412,height:915}};function qOe(){const{id:e=""}=FB(),t=ws(),n=gr(Oe=>Dj(Oe).find(ze=>ze.previewId===e)),r=gr(Oe=>Oe.listLoaded),i=gr(Oe=>{var ze;return((ze=Oe.authoritative)==null?void 0:ze.scope)??null}),s=qo(Oe=>_re(Oe,i,"device",e,"reconnect")),o=b.useRef(null),l=b.useRef(null),u=b.useRef(null),d=b.useRef(null),f=b.useRef(null),p=b.useRef(()=>{}),y=b.useRef(null),g=b.useRef(null),[_,w]=b.useState(0),[x,S]=b.useState("waiting"),[k,T]=b.useState(null),[N,P]=b.useState(null),[R,M]=b.useState(null),[L,X]=b.useState(""),[U,V]=b.useState(!1),[j,A]=b.useState(!1),[D,O]=b.useState(!1),I=n==null?void 0:n.previewId,B=n==null?void 0:n.state,F=n==null?void 0:n.platform,Y=b.useCallback(()=>{const Oe=f.current;f.current=null,Oe==null||Oe.dispose()},[]);b.useEffect(()=>{if(F!=="ios"){d.current=null,M(null);return}const Oe=o.current;if(!Oe)return;const ze=new xOe(Oe,M);return ze.reset(!0),M(null),d.current=ze,()=>{ze.dispose(),d.current=null}},[I,F]),b.useEffect(()=>{if(Y(),p.current=()=>{},y.current=null,g.current=null,P(null),A(!1),O(!1),!I||B!=="ready"){B==="disconnected"?(S("error"),T("模拟器已断开")):(S("waiting"),T(null));return}const Oe=Ft,ze=i;if(!Oe||!ze||!Tt.isActive(Oe,ze)){S("error"),T("开发机连接已断开");return}let et=!1,Ct=null,tt=null,Le=null,it=null,dt=null,be=0,Ve=!1;const ft=()=>{dt=null,Le==null||Le.abort(),Le=null,it==null||it.destroy(),it=null,Ct&&clearTimeout(Ct),Ct=null,tt&&clearTimeout(tt),tt=null},St=yt=>{S("streaming"),tt&&clearTimeout(tt),tt=setTimeout(()=>{tt=null,!(et||yt.signal.aborted||dt!==yt.leaseId||!Tt.isActive(Oe,ze))&&(be=0)},HOe)},wt=()=>{if(et||document.visibilityState==="hidden"||!Tt.isActive(Oe,ze))return;const yt=Math.min(5e3,500*2**be);be+=1,Ct=setTimeout(()=>void fn(),yt)},fn=async()=>{var Zt;if(Y(),ft(),et||document.visibilityState==="hidden"||!Tt.isActive(Oe,ze))return;Ve=!1,(Zt=d.current)==null||Zt.reset(),M(null),S("connecting"),T(null),P(null);const yt=new AbortController;Le=yt;try{const zt=await Tt.requestDevicePreviewStream(ze,I,F==="android"?{format:"h264_annex_b"}:{format:"jpeg",maxFps:15},{signal:yt.signal});if(et||yt.signal.aborted||!Tt.isActive(Oe,ze)||!zt)return;if(!zt.success)throw new Error(zt.error);const yn=zt;if(dt=yn.leaseId,P(yn),F==="android"){const Zn=l.current;if(!Zn)throw new Error("无法初始化 Android 模拟器播放器");let Jn;const gn=new Promise((ce,Te)=>{Jn=Te}),W=setTimeout(()=>{Jn(new Error("Android 模拟器画面启动超时"))},$Oe),ie=ce=>{Jn(ce instanceof Error?ce:new Error(String(ce)))},J=new MOe(Zn,{onStart:()=>{clearTimeout(W),!(et||yn.signal.aborted||!Tt.isActive(Oe,ze))&&St(yn)},onError:ie,onResyncRequired:ie});it=J;try{await Promise.race([BOe(yn.url,{signal:yn.signal,onSize:ce=>{!et&&!yn.signal.aborted&&Tt.isActive(Oe,ze)&&M(ce)},onPacket:ce=>{!et&&!yn.signal.aborted&&Tt.isActive(Oe,ze)&&J.feed(ce)}}),gn])}finally{clearTimeout(W)}if(!et&&!yn.signal.aborted&&Tt.isActive(Oe,ze))throw new Error("模拟器画面已断开");return}let $n=!1;if(await DOe(yn.url,{signal:yn.signal,onFrame:Zn=>{if(et||yn.signal.aborted||!Tt.isActive(Oe,ze))return;const Jn=d.current;Jn&&(Jn.enqueue(Zn.sequence,Zn.jpeg),$n||($n=!0,St(yn)))}}),!et&&!yn.signal.aborted&&Tt.isActive(Oe,ze))throw new Error("模拟器画面已断开")}catch(zt){if(et||yt.signal.aborted||!Tt.isActive(Oe,ze))return;Xt(zt,!1)}},Xt=(yt,Zt)=>{if(et||Ve||!Tt.isActive(Oe,ze))return;Ve=!0;const zt=yt instanceof Error?yt.message:"模拟器画面已断开";Y(),ft(),y.current=null,g.current=null,P(null),A(!1),O(!1),S("error"),T(zt),Zt&&We.error(zt),wt()},Jt=(yt,Zt,zt=!0)=>{yt===dt&&Xt(Zt,zt)};p.current=Jt;const xn=Oe.onMessage(yt=>{if(yt.type!=="device_preview_control_revoked_push"||!tn(yt.scope,ze)||yt.leaseId!==dt||!Tt.isActive(Oe,ze))return;if(g.current=null,O(!1),yt.reason==="taken_over"){y.current=null,A(!1),Y(),P(zt=>(zt==null?void 0:zt.leaseId)===yt.leaseId?{...zt,controlMode:"view_only"}:zt),We.info("控制权已由其他页面接管");return}const Zt=new Error(yt.reason==="proxy_offline"?"开发机连接已断开":yt.reason==="lease_expired"?"模拟器画面连接已过期":"模拟器画面已断开");Jt(yt.leaseId,Zt,!1)}),mn=()=>{if(document.visibilityState==="hidden"){Y(),ft(),y.current=null,g.current=null,P(null),A(!1),O(!1),S("waiting");return}be=0,fn()};return document.addEventListener("visibilitychange",mn),fn(),()=>{et=!0,p.current===Jt&&(p.current=()=>{}),xn(),document.removeEventListener("visibilitychange",mn),Y(),ft()}},[Y,I,F,i,B,_]),b.useEffect(()=>{var Oe;(Oe=f.current)==null||Oe.cancel()},[R==null?void 0:R.height,R==null?void 0:R.width]);const z=(n==null?void 0:n.state)==="ready"&&(N==null?void 0:N.previewId)===n.previewId&&i&&tn(N.scope,i)?N:null,q=(n==null?void 0:n.interactive)===!0&&x==="streaming"&&(z==null?void 0:z.controlMode)==="controller";b.useEffect(()=>{Y();const Oe=Ft,ze=z;if(!Oe||!ze||!q)return;const et=new FOe({send:async Ct=>{const tt=await Tt.sendDevicePreviewInput(ze,Ct);if(!tt)throw new Error("模拟器控制连接已失效");if(!tt.success)throw new Error(tt.error)},onFailure:Ct=>{f.current===et&&p.current(ze.leaseId,Ct)}});return f.current=et,()=>{f.current===et&&(f.current=null),et.dispose()}},[q,z,Y]);const K=R??WOe[(n==null?void 0:n.platform)==="android"?"android":"ios"],$=UOe[(n==null?void 0:n.platform)==="android"?"android":"ios"],re=K.width/K.height,Q=K.width>K.height?"landscape":"portrait",G=Q==="landscape"?`, ${K.width}px`:"",Z={aspectRatio:`${K.width} / ${K.height}`,width:`max(1px, min(calc(100cqw - ${$}px), calc(${(re*100).toFixed(6)}cqh - ${(re*$).toFixed(6)}px)${G}))`};b.useEffect(()=>{q||V(!1)},[q]);const ae=b.useCallback(async(Oe,ze=!0)=>{const et=Ft,Ct=z;if(!et||!Ct||!q)return!1;try{const tt=await Tt.sendDevicePreviewInput(Ct,Oe);return!tt||!Tt.isActive(et,Ct.scope)?!1:tt.success?!0:(ze&&We.error(tt.error),!1)}catch(tt){return Ct.signal.aborted||!Tt.isActive(et,Ct.scope)||ze&&We.error(tt instanceof Error?tt.message:"模拟器操作失败"),!1}},[q,z]);function le(Oe,ze){const et=u.current;if(!et||!R)return null;const Ct=et.getBoundingClientRect(),tt={left:Ct.left,top:Ct.top,width:Ct.width,height:Ct.height,frameWidth:R.width,frameHeight:R.height};return ze==="start"?bOe(Oe.clientX,Oe.clientY,tt):_Oe(Oe.clientX,Oe.clientY,tt)}function me(Oe){var Ct,tt;if(!q||Oe.button!==0)return;const ze=le(Oe,"start");if(!ze)return;const et=f.current;et!=null&&et.begin(Oe.pointerId,ze)&&(Oe.preventDefault(),(tt=(Ct=Oe.currentTarget).setPointerCapture)==null||tt.call(Ct,Oe.pointerId))}function ke(Oe){var et;const ze=le(Oe,"captured");ze&&(et=f.current)!=null&&et.move(Oe.pointerId,ze)&&Oe.preventDefault()}function $e(Oe){var et;const ze=le(Oe,"captured");ze&&((et=f.current)!=null&&et.end(Oe.pointerId,ze))&&Oe.preventDefault()}function he(Oe){var ze;(ze=f.current)==null||ze.cancel(Oe.pointerId)}async function He(){const Oe=Ft,ze=z;if(!Oe||!ze||D||x!=="streaming")return;const et=Symbol("device-preview-control-claim");g.current=et,O(!0);try{const Ct=await Tt.claimDevicePreviewControl(ze);if(g.current!==et||!Ct||!Tt.isActive(Oe,ze.scope))return;if(!Ct.success){We.error(Ct.error);return}P(tt=>(tt==null?void 0:tt.leaseId)===ze.leaseId?{...tt,controlMode:"controller"}:tt)}catch(Ct){if(g.current!==et||ze.signal.aborted||!Tt.isActive(Oe,ze.scope))return;We.error(Ct instanceof Error?Ct.message:"暂时无法取得控制权")}finally{g.current===et&&(g.current=null,O(!1))}}async function Nt(Oe){Oe.preventDefault();const ze=L;if(!ze||j)return;const et=Symbol("device-preview-text-input");y.current=et,A(!0);const Ct=await ae({kind:"text",text:ze});y.current===et&&(Ct&&(X(""),V(!1)),y.current=null,A(!1))}function ye(){var Oe;(Oe=f.current)==null||Oe.cancel(),ae({kind:"orientation",orientation:R&&R.width>R.height?"portrait":"landscape_right"})}async function Ze(){if((n==null?void 0:n.state)!=="disconnected"){w(et=>et+1);return}const Oe=Ft,ze=Tt.getActiveScope();if(!Oe||!ze){We.error("请先连接开发机");return}try{const et=await Tt.reconnectDevicePreview(ze,n.previewId);et.success||We.error(et.error)}catch(et){if(!Tt.isActive(Oe,ze))return;We.error(et instanceof Error?et.message:"无法重新连接模拟器预览")}}return n?m.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background","data-slot":"device-preview-page","data-preview-id":n.previewId,"data-stream-status":x,"data-control-mode":n.interactive?(z==null?void 0:z.controlMode)??"none":"unavailable",children:[m.jsxs("header",{className:"flex min-h-14 shrink-0 items-center gap-2 border-b px-3 md:px-4",children:[m.jsx(gt,{variant:"ghost",size:"icon",className:"md:hidden","aria-label":"返回",onClick:()=>t("/sessions"),children:m.jsx(Qp,{"aria-hidden":"true"})}),m.jsx(oC,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}),m.jsxs("div",{className:"min-w-0 flex-1",children:[m.jsx("p",{className:"truncate text-sm font-medium",children:n.name}),m.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[n.model," · ",n.platform==="ios"?"iOS":"Android"," ",n.osVersion]})]}),n.interactive&&x==="streaming"&&(z==null?void 0:z.controlMode)==="view_only"?m.jsx(gt,{size:"sm",variant:"outline",disabled:D,onClick:()=>void He(),"data-slot":"device-preview-claim-control",children:"接管控制"}):m.jsx("span",{className:"text-xs text-muted-foreground",children:q?"可操控":x==="streaming"?"仅查看":"连接中"})]}),m.jsx("div",{className:"min-h-0 flex-1 overflow-hidden bg-muted/30",children:m.jsxs("div",{className:Ye("grid h-full min-h-0 min-w-0 gap-3 p-3 md:gap-4 md:p-6",Q==="portrait"?"grid-rows-[minmax(0,1fr)_auto] md:grid-cols-[minmax(0,1fr)_auto] md:grid-rows-1":"grid-rows-[minmax(0,1fr)_auto]"),"data-slot":"device-preview-stage","data-orientation":Q,children:[m.jsxs("div",{className:"relative flex min-h-0 min-w-0 items-center justify-center overflow-hidden [container-type:size]","data-slot":"device-preview-viewport",children:[m.jsxs("div",{className:Ye("relative isolate shrink-0 transition-[width,aspect-ratio] duration-300 ease-out motion-reduce:transition-none [container-type:size]",n.platform==="ios"?"[--device-screen-radius:clamp(22px,14cqmin,56px)] [--ios-rail:clamp(10px,4cqmin,16px)]":"[--device-screen-radius:clamp(14px,6.5cqw,38px)]"),style:Z,"data-slot":"device-preview-device-shell","data-platform":n.platform,"data-orientation":Q,children:[m.jsx(VOe,{platform:n.platform,orientation:Q}),m.jsx("div",{ref:u,className:Ye("relative z-10 flex h-full w-full min-h-0 min-w-0 items-center justify-center overflow-hidden rounded-[var(--device-screen-radius)] bg-black ring-1 ring-black",q&&"cursor-pointer"),"data-slot":"device-preview-surface","data-control-enabled":q?"true":"false",children:n.platform==="android"?m.jsx("video",{ref:l,className:"pointer-events-none h-full w-full object-contain","data-slot":"device-preview-video",muted:!0,autoPlay:!0,playsInline:!0,disableRemotePlayback:!0,onLoadedMetadata:Oe=>{const ze=Oe.currentTarget;ze.videoWidth>0&&ze.videoHeight>0&&M({width:ze.videoWidth,height:ze.videoHeight})},onResize:Oe=>{const ze=Oe.currentTarget;ze.videoWidth>0&&ze.videoHeight>0&&M({width:ze.videoWidth,height:ze.videoHeight})}}):m.jsx("canvas",{ref:o,className:"pointer-events-none h-full w-full object-contain","data-slot":"device-preview-canvas"})}),m.jsx("div",{className:Ye("absolute inset-0 z-20 select-none rounded-[var(--device-screen-radius)]",q?"touch-none cursor-pointer":"pointer-events-none"),onPointerDown:me,onPointerMove:ke,onPointerUp:$e,onPointerCancel:he,onLostPointerCapture:he,onContextMenu:Oe=>{q&&Oe.preventDefault()},"data-slot":"device-preview-input-surface","data-control-enabled":q?"true":"false","aria-hidden":"true"})]}),x!=="streaming"?m.jsx("div",{className:"absolute inset-0 z-30 flex items-center justify-center bg-background/55 p-6 backdrop-blur-[1px]","data-slot":"device-preview-stream-overlay","data-stream-status":x,children:m.jsx("div",{className:"grid max-w-sm justify-items-center gap-3 text-center",children:x==="error"?m.jsxs(m.Fragment,{children:[m.jsx("p",{className:"text-sm text-muted-foreground",children:k}),m.jsxs(gt,{variant:"outline",size:"sm",disabled:s,onClick:()=>void Ze(),"data-slot":"device-preview-retry",children:[s?m.jsx(ii,{className:"size-4 animate-spin","aria-hidden":!0}):null,s?"正在重新连接":"重新连接"]})]}):m.jsxs(m.Fragment,{children:[m.jsx(ii,{className:"size-5 animate-spin text-muted-foreground","aria-hidden":!0}),m.jsx("p",{className:"text-sm text-muted-foreground",children:"正在连接画面..."})]})})}):null]}),m.jsx("div",{className:"relative z-20 flex min-w-0 items-center justify-center pb-[max(0px,env(safe-area-inset-bottom))] md:pb-0","data-slot":"device-preview-control-dock","data-orientation":Q,role:"group","aria-label":"模拟器控制",children:m.jsxs("div",{className:Ye("flex max-w-full items-center gap-1 rounded-full border border-border/70 bg-card/85 p-1.5 shadow-xl ring-1 ring-black/5 backdrop-blur-xl",Q==="portrait"&&"md:flex-col"),children:[m.jsx(xS,{control:"home",label:"主屏幕",disabled:!q,icon:m.jsx(jV,{"aria-hidden":"true"}),tooltipSide:Q==="portrait"?"left":"top",onClick:()=>void ae({kind:"button",button:"home"})}),n.platform==="android"?m.jsx(xS,{control:"back",label:"返回",disabled:!q,icon:m.jsx(jY,{"aria-hidden":"true"}),tooltipSide:Q==="portrait"?"left":"top",onClick:()=>void ae({kind:"button",button:"back"})}):null,m.jsx(xS,{control:"orientation",label:"旋转",disabled:!q||!R,icon:m.jsx(yY,{"aria-hidden":"true"}),tooltipSide:Q==="portrait"?"left":"top",onClick:ye}),m.jsx("span",{className:Ye("mx-0.5 h-6 w-px shrink-0 bg-border/80",Q==="portrait"&&"md:mx-0 md:h-px md:w-6"),"aria-hidden":"true"}),m.jsxs(Rb,{open:U,onOpenChange:Oe=>{(!Oe||q)&&V(Oe)},children:[m.jsxs(hf,{children:[m.jsx(pf,{asChild:!0,children:m.jsx(Ab,{asChild:!0,children:m.jsx(gt,{type:"button",variant:"ghost",size:"icon",className:Ye("size-11 rounded-full text-muted-foreground hover:text-foreground",U&&"bg-accent text-foreground"),disabled:!q,"aria-label":"粘贴文字","aria-expanded":U,"aria-controls":"device-preview-text-form","data-slot":"device-preview-text-toggle",children:m.jsx(TS,{"aria-hidden":"true"})})})}),m.jsx(mf,{side:Q==="portrait"?"left":"top",sideOffset:10,hideArrow:!0,children:"粘贴文字"})]}),m.jsx(Nb,{side:Q==="portrait"?"left":"top",align:"center",sideOffset:12,className:"w-[min(20rem,calc(100vw-1.5rem))] rounded-2xl bg-card/95 p-2 shadow-2xl backdrop-blur-xl",children:m.jsxs("form",{id:"device-preview-text-form",className:"flex items-end gap-2","data-slot":"device-preview-text-form",onSubmit:Oe=>void Nt(Oe),children:[m.jsx("textarea",{value:L,onChange:Oe=>X(Oe.target.value),disabled:!q||j,maxLength:4096,rows:3,placeholder:"粘贴文字","aria-label":"粘贴文字","data-slot":"device-preview-text-input",className:"min-h-20 min-w-0 flex-1 resize-none rounded-xl border bg-background px-3 py-2 text-base outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50 md:text-sm"}),m.jsx(gt,{type:"submit",size:"icon",className:"size-10 rounded-xl",disabled:!q||!L||j,"aria-label":"粘贴","data-slot":"device-preview-send-text",children:j?m.jsx(ii,{className:"animate-spin","aria-hidden":"true"}):m.jsx(TS,{"aria-hidden":"true"})})]})})]})]})})]})})]}):m.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center",children:r?m.jsxs("div",{className:"grid gap-3",children:[m.jsx("p",{className:"text-sm text-muted-foreground",children:"无法找到该预览"}),m.jsx(gt,{variant:"outline",onClick:()=>t("/sessions"),children:"返回"})]}):m.jsx(ii,{className:"size-5 animate-spin text-muted-foreground","aria-label":"加载中"})})}function xS({control:e,label:t,icon:n,disabled:r,tooltipSide:i,onClick:s}){return m.jsxs(hf,{children:[m.jsx(pf,{asChild:!0,children:m.jsx(gt,{type:"button",variant:"ghost",size:"icon",className:"size-11 rounded-full text-muted-foreground hover:text-foreground","aria-label":t,disabled:r,onClick:s,"data-slot":"device-preview-control","data-control":e,children:n})}),m.jsx(mf,{side:i,sideOffset:10,hideArrow:!0,className:"border border-border/80 bg-card/95 px-2.5 py-1 text-muted-foreground shadow-sm backdrop-blur",children:t})]})}function VOe({platform:e,orientation:t}){const n=t==="portrait";return e==="ios"?m.jsxs("div",{"aria-hidden":"true","data-slot":"device-preview-device-chrome","data-platform":"ios","data-orientation":t,className:Ye("pointer-events-none absolute -inset-[var(--ios-rail)] z-0 select-none rounded-[calc(var(--device-screen-radius)+var(--ios-rail))] border border-black/85 bg-[#202024] ring-1 ring-black/30","shadow-[inset_1px_1px_0_rgba(255,255,255,0.16),inset_-1px_-1px_0_rgba(0,0,0,0.72)]"),children:[m.jsx("span",{className:"absolute inset-[2px] rounded-[calc(var(--device-screen-radius)+var(--ios-rail)-2px)] ring-1 ring-inset ring-white/[0.05]"}),n?m.jsxs(m.Fragment,{children:[m.jsx("span",{className:"absolute -left-[4px] top-[16%] h-[clamp(12px,4%,22px)] w-[4px] rounded-l-[3px] border border-r-0 border-black/70 bg-[#343439] shadow-[inset_1px_0_0_rgba(255,255,255,0.14)]"}),m.jsx("span",{className:"absolute -left-[4px] top-[23%] h-[clamp(24px,7%,42px)] w-[4px] rounded-l-[3px] border border-r-0 border-black/70 bg-[#343439] shadow-[inset_1px_0_0_rgba(255,255,255,0.14)]"}),m.jsx("span",{className:"absolute -left-[4px] top-[32%] h-[clamp(24px,7%,42px)] w-[4px] rounded-l-[3px] border border-r-0 border-black/70 bg-[#343439] shadow-[inset_1px_0_0_rgba(255,255,255,0.14)]"}),m.jsx("span",{className:"absolute -right-[4px] top-[28%] h-[clamp(36px,12%,64px)] w-[4px] rounded-r-[3px] border border-l-0 border-black/70 bg-[#343439] shadow-[inset_-1px_0_0_rgba(255,255,255,0.14)]"})]}):m.jsxs(m.Fragment,{children:[m.jsx("span",{className:"absolute -top-[4px] left-[16%] h-[4px] w-[clamp(12px,4%,22px)] rounded-t-[3px] border border-b-0 border-black/70 bg-[#343439] shadow-[inset_0_1px_0_rgba(255,255,255,0.14)]"}),m.jsx("span",{className:"absolute -top-[4px] left-[23%] h-[4px] w-[clamp(24px,7%,42px)] rounded-t-[3px] border border-b-0 border-black/70 bg-[#343439] shadow-[inset_0_1px_0_rgba(255,255,255,0.14)]"}),m.jsx("span",{className:"absolute -top-[4px] left-[32%] h-[4px] w-[clamp(24px,7%,42px)] rounded-t-[3px] border border-b-0 border-black/70 bg-[#343439] shadow-[inset_0_1px_0_rgba(255,255,255,0.14)]"}),m.jsx("span",{className:"absolute -bottom-[4px] left-[28%] h-[4px] w-[clamp(36px,12%,64px)] rounded-b-[3px] border border-t-0 border-black/70 bg-[#343439] shadow-[inset_0_-1px_0_rgba(255,255,255,0.14)]"})]})]}):m.jsxs("div",{"aria-hidden":"true","data-slot":"device-preview-device-chrome","data-platform":"android","data-orientation":t,className:Ye("pointer-events-none absolute -inset-[9px] z-0 select-none rounded-[calc(var(--device-screen-radius)+9px)] border border-black/70 bg-[linear-gradient(145deg,#68717a_0%,#22272d_22%,#08090b_58%,#454c55_100%)] ring-1 ring-white/15"),children:[m.jsx("span",{className:Ye("absolute rounded-full bg-white/25 shadow-sm",n?"left-1/2 top-[3px] h-px w-[14%] -translate-x-1/2":"left-[3px] top-1/2 h-[14%] w-px -translate-y-1/2")}),n?m.jsxs(m.Fragment,{children:[m.jsx("span",{className:"absolute -right-[4px] top-[20%] h-[14%] min-h-7 w-[3px] rounded-r-sm bg-slate-500 shadow-sm"}),m.jsx("span",{className:"absolute -right-[4px] top-[38%] h-[9%] min-h-4 w-[3px] rounded-r-sm bg-slate-400 shadow-sm"})]}):m.jsxs(m.Fragment,{children:[m.jsx("span",{className:"absolute -top-[4px] left-[20%] h-[3px] w-[14%] min-w-7 rounded-t-sm bg-slate-500 shadow-sm"}),m.jsx("span",{className:"absolute -top-[4px] left-[38%] h-[3px] w-[9%] min-w-4 rounded-t-sm bg-slate-400 shadow-sm"})]})]})}const zd=b7([{path:"/",element:m.jsx(ISe,{}),children:[{index:!0,element:m.jsx(OSe,{})},{path:"sessions",element:m.jsx(LSe,{})},{path:"chat/:id",element:m.jsx(sOe,{})},{path:"preview/device/:id",element:m.jsx(qOe,{})}]},{path:"/pty-test",element:m.jsx(uOe,{})},{path:"/tokens",element:m.jsx(gOe,{})},{path:"/markdown-test",element:m.jsx(yOe,{})}]);function YOe({browserName:e}){const[t,n]=b.useState("idle"),r=async()=>{const i=await Ap(window.location.href,{allowUserGestureFallback:!0});n(i==="failed"?"failed":"copied")};return m.jsxs("div",{className:"flex min-h-[100dvh] flex-col overflow-hidden bg-background text-foreground","data-slot":"unsupported-ipad-browser",children:[m.jsx("header",{className:"mx-auto flex w-full max-w-5xl items-center px-6 py-5 sm:px-10",children:m.jsx(Cz,{className:"text-sm",slot:"unsupported-browser-brand"})}),m.jsx("main",{className:"mx-auto flex w-full max-w-5xl flex-1 items-center px-6 pb-20 sm:px-10 sm:pb-24",children:m.jsxs("section",{className:"max-w-xl","aria-labelledby":"unsupported-browser-title",children:[m.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[m.jsx(pV,{className:"size-4 text-primary","aria-hidden":"true"}),m.jsx("span",{children:"iPad 浏览器支持"})]}),m.jsx("h1",{id:"unsupported-browser-title",className:"mt-4 text-3xl font-semibold tracking-normal sm:text-4xl",children:"请使用 Safari 打开"}),m.jsxs("p",{className:"mt-4 max-w-lg text-base leading-7 text-muted-foreground",children:["DEV Anywhere 暂不支持 iPad 上的 ",e,"。当前版本仅支持 Safari,以保证终端输入和实体键盘行为稳定。"]}),m.jsxs("div",{className:"mt-7 flex flex-wrap items-center gap-3",children:[m.jsxs(gt,{className:"h-11 px-4",onClick:r,children:[t==="copied"?m.jsx(Co,{className:"size-4","aria-hidden":"true"}):m.jsx(QB,{className:"size-4","aria-hidden":"true"}),t==="copied"?"链接已复制":"复制当前链接"]}),m.jsx("span",{className:"text-sm text-muted-foreground","aria-live":"polite",children:t==="copied"?"请切换到 Safari 后粘贴打开":t==="failed"?"复制失败,请从地址栏复制":"复制后在 Safari 中打开"})]})]})})]})}function KOe({children:e}){const t=PSe();return t.supported?e:m.jsx(YOe,{browserName:t.browserName})}function GOe(){return m.jsx(KOe,{children:m.jsx(XOe,{})})}function XOe(){return Zie(),m.jsx(Kue,{delayDuration:200,children:m.jsx(Uq,{router:zd})})}function ZOe(e=window.history){e.scrollRestoration="manual"}ZOe();QK();phe();sW.createRoot(document.getElementById("root")).render(m.jsx(b.StrictMode,{children:m.jsx(GOe,{})}));export{H6 as _,Vp as a,JOe as g};