@dev-anywhere/relay 0.6.3 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/web/assets/{fvad-BQ0eMlem.js → fvad-DQYOSZdE.js} +1 -1
- package/assets/web/assets/{index-BwXMl6yi.js → index-WMCumAhu.js} +3 -3
- package/assets/web/index.html +1 -1
- package/assets/web/sw.js +1 -1
- package/dist/{chunk-SDL4V2RE.js → chunk-6RWN2VEX.js} +17 -9
- package/dist/chunk-6RWN2VEX.js.map +1 -0
- package/dist/handlers/proxy.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/registry.d.ts +2 -1
- package/dist/registry.d.ts.map +1 -1
- package/dist/server.js +1 -1
- package/package.json +2 -2
- package/dist/chunk-SDL4V2RE.js.map +0 -1
|
@@ -476,7 +476,7 @@ Please change the parent <Route path="${S}"> to <Route path="${S==="/"?"*":`${S}
|
|
|
476
476
|
|
|
477
477
|
`)}g.write("payload.value = newResult;"),g.write("return payload;");const k=g.compile();return(R,P)=>k(y,R,P)};let s;const o=Ph,l=!vI.jitless,d=l&&pY.value,f=t.catchall;let p;e._zod.parse=(y,g)=>{p??(p=r.value);const b=y.value;return o(b)?l&&d&&(g==null?void 0:g.async)===!1&&g.jitless!==!0?(s||(s=i(t.shape)),y=s(y,g),f?OI([],b,y,g,p,e):y):n(y,g):(y.issues.push({expected:"object",code:"invalid_type",input:b,inst:e}),y)}});function mM(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=>!Zu(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=>_l(o,r,bl())))}),t)}const DI=He("$ZodUnion",(e,t)=>{kr.init(e,t),Xn(e._zod,"optin",()=>t.options.some(i=>i._zod.optin==="optional")?"optional":void 0),Xn(e._zod,"optout",()=>t.options.some(i=>i._zod.optout==="optional")?"optional":void 0),Xn(e._zod,"values",()=>{if(t.options.every(i=>i._zod.values))return new Set(t.options.flatMap(i=>Array.from(i._zod.values)))}),Xn(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=>x1(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=>mM(u,i,e,s)):mM(l,i,e,s)}}),eK=He("$ZodDiscriminatedUnion",(e,t)=>{t.inclusive=!1,DI.init(e,t);const n=e._zod.parse;Xn(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=Wv(()=>{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(!Ph(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)}}),tK=He("$ZodIntersection",(e,t)=>{kr.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])=>gM(n,u,d)):gM(n,s,o)}});function X0(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(dd(e)&&dd(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=X0(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=X0(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 gM(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}),Zu(e))return e;const o=X0(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 nK=He("$ZodRecord",(e,t)=>{kr.init(e,t),e._zod.parse=(n,r)=>{const i=n.value;if(!dd(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(...Qu(d,p.issues)),n.value[d]=p.value})):(f.issues.length&&n.issues.push(...Qu(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"&&TI.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=>_l(p,r,bl())),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(...Qu(l,p.issues)),n.value[u.value]=p.value})):(f.issues.length&&n.issues.push(...Qu(l,f.issues)),n.value[u.value]=f.value)}}return s.length?Promise.all(s).then(()=>n):n}}),rK=He("$ZodEnum",(e,t)=>{kr.init(e,t);const n=yI(t.entries),r=new Set(n);e._zod.values=r,e._zod.pattern=new RegExp(`^(${n.filter(i=>mY.has(typeof i)).map(i=>typeof i=="string"?fd(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}}),iK=He("$ZodLiteral",(e,t)=>{if(kr.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"?fd(r):r?fd(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}}),sK=He("$ZodTransform",(e,t)=>{kr.init(e,t),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new gI(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 sd;return n.value=i,n}});function vM(e,t){return e.issues.length&&t===void 0?{issues:[],value:void 0}:e}const II=He("$ZodOptional",(e,t)=>{kr.init(e,t),e._zod.optin="optional",e._zod.optout="optional",Xn(e._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Xn(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${x1(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=>vM(s,n.value)):vM(i,n.value)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),oK=He("$ZodExactOptional",(e,t)=>{II.init(e,t),Xn(e._zod,"values",()=>t.innerType._zod.values),Xn(e._zod,"pattern",()=>t.innerType._zod.pattern),e._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),aK=He("$ZodNullable",(e,t)=>{kr.init(e,t),Xn(e._zod,"optin",()=>t.innerType._zod.optin),Xn(e._zod,"optout",()=>t.innerType._zod.optout),Xn(e._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${x1(n.source)}|null)$`):void 0}),Xn(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)}),lK=He("$ZodDefault",(e,t)=>{kr.init(e,t),e._zod.optin="optional",Xn(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=>yM(s,t)):yM(i,t)}});function yM(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const cK=He("$ZodPrefault",(e,t)=>{kr.init(e,t),e._zod.optin="optional",Xn(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))}),uK=He("$ZodNonOptional",(e,t)=>{kr.init(e,t),Xn(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=>bM(s,e)):bM(i,e)}});function bM(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 dK=He("$ZodCatch",(e,t)=>{kr.init(e,t),Xn(e._zod,"optin",()=>t.innerType._zod.optin),Xn(e._zod,"optout",()=>t.innerType._zod.optout),Xn(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=>_l(o,r,bl()))},input:n.value}),n.issues=[]),n)):(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(s=>_l(s,r,bl()))},input:n.value}),n.issues=[]),n)}}),fK=He("$ZodPipe",(e,t)=>{kr.init(e,t),Xn(e._zod,"values",()=>t.in._zod.values),Xn(e._zod,"optin",()=>t.in._zod.optin),Xn(e._zod,"optout",()=>t.out._zod.optout),Xn(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=>Vm(o,t.in,r)):Vm(s,t.in,r)}const i=t.in._zod.run(n,r);return i instanceof Promise?i.then(s=>Vm(s,t.out,r)):Vm(i,t.out,r)}});function Vm(e,t,n){return e.issues.length?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const hK=He("$ZodReadonly",(e,t)=>{kr.init(e,t),Xn(e._zod,"propValues",()=>t.innerType._zod.propValues),Xn(e._zod,"values",()=>t.innerType._zod.values),Xn(e._zod,"optin",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),Xn(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(_M):_M(i)}});function _M(e){return e.value=Object.freeze(e.value),e}const pK=He("$ZodCustom",(e,t)=>{rs.init(e,t),kr.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=>wM(s,n,r,e));wM(i,n,r,e)}});function wM(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(Lh(i))}}var SM;class mK{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 gK(){return new mK}(SM=globalThis).__zod_globalRegistry??(SM.__zod_globalRegistry=gK());const th=globalThis.__zod_globalRegistry;function vK(e,t){return new e({type:"string",...Wt(t)})}function yK(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...Wt(t)})}function xM(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...Wt(t)})}function bK(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...Wt(t)})}function _K(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Wt(t)})}function wK(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Wt(t)})}function SK(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Wt(t)})}function xK(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...Wt(t)})}function EK(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...Wt(t)})}function CK(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...Wt(t)})}function kK(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...Wt(t)})}function TK(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...Wt(t)})}function RK(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...Wt(t)})}function AK(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...Wt(t)})}function MK(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...Wt(t)})}function NK(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...Wt(t)})}function PK(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...Wt(t)})}function LK(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Wt(t)})}function OK(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Wt(t)})}function DK(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...Wt(t)})}function IK(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...Wt(t)})}function BK(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...Wt(t)})}function zK(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...Wt(t)})}function jK(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Wt(t)})}function $K(e,t){return new e({type:"string",format:"date",check:"string_format",...Wt(t)})}function FK(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...Wt(t)})}function HK(e,t){return new e({type:"string",format:"duration",check:"string_format",...Wt(t)})}function UK(e,t){return new e({type:"number",checks:[],...Wt(t)})}function WK(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...Wt(t)})}function qK(e,t){return new e({type:"boolean",...Wt(t)})}function YK(e){return new e({type:"unknown"})}function VK(e,t){return new e({type:"never",...Wt(t)})}function EM(e,t){return new AI({check:"less_than",...Wt(t),value:e,inclusive:!1})}function tw(e,t){return new AI({check:"less_than",...Wt(t),value:e,inclusive:!0})}function CM(e,t){return new MI({check:"greater_than",...Wt(t),value:e,inclusive:!1})}function nw(e,t){return new MI({check:"greater_than",...Wt(t),value:e,inclusive:!0})}function kM(e,t){return new lV({check:"multiple_of",...Wt(t),value:e})}function BI(e,t){return new uV({check:"max_length",...Wt(t),maximum:e})}function uv(e,t){return new dV({check:"min_length",...Wt(t),minimum:e})}function zI(e,t){return new fV({check:"length_equals",...Wt(t),length:e})}function KK(e,t){return new hV({check:"string_format",format:"regex",...Wt(t),pattern:e})}function GK(e){return new pV({check:"string_format",format:"lowercase",...Wt(e)})}function XK(e){return new mV({check:"string_format",format:"uppercase",...Wt(e)})}function ZK(e,t){return new gV({check:"string_format",format:"includes",...Wt(t),includes:e})}function QK(e,t){return new vV({check:"string_format",format:"starts_with",...Wt(t),prefix:e})}function JK(e,t){return new yV({check:"string_format",format:"ends_with",...Wt(t),suffix:e})}function Cd(e){return new bV({check:"overwrite",tx:e})}function eG(e){return Cd(t=>t.normalize(e))}function tG(){return Cd(e=>e.trim())}function nG(){return Cd(e=>e.toLowerCase())}function rG(){return Cd(e=>e.toUpperCase())}function iG(){return Cd(e=>hY(e))}function sG(e,t,n){return new e({type:"array",element:t,...Wt(n)})}function oG(e,t,n){return new e({type:"custom",check:"custom",fn:t,...Wt(n)})}function aG(e){const t=lG(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(Lh(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(Lh(i))}},e(n.value,n)));return t}function lG(e,t){const n=new rs({check:"custom",...Wt(t)});return n._zod.check=e,n}function jI(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)??th,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 Kr(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 b=o.schema,w=t.processors[i.type];if(!w)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);w(e,t,b,y)}const g=e._zod.parent;g&&(o.ref||(o.ref=g),Kr(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"&&zi(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 $I(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 S=(w=e.external.registry.get(f[0]))==null?void 0:w.id,E=e.external.uri??(T=>T);if(S)return{ref:E(S)};const k=f[1].defId??f[1].schema.id??`schema${e.counter++}`;return f[1].defId=k,{defId:k,ref:`${E("__shared")}#/${p}/${k}`}}if(f[1]===n)return{ref:"#"};const g=`#/${p}/`,b=f[1].schema.id??`__schema${e.counter++}`;return{defId:b,ref:g+b}},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 b=p.schema;for(const w in b)delete b[w];b.$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>
|
|
478
478
|
|
|
479
|
-
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 FI(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),S=w.schema;if(S.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(p.allOf=p.allOf??[],p.allOf.push(S)):Object.assign(p,S),Object.assign(p,y),d._zod.parent===g)for(const k in p)k==="$ref"||k==="allOf"||k in y||delete p[k];if(S.$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 b=d._zod.parent;if(b&&b!==g){r(b);const w=e.seen.get(b);if(w!=null&&w.schema.$ref&&(p.$ref=w.schema.$ref,w.def))for(const S in p)S==="$ref"||S==="allOf"||S in w.def&&JSON.stringify(p[S])===JSON.stringify(w.def[S])&&delete p[S]}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:dv(t,"input",e.processors),output:dv(t,"output",e.processors)}},enumerable:!1,writable:!1}),d}catch{throw new Error("Error converting schema to JSON.")}}function zi(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 zi(r.element,n);if(r.type==="set")return zi(r.valueType,n);if(r.type==="lazy")return zi(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 zi(r.innerType,n);if(r.type==="intersection")return zi(r.left,n)||zi(r.right,n);if(r.type==="record"||r.type==="map")return zi(r.keyType,n)||zi(r.valueType,n);if(r.type==="pipe")return zi(r.in,n)||zi(r.out,n);if(r.type==="object"){for(const i in r.shape)if(zi(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(zi(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(zi(i,n))return!0;return!!(r.rest&&zi(r.rest,n))}return!1}const cG=(e,t={})=>n=>{const r=jI({...n,processors:t});return Kr(e,r),$I(r,e),FI(r,e)},dv=(e,t,n={})=>r=>{const{libraryOptions:i,target:s}=r??{},o=jI({...i??{},target:s,io:t,processors:n});return Kr(e,o),$I(o,e),FI(o,e)},uG={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},dG=(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=uG[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}))])}},fG=(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)},hG=(e,t,n,r)=>{n.type="boolean"},pG=(e,t,n,r)=>{n.not={}},mG=(e,t,n,r)=>{},gG=(e,t,n,r)=>{const i=e._zod.def,s=yI(i.entries);s.every(o=>typeof o=="number")&&(n.type="number"),s.every(o=>typeof o=="string")&&(n.type="string"),n.enum=s},vG=(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},yG=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},bG=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},_G=(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=Kr(s.element,t,{...r,path:[...r.path,"items"]})},wG=(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]=Kr(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=Kr(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},SG=(e,t,n,r)=>{const i=e._zod.def,s=i.inclusive===!1,o=i.options.map((l,u)=>Kr(l,t,{...r,path:[...r.path,s?"oneOf":"anyOf",u]}));s?n.oneOf=o:n.anyOf=o},xG=(e,t,n,r)=>{const i=e._zod.def,s=Kr(i.left,t,{...r,path:[...r.path,"allOf",0]}),o=Kr(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},EG=(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=Kr(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=Kr(s.keyType,t,{...r,path:[...r.path,"propertyNames"]})),i.additionalProperties=Kr(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)}},CG=(e,t,n,r)=>{const i=e._zod.def,s=Kr(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"}]},kG=(e,t,n,r)=>{const i=e._zod.def;Kr(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType},TG=(e,t,n,r)=>{const i=e._zod.def;Kr(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},RG=(e,t,n,r)=>{const i=e._zod.def;Kr(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)))},AG=(e,t,n,r)=>{const i=e._zod.def;Kr(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},MG=(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;Kr(s,t,r);const o=t.seen.get(e);o.ref=s},NG=(e,t,n,r)=>{const i=e._zod.def;Kr(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType,n.readOnly=!0},HI=(e,t,n,r)=>{const i=e._zod.def;Kr(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType},PG=He("ZodISODateTime",(e,t)=>{LV.init(e,t),Rr.init(e,t)});function LG(e){return jK(PG,e)}const OG=He("ZodISODate",(e,t)=>{OV.init(e,t),Rr.init(e,t)});function DG(e){return $K(OG,e)}const IG=He("ZodISOTime",(e,t)=>{DV.init(e,t),Rr.init(e,t)});function BG(e){return FK(IG,e)}const zG=He("ZodISODuration",(e,t)=>{IV.init(e,t),Rr.init(e,t)});function jG(e){return HK(zG,e)}const $G=(e,t)=>{SI.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>kY(e,n)},flatten:{value:n=>CY(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,G0,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,G0,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ws=He("ZodError",$G,{Parent:Error}),FG=C1(Ws),HG=k1(Ws),UG=qv(Ws),WG=Yv(Ws),qG=AY(Ws),YG=MY(Ws),VG=NY(Ws),KG=PY(Ws),GG=LY(Ws),XG=OY(Ws),ZG=DY(Ws),QG=IY(Ws),Tr=He("ZodType",(e,t)=>(kr.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:dv(e,"input"),output:dv(e,"output")}}),e.toJSONSchema=cG(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(Nl(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)=>Pl(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>FG(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>UG(e,n,r),e.parseAsync=async(n,r)=>HG(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>WG(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>qG(e,n,r),e.decode=(n,r)=>YG(e,n,r),e.encodeAsync=async(n,r)=>VG(e,n,r),e.decodeAsync=async(n,r)=>KG(e,n,r),e.safeEncode=(n,r)=>GG(e,n,r),e.safeDecode=(n,r)=>XG(e,n,r),e.safeEncodeAsync=async(n,r)=>ZG(e,n,r),e.safeDecodeAsync=async(n,r)=>QG(e,n,r),e.refine=(n,r)=>e.check(YX(n,r)),e.superRefine=n=>e.check(VX(n)),e.overwrite=n=>e.check(Cd(n)),e.optional=()=>AM(e),e.exactOptional=()=>LX(e),e.nullable=()=>MM(e),e.nullish=()=>AM(MM(e)),e.nonoptional=n=>jX(e,n),e.array=()=>Br(e),e.or=n=>EX([e,n]),e.and=n=>TX(e,n),e.transform=n=>NM(e,NX(n)),e.default=n=>IX(e,n),e.prefault=n=>zX(e,n),e.catch=n=>FX(e,n),e.pipe=n=>NM(e,n),e.readonly=()=>WX(e),e.describe=n=>{const r=e.clone();return th.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){var n;return(n=th.get(e))==null?void 0:n.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return th.get(e);const r=e.clone();return th.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=n=>n(e),e)),UI=He("_ZodString",(e,t)=>{T1.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(r,i,s)=>dG(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(KK(...r)),e.includes=(...r)=>e.check(ZK(...r)),e.startsWith=(...r)=>e.check(QK(...r)),e.endsWith=(...r)=>e.check(JK(...r)),e.min=(...r)=>e.check(uv(...r)),e.max=(...r)=>e.check(BI(...r)),e.length=(...r)=>e.check(zI(...r)),e.nonempty=(...r)=>e.check(uv(1,...r)),e.lowercase=r=>e.check(GK(r)),e.uppercase=r=>e.check(XK(r)),e.trim=()=>e.check(tG()),e.normalize=(...r)=>e.check(eG(...r)),e.toLowerCase=()=>e.check(nG()),e.toUpperCase=()=>e.check(rG()),e.slugify=()=>e.check(iG())}),JG=He("ZodString",(e,t)=>{T1.init(e,t),UI.init(e,t),e.email=n=>e.check(yK(eX,n)),e.url=n=>e.check(xK(tX,n)),e.jwt=n=>e.check(zK(gX,n)),e.emoji=n=>e.check(EK(nX,n)),e.guid=n=>e.check(xM(TM,n)),e.uuid=n=>e.check(bK(Km,n)),e.uuidv4=n=>e.check(_K(Km,n)),e.uuidv6=n=>e.check(wK(Km,n)),e.uuidv7=n=>e.check(SK(Km,n)),e.nanoid=n=>e.check(CK(rX,n)),e.guid=n=>e.check(xM(TM,n)),e.cuid=n=>e.check(kK(iX,n)),e.cuid2=n=>e.check(TK(sX,n)),e.ulid=n=>e.check(RK(oX,n)),e.base64=n=>e.check(DK(hX,n)),e.base64url=n=>e.check(IK(pX,n)),e.xid=n=>e.check(AK(aX,n)),e.ksuid=n=>e.check(MK(lX,n)),e.ipv4=n=>e.check(NK(cX,n)),e.ipv6=n=>e.check(PK(uX,n)),e.cidrv4=n=>e.check(LK(dX,n)),e.cidrv6=n=>e.check(OK(fX,n)),e.e164=n=>e.check(BK(mX,n)),e.datetime=n=>e.check(LG(n)),e.date=n=>e.check(DG(n)),e.time=n=>e.check(BG(n)),e.duration=n=>e.check(jG(n))});function Be(e){return vK(JG,e)}const Rr=He("ZodStringFormat",(e,t)=>{yr.init(e,t),UI.init(e,t)}),eX=He("ZodEmail",(e,t)=>{EV.init(e,t),Rr.init(e,t)}),TM=He("ZodGUID",(e,t)=>{SV.init(e,t),Rr.init(e,t)}),Km=He("ZodUUID",(e,t)=>{xV.init(e,t),Rr.init(e,t)}),tX=He("ZodURL",(e,t)=>{CV.init(e,t),Rr.init(e,t)}),nX=He("ZodEmoji",(e,t)=>{kV.init(e,t),Rr.init(e,t)}),rX=He("ZodNanoID",(e,t)=>{TV.init(e,t),Rr.init(e,t)}),iX=He("ZodCUID",(e,t)=>{RV.init(e,t),Rr.init(e,t)}),sX=He("ZodCUID2",(e,t)=>{AV.init(e,t),Rr.init(e,t)}),oX=He("ZodULID",(e,t)=>{MV.init(e,t),Rr.init(e,t)}),aX=He("ZodXID",(e,t)=>{NV.init(e,t),Rr.init(e,t)}),lX=He("ZodKSUID",(e,t)=>{PV.init(e,t),Rr.init(e,t)}),cX=He("ZodIPv4",(e,t)=>{BV.init(e,t),Rr.init(e,t)}),uX=He("ZodIPv6",(e,t)=>{zV.init(e,t),Rr.init(e,t)}),dX=He("ZodCIDRv4",(e,t)=>{jV.init(e,t),Rr.init(e,t)}),fX=He("ZodCIDRv6",(e,t)=>{$V.init(e,t),Rr.init(e,t)}),hX=He("ZodBase64",(e,t)=>{FV.init(e,t),Rr.init(e,t)}),pX=He("ZodBase64URL",(e,t)=>{UV.init(e,t),Rr.init(e,t)}),mX=He("ZodE164",(e,t)=>{WV.init(e,t),Rr.init(e,t)}),gX=He("ZodJWT",(e,t)=>{YV.init(e,t),Rr.init(e,t)}),WI=He("ZodNumber",(e,t)=>{PI.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(r,i,s)=>fG(e,r,i),e.gt=(r,i)=>e.check(CM(r,i)),e.gte=(r,i)=>e.check(nw(r,i)),e.min=(r,i)=>e.check(nw(r,i)),e.lt=(r,i)=>e.check(EM(r,i)),e.lte=(r,i)=>e.check(tw(r,i)),e.max=(r,i)=>e.check(tw(r,i)),e.int=r=>e.check(RM(r)),e.safe=r=>e.check(RM(r)),e.positive=r=>e.check(CM(0,r)),e.nonnegative=r=>e.check(nw(0,r)),e.negative=r=>e.check(EM(0,r)),e.nonpositive=r=>e.check(tw(0,r)),e.multipleOf=(r,i)=>e.check(kM(r,i)),e.step=(r,i)=>e.check(kM(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 un(e){return UK(WI,e)}const vX=He("ZodNumberFormat",(e,t)=>{VV.init(e,t),WI.init(e,t)});function RM(e){return WK(vX,e)}const yX=He("ZodBoolean",(e,t)=>{KV.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>hG(e,n,r)});function Vn(e){return qK(yX,e)}const bX=He("ZodUnknown",(e,t)=>{GV.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>mG()});function ma(){return YK(bX)}const _X=He("ZodNever",(e,t)=>{XV.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>pG(e,n,r)});function wX(e){return VK(_X,e)}const SX=He("ZodArray",(e,t)=>{ZV.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_G(e,n,r,i),e.element=t.element,e.min=(n,r)=>e.check(uv(n,r)),e.nonempty=n=>e.check(uv(1,n)),e.max=(n,r)=>e.check(BI(n,r)),e.length=(n,r)=>e.check(zI(n,r)),e.unwrap=()=>e.element});function Br(e,t){return sG(SX,e,t)}const xX=He("ZodObject",(e,t)=>{JV.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wG(e,n,r,i),Xn(e,"shape",()=>t.shape),e.keyof=()=>tn(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ma()}),e.loose=()=>e.clone({...e._zod.def,catchall:ma()}),e.strict=()=>e.clone({...e._zod.def,catchall:wX()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>_Y(e,n),e.safeExtend=n=>wY(e,n),e.merge=n=>SY(e,n),e.pick=n=>yY(e,n),e.omit=n=>bY(e,n),e.partial=(...n)=>xY(YI,e,n[0]),e.required=(...n)=>EY(VI,e,n[0])});function It(e,t){const n={type:"object",shape:e??{},...Wt(t)};return new xX(n)}const qI=He("ZodUnion",(e,t)=>{DI.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SG(e,n,r,i),e.options=t.options});function EX(e,t){return new qI({type:"union",options:e,...Wt(t)})}const CX=He("ZodDiscriminatedUnion",(e,t)=>{qI.init(e,t),eK.init(e,t)});function rp(e,t,n){return new CX({type:"union",options:t,discriminator:e,...Wt(n)})}const kX=He("ZodIntersection",(e,t)=>{tK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xG(e,n,r,i)});function TX(e,t){return new kX({type:"intersection",left:e,right:t})}const RX=He("ZodRecord",(e,t)=>{nK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EG(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function hd(e,t,n){return new RX({type:"record",keyType:e,valueType:t,...Wt(n)})}const Z0=He("ZodEnum",(e,t)=>{rK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(r,i,s)=>gG(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 Z0({...t,checks:[],...Wt(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 Z0({...t,checks:[],...Wt(i),entries:s})}});function tn(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Z0({type:"enum",entries:n,...Wt(t)})}const AX=He("ZodLiteral",(e,t)=>{iK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vG(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 ur(e,t){return new AX({type:"literal",values:Array.isArray(e)?e:[e],...Wt(t)})}const MX=He("ZodTransform",(e,t)=>{sK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bG(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new gI(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(Lh(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(Lh(o))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(s=>(n.value=s,n)):(n.value=i,n)}});function NX(e){return new MX({type:"transform",transform:e})}const YI=He("ZodOptional",(e,t)=>{II.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>HI(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function AM(e){return new YI({type:"optional",innerType:e})}const PX=He("ZodExactOptional",(e,t)=>{oK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>HI(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function LX(e){return new PX({type:"optional",innerType:e})}const OX=He("ZodNullable",(e,t)=>{aK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CG(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function MM(e){return new OX({type:"nullable",innerType:e})}const DX=He("ZodDefault",(e,t)=>{lK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TG(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function IX(e,t){return new DX({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():_I(t)}})}const BX=He("ZodPrefault",(e,t)=>{cK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RG(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function zX(e,t){return new BX({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():_I(t)}})}const VI=He("ZodNonOptional",(e,t)=>{uK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kG(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function jX(e,t){return new VI({type:"nonoptional",innerType:e,...Wt(t)})}const $X=He("ZodCatch",(e,t)=>{dK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>AG(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function FX(e,t){return new $X({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const HX=He("ZodPipe",(e,t)=>{fK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MG(e,n,r,i),e.in=t.in,e.out=t.out});function NM(e,t){return new HX({type:"pipe",in:e,out:t})}const UX=He("ZodReadonly",(e,t)=>{hK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>NG(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function WX(e){return new UX({type:"readonly",innerType:e})}const qX=He("ZodCustom",(e,t)=>{pK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yG(e,n)});function YX(e,t={}){return oG(qX,e,t)}function VX(e){return aG(e)}const KX=256,ft=Be().min(1).max(KX),GX=It({text:Be().min(1),messageId:Be().min(1).optional()}),XX=It({turnId:Be().min(1).max(256),revision:un().int().positive(),text:Be(),status:tn(["streaming","completed"])}),ZX=It({text:Be()}),PM=It({toolName:Be(),toolId:ft,parameters:hd(Be(),ma())}),QX=It({toolId:ft,whitelistTool:Vn().optional()}),JX=It({toolId:ft,reason:Be().optional()}),eZ=It({toolId:ft,result:ma(),isError:Vn()}),hl=["claude","codex"],Q0=["local-terminal","proxy-hosted"],vh=["pty","json"],Bg=["agent","terminal"],rw={WORKING:"working",TURN_COMPLETE:"turn_complete",APPROVAL_WAIT:"approval_wait"},tZ=[rw.WORKING,rw.TURN_COMPLETE,rw.APPROVAL_WAIT],zg=80,J0=24,KI=500,GI=200,R1=["idle","working","compacting","waiting_approval","error","terminated"],nZ=["idle","thinking","tool_use","outputting","waiting_permission","error"],rZ=It({sessionId:ft,kind:tn(Bg).optional(),name:Be().optional(),cwd:Be().optional(),nameLocked:Vn().optional(),state:tn(R1),mode:tn(vh).optional(),provider:tn(hl),ptyOwner:tn(Q0).optional(),lastActive:un().optional()}),iZ=It({name:Be().optional(),cwd:Be().optional(),streamDelta:Vn().optional()}),sZ=It({sessions:Br(rZ)}),oZ=It({sessionId:ft}),aZ=It({sessionId:ft}),lZ=It({sessionId:ft,state:tn(R1),lastActive:un()}),cZ=It({state:tn(tZ),seq:un().int().nonnegative().optional(),title:Be().optional(),tool:Be().optional()}),LM=It({provider:tn(hl),phase:tn(nZ),seq:un().int().nonnegative(),updatedAt:un(),toolName:Be().optional(),toolInput:hd(Be(),ma()).optional(),permissionRequest:It({requestId:ft,toolName:Be(),input:hd(Be(),ma())}).optional(),permissionResolution:It({requestId:ft,outcome:tn(["allow","deny"])}).optional(),summary:Be().optional()}),uZ=It({}),dZ=It({pairingCode:Be().optional(),token:Be().optional()}),fZ=It({lastSeq:un().int().nonnegative()}),hZ=It({messages:Br(hd(Be(),ma()))}),Uu={seq:un().int().nonnegative(),timestamp:un(),source:tn(["proxy","client"]),version:Be()},ho={...Uu,sessionId:ft};rp("type",[It({...ho,type:ur("user_input"),payload:GX}),It({...ho,type:ur("assistant_message"),payload:XX}),It({...ho,type:ur("thinking"),payload:ZX}),It({...ho,type:ur("tool_use_request"),payload:PM}),It({...ho,type:ur("tool_result"),payload:eZ}),It({...ho,type:ur("assistant_tool_use"),payload:PM}),It({...ho,type:ur("session_create"),payload:iZ}),It({...Uu,type:ur("session_list"),payload:sZ}),It({...ho,type:ur("session_switch"),payload:oZ}),It({...ho,type:ur("session_terminate"),payload:aZ}),It({...ho,type:ur("session_status"),payload:lZ}),It({...Uu,type:ur("heartbeat"),payload:uZ}),It({...Uu,type:ur("auth"),payload:dZ}),It({...Uu,type:ur("sync_request"),payload:fZ}),It({...Uu,type:ur("sync_response"),payload:hZ})]);const XI=["aliyun-bailian"],A1=["cn","intl"],pZ=["official","custom"],mZ=["male","female","unknown"],OM=It({provider:tn(XI),configured:Vn(),region:tn(A1),asrModel:Be().min(1),ttsModel:Be().min(1),ttsVoice:Be().min(1),turnIdleSeconds:un().int().positive().safe().default(3)}).strict(),DM=It({provider:tn(XI).optional(),apiKey:Be().min(1).optional(),clearApiKey:Vn().optional(),region:tn(A1).optional(),asrModel:Be().min(1).optional(),ttsModel:Be().min(1).optional(),ttsVoice:Be().min(1).optional(),turnIdleSeconds:un().int().positive().safe().optional()}).strict(),iw=It({value:Be().min(1),label:Be().min(1),description:Be().min(1).optional(),gender:tn(mZ).optional(),age:Be().min(1).optional(),model:Be().min(1).optional(),source:tn(pZ)}).strict(),gZ=It({asrModels:Br(iw),ttsModels:Br(iw),ttsVoices:Br(iw),fetchedAt:un().optional()}).strict(),vZ=[{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"}],yZ=[{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"}],bZ=[{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 sw(e){return{...e}}function Gm(e){return{asrModels:vZ.map(sw),ttsModels:yZ.map(sw),ttsVoices:bZ.map(sw)}}const _Z=tn(["code","table","diff","log","stack_trace","long_list","long_text","mixed","approval"]),wZ=tn(["pcm_s16le","mulaw"]),SZ=It({type:ur("start"),sessionId:Be().min(1),attemptId:Be().min(1),sampleRate:un().int().positive(),encoding:wZ}),xZ=It({type:ur("stop"),attemptId:Be().min(1)});rp("type",[SZ,xZ]);const EZ=rp("type",[It({type:ur("ready"),attemptId:Be().min(1)}),It({type:ur("audio_ack"),attemptId:Be().min(1),encodedBytes:un().int().nonnegative(),pcmBytes:un().int().nonnegative(),chunks:un().int().nonnegative()}),It({type:ur("partial"),attemptId:Be().min(1),text:Be()}),It({type:ur("final"),attemptId:Be().min(1),text:Be()}),It({type:ur("closed"),attemptId:Be().min(1),code:un().int().optional(),reason:Be().optional()}),It({type:ur("error"),attemptId:Be().min(1),error:Be().optional(),errorCode:Be().optional()})]);function IM(e){return/^\/compact(?:\s|$)/.test(e.trimStart())}const CZ=/((?:authorization|api[_-]?key|token|password|secret)\s*[:=]\s*)(?:bearer\s+)?[^\s'"]+/giu,kZ=/(--(?:api-key|token|password|secret)(?:=|\s+))[^\s'"]+/giu;function la(e){return typeof e=="string"?e:""}function xu(e,t=140){const n=e.replace(/\s+/gu," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Eu(e){return e.replace(CZ,"$1[redacted]").replace(kZ,"$1[redacted]")}function oc(e){return la(e.file_path)||la(e.path)||la(e.notebook_path)}function TZ(e,t){switch(e){case"Bash":{const n=xu(Eu(la(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=xu(Eu(la(t.input)),80);return n?`发送终端输入:${n}`:"发送终端输入"}case"Read":{const n=oc(t);return n?`读取文件:${n}`:"读取文件"}case"Write":{const n=oc(t);return n?`写入文件:${n}`:"写入文件"}case"Edit":case"MultiEdit":{const n=oc(t);return n?`编辑文件:${n}`:"编辑文件"}case"LS":{const n=oc(t);return n?`列出目录:${n}`:"列出目录"}case"Grep":{const n=xu(Eu(la(t.pattern)),80),r=oc(t);return n&&r?`搜索:${n} in ${r}`:n?`搜索:${n}`:"搜索文本"}case"Glob":{const n=xu(Eu(la(t.pattern)),80);return n?`查找文件:${n}`:"查找文件"}case"WebFetch":{const n=xu(Eu(la(t.url)),100);return n?`读取网页:${n}`:"读取网页"}case"WebSearch":{const n=xu(Eu(la(t.query)),100);return n?`网页搜索:${n}`:"网页搜索"}case"ViewImage":{const n=oc(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=oc(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 RZ={NOT_REGISTERED:"NOT_REGISTERED",NOT_BOUND:"NOT_BOUND",PROXY_OFFLINE:"PROXY_OFFLINE",INVALID_MESSAGE:"INVALID_MESSAGE",UNSUPPORTED:"UNSUPPORTED",INVALID_RANGE:"INVALID_RANGE"},zr={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",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",UNKNOWN:"UNKNOWN"},AZ=It({proxyId:ft,name:Be().optional(),online:Vn(),sessions:Br(Be()).optional()}),MZ=It({clientId:ft,proxyId:ft.optional(),connectedAt:un().int().nonnegative(),current:Vn().optional(),userAgent:Be().optional(),platform:Be().optional(),maxTouchPoints:un().int().nonnegative().optional(),browserName:Be().min(1),osName:Be().min(1),deviceKind:tn(["desktop","tablet","phone","unknown"]),remoteAddress:Be().optional()}),BM=It({available:Vn(),command:Be().optional(),error:Be().optional(),suggestions:Br(Be()).optional()}),zM=It({claude:BM,codex:BM}),ZI=It({name:Be(),isDir:Vn()}),jM=It({path:Be(),entries:Br(ZI)}),$M=It({name:Be(),description:Be(),argumentHint:Be().optional(),source:Be()}),NZ=It({id:Be(),title:Be(),projectDir:Be(),updatedAt:un(),provider:tn(hl).optional(),preferredMode:tn(vh).optional()}),FM={timestamp:un().optional(),cursor:Be().optional()},PZ=rp("role",[It({role:tn(["user","assistant","system"]),text:Be(),...FM}),It({role:ur("activity"),text:Be(),toolId:ft,toolName:Be(),parameters:hd(Be(),ma()).optional(),status:tn(["running","done","error"]),...FM})]),jn={requestId:ft.optional()},ii={requestId:ft},QI=tn(Object.values(zr)),Ur={error:Be().optional(),errorCode:QI.optional()},HM=tn(["inline","download"]),UM=tn(["clipboard_image","file"]);function rt(e,t,n){return{type:e,directions:new Set(Array.isArray(n)?n:n?[n]:[]),schema:It({type:ur(e),...t??{}})}}const M1=[rt("proxy_register",{proxyId:ft,name:Be().optional()}),rt("proxy_register_response",{status:tn(["new","reconnected"])}),rt("proxy_list_request",jn),rt("proxy_list_response",{...jn,proxies:Br(AZ)}),rt("relay_client_list_request",jn),rt("relay_client_list_response",{...jn,clients:Br(MZ)}),rt("relay_client_kick",{...ii,clientId:ft}),rt("relay_client_kick_response",{...ii,clientId:ft,success:Vn(),...Ur}),rt("relay_client_kicked",{reason:Be().optional()}),rt("remote_file_url_request",{...ii,sessionId:ft,path:Be().min(1),disposition:HM}),rt("remote_file_url_response",{...ii,...Ur,sessionId:ft,path:Be().optional(),success:Vn(),url:Be().optional(),expiresAt:un().int().nonnegative().optional()}),rt("remote_file_metadata_request",{...ii,sessionId:ft,path:Be().min(1)}),rt("remote_file_metadata_response",{...ii,...Ur,sessionId:ft,path:Be().optional(),success:Vn(),mimeType:Be().optional(),size:un().int().nonnegative().optional(),fileName:Be().optional()}),rt("remote_file_stream_request",{streamId:ft,sessionId:ft,path:Be().min(1),disposition:HM}),rt("remote_file_stream_response",{...Ur,streamId:ft,sessionId:ft,success:Vn(),path:Be().optional(),mimeType:Be().optional(),size:un().int().nonnegative().optional(),fileName:Be().optional()}),rt("remote_file_stream_complete",{...Ur,streamId:ft,success:Vn()}),rt("remote_file_stream_cancel",{streamId:ft}),rt("remote_file_upload_url_request",{...ii,sessionId:ft,kind:UM,fileName:Be().optional(),mimeType:Be().min(1),size:un().int().nonnegative().optional()}),rt("remote_file_upload_url_response",{...ii,...Ur,sessionId:ft,success:Vn(),uploadUrl:Be().optional(),expiresAt:un().int().nonnegative().optional()}),rt("remote_file_upload_stream_request",{uploadId:ft,sessionId:ft,kind:UM,fileName:Be().optional(),mimeType:Be().min(1),size:un().int().nonnegative().optional()}),rt("remote_file_upload_stream_complete",{uploadId:ft}),rt("remote_file_upload_stream_cancel",{uploadId:ft}),rt("remote_file_upload_stream_response",{...Ur,uploadId:ft,sessionId:ft,success:Vn(),path:Be().optional()}),rt("proxy_select",{...jn,proxyId:ft}),rt("proxy_select_response",{...jn,success:Vn(),proxyId:ft.optional(),...Ur}),rt("relay_error",{code:tn(Object.values(RZ)),message:Be(),requestId:ft.optional()}),rt("voice_config_request",jn),rt("voice_config_response",{...jn,...Ur,config:OM.optional()}),rt("voice_config_update",{...jn,config:DM}),rt("voice_config_update_response",{...jn,...Ur,success:Vn(),config:OM.optional()}),rt("voice_config_test",{...jn,config:DM.optional()}),rt("voice_config_test_response",{...jn,...Ur,success:Vn(),audioBase64:Be().optional(),audioSampleRate:un().int().positive().optional(),audioEncoding:ur("pcm_s16le").optional(),transcript:Be().optional()}),rt("voice_capabilities_request",{...jn,region:tn(A1).optional()}),rt("voice_capabilities_response",{...jn,...Ur,capabilities:gZ.optional()}),rt("latency_web_relay_ping",ii),rt("latency_web_relay_pong",{...ii,relayNow:un().optional()}),rt("latency_relay_proxy_request",ii),rt("latency_relay_proxy_response",{...ii,success:Vn(),rttMs:un().nonnegative().optional(),error:Be().optional()}),rt("latency_relay_proxy_ping",{...ii,relayNow:un().optional()}),rt("latency_relay_proxy_pong",{...ii,proxyNow:un().optional()}),rt("latency_web_proxy_ping",ii,"client_to_proxy"),rt("latency_web_proxy_pong",{...ii,proxyNow:un().optional()},"proxy_to_client"),rt("client_register",{clientId:ft,userAgent:Be().optional(),platform:Be().optional(),maxTouchPoints:un().int().nonnegative().optional(),browserName:Be().min(1),osName:Be().min(1),deviceKind:tn(["desktop","tablet","phone","unknown"])}),rt("client_register_response",{status:tn(["restored","proxy_offline","new"]),proxyId:ft.optional()}),rt("proxy_offline",{proxyId:ft}),rt("proxy_disconnect",{proxyId:ft}),rt("proxy_online",{proxyId:ft}),rt("dir_list_request",{proxyId:ft.optional(),...jn,path:Be()},"client_to_proxy"),rt("dir_list_response",{...jn,...Ur,entries:Br(ZI),path:Be()},"proxy_to_client"),rt("dir_create_request",{...jn,path:Be()},"client_to_proxy"),rt("dir_create_response",{...jn,...Ur,path:Be(),success:Vn()},"proxy_to_client"),rt("command_list_push",{commands:Br($M)},"proxy_to_client"),rt("file_tree_push",{groups:Br(jM)},"proxy_to_client"),rt("session_list",void 0,["client_to_proxy","proxy_to_client"]),rt("permission_mode_change",{mode:tn(["default","auto_accept","plan"]),sessionId:ft.optional()},"client_to_proxy"),rt("session_history_request",ii,"client_to_proxy"),rt("session_history_response",{...ii,...Ur,success:Vn(),sessions:Br(NZ)},"proxy_to_client"),rt("pty_state",{sessionId:ft,payload:cZ},"proxy_to_client"),rt("agent_status",{sessionId:ft,payload:LM},"proxy_to_client"),rt("terminal_title",{sessionId:ft,title:Be()},"proxy_to_client"),rt("terminal_resize",{sessionId:ft,cols:un().int().positive(),rows:un().int().positive()},"proxy_to_client"),rt("terminal_resize_request",{sessionId:ft,cols:un().int().positive(),rows:un().int().positive()},"client_to_proxy"),rt("session_terminate",{sessionId:ft},"client_to_proxy"),rt("session_rename",{...jn,sessionId:ft,name:Be()},"client_to_proxy"),rt("session_rename_response",{...jn,sessionId:ft,success:Vn(),name:Be().optional(),...Ur},"proxy_to_client"),rt("session_worker_abort",{sessionId:ft},"client_to_proxy"),rt("turn_result",{sessionId:ft,success:Vn(),isError:Vn(),result:Be().optional()},"proxy_to_client"),rt("remote_input_raw",{sessionId:ft,data:Be(),traceId:ft.optional()},"client_to_proxy"),rt("proxy_info_request",jn,"client_to_proxy"),rt("proxy_info",{...jn,homePath:Be(),agentCli:zM},"proxy_to_client"),rt("agent_cli_config_update",{...jn,provider:tn(hl),path:Be().min(1)},"client_to_proxy"),rt("agent_cli_config_update_response",{...jn,provider:tn(hl),agentCli:zM.optional(),...Ur},"proxy_to_client"),rt("session_create",{...jn,kind:tn(Bg).optional(),cwd:Be().optional(),name:Be().optional(),provider:tn(hl).optional(),mode:tn(vh).optional(),resumeSessionId:Be().optional(),cols:un().int().positive().max(KI).optional(),rows:un().int().positive().max(GI).optional(),permissionMode:tn(["default","auto","acceptEdits","plan","bypassPermissions","dontAsk"]).optional()},"client_to_proxy"),rt("session_create_response",{...jn,sessionId:ft.optional(),name:Be().optional(),nameLocked:Vn().optional(),kind:tn(Bg).optional(),mode:tn(vh).optional(),provider:tn(hl).optional(),ptyOwner:tn(Q0).optional(),activeWriterPid:un().int().positive().optional(),...Ur},"proxy_to_client"),rt("session_runtime_error",{sessionId:ft,error:Be(),errorCode:QI,activeWriterPid:un().int().positive().optional()},"proxy_to_client"),rt("session_messages_request",{...jn,sessionId:ft,limit:un().int().min(1).max(200).optional(),before:Be().optional()},"client_to_proxy"),rt("session_resources_request",{...jn,sessionId:ft},"client_to_proxy"),rt("session_resources_response",{...jn,...Ur,sessionId:ft,commands:Br($M),groups:Br(jM)},"proxy_to_client"),rt("agent_status_request",{...jn,sessionId:ft.optional()},"client_to_proxy"),rt("agent_status_response",{...jn,statuses:Br(It({sessionId:ft,payload:LM}))},"proxy_to_client"),rt("permission_request_delivered",{sessionId:ft,requestId:ft},"client_to_proxy"),rt("tool_approve",{sessionId:ft,payload:QX},"client_to_proxy"),rt("tool_deny",{sessionId:ft,payload:JX},"client_to_proxy"),rt("permission_decision_result",{sessionId:ft,requestId:ft,outcome:tn(["allow","deny"]),delivered:Vn(),message:Be().optional()},"proxy_to_client"),rt("pending_approvals_push",{sessionId:ft,approvals:Br(It({requestId:ft,toolName:Be(),input:hd(Be(),ma())}))},"proxy_to_client"),rt("voice_summary_request",{...jn,sessionId:ft,messageId:ft,text:Be().min(1),reason:_Z},"client_to_proxy"),rt("voice_summary_response",{...jn,...Ur,sessionId:ft,messageId:ft,success:Vn(),summary:Be().min(1).optional()},"proxy_to_client"),rt("session_history_messages",{...jn,sessionId:ft,before:Be().optional(),messages:Br(PZ),hasMore:Vn().optional(),nextBefore:Be().optional()},"proxy_to_client"),rt("session_sync",{sessions:Br(It({id:Be(),kind:tn(Bg).optional(),mode:tn(vh),provider:tn(hl),ptyOwner:tn(Q0).optional(),cwd:Be().optional(),name:Be().optional(),nameLocked:Vn().optional(),state:tn(R1)}))}),rt("session_subscribe",{sessionId:ft,requestId:ft},"client_to_proxy"),rt("session_snapshot",{sessionId:ft,cols:un().int().positive(),rows:un().int().positive(),data:Be(),outputSeq:un().int().nonnegative(),requestId:ft},"proxy_to_client")],LZ=M1.map(e=>e.schema);rp("type",LZ);new Set(M1.filter(e=>e.directions.has("proxy_to_client")).map(e=>e.type));new Set(M1.filter(e=>e.directions.has("client_to_proxy")).map(e=>e.type));const OZ=3e4,DZ=5e3,N1=OZ+DZ,IZ={CLIENT_KICKED:4401},Pf=1,Xm=4;function BZ(e){if(e.length<Pf+Xm)return null;const t=e[0];if(t===0||e.length<Pf+t+Xm)return null;const n=new TextDecoder().decode(e.subarray(Pf,Pf+t)),r=Pf+t,i=new DataView(e.buffer,e.byteOffset+r,Xm).getUint32(0,!0),s=e.subarray(r+Xm);return{sessionId:n,outputSeq:i,data:s}}const zZ=132,jZ=32635;function $Z(e){let t=e;const n=t<0?128:0;t<0&&(t=-t),t=Math.min(t,jZ)+zZ;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 FZ(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]=$Z(r.getInt16(i*2,!0));return n}function HZ(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 WM(e){let t=e.initial;const n=HZ(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 UZ(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 WZ({userAgent:e="",platform:t,maxTouchPoints:n=0}){return t==="MacIntel"&&n>1&&(e.includes("Mac OS X")||e.includes("Macintosh"))}function qZ(e){const t=e.userAgent??"";if(WZ(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 YZ(e){return e==="iPad"?"tablet":e==="iPhone"||e==="Android"?"phone":e==="macOS"||e==="Windows"?"desktop":"unknown"}function JI(e){const t=e.browserName??(e.userAgent?UZ(e.userAgent):void 0)??"浏览器",n=e.osName??qZ(e)??"未知系统";return{...e,browserName:t,osName:n,deviceKind:e.deviceKind??YZ(n)}}function ip(){const e=typeof navigator>"u"?null:navigator;return JI({...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 VZ(e){return`${e.browserName} · ${e.osName}`}const KZ=1e4,GZ=5e3,ow=15e3,XZ=2e3;class ZZ{constructor(t={}){_t(this,"ws",null);_t(this,"url","");_t(this,"connected",!1);_t(this,"closed",!1);_t(this,"reconnectTimer",null);_t(this,"reconnectAttempt",0);_t(this,"messageHandlers",new Set);_t(this,"binarySubscribers",new Map);_t(this,"statusHandlers",new Set);_t(this,"pendingQueue",[]);_t(this,"wakeListenersAttached",!1);_t(this,"backgroundedAt",null);_t(this,"connectionProbe",null);_t(this,"connectionProbeSeq",0);_t(this,"foregroundWatchdogTimer",null);_t(this,"lastInboundAt",0);_t(this,"probeConnectionLiveness");_t(this,"visibilityListener",()=>{if(document.visibilityState==="hidden"){this.markBackgrounded();return}document.visibilityState==="visible"&&this.resumeFromBackground()});_t(this,"onlineListener",()=>this.wakeReconnect(!0));_t(this,"blurListener",()=>this.markBackgrounded());_t(this,"focusListener",()=>{document.visibilityState!=="hidden"&&this.resumeFromBackground()});_t(this,"pageHideListener",()=>this.markBackgrounded());_t(this,"pageShowListener",()=>this.resumeFromBackground());const n=ip().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>=GZ;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=ow){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.connected||t.readyState!==WebSocket.OPEN){this.wakeReconnect(!0);return}const n=Date.now()-this.lastInboundAt;if(n<ow){this.armForegroundWatchdog(ow-n);return}this.probeConnection()}probeConnection(){if(this.closed)return;const t=this.ws;if(!this.connected||!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))},XZ);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)}connect(t){this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.ws&&(this.ws.close(),this.ws=null),this.cancelReconnectTimer(),this.connected=!1,this.url=t,this.closed=!1,this.reconnectAttempt=0,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.connected||!t&&this.ws&&this.ws.readyState===WebSocket.CONNECTING)return;this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.reconnectAttempt=0,this.cancelReconnectTimer();const n=this.ws,r=this.connected;if(this.ws=null,this.connected=!1,r&&this.statusHandlers.forEach(i=>i(!1)),n)try{n.close()}catch{}this.doConnect()}send(t,n={}){if(!this.ws)return console.warn("WebSocket send dropped: no socket"),!1;if(!this.connected){if(n.queueWhenDisconnected){if(this.pendingQueue.length>=KZ){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!1}return this.doSend(t),!0}close(){var t;this.closed=!0,this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.cancelReconnectTimer(),(t=this.ws)==null||t.close(),this.ws=null,this.connected=!1,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.connected}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.armForegroundWatchdog(),t.addEventListener("open",()=>{this.ws===t&&(this.connected=!0,this.reconnectAttempt=0,this.lastInboundAt=Date.now(),this.armForegroundWatchdog(),this.statusHandlers.forEach(n=>n(!0)),this.flushPendingQueue())}),t.addEventListener("message",n=>{if(this.ws===t)if(n.data instanceof ArrayBuffer)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=>{this.ws===t&&(this.cancelConnectionProbe(t),this.cancelForegroundWatchdog(),n.code===IZ.CLIENT_KICKED&&(this.closed=!0,this.cancelReconnectTimer()),this.connected=!1,this.ws=null,this.statusHandlers.forEach(r=>r(!1)),this.closed||this.scheduleReconnect())}),t.addEventListener("error",()=>{})}scheduleReconnect(){const t=Math.min(1e3*Math.pow(2,this.reconnectAttempt),3e4),n=Math.random()*t;this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.doConnect()},n)}dispatchBinary(t){const n=BZ(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 QZ=24,JZ=48,eQ=1,tQ=4,nQ=8,rQ=8,iQ=32;function qM(e,t,n){return Math.min(n,Math.max(t,e))}function sQ({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:zg,rows:J0};const l=Math.max(0,e-Math.max(0,n)-QZ),u=Math.floor(l/s),f=u<zg?iQ:rQ,p=JZ+eQ+tQ+nQ+f+Math.max(0,r)+Math.max(0,i),y=Math.max(0,t-p),g=Math.floor(y/o);return{cols:qM(u,zg,KI),rows:qM(g,J0,GI)}}function oQ(){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 aQ(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:fI,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 lQ(){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 cQ(){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 uQ(e=ud){if(typeof window>"u")return{cols:zg,rows:J0};const t=cQ(),n=oQ(),r=aQ(e);return sQ({viewportWidth:t.width,viewportHeight:t.height,sidebarWidth:lQ(),safeAreaTop:n.top,safeAreaBottom:n.bottom,cellWidth:r.width,cellHeight:r.height})}const Wr=1e4,dQ=2e4,aw=3e3;let YM=0;function mr(e){return YM+=1,`${e}-${Date.now().toString(36)}-${YM.toString(36)}`}class fQ{constructor(t,n){_t(this,"ws");_t(this,"clientId");_t(this,"boundProxyId",null);_t(this,"messageHandlers",new Set);_t(this,"pendingMessages",[]);this.ws=t,this.clientId=n,this.ws.onMessage(r=>{let i;try{i=JSON.parse(r)}catch(s){console.warn("RelayClient: failed to parse JSON:",r.slice(0,200),s);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.boundProxyId=null;const t=ip();this.ws.send(JSON.stringify({type:"client_register",clientId:this.clientId,...t}))}listProxies(){this.ws.send(JSON.stringify({type:"proxy_list_request"}))}requestProxyList(t=Wr){const n=mr("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)}requestRelayClients(t=Wr){const n=mr("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=Wr){const r=mr("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=Wr){const r=mr("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=t),{success:i.success,proxyId:i.proxyId,error:i.error,errorCode:i.errorCode}))}createDirectory(t,n=Wr){const r=mr("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=Wr){const r=mr("dir-list");return this.waitForMessage(i=>i.type==="dir_list_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"dir_list_request",requestId:r,path:t})),"读取目录超时",n,r).then(i=>({path:i.path,entries:i.entries,error:i.error,errorCode:i.errorCode}))}uploadClipboardImage(t,n){return this.uploadRemoteFile(t,n,"clipboard_image")}requestRemoteFileUrl(t,n,r,i=Wr){const s=mr("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=Wr){const s=mr("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=Wr){const n=mr("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}))}updateAgentCliPath(t,n,r=Wr){const i=mr("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=Wr){const n=mr("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=Wr){const r=mr("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=Wr){const r=mr("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=Wr){const r=mr("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=dQ){const o=mr("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=aw){const n=mr("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=aw){const n=mr("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=aw){const n=mr("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=Wr){const n=mr("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=Wr){return this.requestSessionMessagesPage(t,{},n).then(r=>r.messages)}requestSessionMessagesPage(t,n={},r=Wr){const i=mr("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=Wr){const r=mr("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=Wr){const r=mr("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=N1){const r=mr("session-create"),i=t.mode==="pty"?uQ(De.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=Wr){const i=mr("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){return new Promise((o,l)=>{let u=!1,d=null,f=null,p=null;const y=()=>{d==null||d(),f==null||f(),p&&clearTimeout(p)},g=b=>{u||(u=!0,y(),b())};d=this.onMessage(b=>{if(t(b)){g(()=>o(b));return}if(s&&b.type==="relay_error"&&b.requestId===s){const w=b.message??"relay error";g(()=>l(new Error(`Relay 服务器拒绝请求: ${w}`)))}}),f=this.ws.onStatusChange(b=>{b||g(()=>l(new Error("连接已断开")))}),p=setTimeout(()=>{g(()=>l(new Error(r)))},i);try{n()===!1&&g(()=>l(new Error("连接已断开")))}catch(b){g(()=>l(b instanceof Error?b:new Error(String(b))))}})}getBoundProxyId(){return this.boundProxyId}clearBoundProxy(t){(!t||this.boundProxyId===t)&&(this.boundProxyId=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 Fc=ZO();const eB=Xh(Fc);function hQ(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 pQ=e=>{switch(e){case"success":return vQ;case"info":return bQ;case"warning":return yQ;case"error":return _Q;default:return null}},mQ=Array(12).fill(0),gQ=({visible:e,className:t})=>et.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},et.createElement("div",{className:"sonner-spinner"},mQ.map((n,r)=>et.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),vQ=et.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},et.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"})),yQ=et.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},et.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"})),bQ=et.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},et.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"})),_Q=et.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},et.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"})),wQ=et.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"},et.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),et.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),SQ=()=>{const[e,t]=et.useState(document.hidden);return et.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let eS=1;class xQ{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:eS++,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],et.isValidElement(d))s=!1,this.create({id:r,type:"default",message:d});else if(CQ(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,b=typeof p=="object"&&!et.isValidElement(p)?p:{message:p};this.create({id:r,type:"error",description:y,...b})}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,b=typeof p=="object"&&!et.isValidElement(p)?p:{message:p};this.create({id:r,type:"error",description:y,...b})}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,b=typeof p=="object"&&!et.isValidElement(p)?p:{message:p};this.create({id:r,type:"success",description:y,...b})}}).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"&&!et.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)||eS++;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 ts=new xQ,EQ=(e,t)=>{const n=(t==null?void 0:t.id)||eS++;return ts.addToast({title:e,...t,id:n}),n},CQ=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",kQ=EQ,TQ=()=>ts.toasts,RQ=()=>ts.getActiveToasts(),nt=Object.assign(kQ,{success:ts.success,info:ts.info,warning:ts.warning,error:ts.error,custom:ts.custom,message:ts.message,promise:ts.promise,dismiss:ts.dismiss,loading:ts.loading},{getHistory:TQ,getToasts:RQ});hQ("[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 Zm(e){return e.label!==void 0}const AQ=3,MQ="24px",NQ="16px",VM=4e3,PQ=356,LQ=14,OQ=45,DQ=200;function po(...e){return e.filter(Boolean).join(" ")}function IQ(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const BQ=e=>{var t,n,r,i,s,o,l,u,d;const{invert:f,toast:p,unstyled:y,interacting:g,setHeights:b,visibleToasts:w,heights:S,index:E,toasts:k,expanded:T,removeToast:R,defaultRichColors:P,closeButton:A,style:H,cancelButtonStyle:D,actionButtonStyle:K,className:q="",descriptionClassName:X="",duration:z,position:N,gap:$,expandByDefault:I,classNames:M,icons:O,closeButtonAriaLabel:U="Close toast"}=e,[B,L]=et.useState(null),[Y,V]=et.useState(null),[j,te]=et.useState(!1),[re,oe]=et.useState(!1),[ee,pe]=et.useState(!1),[ae,me]=et.useState(!1),[Ee,Oe]=et.useState(!1),[Se,Qe]=et.useState(0),[Ht,ye]=et.useState(0),Xe=et.useRef(p.duration||z||VM),kt=et.useRef(null),gt=et.useRef(null),Lt=E===0,an=E+1<=w,ut=p.type,Le=p.dismissible!==!1,Ke=p.className||"",lt=p.descriptionClassName||"",ve=et.useMemo(()=>S.findIndex(W=>W.toastId===p.id)||0,[S,p.id]),$e=et.useMemo(()=>{var W;return(W=p.closeButton)!=null?W:A},[p.closeButton,A]),at=et.useMemo(()=>p.duration||z||VM,[p.duration,z]),yt=et.useRef(0),pt=et.useRef(0),cn=et.useRef(0),qt=et.useRef(null),[Gt,vn]=N.split("-"),dn=et.useMemo(()=>S.reduce((W,ne,G)=>G>=ve?W:W+ne.height,0),[S,ve]),$t=SQ(),nn=p.invert||f,rn=ut==="loading";pt.current=et.useMemo(()=>ve*$+dn,[ve,dn]),et.useEffect(()=>{Xe.current=at},[at]),et.useEffect(()=>{te(!0)},[]),et.useEffect(()=>{const W=gt.current;if(W){const ne=W.getBoundingClientRect().height;return ye(ne),b(G=>[{toastId:p.id,height:ne,position:p.position},...G]),()=>b(G=>G.filter(de=>de.toastId!==p.id))}},[b,p.id]),et.useLayoutEffect(()=>{if(!j)return;const W=gt.current,ne=W.style.height;W.style.height="auto";const G=W.getBoundingClientRect().height;W.style.height=ne,ye(G),b(de=>de.find(Q=>Q.toastId===p.id)?de.map(Q=>Q.toastId===p.id?{...Q,height:G}:Q):[{toastId:p.id,height:G,position:p.position},...de])},[j,p.title,p.description,b,p.id,p.jsx,p.action,p.cancel]);const qn=et.useCallback(()=>{oe(!0),Qe(pt.current),b(W=>W.filter(ne=>ne.toastId!==p.id)),setTimeout(()=>{R(p)},DQ)},[p,R,b,pt]);et.useEffect(()=>{if(p.promise&&ut==="loading"||p.duration===1/0||p.type==="loading")return;let W;return T||g||$t?(()=>{if(cn.current<yt.current){const de=new Date().getTime()-yt.current;Xe.current=Xe.current-de}cn.current=new Date().getTime()})():(()=>{Xe.current!==1/0&&(yt.current=new Date().getTime(),W=setTimeout(()=>{p.onAutoClose==null||p.onAutoClose.call(p,p),qn()},Xe.current))})(),()=>clearTimeout(W)},[T,g,p,ut,$t,qn]),et.useEffect(()=>{p.delete&&(qn(),p.onDismiss==null||p.onDismiss.call(p,p))},[qn,p.delete]);function Fn(){var W;if(O!=null&&O.loading){var ne;return et.createElement("div",{className:po(M==null?void 0:M.loader,p==null||(ne=p.classNames)==null?void 0:ne.loader,"sonner-loader"),"data-visible":ut==="loading"},O.loading)}return et.createElement(gQ,{className:po(M==null?void 0:M.loader,p==null||(W=p.classNames)==null?void 0:W.loader),visible:ut==="loading"})}const Jn=p.icon||(O==null?void 0:O[ut])||pQ(ut);var lr,fn;return et.createElement("li",{tabIndex:0,ref:gt,className:po(q,Ke,M==null?void 0:M.toast,p==null||(t=p.classNames)==null?void 0:t.toast,M==null?void 0:M.default,M==null?void 0:M[ut],p==null||(n=p.classNames)==null?void 0:n[ut]),"data-sonner-toast":"","data-rich-colors":(lr=p.richColors)!=null?lr:P,"data-styled":!(p.jsx||p.unstyled||y),"data-mounted":j,"data-promise":!!p.promise,"data-swiped":Ee,"data-removed":re,"data-visible":an,"data-y-position":Gt,"data-x-position":vn,"data-index":E,"data-front":Lt,"data-swiping":ee,"data-dismissible":Le,"data-type":ut,"data-invert":nn,"data-swipe-out":ae,"data-swipe-direction":Y,"data-expanded":!!(T||I&&j),"data-testid":p.testId,style:{"--index":E,"--toasts-before":E,"--z-index":k.length-E,"--offset":`${re?Se:pt.current}px`,"--initial-height":I?"auto":`${Ht}px`,...H,...p.style},onDragEnd:()=>{pe(!1),L(null),qt.current=null},onPointerDown:W=>{W.button!==2&&(rn||!Le||(kt.current=new Date,Qe(pt.current),W.target.setPointerCapture(W.pointerId),W.target.tagName!=="BUTTON"&&(pe(!0),qt.current={x:W.clientX,y:W.clientY})))},onPointerUp:()=>{var W,ne,G;if(ae||!Le)return;qt.current=null;const de=Number(((W=gt.current)==null?void 0:W.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),xe=Number(((ne=gt.current)==null?void 0:ne.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Q=new Date().getTime()-((G=kt.current)==null?void 0:G.getTime()),ie=B==="x"?de:xe,le=Math.abs(ie)/Q;if(Math.abs(ie)>=OQ||le>.11){Qe(pt.current),p.onDismiss==null||p.onDismiss.call(p,p),V(B==="x"?de>0?"right":"left":xe>0?"down":"up"),qn(),me(!0);return}else{var he,Z;(he=gt.current)==null||he.style.setProperty("--swipe-amount-x","0px"),(Z=gt.current)==null||Z.style.setProperty("--swipe-amount-y","0px")}Oe(!1),pe(!1),L(null)},onPointerMove:W=>{var ne,G,de;if(!qt.current||!Le||((ne=window.getSelection())==null?void 0:ne.toString().length)>0)return;const Q=W.clientY-qt.current.y,ie=W.clientX-qt.current.x;var le;const he=(le=e.swipeDirections)!=null?le:IQ(N);!B&&(Math.abs(ie)>1||Math.abs(Q)>1)&&L(Math.abs(ie)>Math.abs(Q)?"x":"y");let Z={x:0,y:0};const se=ce=>1/(1.5+Math.abs(ce)/20);if(B==="y"){if(he.includes("top")||he.includes("bottom"))if(he.includes("top")&&Q<0||he.includes("bottom")&&Q>0)Z.y=Q;else{const ce=Q*se(Q);Z.y=Math.abs(ce)<Math.abs(Q)?ce:Q}}else if(B==="x"&&(he.includes("left")||he.includes("right")))if(he.includes("left")&&ie<0||he.includes("right")&&ie>0)Z.x=ie;else{const ce=ie*se(ie);Z.x=Math.abs(ce)<Math.abs(ie)?ce:ie}(Math.abs(Z.x)>0||Math.abs(Z.y)>0)&&Oe(!0),(G=gt.current)==null||G.style.setProperty("--swipe-amount-x",`${Z.x}px`),(de=gt.current)==null||de.style.setProperty("--swipe-amount-y",`${Z.y}px`)}},$e&&!p.jsx&&ut!=="loading"?et.createElement("button",{"aria-label":U,"data-disabled":rn,"data-close-button":!0,onClick:rn||!Le?()=>{}:()=>{qn(),p.onDismiss==null||p.onDismiss.call(p,p)},className:po(M==null?void 0:M.closeButton,p==null||(r=p.classNames)==null?void 0:r.closeButton)},(fn=O==null?void 0:O.close)!=null?fn:wQ):null,(ut||p.icon||p.promise)&&p.icon!==null&&((O==null?void 0:O[ut])!==null||p.icon)?et.createElement("div",{"data-icon":"",className:po(M==null?void 0:M.icon,p==null||(i=p.classNames)==null?void 0:i.icon)},p.promise||p.type==="loading"&&!p.icon?p.icon||Fn():null,p.type!=="loading"?Jn:null):null,et.createElement("div",{"data-content":"",className:po(M==null?void 0:M.content,p==null||(s=p.classNames)==null?void 0:s.content)},et.createElement("div",{"data-title":"",className:po(M==null?void 0:M.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?et.createElement("div",{"data-description":"",className:po(X,lt,M==null?void 0:M.description,p==null||(l=p.classNames)==null?void 0:l.description)},typeof p.description=="function"?p.description():p.description):null),et.isValidElement(p.cancel)?p.cancel:p.cancel&&Zm(p.cancel)?et.createElement("button",{"data-button":!0,"data-cancel":!0,style:p.cancelButtonStyle||D,onClick:W=>{Zm(p.cancel)&&Le&&(p.cancel.onClick==null||p.cancel.onClick.call(p.cancel,W),qn())},className:po(M==null?void 0:M.cancelButton,p==null||(u=p.classNames)==null?void 0:u.cancelButton)},p.cancel.label):null,et.isValidElement(p.action)?p.action:p.action&&Zm(p.action)?et.createElement("button",{"data-button":!0,"data-action":!0,style:p.actionButtonStyle||K,onClick:W=>{Zm(p.action)&&(p.action.onClick==null||p.action.onClick.call(p.action,W),!W.defaultPrevented&&qn())},className:po(M==null?void 0:M.actionButton,p==null||(d=p.classNames)==null?void 0:d.actionButton)},p.action.label):null)};function KM(){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 zQ(e,t){const n={};return[e,t].forEach((r,i)=>{const s=i===1,o=s?"--mobile-offset":"--offset",l=s?NQ:MQ;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 jQ=et.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:b,style:w,visibleToasts:S=AQ,toastOptions:E,dir:k=KM(),gap:T=LQ,icons:R,containerAriaLabel:P="Notifications"}=t,[A,H]=et.useState([]),D=et.useMemo(()=>r?A.filter(j=>j.toasterId===r):A.filter(j=>!j.toasterId),[A,r]),K=et.useMemo(()=>Array.from(new Set([s].concat(D.filter(j=>j.position).map(j=>j.position)))),[D,s]),[q,X]=et.useState([]),[z,N]=et.useState(!1),[$,I]=et.useState(!1),[M,O]=et.useState(y!=="system"?y:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),U=et.useRef(null),B=o.join("+").replace(/Key/g,"").replace(/Digit/g,""),L=et.useRef(null),Y=et.useRef(!1),V=et.useCallback(j=>{H(te=>{var re;return(re=te.find(oe=>oe.id===j.id))!=null&&re.delete||ts.dismiss(j.id),te.filter(({id:oe})=>oe!==j.id)})},[]);return et.useEffect(()=>ts.subscribe(j=>{if(j.dismiss){requestAnimationFrame(()=>{H(te=>te.map(re=>re.id===j.id?{...re,delete:!0}:re))});return}setTimeout(()=>{eB.flushSync(()=>{H(te=>{const re=te.findIndex(oe=>oe.id===j.id);return re!==-1?[...te.slice(0,re),{...te[re],...j},...te.slice(re+1)]:[j,...te]})})})}),[A]),et.useEffect(()=>{if(y!=="system"){O(y);return}if(y==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?O("dark"):O("light")),typeof window>"u")return;const j=window.matchMedia("(prefers-color-scheme: dark)");try{j.addEventListener("change",({matches:te})=>{O(te?"dark":"light")})}catch{j.addListener(({matches:re})=>{try{O(re?"dark":"light")}catch(oe){console.error(oe)}})}},[y]),et.useEffect(()=>{A.length<=1&&N(!1)},[A]),et.useEffect(()=>{const j=te=>{var re;if(o.every(pe=>te[pe]||te.code===pe)){var ee;N(!0),(ee=U.current)==null||ee.focus()}te.code==="Escape"&&(document.activeElement===U.current||(re=U.current)!=null&&re.contains(document.activeElement))&&N(!1)};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[o]),et.useEffect(()=>{if(U.current)return()=>{L.current&&(L.current.focus({preventScroll:!0}),L.current=null,Y.current=!1)}},[U.current]),et.createElement("section",{ref:n,"aria-label":`${P} ${B}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},K.map((j,te)=>{var re;const[oe,ee]=j.split("-");return D.length?et.createElement("ol",{key:j,dir:k==="auto"?KM():k,tabIndex:-1,ref:U,className:d,"data-sonner-toaster":!0,"data-sonner-theme":M,"data-y-position":oe,"data-x-position":ee,style:{"--front-toast-height":`${((re=q[0])==null?void 0:re.height)||0}px`,"--width":`${PQ}px`,"--gap":`${T}px`,...w,...zQ(f,p)},onBlur:pe=>{Y.current&&!pe.currentTarget.contains(pe.relatedTarget)&&(Y.current=!1,L.current&&(L.current.focus({preventScroll:!0}),L.current=null))},onFocus:pe=>{pe.target instanceof HTMLElement&&pe.target.dataset.dismissible==="false"||Y.current||(Y.current=!0,L.current=pe.relatedTarget)},onMouseEnter:()=>N(!0),onMouseMove:()=>N(!0),onMouseLeave:()=>{$||N(!1)},onDragEnd:()=>N(!1),onPointerDown:pe=>{pe.target instanceof HTMLElement&&pe.target.dataset.dismissible==="false"||I(!0)},onPointerUp:()=>I(!1)},D.filter(pe=>!pe.position&&te===0||pe.position===j).map((pe,ae)=>{var me,Ee;return et.createElement(BQ,{key:pe.id,icons:R,index:ae,toast:pe,defaultRichColors:g,duration:(me=E==null?void 0:E.duration)!=null?me:b,className:E==null?void 0:E.className,descriptionClassName:E==null?void 0:E.descriptionClassName,invert:i,visibleToasts:S,closeButton:(Ee=E==null?void 0:E.closeButton)!=null?Ee:u,interacting:$,position:j,style:E==null?void 0:E.style,unstyled:E==null?void 0:E.unstyled,classNames:E==null?void 0:E.classNames,cancelButtonStyle:E==null?void 0:E.cancelButtonStyle,actionButtonStyle:E==null?void 0:E.actionButtonStyle,closeButtonAriaLabel:E==null?void 0:E.closeButtonAriaLabel,removeToast:V,toasts:D.filter(Oe=>Oe.position==pe.position),heights:q.filter(Oe=>Oe.position==pe.position),setHeights:X,expandByDefault:l,gap:T,expanded:z,swipeDirections:t.swipeDirections})})):null}))});function $Q(){const e=De(t=>t.themePreference);return v.jsx(jQ,{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 tS(e){return"error"in e}async function nS(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:zr.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:zr.SESSION_NOT_FOUND};n=s.proxyId}if(!n)return{error:"No proxy specified",code:zr.UNKNOWN};let r;try{r=await e.selectProxy(n)}catch(i){return{error:i instanceof Error?i.message:String(i),code:zr.UNKNOWN}}return r.success?{proxyId:n}:{error:r.error||"Proxy select failed",code:r.errorCode??zr.UNKNOWN}}async function P1(e,t){const n=De.getState().selectedProxyId;if(!n)return{status:"skipped"};const r=Ft.getState().beginHistoryLoad();try{const i=t===void 0?await e.requestSessionHistory():await e.requestSessionHistory(t);return De.getState().selectedProxyId!==n?(Ft.getState().cancelHistoryLoad(r),{status:"stale"}):Ft.getState().resolveHistoryLoad(r,i)?{status:"loaded",sessions:i}:{status:"stale"}}catch(i){return De.getState().selectedProxyId!==n?(Ft.getState().cancelHistoryLoad(r),{status:"stale"}):Ft.getState().rejectHistoryLoad(r)?{status:"failed",error:i}:{status:"stale"}}}const FQ=3e4,HQ=15e3,UQ=500,WQ=2e3;function qQ(){return{reconnect:null,bindingRetry:null,bindingRetryAttempt:0,bindingAttemptGeneration:null,recoveryGeneration:0,coldStartDone:!1,disposed:!1}}function YQ(){const e=window.location.hash.match(/^#\/chat\/([^/?]+)/);return(e==null?void 0:e[1])??null}function rS(e){const t=De.getState().selectedProxyId;t&&(e.sendControl({type:"session_list"}),e.requestProxyInfo().then(n=>{if(De.getState().selectedProxyId!==t)return;const r=hi.getState();r.setHomePath(n.homePath),r.setAgentCli(n.agentCli)}).catch(n=>{console.error("[phase-machine] requestProxyInfo failed",n),nt.error("无法获取开发机信息")}),e.requestAgentStatuses().then(n=>{if(De.getState().selectedProxyId!==t)return;const r=Ft.getState();for(const i of n)r.setAgentStatus(i.sessionId,i.payload)}).catch(n=>{console.error("[phase-machine] requestAgentStatuses failed",n)}))}function iS(e){P1(e,HQ).then(t=>{if(t.status==="failed"){console.error("[phase-machine] requestSessionHistory failed",t.error);const n=De.getState();if(!n.connected||!n.proxyOnline||n.phase==="reconnecting")return;nt.warning("历史会话加载失败,可点击刷新重试")}})}async function jg(e,t,n=()=>!0){const r=await nS(e,{proxyId:t.proxyId});return tS(r)||!n()?!1:(Er("local",Sn.proxyId,t.proxyId),De.getState().setProxy(t.proxyId,t.name??null),De.getState().setProxyOnline(!0),rS(e),iS(e),!0)}function VQ(e){e.reconnect&&(clearTimeout(e.reconnect),e.reconnect=null)}function Oh(e){e.recoveryGeneration+=1,e.bindingAttemptGeneration=null,e.bindingRetryAttempt=0,e.bindingRetry&&(clearTimeout(e.bindingRetry),e.bindingRetry=null)}function tB(e){VQ(e),Oh(e)}function GM(e){e.reconnect||e.disposed||(e.reconnect=setTimeout(()=>{e.reconnect=null,Oh(e),!(e.disposed||De.getState().phase!=="reconnecting")&&(e.coldStartDone=!1,De.getState().setProxyOnline(!1),De.getState().setProxies([]),De.getState().resetProxyListLoaded(),De.getState().transitionToPhase("connecting"),jv.navigate("/"))},FQ))}function XM(e,t,n){const r=De.getState();return!e.disposed&&e.recoveryGeneration===t&&e.bindingAttemptGeneration===t&&r.connected&&r.phase==="reconnecting"&&r.selectedProxyId===n}function KQ(e,t,n,r){if(e.bindingRetry||e.disposed||e.recoveryGeneration!==r)return;const i=Math.min(e.bindingRetryAttempt,2),s=Math.min(UQ*2**i,WQ);e.bindingRetryAttempt+=1,e.bindingRetry=setTimeout(()=>{e.bindingRetry=null,!(e.disposed||e.recoveryGeneration!==r||De.getState().phase!=="reconnecting")&&sS(e,t,n,r)},s)}async function sS(e,t,n,r=e.recoveryGeneration){const i=De.getState();if(e.disposed||e.recoveryGeneration!==r||e.bindingAttemptGeneration!==null||!i.connected||i.phase!=="reconnecting"||i.selectedProxyId!==n.proxyId)return;e.bindingRetry&&(clearTimeout(e.bindingRetry),e.bindingRetry=null),e.bindingAttemptGeneration=r;const s=await jg(t,n,()=>XM(e,r,n.proxyId));if(XM(e,r,n.proxyId)){if(e.bindingAttemptGeneration=null,s){const o=De.getState().phaseBeforeDisconnect;tB(e),De.getState().transitionToPhase(o??"session_browsing");return}De.getState().setProxyOnline(!1),KQ(e,t,n,r)}}function GQ(e){e.disposed=!0,tB(e)}function XQ(e){switch(e){case zr.SESSION_NOT_FOUND:return"会话不存在或已关闭";case zr.PROXY_OFFLINE:return"开发机已离线";default:return"无法打开会话"}}function ZQ(e,t,n){if(t.disposed)return;De.getState().setConnected(e);const r=De.getState();e?(Oh(t),n.register(),r.phase==="connecting"&&De.getState().setPhase("registering"),r.phase==="reconnecting"&&(De.getState().setProxyOnline(!1),GM(t),n.listProxies())):(Oh(t),De.getState().setProxyOnline(!1),De.getState().setProxies([]),De.getState().resetProxyListLoaded(),r.phase!=="connecting"&&(r.phase!=="reconnecting"&&De.getState().setPhase("reconnecting"),GM(t)))}async function QQ(e,t,n){if(t.disposed)return;const r=De.getState();if(e.type==="client_register_response"){r.phase==="registering"&&(n.listProxies(),De.getState().setPhase("proxy_selecting"));return}if(e.type==="relay_client_kicked"){nt.info("这个客户端已被断开");return}if(e.type==="proxy_offline"){n.listProxies(),e.proxyId===r.selectedProxyId&&(Oh(t),n.clearBoundProxy(typeof e.proxyId=="string"?e.proxyId:void 0),De.getState().setProxyOnline(!1),nt.warning("当前开发机已离线"));return}if(e.type==="proxy_online"){if(n.listProxies(),e.proxyId===r.selectedProxyId){if(n.getBoundProxyId()===e.proxyId&&r.phase!=="reconnecting"){De.getState().setProxyOnline(!0),nt.success("当前开发机已恢复连接");return}De.getState().setProxyOnline(!1);const s=De.getState().proxies.find(o=>o.proxyId===e.proxyId);if(s){const o={...s};r.phase==="reconnecting"?await sS(t,n,o):await jg(n,o)&&nt.success("当前开发机已恢复连接")}}return}if(e.type==="proxy_list_response"){const i=e.proxies;if(De.getState().setProxies(i),!t.coldStartDone&&r.phase==="proxy_selecting"){t.coldStartDone=!0;const s=Oi("local",Sn.proxyId),o=s?null:YQ();if(!s&&o){const l=await nS(n,{sessionId:o});if(tS(l)){const d=XQ(l.code);De.getState().setPendingToast({kind:"error",message:d}),jv.navigate("/"),t.coldStartDone=!1;return}const u=i.find(d=>d.proxyId===l.proxyId);De.getState().setProxy(l.proxyId,(u==null?void 0:u.name)||null),De.getState().setProxyOnline(!0),Er("local",Sn.proxyId,l.proxyId),De.getState().setPhase("chatting"),rS(n),iS(n);return}if(s){const l=await nS(n,{proxyId:s});if(!tS(l)){const u=i.find(d=>d.proxyId===s);De.getState().setProxy(s,(u==null?void 0:u.name)||null),De.getState().setProxyOnline(!0),rS(n),iS(n),De.getState().setPhase("session_browsing");return}t.coldStartDone=!1}}if(r.selectedProxyId){const s=i.find(u=>u.proxyId===r.selectedProxyId),o=(s==null?void 0:s.online)===!0&&n.getBoundProxyId()===s.proxyId;De.getState().setProxyOnline(o);const l=(s==null?void 0:s.online)===!0&&!o;if(r.phase==="reconnecting"){s!=null&&s.online&&await sS(t,n,s);return}if(r.phase==="proxy_selecting"&&(s!=null&&s.online)){await jg(n,s)&&(De.getState().transitionToPhase("session_browsing"),jv.navigate("/sessions"));return}l&&await jg(n,s)}}}function ZM(e){return typeof e=="string"?e:""}function fv(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function oS(e){switch(e){case"add":return"新增";case"delete":return"删除";case"update":return"更新";default:return"变更"}}function lw(e,t){const n=fv(t);return n?{title:e,content:n}:null}function JQ(e,t){return e?t?`${e}
|
|
479
|
+
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 FI(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),S=w.schema;if(S.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0")?(p.allOf=p.allOf??[],p.allOf.push(S)):Object.assign(p,S),Object.assign(p,y),d._zod.parent===g)for(const k in p)k==="$ref"||k==="allOf"||k in y||delete p[k];if(S.$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 b=d._zod.parent;if(b&&b!==g){r(b);const w=e.seen.get(b);if(w!=null&&w.schema.$ref&&(p.$ref=w.schema.$ref,w.def))for(const S in p)S==="$ref"||S==="allOf"||S in w.def&&JSON.stringify(p[S])===JSON.stringify(w.def[S])&&delete p[S]}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:dv(t,"input",e.processors),output:dv(t,"output",e.processors)}},enumerable:!1,writable:!1}),d}catch{throw new Error("Error converting schema to JSON.")}}function zi(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 zi(r.element,n);if(r.type==="set")return zi(r.valueType,n);if(r.type==="lazy")return zi(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 zi(r.innerType,n);if(r.type==="intersection")return zi(r.left,n)||zi(r.right,n);if(r.type==="record"||r.type==="map")return zi(r.keyType,n)||zi(r.valueType,n);if(r.type==="pipe")return zi(r.in,n)||zi(r.out,n);if(r.type==="object"){for(const i in r.shape)if(zi(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(zi(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(zi(i,n))return!0;return!!(r.rest&&zi(r.rest,n))}return!1}const cG=(e,t={})=>n=>{const r=jI({...n,processors:t});return Kr(e,r),$I(r,e),FI(r,e)},dv=(e,t,n={})=>r=>{const{libraryOptions:i,target:s}=r??{},o=jI({...i??{},target:s,io:t,processors:n});return Kr(e,o),$I(o,e),FI(o,e)},uG={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},dG=(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=uG[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}))])}},fG=(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)},hG=(e,t,n,r)=>{n.type="boolean"},pG=(e,t,n,r)=>{n.not={}},mG=(e,t,n,r)=>{},gG=(e,t,n,r)=>{const i=e._zod.def,s=yI(i.entries);s.every(o=>typeof o=="number")&&(n.type="number"),s.every(o=>typeof o=="string")&&(n.type="string"),n.enum=s},vG=(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},yG=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},bG=(e,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},_G=(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=Kr(s.element,t,{...r,path:[...r.path,"items"]})},wG=(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]=Kr(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=Kr(s.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(i.additionalProperties=!1)},SG=(e,t,n,r)=>{const i=e._zod.def,s=i.inclusive===!1,o=i.options.map((l,u)=>Kr(l,t,{...r,path:[...r.path,s?"oneOf":"anyOf",u]}));s?n.oneOf=o:n.anyOf=o},xG=(e,t,n,r)=>{const i=e._zod.def,s=Kr(i.left,t,{...r,path:[...r.path,"allOf",0]}),o=Kr(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},EG=(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=Kr(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=Kr(s.keyType,t,{...r,path:[...r.path,"propertyNames"]})),i.additionalProperties=Kr(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)}},CG=(e,t,n,r)=>{const i=e._zod.def,s=Kr(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"}]},kG=(e,t,n,r)=>{const i=e._zod.def;Kr(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType},TG=(e,t,n,r)=>{const i=e._zod.def;Kr(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},RG=(e,t,n,r)=>{const i=e._zod.def;Kr(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)))},AG=(e,t,n,r)=>{const i=e._zod.def;Kr(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},MG=(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;Kr(s,t,r);const o=t.seen.get(e);o.ref=s},NG=(e,t,n,r)=>{const i=e._zod.def;Kr(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType,n.readOnly=!0},HI=(e,t,n,r)=>{const i=e._zod.def;Kr(i.innerType,t,r);const s=t.seen.get(e);s.ref=i.innerType},PG=He("ZodISODateTime",(e,t)=>{LV.init(e,t),Rr.init(e,t)});function LG(e){return jK(PG,e)}const OG=He("ZodISODate",(e,t)=>{OV.init(e,t),Rr.init(e,t)});function DG(e){return $K(OG,e)}const IG=He("ZodISOTime",(e,t)=>{DV.init(e,t),Rr.init(e,t)});function BG(e){return FK(IG,e)}const zG=He("ZodISODuration",(e,t)=>{IV.init(e,t),Rr.init(e,t)});function jG(e){return HK(zG,e)}const $G=(e,t)=>{SI.init(e,t),e.name="ZodError",Object.defineProperties(e,{format:{value:n=>kY(e,n)},flatten:{value:n=>CY(e,n)},addIssue:{value:n=>{e.issues.push(n),e.message=JSON.stringify(e.issues,G0,2)}},addIssues:{value:n=>{e.issues.push(...n),e.message=JSON.stringify(e.issues,G0,2)}},isEmpty:{get(){return e.issues.length===0}}})},Ws=He("ZodError",$G,{Parent:Error}),FG=C1(Ws),HG=k1(Ws),UG=qv(Ws),WG=Yv(Ws),qG=AY(Ws),YG=MY(Ws),VG=NY(Ws),KG=PY(Ws),GG=LY(Ws),XG=OY(Ws),ZG=DY(Ws),QG=IY(Ws),Tr=He("ZodType",(e,t)=>(kr.init(e,t),Object.assign(e["~standard"],{jsonSchema:{input:dv(e,"input"),output:dv(e,"output")}}),e.toJSONSchema=cG(e,{}),e.def=t,e.type=t.type,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone(Nl(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)=>Pl(e,n,r),e.brand=()=>e,e.register=((n,r)=>(n.add(e,r),e)),e.parse=(n,r)=>FG(e,n,r,{callee:e.parse}),e.safeParse=(n,r)=>UG(e,n,r),e.parseAsync=async(n,r)=>HG(e,n,r,{callee:e.parseAsync}),e.safeParseAsync=async(n,r)=>WG(e,n,r),e.spa=e.safeParseAsync,e.encode=(n,r)=>qG(e,n,r),e.decode=(n,r)=>YG(e,n,r),e.encodeAsync=async(n,r)=>VG(e,n,r),e.decodeAsync=async(n,r)=>KG(e,n,r),e.safeEncode=(n,r)=>GG(e,n,r),e.safeDecode=(n,r)=>XG(e,n,r),e.safeEncodeAsync=async(n,r)=>ZG(e,n,r),e.safeDecodeAsync=async(n,r)=>QG(e,n,r),e.refine=(n,r)=>e.check(YX(n,r)),e.superRefine=n=>e.check(VX(n)),e.overwrite=n=>e.check(Cd(n)),e.optional=()=>AM(e),e.exactOptional=()=>LX(e),e.nullable=()=>MM(e),e.nullish=()=>AM(MM(e)),e.nonoptional=n=>jX(e,n),e.array=()=>Br(e),e.or=n=>EX([e,n]),e.and=n=>TX(e,n),e.transform=n=>NM(e,NX(n)),e.default=n=>IX(e,n),e.prefault=n=>zX(e,n),e.catch=n=>FX(e,n),e.pipe=n=>NM(e,n),e.readonly=()=>WX(e),e.describe=n=>{const r=e.clone();return th.add(r,{description:n}),r},Object.defineProperty(e,"description",{get(){var n;return(n=th.get(e))==null?void 0:n.description},configurable:!0}),e.meta=(...n)=>{if(n.length===0)return th.get(e);const r=e.clone();return th.add(r,n[0]),r},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e.apply=n=>n(e),e)),UI=He("_ZodString",(e,t)=>{T1.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(r,i,s)=>dG(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(KK(...r)),e.includes=(...r)=>e.check(ZK(...r)),e.startsWith=(...r)=>e.check(QK(...r)),e.endsWith=(...r)=>e.check(JK(...r)),e.min=(...r)=>e.check(uv(...r)),e.max=(...r)=>e.check(BI(...r)),e.length=(...r)=>e.check(zI(...r)),e.nonempty=(...r)=>e.check(uv(1,...r)),e.lowercase=r=>e.check(GK(r)),e.uppercase=r=>e.check(XK(r)),e.trim=()=>e.check(tG()),e.normalize=(...r)=>e.check(eG(...r)),e.toLowerCase=()=>e.check(nG()),e.toUpperCase=()=>e.check(rG()),e.slugify=()=>e.check(iG())}),JG=He("ZodString",(e,t)=>{T1.init(e,t),UI.init(e,t),e.email=n=>e.check(yK(eX,n)),e.url=n=>e.check(xK(tX,n)),e.jwt=n=>e.check(zK(gX,n)),e.emoji=n=>e.check(EK(nX,n)),e.guid=n=>e.check(xM(TM,n)),e.uuid=n=>e.check(bK(Km,n)),e.uuidv4=n=>e.check(_K(Km,n)),e.uuidv6=n=>e.check(wK(Km,n)),e.uuidv7=n=>e.check(SK(Km,n)),e.nanoid=n=>e.check(CK(rX,n)),e.guid=n=>e.check(xM(TM,n)),e.cuid=n=>e.check(kK(iX,n)),e.cuid2=n=>e.check(TK(sX,n)),e.ulid=n=>e.check(RK(oX,n)),e.base64=n=>e.check(DK(hX,n)),e.base64url=n=>e.check(IK(pX,n)),e.xid=n=>e.check(AK(aX,n)),e.ksuid=n=>e.check(MK(lX,n)),e.ipv4=n=>e.check(NK(cX,n)),e.ipv6=n=>e.check(PK(uX,n)),e.cidrv4=n=>e.check(LK(dX,n)),e.cidrv6=n=>e.check(OK(fX,n)),e.e164=n=>e.check(BK(mX,n)),e.datetime=n=>e.check(LG(n)),e.date=n=>e.check(DG(n)),e.time=n=>e.check(BG(n)),e.duration=n=>e.check(jG(n))});function Be(e){return vK(JG,e)}const Rr=He("ZodStringFormat",(e,t)=>{yr.init(e,t),UI.init(e,t)}),eX=He("ZodEmail",(e,t)=>{EV.init(e,t),Rr.init(e,t)}),TM=He("ZodGUID",(e,t)=>{SV.init(e,t),Rr.init(e,t)}),Km=He("ZodUUID",(e,t)=>{xV.init(e,t),Rr.init(e,t)}),tX=He("ZodURL",(e,t)=>{CV.init(e,t),Rr.init(e,t)}),nX=He("ZodEmoji",(e,t)=>{kV.init(e,t),Rr.init(e,t)}),rX=He("ZodNanoID",(e,t)=>{TV.init(e,t),Rr.init(e,t)}),iX=He("ZodCUID",(e,t)=>{RV.init(e,t),Rr.init(e,t)}),sX=He("ZodCUID2",(e,t)=>{AV.init(e,t),Rr.init(e,t)}),oX=He("ZodULID",(e,t)=>{MV.init(e,t),Rr.init(e,t)}),aX=He("ZodXID",(e,t)=>{NV.init(e,t),Rr.init(e,t)}),lX=He("ZodKSUID",(e,t)=>{PV.init(e,t),Rr.init(e,t)}),cX=He("ZodIPv4",(e,t)=>{BV.init(e,t),Rr.init(e,t)}),uX=He("ZodIPv6",(e,t)=>{zV.init(e,t),Rr.init(e,t)}),dX=He("ZodCIDRv4",(e,t)=>{jV.init(e,t),Rr.init(e,t)}),fX=He("ZodCIDRv6",(e,t)=>{$V.init(e,t),Rr.init(e,t)}),hX=He("ZodBase64",(e,t)=>{FV.init(e,t),Rr.init(e,t)}),pX=He("ZodBase64URL",(e,t)=>{UV.init(e,t),Rr.init(e,t)}),mX=He("ZodE164",(e,t)=>{WV.init(e,t),Rr.init(e,t)}),gX=He("ZodJWT",(e,t)=>{YV.init(e,t),Rr.init(e,t)}),WI=He("ZodNumber",(e,t)=>{PI.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(r,i,s)=>fG(e,r,i),e.gt=(r,i)=>e.check(CM(r,i)),e.gte=(r,i)=>e.check(nw(r,i)),e.min=(r,i)=>e.check(nw(r,i)),e.lt=(r,i)=>e.check(EM(r,i)),e.lte=(r,i)=>e.check(tw(r,i)),e.max=(r,i)=>e.check(tw(r,i)),e.int=r=>e.check(RM(r)),e.safe=r=>e.check(RM(r)),e.positive=r=>e.check(CM(0,r)),e.nonnegative=r=>e.check(nw(0,r)),e.negative=r=>e.check(EM(0,r)),e.nonpositive=r=>e.check(tw(0,r)),e.multipleOf=(r,i)=>e.check(kM(r,i)),e.step=(r,i)=>e.check(kM(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 un(e){return UK(WI,e)}const vX=He("ZodNumberFormat",(e,t)=>{VV.init(e,t),WI.init(e,t)});function RM(e){return WK(vX,e)}const yX=He("ZodBoolean",(e,t)=>{KV.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>hG(e,n,r)});function Vn(e){return qK(yX,e)}const bX=He("ZodUnknown",(e,t)=>{GV.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>mG()});function ma(){return YK(bX)}const _X=He("ZodNever",(e,t)=>{XV.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>pG(e,n,r)});function wX(e){return VK(_X,e)}const SX=He("ZodArray",(e,t)=>{ZV.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>_G(e,n,r,i),e.element=t.element,e.min=(n,r)=>e.check(uv(n,r)),e.nonempty=n=>e.check(uv(1,n)),e.max=(n,r)=>e.check(BI(n,r)),e.length=(n,r)=>e.check(zI(n,r)),e.unwrap=()=>e.element});function Br(e,t){return sG(SX,e,t)}const xX=He("ZodObject",(e,t)=>{JV.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>wG(e,n,r,i),Xn(e,"shape",()=>t.shape),e.keyof=()=>tn(Object.keys(e._zod.def.shape)),e.catchall=n=>e.clone({...e._zod.def,catchall:n}),e.passthrough=()=>e.clone({...e._zod.def,catchall:ma()}),e.loose=()=>e.clone({...e._zod.def,catchall:ma()}),e.strict=()=>e.clone({...e._zod.def,catchall:wX()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=n=>_Y(e,n),e.safeExtend=n=>wY(e,n),e.merge=n=>SY(e,n),e.pick=n=>yY(e,n),e.omit=n=>bY(e,n),e.partial=(...n)=>xY(YI,e,n[0]),e.required=(...n)=>EY(VI,e,n[0])});function It(e,t){const n={type:"object",shape:e??{},...Wt(t)};return new xX(n)}const qI=He("ZodUnion",(e,t)=>{DI.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>SG(e,n,r,i),e.options=t.options});function EX(e,t){return new qI({type:"union",options:e,...Wt(t)})}const CX=He("ZodDiscriminatedUnion",(e,t)=>{qI.init(e,t),eK.init(e,t)});function rp(e,t,n){return new CX({type:"union",options:t,discriminator:e,...Wt(n)})}const kX=He("ZodIntersection",(e,t)=>{tK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>xG(e,n,r,i)});function TX(e,t){return new kX({type:"intersection",left:e,right:t})}const RX=He("ZodRecord",(e,t)=>{nK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>EG(e,n,r,i),e.keyType=t.keyType,e.valueType=t.valueType});function hd(e,t,n){return new RX({type:"record",keyType:e,valueType:t,...Wt(n)})}const Z0=He("ZodEnum",(e,t)=>{rK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(r,i,s)=>gG(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 Z0({...t,checks:[],...Wt(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 Z0({...t,checks:[],...Wt(i),entries:s})}});function tn(e,t){const n=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new Z0({type:"enum",entries:n,...Wt(t)})}const AX=He("ZodLiteral",(e,t)=>{iK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>vG(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 ur(e,t){return new AX({type:"literal",values:Array.isArray(e)?e:[e],...Wt(t)})}const MX=He("ZodTransform",(e,t)=>{sK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>bG(e,n),e._zod.parse=(n,r)=>{if(r.direction==="backward")throw new gI(e.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(Lh(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(Lh(o))}};const i=t.transform(n.value,n);return i instanceof Promise?i.then(s=>(n.value=s,n)):(n.value=i,n)}});function NX(e){return new MX({type:"transform",transform:e})}const YI=He("ZodOptional",(e,t)=>{II.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>HI(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function AM(e){return new YI({type:"optional",innerType:e})}const PX=He("ZodExactOptional",(e,t)=>{oK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>HI(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function LX(e){return new PX({type:"optional",innerType:e})}const OX=He("ZodNullable",(e,t)=>{aK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>CG(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function MM(e){return new OX({type:"nullable",innerType:e})}const DX=He("ZodDefault",(e,t)=>{lK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>TG(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function IX(e,t){return new DX({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():_I(t)}})}const BX=He("ZodPrefault",(e,t)=>{cK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>RG(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function zX(e,t){return new BX({type:"prefault",innerType:e,get defaultValue(){return typeof t=="function"?t():_I(t)}})}const VI=He("ZodNonOptional",(e,t)=>{uK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>kG(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function jX(e,t){return new VI({type:"nonoptional",innerType:e,...Wt(t)})}const $X=He("ZodCatch",(e,t)=>{dK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>AG(e,n,r,i),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function FX(e,t){return new $X({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}const HX=He("ZodPipe",(e,t)=>{fK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>MG(e,n,r,i),e.in=t.in,e.out=t.out});function NM(e,t){return new HX({type:"pipe",in:e,out:t})}const UX=He("ZodReadonly",(e,t)=>{hK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>NG(e,n,r,i),e.unwrap=()=>e._zod.def.innerType});function WX(e){return new UX({type:"readonly",innerType:e})}const qX=He("ZodCustom",(e,t)=>{pK.init(e,t),Tr.init(e,t),e._zod.processJSONSchema=(n,r,i)=>yG(e,n)});function YX(e,t={}){return oG(qX,e,t)}function VX(e){return aG(e)}const KX=256,ft=Be().min(1).max(KX),GX=It({text:Be().min(1),messageId:Be().min(1).optional()}),XX=It({turnId:Be().min(1).max(256),revision:un().int().positive(),text:Be(),status:tn(["streaming","completed"])}),ZX=It({text:Be()}),PM=It({toolName:Be(),toolId:ft,parameters:hd(Be(),ma())}),QX=It({toolId:ft,whitelistTool:Vn().optional()}),JX=It({toolId:ft,reason:Be().optional()}),eZ=It({toolId:ft,result:ma(),isError:Vn()}),hl=["claude","codex"],Q0=["local-terminal","proxy-hosted"],vh=["pty","json"],Bg=["agent","terminal"],rw={WORKING:"working",TURN_COMPLETE:"turn_complete",APPROVAL_WAIT:"approval_wait"},tZ=[rw.WORKING,rw.TURN_COMPLETE,rw.APPROVAL_WAIT],zg=80,J0=24,KI=500,GI=200,R1=["idle","working","compacting","waiting_approval","error","terminated"],nZ=["idle","thinking","tool_use","outputting","waiting_permission","error"],rZ=It({sessionId:ft,kind:tn(Bg).optional(),name:Be().optional(),cwd:Be().optional(),nameLocked:Vn().optional(),state:tn(R1),mode:tn(vh).optional(),provider:tn(hl),ptyOwner:tn(Q0).optional(),lastActive:un().optional()}),iZ=It({name:Be().optional(),cwd:Be().optional(),streamDelta:Vn().optional()}),sZ=It({sessions:Br(rZ)}),oZ=It({sessionId:ft}),aZ=It({sessionId:ft}),lZ=It({sessionId:ft,state:tn(R1),lastActive:un()}),cZ=It({state:tn(tZ),seq:un().int().nonnegative().optional(),title:Be().optional(),tool:Be().optional()}),LM=It({provider:tn(hl),phase:tn(nZ),seq:un().int().nonnegative(),updatedAt:un(),toolName:Be().optional(),toolInput:hd(Be(),ma()).optional(),permissionRequest:It({requestId:ft,toolName:Be(),input:hd(Be(),ma())}).optional(),permissionResolution:It({requestId:ft,outcome:tn(["allow","deny"])}).optional(),summary:Be().optional()}),uZ=It({}),dZ=It({pairingCode:Be().optional(),token:Be().optional()}),fZ=It({lastSeq:un().int().nonnegative()}),hZ=It({messages:Br(hd(Be(),ma()))}),Uu={seq:un().int().nonnegative(),timestamp:un(),source:tn(["proxy","client"]),version:Be()},ho={...Uu,sessionId:ft};rp("type",[It({...ho,type:ur("user_input"),payload:GX}),It({...ho,type:ur("assistant_message"),payload:XX}),It({...ho,type:ur("thinking"),payload:ZX}),It({...ho,type:ur("tool_use_request"),payload:PM}),It({...ho,type:ur("tool_result"),payload:eZ}),It({...ho,type:ur("assistant_tool_use"),payload:PM}),It({...ho,type:ur("session_create"),payload:iZ}),It({...Uu,type:ur("session_list"),payload:sZ}),It({...ho,type:ur("session_switch"),payload:oZ}),It({...ho,type:ur("session_terminate"),payload:aZ}),It({...ho,type:ur("session_status"),payload:lZ}),It({...Uu,type:ur("heartbeat"),payload:uZ}),It({...Uu,type:ur("auth"),payload:dZ}),It({...Uu,type:ur("sync_request"),payload:fZ}),It({...Uu,type:ur("sync_response"),payload:hZ})]);const XI=["aliyun-bailian"],A1=["cn","intl"],pZ=["official","custom"],mZ=["male","female","unknown"],OM=It({provider:tn(XI),configured:Vn(),region:tn(A1),asrModel:Be().min(1),ttsModel:Be().min(1),ttsVoice:Be().min(1),turnIdleSeconds:un().int().positive().safe().default(3)}).strict(),DM=It({provider:tn(XI).optional(),apiKey:Be().min(1).optional(),clearApiKey:Vn().optional(),region:tn(A1).optional(),asrModel:Be().min(1).optional(),ttsModel:Be().min(1).optional(),ttsVoice:Be().min(1).optional(),turnIdleSeconds:un().int().positive().safe().optional()}).strict(),iw=It({value:Be().min(1),label:Be().min(1),description:Be().min(1).optional(),gender:tn(mZ).optional(),age:Be().min(1).optional(),model:Be().min(1).optional(),source:tn(pZ)}).strict(),gZ=It({asrModels:Br(iw),ttsModels:Br(iw),ttsVoices:Br(iw),fetchedAt:un().optional()}).strict(),vZ=[{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"}],yZ=[{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"}],bZ=[{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 sw(e){return{...e}}function Gm(e){return{asrModels:vZ.map(sw),ttsModels:yZ.map(sw),ttsVoices:bZ.map(sw)}}const _Z=tn(["code","table","diff","log","stack_trace","long_list","long_text","mixed","approval"]),wZ=tn(["pcm_s16le","mulaw"]),SZ=It({type:ur("start"),sessionId:Be().min(1),attemptId:Be().min(1),sampleRate:un().int().positive(),encoding:wZ}),xZ=It({type:ur("stop"),attemptId:Be().min(1)});rp("type",[SZ,xZ]);const EZ=rp("type",[It({type:ur("ready"),attemptId:Be().min(1)}),It({type:ur("audio_ack"),attemptId:Be().min(1),encodedBytes:un().int().nonnegative(),pcmBytes:un().int().nonnegative(),chunks:un().int().nonnegative()}),It({type:ur("partial"),attemptId:Be().min(1),text:Be()}),It({type:ur("final"),attemptId:Be().min(1),text:Be()}),It({type:ur("closed"),attemptId:Be().min(1),code:un().int().optional(),reason:Be().optional()}),It({type:ur("error"),attemptId:Be().min(1),error:Be().optional(),errorCode:Be().optional()})]);function IM(e){return/^\/compact(?:\s|$)/.test(e.trimStart())}const CZ=/((?:authorization|api[_-]?key|token|password|secret)\s*[:=]\s*)(?:bearer\s+)?[^\s'"]+/giu,kZ=/(--(?:api-key|token|password|secret)(?:=|\s+))[^\s'"]+/giu;function la(e){return typeof e=="string"?e:""}function xu(e,t=140){const n=e.replace(/\s+/gu," ").trim();return n.length<=t?n:`${n.slice(0,t-1)}…`}function Eu(e){return e.replace(CZ,"$1[redacted]").replace(kZ,"$1[redacted]")}function oc(e){return la(e.file_path)||la(e.path)||la(e.notebook_path)}function TZ(e,t){switch(e){case"Bash":{const n=xu(Eu(la(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=xu(Eu(la(t.input)),80);return n?`发送终端输入:${n}`:"发送终端输入"}case"Read":{const n=oc(t);return n?`读取文件:${n}`:"读取文件"}case"Write":{const n=oc(t);return n?`写入文件:${n}`:"写入文件"}case"Edit":case"MultiEdit":{const n=oc(t);return n?`编辑文件:${n}`:"编辑文件"}case"LS":{const n=oc(t);return n?`列出目录:${n}`:"列出目录"}case"Grep":{const n=xu(Eu(la(t.pattern)),80),r=oc(t);return n&&r?`搜索:${n} in ${r}`:n?`搜索:${n}`:"搜索文本"}case"Glob":{const n=xu(Eu(la(t.pattern)),80);return n?`查找文件:${n}`:"查找文件"}case"WebFetch":{const n=xu(Eu(la(t.url)),100);return n?`读取网页:${n}`:"读取网页"}case"WebSearch":{const n=xu(Eu(la(t.query)),100);return n?`网页搜索:${n}`:"网页搜索"}case"ViewImage":{const n=oc(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=oc(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 RZ={NOT_REGISTERED:"NOT_REGISTERED",NOT_BOUND:"NOT_BOUND",PROXY_OFFLINE:"PROXY_OFFLINE",INVALID_MESSAGE:"INVALID_MESSAGE",UNSUPPORTED:"UNSUPPORTED",INVALID_RANGE:"INVALID_RANGE"},zr={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",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",UNKNOWN:"UNKNOWN"},AZ=It({proxyId:ft,name:Be().optional(),version:Be().optional(),online:Vn(),sessions:Br(Be()).optional()}),MZ=It({clientId:ft,proxyId:ft.optional(),connectedAt:un().int().nonnegative(),current:Vn().optional(),userAgent:Be().optional(),platform:Be().optional(),maxTouchPoints:un().int().nonnegative().optional(),browserName:Be().min(1),osName:Be().min(1),deviceKind:tn(["desktop","tablet","phone","unknown"]),remoteAddress:Be().optional()}),BM=It({available:Vn(),command:Be().optional(),error:Be().optional(),suggestions:Br(Be()).optional()}),zM=It({claude:BM,codex:BM}),ZI=It({name:Be(),isDir:Vn()}),jM=It({path:Be(),entries:Br(ZI)}),$M=It({name:Be(),description:Be(),argumentHint:Be().optional(),source:Be()}),NZ=It({id:Be(),title:Be(),projectDir:Be(),updatedAt:un(),provider:tn(hl).optional(),preferredMode:tn(vh).optional()}),FM={timestamp:un().optional(),cursor:Be().optional()},PZ=rp("role",[It({role:tn(["user","assistant","system"]),text:Be(),...FM}),It({role:ur("activity"),text:Be(),toolId:ft,toolName:Be(),parameters:hd(Be(),ma()).optional(),status:tn(["running","done","error"]),...FM})]),jn={requestId:ft.optional()},ii={requestId:ft},QI=tn(Object.values(zr)),Ur={error:Be().optional(),errorCode:QI.optional()},HM=tn(["inline","download"]),UM=tn(["clipboard_image","file"]);function rt(e,t,n){return{type:e,directions:new Set(Array.isArray(n)?n:n?[n]:[]),schema:It({type:ur(e),...t??{}})}}const M1=[rt("proxy_register",{proxyId:ft,name:Be().optional(),proxyVersion:Be().min(1).max(64).optional()}),rt("proxy_register_response",{status:tn(["new","reconnected"]),relayVersion:Be().min(1).max(64).optional()}),rt("proxy_list_request",jn),rt("proxy_list_response",{...jn,proxies:Br(AZ)}),rt("relay_client_list_request",jn),rt("relay_client_list_response",{...jn,clients:Br(MZ)}),rt("relay_client_kick",{...ii,clientId:ft}),rt("relay_client_kick_response",{...ii,clientId:ft,success:Vn(),...Ur}),rt("relay_client_kicked",{reason:Be().optional()}),rt("remote_file_url_request",{...ii,sessionId:ft,path:Be().min(1),disposition:HM}),rt("remote_file_url_response",{...ii,...Ur,sessionId:ft,path:Be().optional(),success:Vn(),url:Be().optional(),expiresAt:un().int().nonnegative().optional()}),rt("remote_file_metadata_request",{...ii,sessionId:ft,path:Be().min(1)}),rt("remote_file_metadata_response",{...ii,...Ur,sessionId:ft,path:Be().optional(),success:Vn(),mimeType:Be().optional(),size:un().int().nonnegative().optional(),fileName:Be().optional()}),rt("remote_file_stream_request",{streamId:ft,sessionId:ft,path:Be().min(1),disposition:HM}),rt("remote_file_stream_response",{...Ur,streamId:ft,sessionId:ft,success:Vn(),path:Be().optional(),mimeType:Be().optional(),size:un().int().nonnegative().optional(),fileName:Be().optional()}),rt("remote_file_stream_complete",{...Ur,streamId:ft,success:Vn()}),rt("remote_file_stream_cancel",{streamId:ft}),rt("remote_file_upload_url_request",{...ii,sessionId:ft,kind:UM,fileName:Be().optional(),mimeType:Be().min(1),size:un().int().nonnegative().optional()}),rt("remote_file_upload_url_response",{...ii,...Ur,sessionId:ft,success:Vn(),uploadUrl:Be().optional(),expiresAt:un().int().nonnegative().optional()}),rt("remote_file_upload_stream_request",{uploadId:ft,sessionId:ft,kind:UM,fileName:Be().optional(),mimeType:Be().min(1),size:un().int().nonnegative().optional()}),rt("remote_file_upload_stream_complete",{uploadId:ft}),rt("remote_file_upload_stream_cancel",{uploadId:ft}),rt("remote_file_upload_stream_response",{...Ur,uploadId:ft,sessionId:ft,success:Vn(),path:Be().optional()}),rt("proxy_select",{...jn,proxyId:ft}),rt("proxy_select_response",{...jn,success:Vn(),proxyId:ft.optional(),...Ur}),rt("relay_error",{code:tn(Object.values(RZ)),message:Be(),requestId:ft.optional()}),rt("voice_config_request",jn),rt("voice_config_response",{...jn,...Ur,config:OM.optional()}),rt("voice_config_update",{...jn,config:DM}),rt("voice_config_update_response",{...jn,...Ur,success:Vn(),config:OM.optional()}),rt("voice_config_test",{...jn,config:DM.optional()}),rt("voice_config_test_response",{...jn,...Ur,success:Vn(),audioBase64:Be().optional(),audioSampleRate:un().int().positive().optional(),audioEncoding:ur("pcm_s16le").optional(),transcript:Be().optional()}),rt("voice_capabilities_request",{...jn,region:tn(A1).optional()}),rt("voice_capabilities_response",{...jn,...Ur,capabilities:gZ.optional()}),rt("latency_web_relay_ping",ii),rt("latency_web_relay_pong",{...ii,relayNow:un().optional()}),rt("latency_relay_proxy_request",ii),rt("latency_relay_proxy_response",{...ii,success:Vn(),rttMs:un().nonnegative().optional(),error:Be().optional()}),rt("latency_relay_proxy_ping",{...ii,relayNow:un().optional()}),rt("latency_relay_proxy_pong",{...ii,proxyNow:un().optional()}),rt("latency_web_proxy_ping",ii,"client_to_proxy"),rt("latency_web_proxy_pong",{...ii,proxyNow:un().optional()},"proxy_to_client"),rt("client_register",{clientId:ft,userAgent:Be().optional(),platform:Be().optional(),maxTouchPoints:un().int().nonnegative().optional(),browserName:Be().min(1),osName:Be().min(1),deviceKind:tn(["desktop","tablet","phone","unknown"])}),rt("client_register_response",{status:tn(["restored","proxy_offline","new"]),proxyId:ft.optional()}),rt("proxy_offline",{proxyId:ft}),rt("proxy_disconnect",{proxyId:ft}),rt("proxy_online",{proxyId:ft}),rt("dir_list_request",{proxyId:ft.optional(),...jn,path:Be()},"client_to_proxy"),rt("dir_list_response",{...jn,...Ur,entries:Br(ZI),path:Be()},"proxy_to_client"),rt("dir_create_request",{...jn,path:Be()},"client_to_proxy"),rt("dir_create_response",{...jn,...Ur,path:Be(),success:Vn()},"proxy_to_client"),rt("command_list_push",{commands:Br($M)},"proxy_to_client"),rt("file_tree_push",{groups:Br(jM)},"proxy_to_client"),rt("session_list",void 0,["client_to_proxy","proxy_to_client"]),rt("permission_mode_change",{mode:tn(["default","auto_accept","plan"]),sessionId:ft.optional()},"client_to_proxy"),rt("session_history_request",ii,"client_to_proxy"),rt("session_history_response",{...ii,...Ur,success:Vn(),sessions:Br(NZ)},"proxy_to_client"),rt("pty_state",{sessionId:ft,payload:cZ},"proxy_to_client"),rt("agent_status",{sessionId:ft,payload:LM},"proxy_to_client"),rt("terminal_title",{sessionId:ft,title:Be()},"proxy_to_client"),rt("terminal_resize",{sessionId:ft,cols:un().int().positive(),rows:un().int().positive()},"proxy_to_client"),rt("terminal_resize_request",{sessionId:ft,cols:un().int().positive(),rows:un().int().positive()},"client_to_proxy"),rt("session_terminate",{sessionId:ft},"client_to_proxy"),rt("session_rename",{...jn,sessionId:ft,name:Be()},"client_to_proxy"),rt("session_rename_response",{...jn,sessionId:ft,success:Vn(),name:Be().optional(),...Ur},"proxy_to_client"),rt("session_worker_abort",{sessionId:ft},"client_to_proxy"),rt("turn_result",{sessionId:ft,success:Vn(),isError:Vn(),result:Be().optional()},"proxy_to_client"),rt("remote_input_raw",{sessionId:ft,data:Be(),traceId:ft.optional()},"client_to_proxy"),rt("proxy_info_request",jn,"client_to_proxy"),rt("proxy_info",{...jn,homePath:Be(),agentCli:zM},"proxy_to_client"),rt("agent_cli_config_update",{...jn,provider:tn(hl),path:Be().min(1)},"client_to_proxy"),rt("agent_cli_config_update_response",{...jn,provider:tn(hl),agentCli:zM.optional(),...Ur},"proxy_to_client"),rt("session_create",{...jn,kind:tn(Bg).optional(),cwd:Be().optional(),name:Be().optional(),provider:tn(hl).optional(),mode:tn(vh).optional(),resumeSessionId:Be().optional(),cols:un().int().positive().max(KI).optional(),rows:un().int().positive().max(GI).optional(),permissionMode:tn(["default","auto","acceptEdits","plan","bypassPermissions","dontAsk"]).optional()},"client_to_proxy"),rt("session_create_response",{...jn,sessionId:ft.optional(),name:Be().optional(),nameLocked:Vn().optional(),kind:tn(Bg).optional(),mode:tn(vh).optional(),provider:tn(hl).optional(),ptyOwner:tn(Q0).optional(),activeWriterPid:un().int().positive().optional(),...Ur},"proxy_to_client"),rt("session_runtime_error",{sessionId:ft,error:Be(),errorCode:QI,activeWriterPid:un().int().positive().optional()},"proxy_to_client"),rt("session_messages_request",{...jn,sessionId:ft,limit:un().int().min(1).max(200).optional(),before:Be().optional()},"client_to_proxy"),rt("session_resources_request",{...jn,sessionId:ft},"client_to_proxy"),rt("session_resources_response",{...jn,...Ur,sessionId:ft,commands:Br($M),groups:Br(jM)},"proxy_to_client"),rt("agent_status_request",{...jn,sessionId:ft.optional()},"client_to_proxy"),rt("agent_status_response",{...jn,statuses:Br(It({sessionId:ft,payload:LM}))},"proxy_to_client"),rt("permission_request_delivered",{sessionId:ft,requestId:ft},"client_to_proxy"),rt("tool_approve",{sessionId:ft,payload:QX},"client_to_proxy"),rt("tool_deny",{sessionId:ft,payload:JX},"client_to_proxy"),rt("permission_decision_result",{sessionId:ft,requestId:ft,outcome:tn(["allow","deny"]),delivered:Vn(),message:Be().optional()},"proxy_to_client"),rt("pending_approvals_push",{sessionId:ft,approvals:Br(It({requestId:ft,toolName:Be(),input:hd(Be(),ma())}))},"proxy_to_client"),rt("voice_summary_request",{...jn,sessionId:ft,messageId:ft,text:Be().min(1),reason:_Z},"client_to_proxy"),rt("voice_summary_response",{...jn,...Ur,sessionId:ft,messageId:ft,success:Vn(),summary:Be().min(1).optional()},"proxy_to_client"),rt("session_history_messages",{...jn,sessionId:ft,before:Be().optional(),messages:Br(PZ),hasMore:Vn().optional(),nextBefore:Be().optional()},"proxy_to_client"),rt("session_sync",{sessions:Br(It({id:Be(),kind:tn(Bg).optional(),mode:tn(vh),provider:tn(hl),ptyOwner:tn(Q0).optional(),cwd:Be().optional(),name:Be().optional(),nameLocked:Vn().optional(),state:tn(R1)}))}),rt("session_subscribe",{sessionId:ft,requestId:ft},"client_to_proxy"),rt("session_snapshot",{sessionId:ft,cols:un().int().positive(),rows:un().int().positive(),data:Be(),outputSeq:un().int().nonnegative(),requestId:ft},"proxy_to_client")],LZ=M1.map(e=>e.schema);rp("type",LZ);new Set(M1.filter(e=>e.directions.has("proxy_to_client")).map(e=>e.type));new Set(M1.filter(e=>e.directions.has("client_to_proxy")).map(e=>e.type));const OZ=3e4,DZ=5e3,N1=OZ+DZ,IZ={CLIENT_KICKED:4401},Pf=1,Xm=4;function BZ(e){if(e.length<Pf+Xm)return null;const t=e[0];if(t===0||e.length<Pf+t+Xm)return null;const n=new TextDecoder().decode(e.subarray(Pf,Pf+t)),r=Pf+t,i=new DataView(e.buffer,e.byteOffset+r,Xm).getUint32(0,!0),s=e.subarray(r+Xm);return{sessionId:n,outputSeq:i,data:s}}const zZ=132,jZ=32635;function $Z(e){let t=e;const n=t<0?128:0;t<0&&(t=-t),t=Math.min(t,jZ)+zZ;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 FZ(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]=$Z(r.getInt16(i*2,!0));return n}function HZ(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 WM(e){let t=e.initial;const n=HZ(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 UZ(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 WZ({userAgent:e="",platform:t,maxTouchPoints:n=0}){return t==="MacIntel"&&n>1&&(e.includes("Mac OS X")||e.includes("Macintosh"))}function qZ(e){const t=e.userAgent??"";if(WZ(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 YZ(e){return e==="iPad"?"tablet":e==="iPhone"||e==="Android"?"phone":e==="macOS"||e==="Windows"?"desktop":"unknown"}function JI(e){const t=e.browserName??(e.userAgent?UZ(e.userAgent):void 0)??"浏览器",n=e.osName??qZ(e)??"未知系统";return{...e,browserName:t,osName:n,deviceKind:e.deviceKind??YZ(n)}}function ip(){const e=typeof navigator>"u"?null:navigator;return JI({...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 VZ(e){return`${e.browserName} · ${e.osName}`}const KZ=1e4,GZ=5e3,ow=15e3,XZ=2e3;class ZZ{constructor(t={}){_t(this,"ws",null);_t(this,"url","");_t(this,"connected",!1);_t(this,"closed",!1);_t(this,"reconnectTimer",null);_t(this,"reconnectAttempt",0);_t(this,"messageHandlers",new Set);_t(this,"binarySubscribers",new Map);_t(this,"statusHandlers",new Set);_t(this,"pendingQueue",[]);_t(this,"wakeListenersAttached",!1);_t(this,"backgroundedAt",null);_t(this,"connectionProbe",null);_t(this,"connectionProbeSeq",0);_t(this,"foregroundWatchdogTimer",null);_t(this,"lastInboundAt",0);_t(this,"probeConnectionLiveness");_t(this,"visibilityListener",()=>{if(document.visibilityState==="hidden"){this.markBackgrounded();return}document.visibilityState==="visible"&&this.resumeFromBackground()});_t(this,"onlineListener",()=>this.wakeReconnect(!0));_t(this,"blurListener",()=>this.markBackgrounded());_t(this,"focusListener",()=>{document.visibilityState!=="hidden"&&this.resumeFromBackground()});_t(this,"pageHideListener",()=>this.markBackgrounded());_t(this,"pageShowListener",()=>this.resumeFromBackground());const n=ip().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>=GZ;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=ow){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.connected||t.readyState!==WebSocket.OPEN){this.wakeReconnect(!0);return}const n=Date.now()-this.lastInboundAt;if(n<ow){this.armForegroundWatchdog(ow-n);return}this.probeConnection()}probeConnection(){if(this.closed)return;const t=this.ws;if(!this.connected||!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))},XZ);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)}connect(t){this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.ws&&(this.ws.close(),this.ws=null),this.cancelReconnectTimer(),this.connected=!1,this.url=t,this.closed=!1,this.reconnectAttempt=0,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.connected||!t&&this.ws&&this.ws.readyState===WebSocket.CONNECTING)return;this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.reconnectAttempt=0,this.cancelReconnectTimer();const n=this.ws,r=this.connected;if(this.ws=null,this.connected=!1,r&&this.statusHandlers.forEach(i=>i(!1)),n)try{n.close()}catch{}this.doConnect()}send(t,n={}){if(!this.ws)return console.warn("WebSocket send dropped: no socket"),!1;if(!this.connected){if(n.queueWhenDisconnected){if(this.pendingQueue.length>=KZ){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!1}return this.doSend(t),!0}close(){var t;this.closed=!0,this.cancelConnectionProbe(),this.cancelForegroundWatchdog(),this.cancelReconnectTimer(),(t=this.ws)==null||t.close(),this.ws=null,this.connected=!1,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.connected}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.armForegroundWatchdog(),t.addEventListener("open",()=>{this.ws===t&&(this.connected=!0,this.reconnectAttempt=0,this.lastInboundAt=Date.now(),this.armForegroundWatchdog(),this.statusHandlers.forEach(n=>n(!0)),this.flushPendingQueue())}),t.addEventListener("message",n=>{if(this.ws===t)if(n.data instanceof ArrayBuffer)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=>{this.ws===t&&(this.cancelConnectionProbe(t),this.cancelForegroundWatchdog(),n.code===IZ.CLIENT_KICKED&&(this.closed=!0,this.cancelReconnectTimer()),this.connected=!1,this.ws=null,this.statusHandlers.forEach(r=>r(!1)),this.closed||this.scheduleReconnect())}),t.addEventListener("error",()=>{})}scheduleReconnect(){const t=Math.min(1e3*Math.pow(2,this.reconnectAttempt),3e4),n=Math.random()*t;this.reconnectAttempt++,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,this.doConnect()},n)}dispatchBinary(t){const n=BZ(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 QZ=24,JZ=48,eQ=1,tQ=4,nQ=8,rQ=8,iQ=32;function qM(e,t,n){return Math.min(n,Math.max(t,e))}function sQ({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:zg,rows:J0};const l=Math.max(0,e-Math.max(0,n)-QZ),u=Math.floor(l/s),f=u<zg?iQ:rQ,p=JZ+eQ+tQ+nQ+f+Math.max(0,r)+Math.max(0,i),y=Math.max(0,t-p),g=Math.floor(y/o);return{cols:qM(u,zg,KI),rows:qM(g,J0,GI)}}function oQ(){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 aQ(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:fI,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 lQ(){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 cQ(){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 uQ(e=ud){if(typeof window>"u")return{cols:zg,rows:J0};const t=cQ(),n=oQ(),r=aQ(e);return sQ({viewportWidth:t.width,viewportHeight:t.height,sidebarWidth:lQ(),safeAreaTop:n.top,safeAreaBottom:n.bottom,cellWidth:r.width,cellHeight:r.height})}const Wr=1e4,dQ=2e4,aw=3e3;let YM=0;function mr(e){return YM+=1,`${e}-${Date.now().toString(36)}-${YM.toString(36)}`}class fQ{constructor(t,n){_t(this,"ws");_t(this,"clientId");_t(this,"boundProxyId",null);_t(this,"messageHandlers",new Set);_t(this,"pendingMessages",[]);this.ws=t,this.clientId=n,this.ws.onMessage(r=>{let i;try{i=JSON.parse(r)}catch(s){console.warn("RelayClient: failed to parse JSON:",r.slice(0,200),s);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.boundProxyId=null;const t=ip();this.ws.send(JSON.stringify({type:"client_register",clientId:this.clientId,...t}))}listProxies(){this.ws.send(JSON.stringify({type:"proxy_list_request"}))}requestProxyList(t=Wr){const n=mr("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)}requestRelayClients(t=Wr){const n=mr("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=Wr){const r=mr("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=Wr){const r=mr("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=t),{success:i.success,proxyId:i.proxyId,error:i.error,errorCode:i.errorCode}))}createDirectory(t,n=Wr){const r=mr("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=Wr){const r=mr("dir-list");return this.waitForMessage(i=>i.type==="dir_list_response"&&i.requestId===r,()=>this.ws.send(JSON.stringify({type:"dir_list_request",requestId:r,path:t})),"读取目录超时",n,r).then(i=>({path:i.path,entries:i.entries,error:i.error,errorCode:i.errorCode}))}uploadClipboardImage(t,n){return this.uploadRemoteFile(t,n,"clipboard_image")}requestRemoteFileUrl(t,n,r,i=Wr){const s=mr("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=Wr){const s=mr("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=Wr){const n=mr("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}))}updateAgentCliPath(t,n,r=Wr){const i=mr("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=Wr){const n=mr("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=Wr){const r=mr("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=Wr){const r=mr("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=Wr){const r=mr("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=dQ){const o=mr("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=aw){const n=mr("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=aw){const n=mr("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=aw){const n=mr("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=Wr){const n=mr("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=Wr){return this.requestSessionMessagesPage(t,{},n).then(r=>r.messages)}requestSessionMessagesPage(t,n={},r=Wr){const i=mr("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=Wr){const r=mr("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=Wr){const r=mr("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=N1){const r=mr("session-create"),i=t.mode==="pty"?uQ(De.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=Wr){const i=mr("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){return new Promise((o,l)=>{let u=!1,d=null,f=null,p=null;const y=()=>{d==null||d(),f==null||f(),p&&clearTimeout(p)},g=b=>{u||(u=!0,y(),b())};d=this.onMessage(b=>{if(t(b)){g(()=>o(b));return}if(s&&b.type==="relay_error"&&b.requestId===s){const w=b.message??"relay error";g(()=>l(new Error(`Relay 服务器拒绝请求: ${w}`)))}}),f=this.ws.onStatusChange(b=>{b||g(()=>l(new Error("连接已断开")))}),p=setTimeout(()=>{g(()=>l(new Error(r)))},i);try{n()===!1&&g(()=>l(new Error("连接已断开")))}catch(b){g(()=>l(b instanceof Error?b:new Error(String(b))))}})}getBoundProxyId(){return this.boundProxyId}clearBoundProxy(t){(!t||this.boundProxyId===t)&&(this.boundProxyId=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 Fc=ZO();const eB=Xh(Fc);function hQ(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 pQ=e=>{switch(e){case"success":return vQ;case"info":return bQ;case"warning":return yQ;case"error":return _Q;default:return null}},mQ=Array(12).fill(0),gQ=({visible:e,className:t})=>et.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},et.createElement("div",{className:"sonner-spinner"},mQ.map((n,r)=>et.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),vQ=et.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},et.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"})),yQ=et.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},et.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"})),bQ=et.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},et.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"})),_Q=et.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},et.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"})),wQ=et.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"},et.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),et.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),SQ=()=>{const[e,t]=et.useState(document.hidden);return et.useEffect(()=>{const n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e};let eS=1;class xQ{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:eS++,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],et.isValidElement(d))s=!1,this.create({id:r,type:"default",message:d});else if(CQ(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,b=typeof p=="object"&&!et.isValidElement(p)?p:{message:p};this.create({id:r,type:"error",description:y,...b})}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,b=typeof p=="object"&&!et.isValidElement(p)?p:{message:p};this.create({id:r,type:"error",description:y,...b})}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,b=typeof p=="object"&&!et.isValidElement(p)?p:{message:p};this.create({id:r,type:"success",description:y,...b})}}).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"&&!et.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)||eS++;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 ts=new xQ,EQ=(e,t)=>{const n=(t==null?void 0:t.id)||eS++;return ts.addToast({title:e,...t,id:n}),n},CQ=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",kQ=EQ,TQ=()=>ts.toasts,RQ=()=>ts.getActiveToasts(),nt=Object.assign(kQ,{success:ts.success,info:ts.info,warning:ts.warning,error:ts.error,custom:ts.custom,message:ts.message,promise:ts.promise,dismiss:ts.dismiss,loading:ts.loading},{getHistory:TQ,getToasts:RQ});hQ("[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 Zm(e){return e.label!==void 0}const AQ=3,MQ="24px",NQ="16px",VM=4e3,PQ=356,LQ=14,OQ=45,DQ=200;function po(...e){return e.filter(Boolean).join(" ")}function IQ(e){const[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}const BQ=e=>{var t,n,r,i,s,o,l,u,d;const{invert:f,toast:p,unstyled:y,interacting:g,setHeights:b,visibleToasts:w,heights:S,index:E,toasts:k,expanded:T,removeToast:R,defaultRichColors:P,closeButton:A,style:H,cancelButtonStyle:D,actionButtonStyle:K,className:q="",descriptionClassName:X="",duration:z,position:N,gap:$,expandByDefault:I,classNames:M,icons:O,closeButtonAriaLabel:U="Close toast"}=e,[B,L]=et.useState(null),[Y,V]=et.useState(null),[j,te]=et.useState(!1),[re,oe]=et.useState(!1),[ee,pe]=et.useState(!1),[ae,me]=et.useState(!1),[Ee,Oe]=et.useState(!1),[Se,Qe]=et.useState(0),[Ht,ye]=et.useState(0),Xe=et.useRef(p.duration||z||VM),kt=et.useRef(null),gt=et.useRef(null),Lt=E===0,an=E+1<=w,ut=p.type,Le=p.dismissible!==!1,Ke=p.className||"",lt=p.descriptionClassName||"",ve=et.useMemo(()=>S.findIndex(W=>W.toastId===p.id)||0,[S,p.id]),$e=et.useMemo(()=>{var W;return(W=p.closeButton)!=null?W:A},[p.closeButton,A]),at=et.useMemo(()=>p.duration||z||VM,[p.duration,z]),yt=et.useRef(0),pt=et.useRef(0),cn=et.useRef(0),qt=et.useRef(null),[Gt,vn]=N.split("-"),dn=et.useMemo(()=>S.reduce((W,ne,G)=>G>=ve?W:W+ne.height,0),[S,ve]),$t=SQ(),nn=p.invert||f,rn=ut==="loading";pt.current=et.useMemo(()=>ve*$+dn,[ve,dn]),et.useEffect(()=>{Xe.current=at},[at]),et.useEffect(()=>{te(!0)},[]),et.useEffect(()=>{const W=gt.current;if(W){const ne=W.getBoundingClientRect().height;return ye(ne),b(G=>[{toastId:p.id,height:ne,position:p.position},...G]),()=>b(G=>G.filter(de=>de.toastId!==p.id))}},[b,p.id]),et.useLayoutEffect(()=>{if(!j)return;const W=gt.current,ne=W.style.height;W.style.height="auto";const G=W.getBoundingClientRect().height;W.style.height=ne,ye(G),b(de=>de.find(Q=>Q.toastId===p.id)?de.map(Q=>Q.toastId===p.id?{...Q,height:G}:Q):[{toastId:p.id,height:G,position:p.position},...de])},[j,p.title,p.description,b,p.id,p.jsx,p.action,p.cancel]);const qn=et.useCallback(()=>{oe(!0),Qe(pt.current),b(W=>W.filter(ne=>ne.toastId!==p.id)),setTimeout(()=>{R(p)},DQ)},[p,R,b,pt]);et.useEffect(()=>{if(p.promise&&ut==="loading"||p.duration===1/0||p.type==="loading")return;let W;return T||g||$t?(()=>{if(cn.current<yt.current){const de=new Date().getTime()-yt.current;Xe.current=Xe.current-de}cn.current=new Date().getTime()})():(()=>{Xe.current!==1/0&&(yt.current=new Date().getTime(),W=setTimeout(()=>{p.onAutoClose==null||p.onAutoClose.call(p,p),qn()},Xe.current))})(),()=>clearTimeout(W)},[T,g,p,ut,$t,qn]),et.useEffect(()=>{p.delete&&(qn(),p.onDismiss==null||p.onDismiss.call(p,p))},[qn,p.delete]);function Fn(){var W;if(O!=null&&O.loading){var ne;return et.createElement("div",{className:po(M==null?void 0:M.loader,p==null||(ne=p.classNames)==null?void 0:ne.loader,"sonner-loader"),"data-visible":ut==="loading"},O.loading)}return et.createElement(gQ,{className:po(M==null?void 0:M.loader,p==null||(W=p.classNames)==null?void 0:W.loader),visible:ut==="loading"})}const Jn=p.icon||(O==null?void 0:O[ut])||pQ(ut);var lr,fn;return et.createElement("li",{tabIndex:0,ref:gt,className:po(q,Ke,M==null?void 0:M.toast,p==null||(t=p.classNames)==null?void 0:t.toast,M==null?void 0:M.default,M==null?void 0:M[ut],p==null||(n=p.classNames)==null?void 0:n[ut]),"data-sonner-toast":"","data-rich-colors":(lr=p.richColors)!=null?lr:P,"data-styled":!(p.jsx||p.unstyled||y),"data-mounted":j,"data-promise":!!p.promise,"data-swiped":Ee,"data-removed":re,"data-visible":an,"data-y-position":Gt,"data-x-position":vn,"data-index":E,"data-front":Lt,"data-swiping":ee,"data-dismissible":Le,"data-type":ut,"data-invert":nn,"data-swipe-out":ae,"data-swipe-direction":Y,"data-expanded":!!(T||I&&j),"data-testid":p.testId,style:{"--index":E,"--toasts-before":E,"--z-index":k.length-E,"--offset":`${re?Se:pt.current}px`,"--initial-height":I?"auto":`${Ht}px`,...H,...p.style},onDragEnd:()=>{pe(!1),L(null),qt.current=null},onPointerDown:W=>{W.button!==2&&(rn||!Le||(kt.current=new Date,Qe(pt.current),W.target.setPointerCapture(W.pointerId),W.target.tagName!=="BUTTON"&&(pe(!0),qt.current={x:W.clientX,y:W.clientY})))},onPointerUp:()=>{var W,ne,G;if(ae||!Le)return;qt.current=null;const de=Number(((W=gt.current)==null?void 0:W.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),xe=Number(((ne=gt.current)==null?void 0:ne.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Q=new Date().getTime()-((G=kt.current)==null?void 0:G.getTime()),ie=B==="x"?de:xe,le=Math.abs(ie)/Q;if(Math.abs(ie)>=OQ||le>.11){Qe(pt.current),p.onDismiss==null||p.onDismiss.call(p,p),V(B==="x"?de>0?"right":"left":xe>0?"down":"up"),qn(),me(!0);return}else{var he,Z;(he=gt.current)==null||he.style.setProperty("--swipe-amount-x","0px"),(Z=gt.current)==null||Z.style.setProperty("--swipe-amount-y","0px")}Oe(!1),pe(!1),L(null)},onPointerMove:W=>{var ne,G,de;if(!qt.current||!Le||((ne=window.getSelection())==null?void 0:ne.toString().length)>0)return;const Q=W.clientY-qt.current.y,ie=W.clientX-qt.current.x;var le;const he=(le=e.swipeDirections)!=null?le:IQ(N);!B&&(Math.abs(ie)>1||Math.abs(Q)>1)&&L(Math.abs(ie)>Math.abs(Q)?"x":"y");let Z={x:0,y:0};const se=ce=>1/(1.5+Math.abs(ce)/20);if(B==="y"){if(he.includes("top")||he.includes("bottom"))if(he.includes("top")&&Q<0||he.includes("bottom")&&Q>0)Z.y=Q;else{const ce=Q*se(Q);Z.y=Math.abs(ce)<Math.abs(Q)?ce:Q}}else if(B==="x"&&(he.includes("left")||he.includes("right")))if(he.includes("left")&&ie<0||he.includes("right")&&ie>0)Z.x=ie;else{const ce=ie*se(ie);Z.x=Math.abs(ce)<Math.abs(ie)?ce:ie}(Math.abs(Z.x)>0||Math.abs(Z.y)>0)&&Oe(!0),(G=gt.current)==null||G.style.setProperty("--swipe-amount-x",`${Z.x}px`),(de=gt.current)==null||de.style.setProperty("--swipe-amount-y",`${Z.y}px`)}},$e&&!p.jsx&&ut!=="loading"?et.createElement("button",{"aria-label":U,"data-disabled":rn,"data-close-button":!0,onClick:rn||!Le?()=>{}:()=>{qn(),p.onDismiss==null||p.onDismiss.call(p,p)},className:po(M==null?void 0:M.closeButton,p==null||(r=p.classNames)==null?void 0:r.closeButton)},(fn=O==null?void 0:O.close)!=null?fn:wQ):null,(ut||p.icon||p.promise)&&p.icon!==null&&((O==null?void 0:O[ut])!==null||p.icon)?et.createElement("div",{"data-icon":"",className:po(M==null?void 0:M.icon,p==null||(i=p.classNames)==null?void 0:i.icon)},p.promise||p.type==="loading"&&!p.icon?p.icon||Fn():null,p.type!=="loading"?Jn:null):null,et.createElement("div",{"data-content":"",className:po(M==null?void 0:M.content,p==null||(s=p.classNames)==null?void 0:s.content)},et.createElement("div",{"data-title":"",className:po(M==null?void 0:M.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?et.createElement("div",{"data-description":"",className:po(X,lt,M==null?void 0:M.description,p==null||(l=p.classNames)==null?void 0:l.description)},typeof p.description=="function"?p.description():p.description):null),et.isValidElement(p.cancel)?p.cancel:p.cancel&&Zm(p.cancel)?et.createElement("button",{"data-button":!0,"data-cancel":!0,style:p.cancelButtonStyle||D,onClick:W=>{Zm(p.cancel)&&Le&&(p.cancel.onClick==null||p.cancel.onClick.call(p.cancel,W),qn())},className:po(M==null?void 0:M.cancelButton,p==null||(u=p.classNames)==null?void 0:u.cancelButton)},p.cancel.label):null,et.isValidElement(p.action)?p.action:p.action&&Zm(p.action)?et.createElement("button",{"data-button":!0,"data-action":!0,style:p.actionButtonStyle||K,onClick:W=>{Zm(p.action)&&(p.action.onClick==null||p.action.onClick.call(p.action,W),!W.defaultPrevented&&qn())},className:po(M==null?void 0:M.actionButton,p==null||(d=p.classNames)==null?void 0:d.actionButton)},p.action.label):null)};function KM(){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 zQ(e,t){const n={};return[e,t].forEach((r,i)=>{const s=i===1,o=s?"--mobile-offset":"--offset",l=s?NQ:MQ;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 jQ=et.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:b,style:w,visibleToasts:S=AQ,toastOptions:E,dir:k=KM(),gap:T=LQ,icons:R,containerAriaLabel:P="Notifications"}=t,[A,H]=et.useState([]),D=et.useMemo(()=>r?A.filter(j=>j.toasterId===r):A.filter(j=>!j.toasterId),[A,r]),K=et.useMemo(()=>Array.from(new Set([s].concat(D.filter(j=>j.position).map(j=>j.position)))),[D,s]),[q,X]=et.useState([]),[z,N]=et.useState(!1),[$,I]=et.useState(!1),[M,O]=et.useState(y!=="system"?y:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),U=et.useRef(null),B=o.join("+").replace(/Key/g,"").replace(/Digit/g,""),L=et.useRef(null),Y=et.useRef(!1),V=et.useCallback(j=>{H(te=>{var re;return(re=te.find(oe=>oe.id===j.id))!=null&&re.delete||ts.dismiss(j.id),te.filter(({id:oe})=>oe!==j.id)})},[]);return et.useEffect(()=>ts.subscribe(j=>{if(j.dismiss){requestAnimationFrame(()=>{H(te=>te.map(re=>re.id===j.id?{...re,delete:!0}:re))});return}setTimeout(()=>{eB.flushSync(()=>{H(te=>{const re=te.findIndex(oe=>oe.id===j.id);return re!==-1?[...te.slice(0,re),{...te[re],...j},...te.slice(re+1)]:[j,...te]})})})}),[A]),et.useEffect(()=>{if(y!=="system"){O(y);return}if(y==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?O("dark"):O("light")),typeof window>"u")return;const j=window.matchMedia("(prefers-color-scheme: dark)");try{j.addEventListener("change",({matches:te})=>{O(te?"dark":"light")})}catch{j.addListener(({matches:re})=>{try{O(re?"dark":"light")}catch(oe){console.error(oe)}})}},[y]),et.useEffect(()=>{A.length<=1&&N(!1)},[A]),et.useEffect(()=>{const j=te=>{var re;if(o.every(pe=>te[pe]||te.code===pe)){var ee;N(!0),(ee=U.current)==null||ee.focus()}te.code==="Escape"&&(document.activeElement===U.current||(re=U.current)!=null&&re.contains(document.activeElement))&&N(!1)};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[o]),et.useEffect(()=>{if(U.current)return()=>{L.current&&(L.current.focus({preventScroll:!0}),L.current=null,Y.current=!1)}},[U.current]),et.createElement("section",{ref:n,"aria-label":`${P} ${B}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},K.map((j,te)=>{var re;const[oe,ee]=j.split("-");return D.length?et.createElement("ol",{key:j,dir:k==="auto"?KM():k,tabIndex:-1,ref:U,className:d,"data-sonner-toaster":!0,"data-sonner-theme":M,"data-y-position":oe,"data-x-position":ee,style:{"--front-toast-height":`${((re=q[0])==null?void 0:re.height)||0}px`,"--width":`${PQ}px`,"--gap":`${T}px`,...w,...zQ(f,p)},onBlur:pe=>{Y.current&&!pe.currentTarget.contains(pe.relatedTarget)&&(Y.current=!1,L.current&&(L.current.focus({preventScroll:!0}),L.current=null))},onFocus:pe=>{pe.target instanceof HTMLElement&&pe.target.dataset.dismissible==="false"||Y.current||(Y.current=!0,L.current=pe.relatedTarget)},onMouseEnter:()=>N(!0),onMouseMove:()=>N(!0),onMouseLeave:()=>{$||N(!1)},onDragEnd:()=>N(!1),onPointerDown:pe=>{pe.target instanceof HTMLElement&&pe.target.dataset.dismissible==="false"||I(!0)},onPointerUp:()=>I(!1)},D.filter(pe=>!pe.position&&te===0||pe.position===j).map((pe,ae)=>{var me,Ee;return et.createElement(BQ,{key:pe.id,icons:R,index:ae,toast:pe,defaultRichColors:g,duration:(me=E==null?void 0:E.duration)!=null?me:b,className:E==null?void 0:E.className,descriptionClassName:E==null?void 0:E.descriptionClassName,invert:i,visibleToasts:S,closeButton:(Ee=E==null?void 0:E.closeButton)!=null?Ee:u,interacting:$,position:j,style:E==null?void 0:E.style,unstyled:E==null?void 0:E.unstyled,classNames:E==null?void 0:E.classNames,cancelButtonStyle:E==null?void 0:E.cancelButtonStyle,actionButtonStyle:E==null?void 0:E.actionButtonStyle,closeButtonAriaLabel:E==null?void 0:E.closeButtonAriaLabel,removeToast:V,toasts:D.filter(Oe=>Oe.position==pe.position),heights:q.filter(Oe=>Oe.position==pe.position),setHeights:X,expandByDefault:l,gap:T,expanded:z,swipeDirections:t.swipeDirections})})):null}))});function $Q(){const e=De(t=>t.themePreference);return v.jsx(jQ,{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 tS(e){return"error"in e}async function nS(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:zr.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:zr.SESSION_NOT_FOUND};n=s.proxyId}if(!n)return{error:"No proxy specified",code:zr.UNKNOWN};let r;try{r=await e.selectProxy(n)}catch(i){return{error:i instanceof Error?i.message:String(i),code:zr.UNKNOWN}}return r.success?{proxyId:n}:{error:r.error||"Proxy select failed",code:r.errorCode??zr.UNKNOWN}}async function P1(e,t){const n=De.getState().selectedProxyId;if(!n)return{status:"skipped"};const r=Ft.getState().beginHistoryLoad();try{const i=t===void 0?await e.requestSessionHistory():await e.requestSessionHistory(t);return De.getState().selectedProxyId!==n?(Ft.getState().cancelHistoryLoad(r),{status:"stale"}):Ft.getState().resolveHistoryLoad(r,i)?{status:"loaded",sessions:i}:{status:"stale"}}catch(i){return De.getState().selectedProxyId!==n?(Ft.getState().cancelHistoryLoad(r),{status:"stale"}):Ft.getState().rejectHistoryLoad(r)?{status:"failed",error:i}:{status:"stale"}}}const FQ=3e4,HQ=15e3,UQ=500,WQ=2e3;function qQ(){return{reconnect:null,bindingRetry:null,bindingRetryAttempt:0,bindingAttemptGeneration:null,recoveryGeneration:0,coldStartDone:!1,disposed:!1}}function YQ(){const e=window.location.hash.match(/^#\/chat\/([^/?]+)/);return(e==null?void 0:e[1])??null}function rS(e){const t=De.getState().selectedProxyId;t&&(e.sendControl({type:"session_list"}),e.requestProxyInfo().then(n=>{if(De.getState().selectedProxyId!==t)return;const r=hi.getState();r.setHomePath(n.homePath),r.setAgentCli(n.agentCli)}).catch(n=>{console.error("[phase-machine] requestProxyInfo failed",n),nt.error("无法获取开发机信息")}),e.requestAgentStatuses().then(n=>{if(De.getState().selectedProxyId!==t)return;const r=Ft.getState();for(const i of n)r.setAgentStatus(i.sessionId,i.payload)}).catch(n=>{console.error("[phase-machine] requestAgentStatuses failed",n)}))}function iS(e){P1(e,HQ).then(t=>{if(t.status==="failed"){console.error("[phase-machine] requestSessionHistory failed",t.error);const n=De.getState();if(!n.connected||!n.proxyOnline||n.phase==="reconnecting")return;nt.warning("历史会话加载失败,可点击刷新重试")}})}async function jg(e,t,n=()=>!0){const r=await nS(e,{proxyId:t.proxyId});return tS(r)||!n()?!1:(Er("local",Sn.proxyId,t.proxyId),De.getState().setProxy(t.proxyId,t.name??null),De.getState().setProxyOnline(!0),rS(e),iS(e),!0)}function VQ(e){e.reconnect&&(clearTimeout(e.reconnect),e.reconnect=null)}function Oh(e){e.recoveryGeneration+=1,e.bindingAttemptGeneration=null,e.bindingRetryAttempt=0,e.bindingRetry&&(clearTimeout(e.bindingRetry),e.bindingRetry=null)}function tB(e){VQ(e),Oh(e)}function GM(e){e.reconnect||e.disposed||(e.reconnect=setTimeout(()=>{e.reconnect=null,Oh(e),!(e.disposed||De.getState().phase!=="reconnecting")&&(e.coldStartDone=!1,De.getState().setProxyOnline(!1),De.getState().setProxies([]),De.getState().resetProxyListLoaded(),De.getState().transitionToPhase("connecting"),jv.navigate("/"))},FQ))}function XM(e,t,n){const r=De.getState();return!e.disposed&&e.recoveryGeneration===t&&e.bindingAttemptGeneration===t&&r.connected&&r.phase==="reconnecting"&&r.selectedProxyId===n}function KQ(e,t,n,r){if(e.bindingRetry||e.disposed||e.recoveryGeneration!==r)return;const i=Math.min(e.bindingRetryAttempt,2),s=Math.min(UQ*2**i,WQ);e.bindingRetryAttempt+=1,e.bindingRetry=setTimeout(()=>{e.bindingRetry=null,!(e.disposed||e.recoveryGeneration!==r||De.getState().phase!=="reconnecting")&&sS(e,t,n,r)},s)}async function sS(e,t,n,r=e.recoveryGeneration){const i=De.getState();if(e.disposed||e.recoveryGeneration!==r||e.bindingAttemptGeneration!==null||!i.connected||i.phase!=="reconnecting"||i.selectedProxyId!==n.proxyId)return;e.bindingRetry&&(clearTimeout(e.bindingRetry),e.bindingRetry=null),e.bindingAttemptGeneration=r;const s=await jg(t,n,()=>XM(e,r,n.proxyId));if(XM(e,r,n.proxyId)){if(e.bindingAttemptGeneration=null,s){const o=De.getState().phaseBeforeDisconnect;tB(e),De.getState().transitionToPhase(o??"session_browsing");return}De.getState().setProxyOnline(!1),KQ(e,t,n,r)}}function GQ(e){e.disposed=!0,tB(e)}function XQ(e){switch(e){case zr.SESSION_NOT_FOUND:return"会话不存在或已关闭";case zr.PROXY_OFFLINE:return"开发机已离线";default:return"无法打开会话"}}function ZQ(e,t,n){if(t.disposed)return;De.getState().setConnected(e);const r=De.getState();e?(Oh(t),n.register(),r.phase==="connecting"&&De.getState().setPhase("registering"),r.phase==="reconnecting"&&(De.getState().setProxyOnline(!1),GM(t),n.listProxies())):(Oh(t),De.getState().setProxyOnline(!1),De.getState().setProxies([]),De.getState().resetProxyListLoaded(),r.phase!=="connecting"&&(r.phase!=="reconnecting"&&De.getState().setPhase("reconnecting"),GM(t)))}async function QQ(e,t,n){if(t.disposed)return;const r=De.getState();if(e.type==="client_register_response"){r.phase==="registering"&&(n.listProxies(),De.getState().setPhase("proxy_selecting"));return}if(e.type==="relay_client_kicked"){nt.info("这个客户端已被断开");return}if(e.type==="proxy_offline"){n.listProxies(),e.proxyId===r.selectedProxyId&&(Oh(t),n.clearBoundProxy(typeof e.proxyId=="string"?e.proxyId:void 0),De.getState().setProxyOnline(!1),nt.warning("当前开发机已离线"));return}if(e.type==="proxy_online"){if(n.listProxies(),e.proxyId===r.selectedProxyId){if(n.getBoundProxyId()===e.proxyId&&r.phase!=="reconnecting"){De.getState().setProxyOnline(!0),nt.success("当前开发机已恢复连接");return}De.getState().setProxyOnline(!1);const s=De.getState().proxies.find(o=>o.proxyId===e.proxyId);if(s){const o={...s};r.phase==="reconnecting"?await sS(t,n,o):await jg(n,o)&&nt.success("当前开发机已恢复连接")}}return}if(e.type==="proxy_list_response"){const i=e.proxies;if(De.getState().setProxies(i),!t.coldStartDone&&r.phase==="proxy_selecting"){t.coldStartDone=!0;const s=Oi("local",Sn.proxyId),o=s?null:YQ();if(!s&&o){const l=await nS(n,{sessionId:o});if(tS(l)){const d=XQ(l.code);De.getState().setPendingToast({kind:"error",message:d}),jv.navigate("/"),t.coldStartDone=!1;return}const u=i.find(d=>d.proxyId===l.proxyId);De.getState().setProxy(l.proxyId,(u==null?void 0:u.name)||null),De.getState().setProxyOnline(!0),Er("local",Sn.proxyId,l.proxyId),De.getState().setPhase("chatting"),rS(n),iS(n);return}if(s){const l=await nS(n,{proxyId:s});if(!tS(l)){const u=i.find(d=>d.proxyId===s);De.getState().setProxy(s,(u==null?void 0:u.name)||null),De.getState().setProxyOnline(!0),rS(n),iS(n),De.getState().setPhase("session_browsing");return}t.coldStartDone=!1}}if(r.selectedProxyId){const s=i.find(u=>u.proxyId===r.selectedProxyId),o=(s==null?void 0:s.online)===!0&&n.getBoundProxyId()===s.proxyId;De.getState().setProxyOnline(o);const l=(s==null?void 0:s.online)===!0&&!o;if(r.phase==="reconnecting"){s!=null&&s.online&&await sS(t,n,s);return}if(r.phase==="proxy_selecting"&&(s!=null&&s.online)){await jg(n,s)&&(De.getState().transitionToPhase("session_browsing"),jv.navigate("/sessions"));return}l&&await jg(n,s)}}}function ZM(e){return typeof e=="string"?e:""}function fv(e){if(typeof e=="string")return e;if(e==null)return"";try{return JSON.stringify(e,null,2)}catch{return String(e)}}function oS(e){switch(e){case"add":return"新增";case"delete":return"删除";case"update":return"更新";default:return"变更"}}function lw(e,t){const n=fv(t);return n?{title:e,content:n}:null}function JQ(e,t){return e?t?`${e}
|
|
480
480
|
${t}`:e:t}function cw(e,t,n){const r=fv(t),i=fv(n);return!r&&!i?null:{kind:"diff",title:e,content:JQ(r,i),oldContent:r,newContent:i}}function eJ(e){const t=e.replace(/\r\n?/gu,`
|
|
481
481
|
`).split(`
|
|
482
482
|
`);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(`
|
|
@@ -531,7 +531,7 @@ ${s}`,l=nB(`${oS(r.kind)}:${r.path}`,o,r.kind);n.push(l.kind==="diff"?{...l,co
|
|
|
531
531
|
|
|
532
532
|
If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component.
|
|
533
533
|
|
|
534
|
-
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return _.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},Tte="DialogDescriptionWarning",Rte=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${FB(Tte).contentName}}.`;return _.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},W1=TB,Ate=AB,q1=NB,Y1=PB,V1=LB,HB=DB,UB=BB,ey=jB;function Mte(e){const t=_.useRef({value:e,previous:e});return _.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}function Nte(e){const[t,n]=_.useState(void 0);return Di(()=>{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 Pte=["top","right","bottom","left"],Sl=Math.min,vs=Math.max,pv=Math.round,ig=Math.floor,Mo=e=>({x:e,y:e}),Lte={left:"right",right:"left",bottom:"top",top:"bottom"};function cS(e,t,n){return vs(e,Sl(t,n))}function va(e,t){return typeof e=="function"?e(t):e}function ya(e){return e.split("-")[0]}function Rd(e){return e.split("-")[1]}function K1(e){return e==="x"?"y":"x"}function G1(e){return e==="y"?"height":"width"}function Ro(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function X1(e){return K1(Ro(e))}function Ote(e,t,n){n===void 0&&(n=!1);const r=Rd(e),i=X1(e),s=G1(i);let o=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(o=mv(o)),[o,mv(o)]}function Dte(e){const t=mv(e);return[uS(e),t,uS(t)]}function uS(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const _N=["left","right"],wN=["right","left"],Ite=["top","bottom"],Bte=["bottom","top"];function zte(e,t,n){switch(e){case"top":case"bottom":return n?t?wN:_N:t?_N:wN;case"left":case"right":return t?Ite:Bte;default:return[]}}function jte(e,t,n,r){const i=Rd(e);let s=zte(ya(e),n==="start",r);return i&&(s=s.map(o=>o+"-"+i),t&&(s=s.concat(s.map(uS)))),s}function mv(e){const t=ya(e);return Lte[t]+e.slice(t.length)}function $te(e){return{top:0,right:0,bottom:0,left:0,...e}}function WB(e){return typeof e!="number"?$te(e):{top:e,right:e,bottom:e,left:e}}function gv(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 SN(e,t,n){let{reference:r,floating:i}=e;const s=Ro(t),o=X1(t),l=G1(o),u=ya(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(Rd(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 Fte(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}=va(t,e),b=WB(g),S=l[y?p==="floating"?"reference":"floating":p],E=gv(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(S)))==null||n?S:S.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)),R=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=gv(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:k,offsetParent:T,strategy:u}):k);return{top:(E.top-P.top+b.top)/R.y,bottom:(P.bottom-E.bottom+b.bottom)/R.y,left:(E.left-P.left+b.left)/R.x,right:(P.right-E.right+b.right)/R.x}}const Hte=50,Ute=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:s=[],platform:o}=n,l=o.detectOverflow?o:{...o,detectOverflow:Fte},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}=SN(d,r,u),y=r,g=0;const b={};for(let w=0;w<s.length;w++){const S=s[w];if(!S)continue;const{name:E,fn:k}=S,{x:T,y:R,data:P,reset:A}=await k({x:f,y:p,initialPlacement:r,placement:y,strategy:i,middlewareData:b,rects:d,platform:l,elements:{reference:e,floating:t}});f=T??f,p=R??p,b[E]={...b[E],...P},A&&g<Hte&&(g++,typeof A=="object"&&(A.placement&&(y=A.placement),A.rects&&(d=A.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:i}):A.rects),{x:f,y:p}=SN(d,y,u)),w=-1)}return{x:f,y:p,placement:y,strategy:i,middlewareData:b}},Wte=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}=va(e,t)||{};if(d==null)return{};const p=WB(f),y={x:n,y:r},g=X1(i),b=G1(g),w=await o.getDimensions(d),S=g==="y",E=S?"top":"left",k=S?"bottom":"right",T=S?"clientHeight":"clientWidth",R=s.reference[b]+s.reference[g]-y[g]-s.floating[b],P=y[g]-s.reference[g],A=await(o.getOffsetParent==null?void 0:o.getOffsetParent(d));let H=A?A[T]:0;(!H||!await(o.isElement==null?void 0:o.isElement(A)))&&(H=l.floating[T]||s.floating[b]);const D=R/2-P/2,K=H/2-w[b]/2-1,q=Sl(p[E],K),X=Sl(p[k],K),z=q,N=H-w[b]-X,$=H/2-w[b]/2+D,I=cS(z,$,N),M=!u.arrow&&Rd(i)!=null&&$!==I&&s.reference[b]/2-($<z?q:X)-w[b]/2<0,O=M?$<z?$-z:$-N:0;return{[g]:y[g]+O,data:{[g]:I,centerOffset:$-I-O,...M&&{alignmentOffset:O}},reset:M}}}),qte=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:b="none",flipAlignment:w=!0,...S}=va(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const E=ya(i),k=Ro(l),T=ya(l)===l,R=await(u.isRTL==null?void 0:u.isRTL(d.floating)),P=y||(T||!w?[mv(l)]:Dte(l)),A=b!=="none";!y&&A&&P.push(...jte(l,w,b,R));const H=[l,...P],D=await u.detectOverflow(t,S),K=[];let q=((r=s.flip)==null?void 0:r.overflows)||[];if(f&&K.push(D[E]),p){const $=Ote(i,o,R);K.push(D[$[0]],D[$[1]])}if(q=[...q,{placement:i,overflows:K}],!K.every($=>$<=0)){var X,z;const $=(((X=s.flip)==null?void 0:X.index)||0)+1,I=H[$];if(I&&(!(p==="alignment"?k!==Ro(I):!1)||q.every(U=>Ro(U.placement)===k?U.overflows[0]>0:!0)))return{data:{index:$,overflows:q},reset:{placement:I}};let M=(z=q.filter(O=>O.overflows[0]<=0).sort((O,U)=>O.overflows[1]-U.overflows[1])[0])==null?void 0:z.placement;if(!M)switch(g){case"bestFit":{var N;const O=(N=q.filter(U=>{if(A){const B=Ro(U.placement);return B===k||B==="y"}return!0}).map(U=>[U.placement,U.overflows.filter(B=>B>0).reduce((B,L)=>B+L,0)]).sort((U,B)=>U[1]-B[1])[0])==null?void 0:N[0];O&&(M=O);break}case"initialPlacement":M=l;break}if(i!==M)return{reset:{placement:M}}}return{}}}};function xN(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function EN(e){return Pte.some(t=>e[t]>=0)}const Yte=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...s}=va(e,t);switch(i){case"referenceHidden":{const o=await r.detectOverflow(t,{...s,elementContext:"reference"}),l=xN(o,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:EN(l)}}}case"escaped":{const o=await r.detectOverflow(t,{...s,altBoundary:!0}),l=xN(o,n.floating);return{data:{escapedOffsets:l,escaped:EN(l)}}}default:return{}}}}},qB=new Set(["left","top"]);async function Vte(e,t){const{placement:n,platform:r,elements:i}=e,s=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=ya(n),l=Rd(n),u=Ro(n)==="y",d=qB.has(o)?-1:1,f=s&&u?-1:1,p=va(t,e);let{mainAxis:y,crossAxis:g,alignmentAxis:b}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return l&&typeof b=="number"&&(g=l==="end"?b*-1:b),u?{x:g*f,y:y*d}:{x:y*d,y:g*f}}const Kte=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 Vte(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}}}}},Gte=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:E=>{let{x:k,y:T}=E;return{x:k,y:T}}},...d}=va(e,t),f={x:n,y:r},p=await s.detectOverflow(t,d),y=Ro(ya(i)),g=K1(y);let b=f[g],w=f[y];if(o){const E=g==="y"?"top":"left",k=g==="y"?"bottom":"right",T=b+p[E],R=b-p[k];b=cS(T,b,R)}if(l){const E=y==="y"?"top":"left",k=y==="y"?"bottom":"right",T=w+p[E],R=w-p[k];w=cS(T,w,R)}const S=u.fn({...t,[g]:b,[y]:w});return{...S,data:{x:S.x-n,y:S.y-r,enabled:{[g]:o,[y]:l}}}}}},Xte=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}=va(e,t),f={x:n,y:r},p=Ro(i),y=K1(p);let g=f[y],b=f[p];const w=va(l,t),S=typeof w=="number"?{mainAxis:w,crossAxis:0}:{mainAxis:0,crossAxis:0,...w};if(u){const T=y==="y"?"height":"width",R=s.reference[y]-s.floating[T]+S.mainAxis,P=s.reference[y]+s.reference[T]-S.mainAxis;g<R?g=R:g>P&&(g=P)}if(d){var E,k;const T=y==="y"?"width":"height",R=qB.has(ya(i)),P=s.reference[p]-s.floating[T]+(R&&((E=o.offset)==null?void 0:E[p])||0)+(R?0:S.crossAxis),A=s.reference[p]+s.reference[T]+(R?0:((k=o.offset)==null?void 0:k[p])||0)-(R?S.crossAxis:0);b<P?b=P:b>A&&(b=A)}return{[y]:g,[p]:b}}}},Zte=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}=va(e,t),f=await o.detectOverflow(t,d),p=ya(i),y=Rd(i),g=Ro(i)==="y",{width:b,height:w}=s.floating;let S,E;p==="top"||p==="bottom"?(S=p,E=y===(await(o.isRTL==null?void 0:o.isRTL(l.floating))?"start":"end")?"left":"right"):(E=p,S=y==="end"?"top":"bottom");const k=w-f.top-f.bottom,T=b-f.left-f.right,R=Sl(w-f[S],k),P=Sl(b-f[E],T),A=!t.middlewareData.shift;let H=R,D=P;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(D=T),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(H=k),A&&!y){const q=vs(f.left,0),X=vs(f.right,0),z=vs(f.top,0),N=vs(f.bottom,0);g?D=b-2*(q!==0||X!==0?q+X:vs(f.left,f.right)):H=w-2*(z!==0||N!==0?z+N:vs(f.top,f.bottom))}await u({...t,availableWidth:D,availableHeight:H});const K=await o.getDimensions(l.floating);return b!==K.width||w!==K.height?{reset:{rects:!0}}:{}}}};function ty(){return typeof window<"u"}function Ad(e){return YB(e)?(e.nodeName||"").toLowerCase():"#document"}function bs(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Io(e){var t;return(t=(YB(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function YB(e){return ty()?e instanceof Node||e instanceof bs(e).Node:!1}function no(e){return ty()?e instanceof Element||e instanceof bs(e).Element:!1}function wa(e){return ty()?e instanceof HTMLElement||e instanceof bs(e).HTMLElement:!1}function CN(e){return!ty()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof bs(e).ShadowRoot}function ap(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=ro(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function Qte(e){return/^(table|td|th)$/.test(Ad(e))}function ny(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const Jte=/transform|translate|scale|rotate|perspective|filter/,ene=/paint|layout|strict|content/,ac=e=>!!e&&e!=="none";let _w;function Z1(e){const t=no(e)?ro(e):e;return ac(t.transform)||ac(t.translate)||ac(t.scale)||ac(t.rotate)||ac(t.perspective)||!Q1()&&(ac(t.backdropFilter)||ac(t.filter))||Jte.test(t.willChange||"")||ene.test(t.contain||"")}function tne(e){let t=xl(e);for(;wa(t)&&!md(t);){if(Z1(t))return t;if(ny(t))return null;t=xl(t)}return null}function Q1(){return _w==null&&(_w=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),_w}function md(e){return/^(html|body|#document)$/.test(Ad(e))}function ro(e){return bs(e).getComputedStyle(e)}function ry(e){return no(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function xl(e){if(Ad(e)==="html")return e;const t=e.assignedSlot||e.parentNode||CN(e)&&e.host||Io(e);return CN(t)?t.host:t}function VB(e){const t=xl(e);return md(t)?e.ownerDocument?e.ownerDocument.body:e.body:wa(t)&&ap(t)?t:VB(t)}function Dh(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=VB(e),s=i===((r=e.ownerDocument)==null?void 0:r.body),o=bs(i);if(s){const l=dS(o);return t.concat(o,o.visualViewport||[],ap(i)?i:[],l&&n?Dh(l):[])}else return t.concat(i,Dh(i,[],n))}function dS(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function KB(e){const t=ro(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=pv(n)!==s||pv(r)!==o;return l&&(n=s,r=o),{width:n,height:r,$:l}}function J1(e){return no(e)?e:e.contextElement}function ad(e){const t=J1(e);if(!wa(t))return Mo(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:s}=KB(t);let o=(s?pv(n.width):n.width)/r,l=(s?pv(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!l||!Number.isFinite(l))&&(l=1),{x:o,y:l}}const nne=Mo(0);function GB(e){const t=bs(e);return!Q1()||!t.visualViewport?nne:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function rne(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==bs(e)?!1:t}function Tc(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),s=J1(e);let o=Mo(1);t&&(r?no(r)&&(o=ad(r)):o=ad(e));const l=rne(s,n,r)?GB(s):Mo(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=bs(s),g=r&&no(r)?bs(r):r;let b=y,w=dS(b);for(;w&&r&&g!==b;){const S=ad(w),E=w.getBoundingClientRect(),k=ro(w),T=E.left+(w.clientLeft+parseFloat(k.paddingLeft))*S.x,R=E.top+(w.clientTop+parseFloat(k.paddingTop))*S.y;u*=S.x,d*=S.y,f*=S.x,p*=S.y,u+=T,d+=R,b=bs(w),w=dS(b)}}return gv({width:f,height:p,x:u,y:d})}function iy(e,t){const n=ry(e).scrollLeft;return t?t.left+n:Tc(Io(e)).left+n}function XB(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-iy(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function ine(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const s=i==="fixed",o=Io(r),l=t?ny(t.floating):!1;if(r===o||l&&s)return n;let u={scrollLeft:0,scrollTop:0},d=Mo(1);const f=Mo(0),p=wa(r);if((p||!p&&!s)&&((Ad(r)!=="body"||ap(o))&&(u=ry(r)),p)){const g=Tc(r);d=ad(r),f.x=g.x+r.clientLeft,f.y=g.y+r.clientTop}const y=o&&!p&&!s?XB(o,u):Mo(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 sne(e){return Array.from(e.getClientRects())}function one(e){const t=Io(e),n=ry(e),r=e.ownerDocument.body,i=vs(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=vs(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let o=-n.scrollLeft+iy(e);const l=-n.scrollTop;return ro(r).direction==="rtl"&&(o+=vs(t.clientWidth,r.clientWidth)-i),{width:i,height:s,x:o,y:l}}const kN=25;function ane(e,t){const n=bs(e),r=Io(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=Q1();(!f||f&&t==="fixed")&&(l=i.offsetLeft,u=i.offsetTop)}const d=iy(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,b=Math.abs(r.clientWidth-p.clientWidth-g);b<=kN&&(s-=b)}else d<=kN&&(s+=d);return{width:s,height:o,x:l,y:u}}function lne(e,t){const n=Tc(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,s=wa(e)?ad(e):Mo(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 TN(e,t,n){let r;if(t==="viewport")r=ane(e,n);else if(t==="document")r=one(Io(e));else if(no(t))r=lne(t,n);else{const i=GB(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return gv(r)}function ZB(e,t){const n=xl(e);return n===t||!no(n)||md(n)?!1:ro(n).position==="fixed"||ZB(n,t)}function cne(e,t){const n=t.get(e);if(n)return n;let r=Dh(e,[],!1).filter(l=>no(l)&&Ad(l)!=="body"),i=null;const s=ro(e).position==="fixed";let o=s?xl(e):e;for(;no(o)&&!md(o);){const l=ro(o),u=Z1(o);!u&&l.position==="fixed"&&(i=null),(s?!u&&!i:!u&&l.position==="static"&&!!i&&(i.position==="absolute"||i.position==="fixed")||ap(o)&&!u&&ZB(e,o))?r=r.filter(f=>f!==o):i=l,o=xl(o)}return t.set(e,r),r}function une(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[...n==="clippingAncestors"?ny(t)?[]:cne(t,this._c):[].concat(n),r],l=TN(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=TN(t,o[y],i);u=vs(g.top,u),d=Sl(g.right,d),f=Sl(g.bottom,f),p=vs(g.left,p)}return{width:d-p,height:f-u,x:p,y:u}}function dne(e){const{width:t,height:n}=KB(e);return{width:t,height:n}}function fne(e,t,n){const r=wa(t),i=Io(t),s=n==="fixed",o=Tc(e,!0,s,t);let l={scrollLeft:0,scrollTop:0};const u=Mo(0);function d(){u.x=iy(i)}if(r||!r&&!s)if((Ad(t)!=="body"||ap(i))&&(l=ry(t)),r){const g=Tc(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?XB(i,l):Mo(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 ww(e){return ro(e).position==="static"}function RN(e,t){if(!wa(e)||ro(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Io(e)===n&&(n=n.ownerDocument.body),n}function QB(e,t){const n=bs(e);if(ny(e))return n;if(!wa(e)){let i=xl(e);for(;i&&!md(i);){if(no(i)&&!ww(i))return i;i=xl(i)}return n}let r=RN(e,t);for(;r&&Qte(r)&&ww(r);)r=RN(r,t);return r&&md(r)&&ww(r)&&!Z1(r)?n:r||tne(e)||n}const hne=async function(e){const t=this.getOffsetParent||QB,n=this.getDimensions,r=await n(e.floating);return{reference:fne(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function pne(e){return ro(e).direction==="rtl"}const mne={convertOffsetParentRelativeRectToViewportRelativeRect:ine,getDocumentElement:Io,getClippingRect:une,getOffsetParent:QB,getElementRects:hne,getClientRects:sne,getDimensions:dne,getScale:ad,isElement:no,isRTL:pne};function JB(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function gne(e,t){let n=null,r;const i=Io(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 b=ig(p),w=ig(i.clientWidth-(f+y)),S=ig(i.clientHeight-(p+g)),E=ig(f),T={rootMargin:-b+"px "+-w+"px "+-S+"px "+-E+"px",threshold:vs(0,Sl(1,u))||1};let R=!0;function P(A){const H=A[0].intersectionRatio;if(H!==u){if(!R)return o();H?o(!1,H):r=setTimeout(()=>{o(!1,1e-7)},1e3)}H===1&&!JB(d,e.getBoundingClientRect())&&o(),R=!1}try{n=new IntersectionObserver(P,{...T,root:i.ownerDocument})}catch{n=new IntersectionObserver(P,T)}n.observe(e)}return o(!0),s}function vne(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=J1(e),f=i||s?[...d?Dh(d):[],...t?Dh(t):[]]:[];f.forEach(E=>{i&&E.addEventListener("scroll",n,{passive:!0}),s&&E.addEventListener("resize",n)});const p=d&&l?gne(d,n):null;let y=-1,g=null;o&&(g=new ResizeObserver(E=>{let[k]=E;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 b,w=u?Tc(e):null;u&&S();function S(){const E=Tc(e);w&&!JB(w,E)&&n(),w=E,b=requestAnimationFrame(S)}return n(),()=>{var E;f.forEach(k=>{i&&k.removeEventListener("scroll",n),s&&k.removeEventListener("resize",n)}),p==null||p(),(E=g)==null||E.disconnect(),g=null,u&&cancelAnimationFrame(b)}}const yne=Kte,bne=Gte,_ne=qte,wne=Zte,Sne=Yte,AN=Wte,xne=Xte,Ene=(e,t,n)=>{const r=new Map,i={platform:mne,...n},s={...i.platform,_c:r};return Ute(e,t,{...i,platform:s})};var Cne=typeof document<"u",kne=function(){},Hg=Cne?_.useLayoutEffect:kne;function vv(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(!vv(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)&&!vv(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function ez(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function MN(e,t){const n=ez(e);return Math.round(t*n)/n}function Sw(e){const t=_.useRef(e);return Hg(()=>{t.current=e}),t}function Tne(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]=_.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[y,g]=_.useState(r);vv(y,r)||g(r);const[b,w]=_.useState(null),[S,E]=_.useState(null),k=_.useCallback(U=>{U!==A.current&&(A.current=U,w(U))},[]),T=_.useCallback(U=>{U!==H.current&&(H.current=U,E(U))},[]),R=s||b,P=o||S,A=_.useRef(null),H=_.useRef(null),D=_.useRef(f),K=u!=null,q=Sw(u),X=Sw(i),z=Sw(d),N=_.useCallback(()=>{if(!A.current||!H.current)return;const U={placement:t,strategy:n,middleware:y};X.current&&(U.platform=X.current),Ene(A.current,H.current,U).then(B=>{const L={...B,isPositioned:z.current!==!1};$.current&&!vv(D.current,L)&&(D.current=L,Fc.flushSync(()=>{p(L)}))})},[y,t,n,X,z]);Hg(()=>{d===!1&&D.current.isPositioned&&(D.current.isPositioned=!1,p(U=>({...U,isPositioned:!1})))},[d]);const $=_.useRef(!1);Hg(()=>($.current=!0,()=>{$.current=!1}),[]),Hg(()=>{if(R&&(A.current=R),P&&(H.current=P),R&&P){if(q.current)return q.current(R,P,N);N()}},[R,P,N,q,K]);const I=_.useMemo(()=>({reference:A,floating:H,setReference:k,setFloating:T}),[k,T]),M=_.useMemo(()=>({reference:R,floating:P}),[R,P]),O=_.useMemo(()=>{const U={position:n,left:0,top:0};if(!M.floating)return U;const B=MN(M.floating,f.x),L=MN(M.floating,f.y);return l?{...U,transform:"translate("+B+"px, "+L+"px)",...ez(M.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:B,top:L}},[n,l,M.floating,f.x,f.y]);return _.useMemo(()=>({...f,update:N,refs:I,elements:M,floatingStyles:O}),[f,N,I,M,O])}const Rne=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?AN({element:r.current,padding:i}).fn(n):{}:r?AN({element:r,padding:i}).fn(n):{}}}},Ane=(e,t)=>{const n=yne(e);return{name:n.name,fn:n.fn,options:[e,t]}},Mne=(e,t)=>{const n=bne(e);return{name:n.name,fn:n.fn,options:[e,t]}},Nne=(e,t)=>({fn:xne(e).fn,options:[e,t]}),Pne=(e,t)=>{const n=_ne(e);return{name:n.name,fn:n.fn,options:[e,t]}},Lne=(e,t)=>{const n=wne(e);return{name:n.name,fn:n.fn,options:[e,t]}},One=(e,t)=>{const n=Sne(e);return{name:n.name,fn:n.fn,options:[e,t]}},Dne=(e,t)=>{const n=Rne(e);return{name:n.name,fn:n.fn,options:[e,t]}};var Ine="Arrow",tz=_.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...s}=e;return v.jsx(hn.svg,{...s,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:v.jsx("polygon",{points:"0,0 30,0 15,10"})})});tz.displayName=Ine;var Bne=tz,eE="Popper",[nz,Ll]=_a(eE),[zne,rz]=nz(eE),iz=e=>{const{__scopePopper:t,children:n}=e,[r,i]=_.useState(null);return v.jsx(zne,{scope:t,anchor:r,onAnchorChange:i,children:n})};iz.displayName=eE;var sz="PopperAnchor",oz=_.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,s=rz(sz,n),o=_.useRef(null),l=Kn(t,o),u=_.useRef(null);return _.useEffect(()=>{const d=u.current;u.current=(r==null?void 0:r.current)||o.current,d!==u.current&&s.onAnchorChange(u.current)}),r?null:v.jsx(hn.div,{...i,ref:l})});oz.displayName=sz;var tE="PopperContent",[jne,$ne]=nz(tE),az=_.forwardRef((e,t)=>{var ee,pe,ae,me,Ee,Oe;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:b,...w}=e,S=rz(tE,n),[E,k]=_.useState(null),T=Kn(t,Se=>k(Se)),[R,P]=_.useState(null),A=Nte(R),H=(A==null?void 0:A.width)??0,D=(A==null?void 0:A.height)??0,K=r+(s!=="center"?"-"+s:""),q=typeof f=="number"?f:{top:0,right:0,bottom:0,left:0,...f},X=Array.isArray(d)?d:[d],z=X.length>0,N={padding:q,boundary:X.filter(Hne),altBoundary:z},{refs:$,floatingStyles:I,placement:M,isPositioned:O,middlewareData:U}=Tne({strategy:"fixed",placement:K,whileElementsMounted:(...Se)=>vne(...Se,{animationFrame:g==="always"}),elements:{reference:S.anchor},middleware:[Ane({mainAxis:i+D,alignmentAxis:o}),u&&Mne({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?Nne():void 0,...N}),u&&Pne({...N}),Lne({...N,apply:({elements:Se,rects:Qe,availableWidth:Ht,availableHeight:ye})=>{const{width:Xe,height:kt}=Qe.reference,gt=Se.floating.style;gt.setProperty("--radix-popper-available-width",`${Ht}px`),gt.setProperty("--radix-popper-available-height",`${ye}px`),gt.setProperty("--radix-popper-anchor-width",`${Xe}px`),gt.setProperty("--radix-popper-anchor-height",`${kt}px`)}}),R&&Dne({element:R,padding:l}),Une({arrowWidth:H,arrowHeight:D}),y&&One({strategy:"referenceHidden",...N})]}),[B,L]=uz(M),Y=Lo(b);Di(()=>{O&&(Y==null||Y())},[O,Y]);const V=(ee=U.arrow)==null?void 0:ee.x,j=(pe=U.arrow)==null?void 0:pe.y,te=((ae=U.arrow)==null?void 0:ae.centerOffset)!==0,[re,oe]=_.useState();return Di(()=>{E&&oe(window.getComputedStyle(E).zIndex)},[E]),v.jsx("div",{ref:$.setFloating,"data-radix-popper-content-wrapper":"",style:{...I,transform:O?I.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[(me=U.transformOrigin)==null?void 0:me.x,(Ee=U.transformOrigin)==null?void 0:Ee.y].join(" "),...((Oe=U.hide)==null?void 0:Oe.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:v.jsx(jne,{scope:n,placedSide:B,onArrowChange:P,arrowX:V,arrowY:j,shouldHideArrow:te,children:v.jsx(hn.div,{"data-side":B,"data-align":L,...w,ref:T,style:{...w.style,animation:O?void 0:"none"}})})})});az.displayName=tE;var lz="PopperArrow",Fne={top:"bottom",right:"left",bottom:"top",left:"right"},cz=_.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,s=$ne(lz,r),o=Fne[s.placedSide];return v.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:v.jsx(Bne,{...i,ref:n,style:{...i.style,display:"block"}})})});cz.displayName=lz;function Hne(e){return e!==null}var Une=e=>({name:"transformOrigin",options:e,fn(t){var S,E,k;const{placement:n,rects:r,middlewareData:i}=t,o=((S=i.arrow)==null?void 0:S.centerOffset)!==0,l=o?0:e.arrowWidth,u=o?0:e.arrowHeight,[d,f]=uz(n),p={start:"0%",center:"50%",end:"100%"}[f],y=(((E=i.arrow)==null?void 0:E.x)??0)+l/2,g=(((k=i.arrow)==null?void 0:k.y)??0)+u/2;let b="",w="";return d==="bottom"?(b=o?p:`${y}px`,w=`${-u}px`):d==="top"?(b=o?p:`${y}px`,w=`${r.floating.height+u}px`):d==="right"?(b=`${-u}px`,w=o?p:`${g}px`):d==="left"&&(b=`${r.floating.width+u}px`,w=o?p:`${g}px`),{data:{x:b,y:w}}}});function uz(e){const[t,n="center"]=e.split("-");return[t,n]}var sy=iz,lp=oz,oy=az,ay=cz,xw="rovingFocusGroup.onEntryFocus",Wne={bubbles:!1,cancelable:!0},cp="RovingFocusGroup",[fS,dz,qne]=j1(cp),[Yne,fz]=_a(cp,[qne]),[Vne,Kne]=Yne(cp),hz=_.forwardRef((e,t)=>v.jsx(fS.Provider,{scope:e.__scopeRovingFocusGroup,children:v.jsx(fS.Slot,{scope:e.__scopeRovingFocusGroup,children:v.jsx(Gne,{...e,ref:t})})}));hz.displayName=cp;var Gne=_.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=_.useRef(null),g=Kn(t,y),b=$1(s),[w,S]=Cc({prop:o,defaultProp:l??null,onChange:u,caller:cp}),[E,k]=_.useState(!1),T=Lo(d),R=dz(n),P=_.useRef(!1),[A,H]=_.useState(0);return _.useEffect(()=>{const D=y.current;if(D)return D.addEventListener(xw,T),()=>D.removeEventListener(xw,T)},[T]),v.jsx(Vne,{scope:n,orientation:r,dir:b,loop:i,currentTabStopId:w,onItemFocus:_.useCallback(D=>S(D),[S]),onItemShiftTab:_.useCallback(()=>k(!0),[]),onFocusableItemAdd:_.useCallback(()=>H(D=>D+1),[]),onFocusableItemRemove:_.useCallback(()=>H(D=>D-1),[]),children:v.jsx(hn.div,{tabIndex:E||A===0?-1:0,"data-orientation":r,...p,ref:g,style:{outline:"none",...e.style},onMouseDown:Mt(e.onMouseDown,()=>{P.current=!0}),onFocus:Mt(e.onFocus,D=>{const K=!P.current;if(D.target===D.currentTarget&&K&&!E){const q=new CustomEvent(xw,Wne);if(D.currentTarget.dispatchEvent(q),!q.defaultPrevented){const X=R().filter(M=>M.focusable),z=X.find(M=>M.active),N=X.find(M=>M.id===w),I=[z,N,...X].filter(Boolean).map(M=>M.ref.current);gz(I,f)}}P.current=!1}),onBlur:Mt(e.onBlur,()=>k(!1))})})}),pz="RovingFocusGroupItem",mz=_.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:s,children:o,...l}=e,u=Ci(),d=s||u,f=Kne(pz,n),p=f.currentTabStopId===d,y=dz(n),{onFocusableItemAdd:g,onFocusableItemRemove:b,currentTabStopId:w}=f;return _.useEffect(()=>{if(r)return g(),()=>b()},[r,g,b]),v.jsx(fS.ItemSlot,{scope:n,id:d,focusable:r,active:i,children:v.jsx(hn.span,{tabIndex:p?0:-1,"data-orientation":f.orientation,...l,ref:t,onMouseDown:Mt(e.onMouseDown,S=>{r?f.onItemFocus(d):S.preventDefault()}),onFocus:Mt(e.onFocus,()=>f.onItemFocus(d)),onKeyDown:Mt(e.onKeyDown,S=>{if(S.key==="Tab"&&S.shiftKey){f.onItemShiftTab();return}if(S.target!==S.currentTarget)return;const E=Qne(S,f.orientation,f.dir);if(E!==void 0){if(S.metaKey||S.ctrlKey||S.altKey||S.shiftKey)return;S.preventDefault();let T=y().filter(R=>R.focusable).map(R=>R.ref.current);if(E==="last")T.reverse();else if(E==="prev"||E==="next"){E==="prev"&&T.reverse();const R=T.indexOf(S.currentTarget);T=f.loop?Jne(T,R+1):T.slice(R+1)}setTimeout(()=>gz(T))}}),children:typeof o=="function"?o({isCurrentTabStop:p,hasTabStop:w!=null}):o})})});mz.displayName=pz;var Xne={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Zne(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Qne(e,t,n){const r=Zne(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Xne[r]}function gz(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Jne(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var ere=hz,tre=mz,hS=["Enter"," "],nre=["ArrowDown","PageUp","Home"],vz=["ArrowUp","PageDown","End"],rre=[...nre,...vz],ire={ltr:[...hS,"ArrowRight"],rtl:[...hS,"ArrowLeft"]},sre={ltr:["ArrowLeft"],rtl:["ArrowRight"]},up="Menu",[Ih,ore,are]=j1(up),[Hc,yz]=_a(up,[are,Ll,fz]),ly=Ll(),bz=fz(),[lre,Uc]=Hc(up),[cre,dp]=Hc(up),_z=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:s,modal:o=!0}=e,l=ly(t),[u,d]=_.useState(null),f=_.useRef(!1),p=Lo(s),y=$1(i);return _.useEffect(()=>{const g=()=>{f.current=!0,document.addEventListener("pointerdown",b,{capture:!0,once:!0}),document.addEventListener("pointermove",b,{capture:!0,once:!0})},b=()=>f.current=!1;return document.addEventListener("keydown",g,{capture:!0}),()=>{document.removeEventListener("keydown",g,{capture:!0}),document.removeEventListener("pointerdown",b,{capture:!0}),document.removeEventListener("pointermove",b,{capture:!0})}},[]),v.jsx(sy,{...l,children:v.jsx(lre,{scope:t,open:n,onOpenChange:p,content:u,onContentChange:d,children:v.jsx(cre,{scope:t,onClose:_.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:f,dir:y,modal:o,children:r})})})};_z.displayName=up;var ure="MenuAnchor",nE=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=ly(n);return v.jsx(lp,{...i,...r,ref:t})});nE.displayName=ure;var rE="MenuPortal",[dre,wz]=Hc(rE,{forceMount:void 0}),Sz=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,s=Uc(rE,t);return v.jsx(dre,{scope:t,forceMount:n,children:v.jsx(qs,{present:n||s.open,children:v.jsx(Td,{asChild:!0,container:i,children:r})})})};Sz.displayName=rE;var $s="MenuContent",[fre,iE]=Hc($s),xz=_.forwardRef((e,t)=>{const n=wz($s,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,s=Uc($s,e.__scopeMenu),o=dp($s,e.__scopeMenu);return v.jsx(Ih.Provider,{scope:e.__scopeMenu,children:v.jsx(qs,{present:r||s.open,children:v.jsx(Ih.Slot,{scope:e.__scopeMenu,children:o.modal?v.jsx(hre,{...i,ref:t}):v.jsx(pre,{...i,ref:t})})})})}),hre=_.forwardRef((e,t)=>{const n=Uc($s,e.__scopeMenu),r=_.useRef(null),i=Kn(t,r);return _.useEffect(()=>{const s=r.current;if(s)return Qv(s)},[]),v.jsx(sE,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Mt(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),pre=_.forwardRef((e,t)=>{const n=Uc($s,e.__scopeMenu);return v.jsx(sE,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),mre=wl("MenuContent.ScrollLock"),sE=_.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:b,...w}=e,S=Uc($s,n),E=dp($s,n),k=ly(n),T=bz(n),R=ore(n),[P,A]=_.useState(null),H=_.useRef(null),D=Kn(t,H,S.onContentChange),K=_.useRef(0),q=_.useRef(""),X=_.useRef(0),z=_.useRef(null),N=_.useRef("right"),$=_.useRef(0),I=b?op:_.Fragment,M=b?{as:mre,allowPinchZoom:!0}:void 0,O=B=>{var ee,pe;const L=q.current+B,Y=R().filter(ae=>!ae.disabled),V=document.activeElement,j=(ee=Y.find(ae=>ae.ref.current===V))==null?void 0:ee.textValue,te=Y.map(ae=>ae.textValue),re=Tre(te,L,j),oe=(pe=Y.find(ae=>ae.textValue===re))==null?void 0:pe.ref.current;(function ae(me){q.current=me,window.clearTimeout(K.current),me!==""&&(K.current=window.setTimeout(()=>ae(""),1e3))})(L),oe&&setTimeout(()=>oe.focus())};_.useEffect(()=>()=>window.clearTimeout(K.current),[]),Xv();const U=_.useCallback(B=>{var Y,V;return N.current===((Y=z.current)==null?void 0:Y.side)&&Are(B,(V=z.current)==null?void 0:V.area)},[]);return v.jsx(fre,{scope:n,searchRef:q,onItemEnter:_.useCallback(B=>{U(B)&&B.preventDefault()},[U]),onItemLeave:_.useCallback(B=>{var L;U(B)||((L=H.current)==null||L.focus(),A(null))},[U]),onTriggerLeave:_.useCallback(B=>{U(B)&&B.preventDefault()},[U]),pointerGraceTimerRef:X,onPointerGraceIntentChange:_.useCallback(B=>{z.current=B},[]),children:v.jsx(I,{...M,children:v.jsx(sp,{asChild:!0,trapped:i,onMountAutoFocus:Mt(s,B=>{var L;B.preventDefault(),(L=H.current)==null||L.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:v.jsx(kd,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:f,onFocusOutside:p,onInteractOutside:y,onDismiss:g,children:v.jsx(ere,{asChild:!0,...T,dir:E.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:A,onEntryFocus:Mt(u,B=>{E.isUsingKeyboardRef.current||B.preventDefault()}),preventScrollOnEntryFocus:!0,children:v.jsx(oy,{role:"menu","aria-orientation":"vertical","data-state":jz(S.open),"data-radix-menu-content":"",dir:E.dir,...k,...w,ref:D,style:{outline:"none",...w.style},onKeyDown:Mt(w.onKeyDown,B=>{const Y=B.target.closest("[data-radix-menu-content]")===B.currentTarget,V=B.ctrlKey||B.altKey||B.metaKey,j=B.key.length===1;Y&&(B.key==="Tab"&&B.preventDefault(),!V&&j&&O(B.key));const te=H.current;if(B.target!==te||!rre.includes(B.key))return;B.preventDefault();const oe=R().filter(ee=>!ee.disabled).map(ee=>ee.ref.current);vz.includes(B.key)&&oe.reverse(),Cre(oe)}),onBlur:Mt(e.onBlur,B=>{B.currentTarget.contains(B.target)||(window.clearTimeout(K.current),q.current="")}),onPointerMove:Mt(e.onPointerMove,Bh(B=>{const L=B.target,Y=$.current!==B.clientX;if(B.currentTarget.contains(L)&&Y){const V=B.clientX>$.current?"right":"left";N.current=V,$.current=B.clientX}}))})})})})})})});xz.displayName=$s;var gre="MenuGroup",oE=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return v.jsx(hn.div,{role:"group",...r,ref:t})});oE.displayName=gre;var vre="MenuLabel",Ez=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return v.jsx(hn.div,{...r,ref:t})});Ez.displayName=vre;var yv="MenuItem",NN="menu.itemSelect",cy=_.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,s=_.useRef(null),o=dp(yv,e.__scopeMenu),l=iE(yv,e.__scopeMenu),u=Kn(t,s),d=_.useRef(!1),f=()=>{const p=s.current;if(!n&&p){const y=new CustomEvent(NN,{bubbles:!0,cancelable:!0});p.addEventListener(NN,g=>r==null?void 0:r(g),{once:!0}),dB(p,y),y.defaultPrevented?d.current=!1:o.onClose()}};return v.jsx(Cz,{...i,ref:u,disabled:n,onClick:Mt(e.onClick,f),onPointerDown:p=>{var y;(y=e.onPointerDown)==null||y.call(e,p),d.current=!0},onPointerUp:Mt(e.onPointerUp,p=>{var y;d.current||(y=p.currentTarget)==null||y.click()}),onKeyDown:Mt(e.onKeyDown,p=>{const y=l.searchRef.current!=="";n||y&&p.key===" "||hS.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});cy.displayName=yv;var Cz=_.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...s}=e,o=iE(yv,n),l=bz(n),u=_.useRef(null),d=Kn(t,u),[f,p]=_.useState(!1),[y,g]=_.useState("");return _.useEffect(()=>{const b=u.current;b&&g((b.textContent??"").trim())},[s.children]),v.jsx(Ih.ItemSlot,{scope:n,disabled:r,textValue:i??y,children:v.jsx(tre,{asChild:!0,...l,focusable:!r,children:v.jsx(hn.div,{role:"menuitem","data-highlighted":f?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:d,onPointerMove:Mt(e.onPointerMove,Bh(b=>{r?o.onItemLeave(b):(o.onItemEnter(b),b.defaultPrevented||b.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Mt(e.onPointerLeave,Bh(b=>o.onItemLeave(b))),onFocus:Mt(e.onFocus,()=>p(!0)),onBlur:Mt(e.onBlur,()=>p(!1))})})})}),yre="MenuCheckboxItem",kz=_.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return v.jsx(Nz,{scope:e.__scopeMenu,checked:n,children:v.jsx(cy,{role:"menuitemcheckbox","aria-checked":bv(n)?"mixed":n,...i,ref:t,"data-state":lE(n),onSelect:Mt(i.onSelect,()=>r==null?void 0:r(bv(n)?!0:!n),{checkForDefaultPrevented:!1})})})});kz.displayName=yre;var Tz="MenuRadioGroup",[bre,_re]=Hc(Tz,{value:void 0,onValueChange:()=>{}}),Rz=_.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,s=Lo(r);return v.jsx(bre,{scope:e.__scopeMenu,value:n,onValueChange:s,children:v.jsx(oE,{...i,ref:t})})});Rz.displayName=Tz;var Az="MenuRadioItem",Mz=_.forwardRef((e,t)=>{const{value:n,...r}=e,i=_re(Az,e.__scopeMenu),s=n===i.value;return v.jsx(Nz,{scope:e.__scopeMenu,checked:s,children:v.jsx(cy,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":lE(s),onSelect:Mt(r.onSelect,()=>{var o;return(o=i.onValueChange)==null?void 0:o.call(i,n)},{checkForDefaultPrevented:!1})})})});Mz.displayName=Az;var aE="MenuItemIndicator",[Nz,wre]=Hc(aE,{checked:!1}),Pz=_.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,s=wre(aE,n);return v.jsx(qs,{present:r||bv(s.checked)||s.checked===!0,children:v.jsx(hn.span,{...i,ref:t,"data-state":lE(s.checked)})})});Pz.displayName=aE;var Sre="MenuSeparator",Lz=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return v.jsx(hn.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Lz.displayName=Sre;var xre="MenuArrow",Oz=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=ly(n);return v.jsx(ay,{...i,...r,ref:t})});Oz.displayName=xre;var Ere="MenuSub",[yMe,Dz]=Hc(Ere),nh="MenuSubTrigger",Iz=_.forwardRef((e,t)=>{const n=Uc(nh,e.__scopeMenu),r=dp(nh,e.__scopeMenu),i=Dz(nh,e.__scopeMenu),s=iE(nh,e.__scopeMenu),o=_.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=s,d={__scopeMenu:e.__scopeMenu},f=_.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);return _.useEffect(()=>f,[f]),_.useEffect(()=>{const p=l.current;return()=>{window.clearTimeout(p),u(null)}},[l,u]),v.jsx(nE,{asChild:!0,...d,children:v.jsx(Cz,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":i.contentId,"data-state":jz(n.open),...e,ref:ga(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:Mt(e.onPointerMove,Bh(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:Mt(e.onPointerLeave,Bh(p=>{var g,b;f();const y=(g=n.content)==null?void 0:g.getBoundingClientRect();if(y){const w=(b=n.content)==null?void 0:b.dataset.side,S=w==="right",E=S?-5:5,k=y[S?"left":"right"],T=y[S?"right":"left"];s.onPointerGraceIntentChange({area:[{x:p.clientX+E,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:Mt(e.onKeyDown,p=>{var g;const y=s.searchRef.current!=="";e.disabled||y&&p.key===" "||ire[r.dir].includes(p.key)&&(n.onOpenChange(!0),(g=n.content)==null||g.focus(),p.preventDefault())})})})});Iz.displayName=nh;var Bz="MenuSubContent",zz=_.forwardRef((e,t)=>{const n=wz($s,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,s=Uc($s,e.__scopeMenu),o=dp($s,e.__scopeMenu),l=Dz(Bz,e.__scopeMenu),u=_.useRef(null),d=Kn(t,u);return v.jsx(Ih.Provider,{scope:e.__scopeMenu,children:v.jsx(qs,{present:r||s.open,children:v.jsx(Ih.Slot,{scope:e.__scopeMenu,children:v.jsx(sE,{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:Mt(e.onFocusOutside,f=>{f.target!==l.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:Mt(e.onEscapeKeyDown,f=>{o.onClose(),f.preventDefault()}),onKeyDown:Mt(e.onKeyDown,f=>{var g;const p=f.currentTarget.contains(f.target),y=sre[o.dir].includes(f.key);p&&y&&(s.onOpenChange(!1),(g=l.trigger)==null||g.focus(),f.preventDefault())})})})})})});zz.displayName=Bz;function jz(e){return e?"open":"closed"}function bv(e){return e==="indeterminate"}function lE(e){return bv(e)?"indeterminate":e?"checked":"unchecked"}function Cre(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function kre(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function Tre(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=kre(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 Rre(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 Are(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Rre(n,t)}function Bh(e){return t=>t.pointerType==="mouse"?e(t):void 0}var Mre=_z,Nre=nE,Pre=Sz,Lre=xz,Ore=oE,Dre=Ez,Ire=cy,Bre=kz,zre=Rz,jre=Mz,$re=Pz,Fre=Lz,Hre=Oz,Ure=Iz,Wre=zz,uy="DropdownMenu",[qre]=_a(uy,[yz]),Wi=yz(),[Yre,$z]=qre(uy),Fz=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:s,onOpenChange:o,modal:l=!0}=e,u=Wi(t),d=_.useRef(null),[f,p]=Cc({prop:i,defaultProp:s??!1,onChange:o,caller:uy});return v.jsx(Yre,{scope:t,triggerId:Ci(),triggerRef:d,contentId:Ci(),open:f,onOpenChange:p,onOpenToggle:_.useCallback(()=>p(y=>!y),[p]),modal:l,children:v.jsx(Mre,{...u,open:f,onOpenChange:p,dir:r,modal:l,children:n})})};Fz.displayName=uy;var Hz="DropdownMenuTrigger",Uz=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,s=$z(Hz,n),o=Wi(n);return v.jsx(Nre,{asChild:!0,...o,children:v.jsx(hn.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:ga(t,s.triggerRef),onPointerDown:Mt(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(s.onOpenToggle(),s.open||l.preventDefault())}),onKeyDown:Mt(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&s.onOpenToggle(),l.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});Uz.displayName=Hz;var Vre="DropdownMenuPortal",Wz=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Wi(t);return v.jsx(Pre,{...r,...n})};Wz.displayName=Vre;var qz="DropdownMenuContent",Yz=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=$z(qz,n),s=Wi(n),o=_.useRef(!1);return v.jsx(Lre,{id:i.contentId,"aria-labelledby":i.triggerId,...s,...r,ref:t,onCloseAutoFocus:Mt(e.onCloseAutoFocus,l=>{var u;o.current||(u=i.triggerRef.current)==null||u.focus(),o.current=!1,l.preventDefault()}),onInteractOutside:Mt(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)"}})});Yz.displayName=qz;var Kre="DropdownMenuGroup",Gre=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(Ore,{...i,...r,ref:t})});Gre.displayName=Kre;var Xre="DropdownMenuLabel",Vz=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(Dre,{...i,...r,ref:t})});Vz.displayName=Xre;var Zre="DropdownMenuItem",Kz=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(Ire,{...i,...r,ref:t})});Kz.displayName=Zre;var Qre="DropdownMenuCheckboxItem",Gz=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(Bre,{...i,...r,ref:t})});Gz.displayName=Qre;var Jre="DropdownMenuRadioGroup",eie=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(zre,{...i,...r,ref:t})});eie.displayName=Jre;var tie="DropdownMenuRadioItem",nie=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(jre,{...i,...r,ref:t})});nie.displayName=tie;var rie="DropdownMenuItemIndicator",Xz=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx($re,{...i,...r,ref:t})});Xz.displayName=rie;var iie="DropdownMenuSeparator",Zz=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(Fre,{...i,...r,ref:t})});Zz.displayName=iie;var sie="DropdownMenuArrow",oie=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(Hre,{...i,...r,ref:t})});oie.displayName=sie;var aie="DropdownMenuSubTrigger",lie=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(Ure,{...i,...r,ref:t})});lie.displayName=aie;var cie="DropdownMenuSubContent",uie=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(Wre,{...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)"}})});uie.displayName=cie;var die=Fz,fie=Uz,hie=Wz,pie=Yz,mie=Vz,gie=Kz,vie=Gz,yie=Xz,bie=Zz;function PN(e,[t,n]){return Math.min(n,Math.max(t,e))}var dy="Popover",[Qz]=_a(dy,[Ll]),fp=Ll(),[_ie,Ol]=Qz(dy),Jz=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:s,modal:o=!1}=e,l=fp(t),u=_.useRef(null),[d,f]=_.useState(!1),[p,y]=Cc({prop:r,defaultProp:i??!1,onChange:s,caller:dy});return v.jsx(sy,{...l,children:v.jsx(_ie,{scope:t,contentId:Ci(),triggerRef:u,open:p,onOpenChange:y,onOpenToggle:_.useCallback(()=>y(g=>!g),[y]),hasCustomAnchor:d,onCustomAnchorAdd:_.useCallback(()=>f(!0),[]),onCustomAnchorRemove:_.useCallback(()=>f(!1),[]),modal:o,children:n})})};Jz.displayName=dy;var e3="PopoverAnchor",wie=_.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Ol(e3,n),s=fp(n),{onCustomAnchorAdd:o,onCustomAnchorRemove:l}=i;return _.useEffect(()=>(o(),()=>l()),[o,l]),v.jsx(lp,{...s,...r,ref:t})});wie.displayName=e3;var t3="PopoverTrigger",n3=_.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Ol(t3,n),s=fp(n),o=Kn(t,i.triggerRef),l=v.jsx(hn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":a3(i.open),...r,ref:o,onClick:Mt(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?l:v.jsx(lp,{asChild:!0,...s,children:l})});n3.displayName=t3;var cE="PopoverPortal",[Sie,xie]=Qz(cE,{forceMount:void 0}),r3=e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,s=Ol(cE,t);return v.jsx(Sie,{scope:t,forceMount:n,children:v.jsx(qs,{present:n||s.open,children:v.jsx(Td,{asChild:!0,container:i,children:r})})})};r3.displayName=cE;var gd="PopoverContent",i3=_.forwardRef((e,t)=>{const n=xie(gd,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,s=Ol(gd,e.__scopePopover);return v.jsx(qs,{present:r||s.open,children:s.modal?v.jsx(Cie,{...i,ref:t}):v.jsx(kie,{...i,ref:t})})});i3.displayName=gd;var Eie=wl("PopoverContent.RemoveScroll"),Cie=_.forwardRef((e,t)=>{const n=Ol(gd,e.__scopePopover),r=_.useRef(null),i=Kn(t,r),s=_.useRef(!1);return _.useEffect(()=>{const o=r.current;if(o)return Qv(o)},[]),v.jsx(op,{as:Eie,allowPinchZoom:!0,children:v.jsx(s3,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Mt(e.onCloseAutoFocus,o=>{var l;o.preventDefault(),s.current||(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:Mt(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:Mt(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1})})})}),kie=_.forwardRef((e,t)=>{const n=Ol(gd,e.__scopePopover),r=_.useRef(!1),i=_.useRef(!1);return v.jsx(s3,{...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()}})}),s3=_.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=Ol(gd,n),g=fp(n);return Xv(),v.jsx(sp,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:s,children:v.jsx(kd,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:f,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onDismiss:()=>y.onOpenChange(!1),children:v.jsx(oy,{"data-state":a3(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)"}})})})}),o3="PopoverClose",Tie=_.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Ol(o3,n);return v.jsx(hn.button,{type:"button",...r,ref:t,onClick:Mt(e.onClick,()=>i.onOpenChange(!1))})});Tie.displayName=o3;var Rie="PopoverArrow",Aie=_.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=fp(n);return v.jsx(ay,{...i,...r,ref:t})});Aie.displayName=Rie;function a3(e){return e?"open":"closed"}var Mie=Jz,Nie=n3,Pie=r3,Lie=i3,Oie=[" ","Enter","ArrowUp","ArrowDown"],Die=[" ","Enter"],Rc="Select",[fy,hy,Iie]=j1(Rc),[Md]=_a(Rc,[Iie,Ll]),py=Ll(),[Bie,Dl]=Md(Rc),[zie,jie]=Md(Rc),l3=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:b}=e,w=py(t),[S,E]=_.useState(null),[k,T]=_.useState(null),[R,P]=_.useState(!1),A=$1(d),[H,D]=Cc({prop:r,defaultProp:i??!1,onChange:s,caller:Rc}),[K,q]=Cc({prop:o,defaultProp:l,onChange:u,caller:Rc}),X=_.useRef(null),z=S?b||!!S.closest("form"):!0,[N,$]=_.useState(new Set),I=Array.from(N).map(M=>M.props.value).join(";");return v.jsx(sy,{...w,children:v.jsxs(Bie,{required:g,scope:t,trigger:S,onTriggerChange:E,valueNode:k,onValueNodeChange:T,valueNodeHasChildren:R,onValueNodeHasChildrenChange:P,contentId:Ci(),value:K,onValueChange:q,open:H,onOpenChange:D,dir:A,triggerPointerDownPosRef:X,disabled:y,children:[v.jsx(fy.Provider,{scope:t,children:v.jsx(zie,{scope:e.__scopeSelect,onNativeOptionAdd:_.useCallback(M=>{$(O=>new Set(O).add(M))},[]),onNativeOptionRemove:_.useCallback(M=>{$(O=>{const U=new Set(O);return U.delete(M),U})},[]),children:n})}),z?v.jsxs(M3,{"aria-hidden":!0,required:g,tabIndex:-1,name:f,autoComplete:p,value:K,onChange:M=>q(M.target.value),disabled:y,form:b,children:[K===void 0?v.jsx("option",{value:""}):null,Array.from(N)]},I):null]})})};l3.displayName=Rc;var c3="SelectTrigger",u3=_.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...i}=e,s=py(n),o=Dl(c3,n),l=o.disabled||r,u=Kn(t,o.onTriggerChange),d=hy(n),f=_.useRef("touch"),[p,y,g]=P3(w=>{const S=d().filter(T=>!T.disabled),E=S.find(T=>T.value===o.value),k=L3(S,w,E);k!==void 0&&o.onValueChange(k.value)}),b=w=>{l||(o.onOpenChange(!0),g()),w&&(o.triggerPointerDownPosRef.current={x:Math.round(w.pageX),y:Math.round(w.pageY)})};return v.jsx(lp,{asChild:!0,...s,children:v.jsx(hn.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":N3(o.value)?"":void 0,...i,ref:u,onClick:Mt(i.onClick,w=>{w.currentTarget.focus(),f.current!=="mouse"&&b(w)}),onPointerDown:Mt(i.onPointerDown,w=>{f.current=w.pointerType;const S=w.target;S.hasPointerCapture(w.pointerId)&&S.releasePointerCapture(w.pointerId),w.button===0&&w.ctrlKey===!1&&w.pointerType==="mouse"&&(b(w),w.preventDefault())}),onKeyDown:Mt(i.onKeyDown,w=>{const S=p.current!=="";!(w.ctrlKey||w.altKey||w.metaKey)&&w.key.length===1&&y(w.key),!(S&&w.key===" ")&&Oie.includes(w.key)&&(b(),w.preventDefault())})})})});u3.displayName=c3;var d3="SelectValue",f3=_.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:i,children:s,placeholder:o="",...l}=e,u=Dl(d3,n),{onValueNodeHasChildrenChange:d}=u,f=s!==void 0,p=Kn(t,u.onValueNodeChange);return Di(()=>{d(f)},[d,f]),v.jsx(hn.span,{...l,ref:p,style:{pointerEvents:"none"},children:N3(u.value)?v.jsx(v.Fragment,{children:o}):s})});f3.displayName=d3;var $ie="SelectIcon",h3=_.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...i}=e;return v.jsx(hn.span,{"aria-hidden":!0,...i,ref:t,children:r||"▼"})});h3.displayName=$ie;var Fie="SelectPortal",p3=e=>v.jsx(Td,{asChild:!0,...e});p3.displayName=Fie;var Ac="SelectContent",m3=_.forwardRef((e,t)=>{const n=Dl(Ac,e.__scopeSelect),[r,i]=_.useState();if(Di(()=>{i(new DocumentFragment)},[]),!n.open){const s=r;return s?Fc.createPortal(v.jsx(g3,{scope:e.__scopeSelect,children:v.jsx(fy.Slot,{scope:e.__scopeSelect,children:v.jsx("div",{children:e.children})})}),s):null}return v.jsx(v3,{...e,ref:t})});m3.displayName=Ac;var Qs=10,[g3,Il]=Md(Ac),Hie="SelectContentImpl",Uie=wl("SelectContent.RemoveScroll"),v3=_.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:b,hideWhenDetached:w,avoidCollisions:S,...E}=e,k=Dl(Ac,n),[T,R]=_.useState(null),[P,A]=_.useState(null),H=Kn(t,ee=>R(ee)),[D,K]=_.useState(null),[q,X]=_.useState(null),z=hy(n),[N,$]=_.useState(!1),I=_.useRef(!1);_.useEffect(()=>{if(T)return Qv(T)},[T]),Xv();const M=_.useCallback(ee=>{const[pe,...ae]=z().map(Oe=>Oe.ref.current),[me]=ae.slice(-1),Ee=document.activeElement;for(const Oe of ee)if(Oe===Ee||(Oe==null||Oe.scrollIntoView({block:"nearest"}),Oe===pe&&P&&(P.scrollTop=0),Oe===me&&P&&(P.scrollTop=P.scrollHeight),Oe==null||Oe.focus(),document.activeElement!==Ee))return},[z,P]),O=_.useCallback(()=>M([D,T]),[M,D,T]);_.useEffect(()=>{N&&O()},[N,O]);const{onOpenChange:U,triggerPointerDownPosRef:B}=k;_.useEffect(()=>{if(T){let ee={x:0,y:0};const pe=me=>{var Ee,Oe;ee={x:Math.abs(Math.round(me.pageX)-(((Ee=B.current)==null?void 0:Ee.x)??0)),y:Math.abs(Math.round(me.pageY)-(((Oe=B.current)==null?void 0:Oe.y)??0))}},ae=me=>{ee.x<=10&&ee.y<=10?me.preventDefault():T.contains(me.target)||U(!1),document.removeEventListener("pointermove",pe),B.current=null};return B.current!==null&&(document.addEventListener("pointermove",pe),document.addEventListener("pointerup",ae,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",pe),document.removeEventListener("pointerup",ae,{capture:!0})}}},[T,U,B]),_.useEffect(()=>{const ee=()=>U(!1);return window.addEventListener("blur",ee),window.addEventListener("resize",ee),()=>{window.removeEventListener("blur",ee),window.removeEventListener("resize",ee)}},[U]);const[L,Y]=P3(ee=>{const pe=z().filter(Ee=>!Ee.disabled),ae=pe.find(Ee=>Ee.ref.current===document.activeElement),me=L3(pe,ee,ae);me&&setTimeout(()=>me.ref.current.focus())}),V=_.useCallback((ee,pe,ae)=>{const me=!I.current&&!ae;(k.value!==void 0&&k.value===pe||me)&&(K(ee),me&&(I.current=!0))},[k.value]),j=_.useCallback(()=>T==null?void 0:T.focus(),[T]),te=_.useCallback((ee,pe,ae)=>{const me=!I.current&&!ae;(k.value!==void 0&&k.value===pe||me)&&X(ee)},[k.value]),re=r==="popper"?pS:y3,oe=re===pS?{side:l,sideOffset:u,align:d,alignOffset:f,arrowPadding:p,collisionBoundary:y,collisionPadding:g,sticky:b,hideWhenDetached:w,avoidCollisions:S}:{};return v.jsx(g3,{scope:n,content:T,viewport:P,onViewportChange:A,itemRefCallback:V,selectedItem:D,onItemLeave:j,itemTextRefCallback:te,focusSelectedItem:O,selectedItemText:q,position:r,isPositioned:N,searchRef:L,children:v.jsx(op,{as:Uie,allowPinchZoom:!0,children:v.jsx(sp,{asChild:!0,trapped:k.open,onMountAutoFocus:ee=>{ee.preventDefault()},onUnmountAutoFocus:Mt(i,ee=>{var pe;(pe=k.trigger)==null||pe.focus({preventScroll:!0}),ee.preventDefault()}),children:v.jsx(kd,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:ee=>ee.preventDefault(),onDismiss:()=>k.onOpenChange(!1),children:v.jsx(re,{role:"listbox",id:k.contentId,"data-state":k.open?"open":"closed",dir:k.dir,onContextMenu:ee=>ee.preventDefault(),...E,...oe,onPlaced:()=>$(!0),ref:H,style:{display:"flex",flexDirection:"column",outline:"none",...E.style},onKeyDown:Mt(E.onKeyDown,ee=>{const pe=ee.ctrlKey||ee.altKey||ee.metaKey;if(ee.key==="Tab"&&ee.preventDefault(),!pe&&ee.key.length===1&&Y(ee.key),["ArrowUp","ArrowDown","Home","End"].includes(ee.key)){let me=z().filter(Ee=>!Ee.disabled).map(Ee=>Ee.ref.current);if(["ArrowUp","End"].includes(ee.key)&&(me=me.slice().reverse()),["ArrowUp","ArrowDown"].includes(ee.key)){const Ee=ee.target,Oe=me.indexOf(Ee);me=me.slice(Oe+1)}setTimeout(()=>M(me)),ee.preventDefault()}})})})})})})});v3.displayName=Hie;var Wie="SelectItemAlignedPosition",y3=_.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...i}=e,s=Dl(Ac,n),o=Il(Ac,n),[l,u]=_.useState(null),[d,f]=_.useState(null),p=Kn(t,H=>f(H)),y=hy(n),g=_.useRef(!1),b=_.useRef(!0),{viewport:w,selectedItem:S,selectedItemText:E,focusSelectedItem:k}=o,T=_.useCallback(()=>{if(s.trigger&&s.valueNode&&l&&d&&w&&S&&E){const H=s.trigger.getBoundingClientRect(),D=d.getBoundingClientRect(),K=s.valueNode.getBoundingClientRect(),q=E.getBoundingClientRect();if(s.dir!=="rtl"){const Ee=q.left-D.left,Oe=K.left-Ee,Se=H.left-Oe,Qe=H.width+Se,Ht=Math.max(Qe,D.width),ye=window.innerWidth-Qs,Xe=PN(Oe,[Qs,Math.max(Qs,ye-Ht)]);l.style.minWidth=Qe+"px",l.style.left=Xe+"px"}else{const Ee=D.right-q.right,Oe=window.innerWidth-K.right-Ee,Se=window.innerWidth-H.right-Oe,Qe=H.width+Se,Ht=Math.max(Qe,D.width),ye=window.innerWidth-Qs,Xe=PN(Oe,[Qs,Math.max(Qs,ye-Ht)]);l.style.minWidth=Qe+"px",l.style.right=Xe+"px"}const X=y(),z=window.innerHeight-Qs*2,N=w.scrollHeight,$=window.getComputedStyle(d),I=parseInt($.borderTopWidth,10),M=parseInt($.paddingTop,10),O=parseInt($.borderBottomWidth,10),U=parseInt($.paddingBottom,10),B=I+M+N+U+O,L=Math.min(S.offsetHeight*5,B),Y=window.getComputedStyle(w),V=parseInt(Y.paddingTop,10),j=parseInt(Y.paddingBottom,10),te=H.top+H.height/2-Qs,re=z-te,oe=S.offsetHeight/2,ee=S.offsetTop+oe,pe=I+M+ee,ae=B-pe;if(pe<=te){const Ee=X.length>0&&S===X[X.length-1].ref.current;l.style.bottom="0px";const Oe=d.clientHeight-w.offsetTop-w.offsetHeight,Se=Math.max(re,oe+(Ee?j:0)+Oe+O),Qe=pe+Se;l.style.height=Qe+"px"}else{const Ee=X.length>0&&S===X[0].ref.current;l.style.top="0px";const Se=Math.max(te,I+w.offsetTop+(Ee?V:0)+oe)+ae;l.style.height=Se+"px",w.scrollTop=pe-te+w.offsetTop}l.style.margin=`${Qs}px 0`,l.style.minHeight=L+"px",l.style.maxHeight=z+"px",r==null||r(),requestAnimationFrame(()=>g.current=!0)}},[y,s.trigger,s.valueNode,l,d,w,S,E,s.dir,r]);Di(()=>T(),[T]);const[R,P]=_.useState();Di(()=>{d&&P(window.getComputedStyle(d).zIndex)},[d]);const A=_.useCallback(H=>{H&&b.current===!0&&(T(),k==null||k(),b.current=!1)},[T,k]);return v.jsx(Yie,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:g,onScrollButtonChange:A,children:v.jsx("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:R},children:v.jsx(hn.div,{...i,ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})});y3.displayName=Wie;var qie="SelectPopperPosition",pS=_.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:i=Qs,...s}=e,o=py(n);return v.jsx(oy,{...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)"}})});pS.displayName=qie;var[Yie,uE]=Md(Ac,{}),mS="SelectViewport",b3=_.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...i}=e,s=Il(mS,n),o=uE(mS,n),l=Kn(t,s.onViewportChange),u=_.useRef(0);return v.jsxs(v.Fragment,{children:[v.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}),v.jsx(fy.Slot,{scope:n,children:v.jsx(hn.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:l,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:Mt(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 b=window.innerHeight-Qs*2,w=parseFloat(p.style.minHeight),S=parseFloat(p.style.height),E=Math.max(w,S);if(E<b){const k=E+g,T=Math.min(b,k),R=k-T;p.style.height=T+"px",p.style.bottom==="0px"&&(f.scrollTop=R>0?R:0,p.style.justifyContent="flex-end")}}}u.current=f.scrollTop})})})]})});b3.displayName=mS;var _3="SelectGroup",[Vie,Kie]=Md(_3),Gie=_.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,i=Ci();return v.jsx(Vie,{scope:n,id:i,children:v.jsx(hn.div,{role:"group","aria-labelledby":i,...r,ref:t})})});Gie.displayName=_3;var w3="SelectLabel",Xie=_.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,i=Kie(w3,n);return v.jsx(hn.div,{id:i.id,...r,ref:t})});Xie.displayName=w3;var _v="SelectItem",[Zie,S3]=Md(_v),x3=_.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:i=!1,textValue:s,...o}=e,l=Dl(_v,n),u=Il(_v,n),d=l.value===r,[f,p]=_.useState(s??""),[y,g]=_.useState(!1),b=Kn(t,k=>{var T;return(T=u.itemRefCallback)==null?void 0:T.call(u,k,r,i)}),w=Ci(),S=_.useRef("touch"),E=()=>{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 v.jsx(Zie,{scope:n,value:r,disabled:i,textId:w,isSelected:d,onItemTextChange:_.useCallback(k=>{p(T=>T||((k==null?void 0:k.textContent)??"").trim())},[]),children:v.jsx(fy.ItemSlot,{scope:n,value:r,disabled:i,textValue:f,children:v.jsx(hn.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:b,onFocus:Mt(o.onFocus,()=>g(!0)),onBlur:Mt(o.onBlur,()=>g(!1)),onClick:Mt(o.onClick,()=>{S.current!=="mouse"&&E()}),onPointerUp:Mt(o.onPointerUp,()=>{S.current==="mouse"&&E()}),onPointerDown:Mt(o.onPointerDown,k=>{S.current=k.pointerType}),onPointerMove:Mt(o.onPointerMove,k=>{var T;S.current=k.pointerType,i?(T=u.onItemLeave)==null||T.call(u):S.current==="mouse"&&k.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Mt(o.onPointerLeave,k=>{var T;k.currentTarget===document.activeElement&&((T=u.onItemLeave)==null||T.call(u))}),onKeyDown:Mt(o.onKeyDown,k=>{var R;((R=u.searchRef)==null?void 0:R.current)!==""&&k.key===" "||(Die.includes(k.key)&&E(),k.key===" "&&k.preventDefault())})})})})});x3.displayName=_v;var rh="SelectItemText",E3=_.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:i,...s}=e,o=Dl(rh,n),l=Il(rh,n),u=S3(rh,n),d=jie(rh,n),[f,p]=_.useState(null),y=Kn(t,E=>p(E),u.onItemTextChange,E=>{var k;return(k=l.itemTextRefCallback)==null?void 0:k.call(l,E,u.value,u.disabled)}),g=f==null?void 0:f.textContent,b=_.useMemo(()=>v.jsx("option",{value:u.value,disabled:u.disabled,children:g},u.value),[u.disabled,u.value,g]),{onNativeOptionAdd:w,onNativeOptionRemove:S}=d;return Di(()=>(w(b),()=>S(b)),[w,S,b]),v.jsxs(v.Fragment,{children:[v.jsx(hn.span,{id:u.textId,...s,ref:y}),u.isSelected&&o.valueNode&&!o.valueNodeHasChildren?Fc.createPortal(s.children,o.valueNode):null]})});E3.displayName=rh;var C3="SelectItemIndicator",k3=_.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return S3(C3,n).isSelected?v.jsx(hn.span,{"aria-hidden":!0,...r,ref:t}):null});k3.displayName=C3;var gS="SelectScrollUpButton",T3=_.forwardRef((e,t)=>{const n=Il(gS,e.__scopeSelect),r=uE(gS,e.__scopeSelect),[i,s]=_.useState(!1),o=Kn(t,r.onScrollButtonChange);return Di(()=>{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?v.jsx(A3,{...e,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}}):null});T3.displayName=gS;var vS="SelectScrollDownButton",R3=_.forwardRef((e,t)=>{const n=Il(vS,e.__scopeSelect),r=uE(vS,e.__scopeSelect),[i,s]=_.useState(!1),o=Kn(t,r.onScrollButtonChange);return Di(()=>{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?v.jsx(A3,{...e,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}}):null});R3.displayName=vS;var A3=_.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...i}=e,s=Il("SelectScrollButton",n),o=_.useRef(null),l=hy(n),u=_.useCallback(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return _.useEffect(()=>()=>u(),[u]),Di(()=>{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]),v.jsx(hn.div,{"aria-hidden":!0,...i,ref:t,style:{flexShrink:0,...i.style},onPointerDown:Mt(i.onPointerDown,()=>{o.current===null&&(o.current=window.setInterval(r,50))}),onPointerMove:Mt(i.onPointerMove,()=>{var d;(d=s.onItemLeave)==null||d.call(s),o.current===null&&(o.current=window.setInterval(r,50))}),onPointerLeave:Mt(i.onPointerLeave,()=>{u()})})}),Qie="SelectSeparator",Jie=_.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return v.jsx(hn.div,{"aria-hidden":!0,...r,ref:t})});Jie.displayName=Qie;var yS="SelectArrow",ese=_.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,i=py(n),s=Dl(yS,n),o=Il(yS,n);return s.open&&o.position==="popper"?v.jsx(ay,{...i,...r,ref:t}):null});ese.displayName=yS;var tse="SelectBubbleInput",M3=_.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const i=_.useRef(null),s=Kn(r,i),o=Mte(t);return _.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]),v.jsx(hn.select,{...n,style:{...fB,...n.style},ref:s,defaultValue:t})});M3.displayName=tse;function N3(e){return e===""||e===void 0}function P3(e){const t=Lo(e),n=_.useRef(""),r=_.useRef(0),i=_.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=_.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return _.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,i,s]}function L3(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=nse(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 nse(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var rse=l3,ise=u3,sse=f3,ose=h3,ase=p3,lse=m3,cse=b3,use=x3,dse=E3,fse=k3,hse=T3,pse=R3,[my]=_a("Tooltip",[Ll]),gy=Ll(),O3="TooltipProvider",mse=700,bS="tooltip.open",[gse,dE]=my(O3),D3=e=>{const{__scopeTooltip:t,delayDuration:n=mse,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:s}=e,o=_.useRef(!0),l=_.useRef(!1),u=_.useRef(0);return _.useEffect(()=>{const d=u.current;return()=>window.clearTimeout(d)},[]),v.jsx(gse,{scope:t,isOpenDelayedRef:o,delayDuration:n,onOpen:_.useCallback(()=>{window.clearTimeout(u.current),o.current=!1},[]),onClose:_.useCallback(()=>{window.clearTimeout(u.current),u.current=window.setTimeout(()=>o.current=!0,r)},[r]),isPointerInTransitRef:l,onPointerInTransitChange:_.useCallback(d=>{l.current=d},[]),disableHoverableContent:i,children:s})};D3.displayName=O3;var zh="Tooltip",[vse,hp]=my(zh),I3=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:s,disableHoverableContent:o,delayDuration:l}=e,u=dE(zh,e.__scopeTooltip),d=gy(t),[f,p]=_.useState(null),y=Ci(),g=_.useRef(0),b=o??u.disableHoverableContent,w=l??u.delayDuration,S=_.useRef(!1),[E,k]=Cc({prop:r,defaultProp:i??!1,onChange:H=>{H?(u.onOpen(),document.dispatchEvent(new CustomEvent(bS))):u.onClose(),s==null||s(H)},caller:zh}),T=_.useMemo(()=>E?S.current?"delayed-open":"instant-open":"closed",[E]),R=_.useCallback(()=>{window.clearTimeout(g.current),g.current=0,S.current=!1,k(!0)},[k]),P=_.useCallback(()=>{window.clearTimeout(g.current),g.current=0,k(!1)},[k]),A=_.useCallback(()=>{window.clearTimeout(g.current),g.current=window.setTimeout(()=>{S.current=!0,k(!0),g.current=0},w)},[w,k]);return _.useEffect(()=>()=>{g.current&&(window.clearTimeout(g.current),g.current=0)},[]),v.jsx(sy,{...d,children:v.jsx(vse,{scope:t,contentId:y,open:E,stateAttribute:T,trigger:f,onTriggerChange:p,onTriggerEnter:_.useCallback(()=>{u.isOpenDelayedRef.current?A():R()},[u.isOpenDelayedRef,A,R]),onTriggerLeave:_.useCallback(()=>{b?P():(window.clearTimeout(g.current),g.current=0)},[P,b]),onOpen:R,onClose:P,disableHoverableContent:b,children:n})})};I3.displayName=zh;var _S="TooltipTrigger",B3=_.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=hp(_S,n),s=dE(_S,n),o=gy(n),l=_.useRef(null),u=Kn(t,l,i.onTriggerChange),d=_.useRef(!1),f=_.useRef(!1),p=_.useCallback(()=>d.current=!1,[]);return _.useEffect(()=>()=>document.removeEventListener("pointerup",p),[p]),v.jsx(lp,{asChild:!0,...o,children:v.jsx(hn.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:u,onPointerMove:Mt(e.onPointerMove,y=>{y.pointerType!=="touch"&&!f.current&&!s.isPointerInTransitRef.current&&(i.onTriggerEnter(),f.current=!0)}),onPointerLeave:Mt(e.onPointerLeave,()=>{i.onTriggerLeave(),f.current=!1}),onPointerDown:Mt(e.onPointerDown,()=>{i.open&&i.onClose(),d.current=!0,document.addEventListener("pointerup",p,{once:!0})}),onFocus:Mt(e.onFocus,()=>{d.current||i.onOpen()}),onBlur:Mt(e.onBlur,i.onClose),onClick:Mt(e.onClick,i.onClose)})})});B3.displayName=_S;var fE="TooltipPortal",[yse,bse]=my(fE,{forceMount:void 0}),z3=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,s=hp(fE,t);return v.jsx(yse,{scope:t,forceMount:n,children:v.jsx(qs,{present:n||s.open,children:v.jsx(Td,{asChild:!0,container:i,children:r})})})};z3.displayName=fE;var vd="TooltipContent",j3=_.forwardRef((e,t)=>{const n=bse(vd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...s}=e,o=hp(vd,e.__scopeTooltip);return v.jsx(qs,{present:r||o.open,children:o.disableHoverableContent?v.jsx($3,{side:i,...s,ref:t}):v.jsx(_se,{side:i,...s,ref:t})})}),_se=_.forwardRef((e,t)=>{const n=hp(vd,e.__scopeTooltip),r=dE(vd,e.__scopeTooltip),i=_.useRef(null),s=Kn(t,i),[o,l]=_.useState(null),{trigger:u,onClose:d}=n,f=i.current,{onPointerInTransitChange:p}=r,y=_.useCallback(()=>{l(null),p(!1)},[p]),g=_.useCallback((b,w)=>{const S=b.currentTarget,E={x:b.clientX,y:b.clientY},k=Ese(E,S.getBoundingClientRect()),T=Cse(E,k),R=kse(w.getBoundingClientRect()),P=Rse([...T,...R]);l(P),p(!0)},[p]);return _.useEffect(()=>()=>y(),[y]),_.useEffect(()=>{if(u&&f){const b=S=>g(S,f),w=S=>g(S,u);return u.addEventListener("pointerleave",b),f.addEventListener("pointerleave",w),()=>{u.removeEventListener("pointerleave",b),f.removeEventListener("pointerleave",w)}}},[u,f,g,y]),_.useEffect(()=>{if(o){const b=w=>{const S=w.target,E={x:w.clientX,y:w.clientY},k=(u==null?void 0:u.contains(S))||(f==null?void 0:f.contains(S)),T=!Tse(E,o);k?y():T&&(y(),d())};return document.addEventListener("pointermove",b),()=>document.removeEventListener("pointermove",b)}},[u,f,o,d,y]),v.jsx($3,{...e,ref:s})}),[wse,Sse]=my(zh,{isInside:!1}),xse=nee("TooltipContent"),$3=_.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:s,onPointerDownOutside:o,...l}=e,u=hp(vd,n),d=gy(n),{onClose:f}=u;return _.useEffect(()=>(document.addEventListener(bS,f),()=>document.removeEventListener(bS,f)),[f]),_.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]),v.jsx(kd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:p=>p.preventDefault(),onDismiss:f,children:v.jsxs(oy,{"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:[v.jsx(xse,{children:r}),v.jsx(wse,{scope:n,isInside:!0,children:v.jsx(pB,{id:u.contentId,role:"tooltip",children:i||r})})]})})});j3.displayName=vd;var F3="TooltipArrow",H3=_.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=gy(n);return Sse(F3,n).isInside?null:v.jsx(ay,{...i,...r,ref:t})});H3.displayName=F3;function Ese(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 Cse(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 kse(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 Tse(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 Rse(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),Ase(t)}function Ase(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 Mse=D3,Nse=I3,Pse=B3,Lse=z3,Ose=j3,Dse=H3;function hE({...e}){return v.jsx(Mie,{"data-slot":"popover",...e})}function pE({...e}){return v.jsx(Nie,{"data-slot":"popover-trigger",...e})}function mE({className:e,align:t="center",sideOffset:n=4,...r}){return v.jsx(Pie,{children:v.jsx(Lie,{"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),...r})})}const Ise={"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 wc({variant:e,action:t}){const{heading:n,body:r}=Ise[e];return e==="no-messages"?v.jsx("div",{className:"flex h-full w-full items-center justify-center animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:v.jsx("p",{className:"text-sm text-muted-foreground",children:n})}):v.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:[v.jsx("h2",{className:"text-2xl font-semibold",children:n}),r&&v.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:r}),t&&v.jsx("div",{children:t})]})}const Bse={online:"bg-[var(--color-status-success)]",offline:"bg-[var(--muted-foreground)]",connecting:"bg-[var(--color-status-working)] animate-pulse"},zse={online:"开发机在线",offline:"开发机离线",connecting:"正在连接开发机"};function LN({status:e,className:t}){return v.jsx("span",{className:Ye("inline-block w-2 h-2 rounded-full shrink-0",Bse[e],t),role:"status","aria-label":zse[e]})}function U3({layout:e,variant:t="default"}){const n=De(b=>b.proxies),r=De(b=>b.proxyListLoaded),i=De(b=>b.relayClientAuthIssue),s=De(b=>b.selectedProxyId),o=De(b=>b.proxySwitchTarget),l=Ui(),u=so(),[d,f]=_.useState(!1);async function p(b,w){if(o)return;const S=Ut;if(!S){nt.error("请先连接开发机");return}const E=w??b,k=s!==null&&s!==b;De.getState().setProxySwitchTarget({proxyId:b,name:E});try{const T=await S.selectProxy(b);if(!T.success){nt.error(`无法连接 ${E}:${T.error??"未知错误"}`);return}k&&(Ft.getState().prepareForProxySwitch(E),hi.getState().prepareForProxySwitch()),Er("local",Sn.proxyId,b),De.getState().setProxy(b,w??null),De.getState().setProxyOnline(!0),De.getState().transitionToPhase("session_browsing"),S.sendControl({type:"session_list"}),S.requestProxyInfo().then(R=>{if(De.getState().selectedProxyId!==b)return;const P=hi.getState();P.setHomePath(R.homePath),P.setAgentCli(R.agentCli)}).catch(R=>{console.error("[proxy-switcher] post-bind proxy info fetch failed",R)}),S.requestAgentStatuses().then(R=>{if(De.getState().selectedProxyId!==b)return;const P=Ft.getState();for(const A of R)P.setAgentStatus(A.sessionId,A.payload)}).catch(R=>{console.error("[proxy-switcher] post-bind data fetch failed",R)}),P1(S).then(R=>{R.status==="failed"&&console.error("[proxy-switcher] post-bind data fetch failed",R.error)}),f(!1),(e==="page"||l.pathname.startsWith("/chat/"))&&u("/sessions")}catch(T){const R=T instanceof Error?T.message:"未知错误";nt.error(`无法连接 ${E}:${R}`)}finally{De.getState().setProxySwitchTarget(null)}}if(e==="page")return i==="missing_client_token"?v.jsx(wc,{variant:"client-token-missing"}):i==="invalid_client_token"?v.jsx(wc,{variant:"client-token-invalid"}):r?n.length===0?v.jsx(wc,{variant:"no-proxy"}):v.jsxs("div",{className:"flex flex-col gap-3 p-4 h-full overflow-auto",children:[v.jsx("h3",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"可连接开发机"}),v.jsx("ul",{role:"list",className:"flex flex-col gap-2",children:n.map(b=>{const w=(o==null?void 0:o.proxyId)===b.proxyId,S=o!==null;return v.jsx("li",{children:v.jsxs("button",{type:"button","data-slot":"proxy-item","data-proxy-id":b.proxyId,"data-online":b.online,"data-selecting":w||void 0,disabled:!b.online||S,"aria-busy":w||void 0,onClick:()=>p(b.proxyId,b.name),className:Ye("w-full flex items-center gap-3 px-3 h-11 min-h-[44px] rounded-md border bg-card transition-colors text-left disabled:cursor-not-allowed disabled:hover:bg-card",w?"border-primary/40 bg-accent text-accent-foreground":"border-border hover:bg-accent",S&&!w?"opacity-50":"",b.online?"":"opacity-50"),"aria-pressed":s===b.proxyId,title:b.online?void 0:"这台开发机离线,暂时无法连接",children:[v.jsx(LN,{status:b.online?"online":"offline"}),v.jsx("span",{className:"text-sm font-normal flex-1 truncate min-w-0",children:b.name??b.proxyId}),w?v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:"正在连接"}),v.jsx(fa,{className:"h-4 w-4 animate-spin text-primary shrink-0","aria-hidden":!0})]}):s===b.proxyId?v.jsx(pa,{className:"h-4 w-4 text-primary shrink-0","aria-label":"已选"}):null,!b.online&&!w&&v.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:"离线"})]})},b.proxyId)})})]}):v.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:[v.jsx(fa,{className:"h-5 w-5 animate-spin","aria-hidden":!0}),v.jsx("p",{className:"text-sm",children:"连接中..."})]});const y=n.find(b=>b.proxyId===s),g=(y==null?void 0:y.name)??(y==null?void 0:y.proxyId)??"未选择开发机";return v.jsxs(hE,{open:d,onOpenChange:f,children:[v.jsx(pE,{asChild:!0,children:v.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":`当前连接:${g}`,children:[t==="default"&&v.jsx("span",{className:"h-4 w-4 shrink-0","aria-hidden":!0}),v.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:g}),v.jsx(Al,{className:"h-4 w-4 text-muted-foreground shrink-0 transition-transform group-data-[state=open]:rotate-180","aria-hidden":!0})]})}),v.jsx(mE,{align:"start",className:"w-[260px] p-1",children:n.length===0?v.jsx("div",{className:"text-xs text-muted-foreground p-2",children:"暂无可连接开发机"}):v.jsx("ul",{role:"list",className:"flex flex-col",children:n.map(b=>{const w=(o==null?void 0:o.proxyId)===b.proxyId,S=o!==null;return v.jsx("li",{children:v.jsxs("button",{type:"button","data-slot":"proxy-item","data-proxy-id":b.proxyId,"data-online":b.online,"data-selecting":w||void 0,disabled:!b.online||S,"aria-busy":w||void 0,onClick:()=>p(b.proxyId,b.name),className:Ye("w-full flex items-center gap-2 px-2 h-9 rounded-md transition-colors text-left disabled:cursor-not-allowed disabled:hover:bg-transparent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",w?"bg-accent text-accent-foreground":"hover:bg-accent",S&&!w?"opacity-50":"",b.online?"":"opacity-50"),"aria-pressed":s===b.proxyId,title:b.online?void 0:"这台开发机离线",children:[v.jsx(LN,{status:b.online?"online":"offline"}),v.jsx("span",{className:"text-sm font-normal flex-1 truncate min-w-0",children:b.name??b.proxyId}),w?v.jsx(fa,{className:"h-4 w-4 animate-spin text-primary shrink-0","aria-label":"正在连接"}):s===b.proxyId?v.jsx(pa,{className:"h-4 w-4 text-primary shrink-0","aria-label":"已选"}):null,!b.online&&s!==b.proxyId&&!w&&v.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:"离线"})]})},b.proxyId)})})})]})}const ON=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,DN=VD,jse=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return DN(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=ON(f)||ON(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(b=>{let[w,S]=b;return Array.isArray(S)?S.includes({...s,...l}[w]):{...s,...l}[w]===S})?[...d,p,y]:d},[]);return DN(e,o,u,n==null?void 0:n.class,n==null?void 0:n.className)},$se=jse("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 At({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const s=r?eee:"button";return v.jsx(s,{"data-slot":"button","data-variant":t,"data-size":n,className:Ye($se({variant:t,size:n,className:e})),...i})}function Fse({delayDuration:e=0,...t}){return v.jsx(Mse,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function pp({...e}){return v.jsx(Nse,{"data-slot":"tooltip",...e})}function mp({...e}){return v.jsx(Pse,{"data-slot":"tooltip-trigger",...e})}function gp({className:e,sideOffset:t=0,children:n,hideArrow:r=!1,...i}){return v.jsx(Lse,{children:v.jsxs(Ose,{"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&&v.jsx(Dse,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}function vy({...e}){return v.jsx(W1,{"data-slot":"sheet",...e})}function Hse({...e}){return v.jsx(Ate,{"data-slot":"sheet-trigger",...e})}function Use({...e}){return v.jsx(q1,{"data-slot":"sheet-portal",...e})}function Wse({className:e,...t}){return v.jsx(Y1,{"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 yy({className:e,overlayClassName:t,children:n,side:r="right",showCloseButton:i=!0,focusSurfaceOnOpen:s=!1,onOpenAutoFocus:o,...l}){return v.jsxs(Use,{children:[v.jsx(Wse,{className:t}),v.jsxs(V1,{"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:u=>{o==null||o(u),!(!s||u.defaultPrevented)&&(u.preventDefault(),u.currentTarget.focus({preventScroll:!0}))},...l,children:[n,i&&v.jsxs(ey,{"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:[v.jsx(zc,{className:"size-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function gE({className:e,...t}){return v.jsx("div",{"data-slot":"sheet-header",className:Ye("flex flex-col gap-1.5 p-4",e),...t})}function by({className:e,...t}){return v.jsx(HB,{"data-slot":"sheet-title",className:Ye("font-semibold text-foreground",e),...t})}function qse({className:e,...t}){return v.jsx(UB,{"data-slot":"sheet-description",className:Ye("text-sm text-muted-foreground",e),...t})}function vE({...e}){return v.jsx(die,{"data-slot":"dropdown-menu",...e})}function yE({...e}){return v.jsx(fie,{"data-slot":"dropdown-menu-trigger",...e})}function bE({className:e,sideOffset:t=4,...n}){return v.jsx(hie,{children:v.jsx(pie,{"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),...n})})}function ko({className:e,inset:t,variant:n="default",...r}){return v.jsx(gie,{"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 Ew({className:e,children:t,checked:n,...r}){return v.jsxs(vie,{"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:[v.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:v.jsx(yie,{children:v.jsx(pa,{className:"size-4"})})}),t]})}function sg({className:e,inset:t,...n}){return v.jsx(mie,{"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 Cw({className:e,...t}){return v.jsx(bie,{"data-slot":"dropdown-menu-separator",className:Ye("-mx-1 my-1 h-px bg-border",e),...t})}const Yse={claude:"Claude Code",codex:"Codex"},IN=["claude","codex"];function _y(e){return Yse[e]}function W3(e,t){return IN.indexOf(e)-IN.indexOf(t)}function jh(e){return e.provider??"claude"}const wS=60*1e3,SS=60*wS,Vse=24*SS;function q3(e,t=Date.now()){const n=t-e;if(n<wS)return"刚刚";if(n<SS)return`${Math.floor(n/wS)} 分钟前`;if(n<Vse)return`${Math.floor(n/SS)} 小时前`;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 BN={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 xS(e){return e.kind!=="terminal"?BN[e.state]:e.state==="terminated"?BN.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 Kse({session:e}){const t=xS(e);return v.jsx("span",{className:Ye("inline-block size-2 rounded-full shrink-0",t.dot),"aria-label":`会话状态:${t.label}`,role:"status"})}function Gse({mode:e}){if(e!=="pty"&&e!=="json")return null;const t=e==="json"?"聊天视图":"终端视图",n=e==="json"?p1:g1;return v.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:v.jsx(n,{className:"size-3.5","aria-hidden":"true"})})}function Xse({session:e,selected:t,now:n,onClick:r,onRename:i,onTerminate:s}){const o=e.lastActive,l=e.cwd??e.name??e.sessionId,u=Kv(e.name),d=D1(e),f=e.nameLocked&&e.name?e.name:d||(u==="New Session"?e.sessionId.slice(0,8):u),p=!!e.mode||!!e.provider||o!==void 0,y=o!==void 0?q3(o,n):null,g=e.mode==="pty"&&e.ptyOwner==="local-terminal",b=e.kind==="terminal"?"终止终端":g?"断开远程连接":"终止会话";return v.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&&v.jsx("span",{className:"dev-sidebar-active-indicator absolute left-0 top-0 bottom-0 w-[2px]","aria-hidden":"true"}),v.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:[v.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[v.jsx(Kse,{session:e}),v.jsx("span",{className:"text-sm font-normal truncate flex-1",title:l,children:f})]}),p&&v.jsxs("span",{className:"flex items-center gap-1.5 text-xs leading-5 h-5",children:[e.mode&&v.jsx(Gse,{mode:e.mode}),e.mode&&v.jsx("span",{className:"text-muted-foreground/60 shrink-0","aria-hidden":"true",children:"·"}),e.provider&&e.kind!=="terminal"&&v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"font-mono text-muted-foreground shrink-0",children:_y(e.provider)}),v.jsx("span",{className:"text-muted-foreground/60 shrink-0","aria-hidden":"true",children:"·"})]}),v.jsx("span",{className:Ye("shrink-0",xS(e).text),children:xS(e).label}),y&&v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"text-muted-foreground/60 shrink-0","aria-hidden":"true",children:"·"}),v.jsx("span",{className:"text-muted-foreground shrink-0 tabular-nums",children:y})]})]})]}),(i||s)&&v.jsxs(vE,{children:[v.jsx(yE,{asChild:!0,children:v.jsx(At,{variant:"ghost",size:"icon-xs",className:"size-11 md:size-6","aria-label":"会话操作","data-slot":"session-row-menu-trigger",onClick:w=>w.stopPropagation(),children:v.jsx(AW,{"aria-hidden":"true"})})}),v.jsxs(bE,{align:"end","data-slot":"session-row-menu",children:[i&&v.jsx(ko,{"data-slot":"session-row-rename-item",onSelect:w=>{w.stopPropagation(),i()},children:"重命名"}),s&&v.jsx(ko,{variant:"destructive","data-slot":"session-row-terminate-item",onSelect:w=>{w.stopPropagation(),s()},children:b})]})]})]})}function Bl({...e}){return v.jsx(W1,{"data-slot":"dialog",...e})}function Zse({...e}){return v.jsx(q1,{"data-slot":"dialog-portal",...e})}function Qse({...e}){return v.jsx(ey,{"data-slot":"dialog-close",...e})}function Jse({className:e,...t}){return v.jsx(Y1,{"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 zl({className:e,children:t,showCloseButton:n=!0,focusSurfaceOnOpen:r=!1,onOpenAutoFocus:i,...s}){return v.jsxs(Zse,{"data-slot":"dialog-portal",children:[v.jsx(Jse,{}),v.jsxs(V1,{"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:o=>{i==null||i(o),!(!r||o.defaultPrevented)&&(o.preventDefault(),o.currentTarget.focus({preventScroll:!0}))},...s,children:[t,n&&v.jsxs(ey,{"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:[v.jsx(zc,{}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function jl({className:e,...t}){return v.jsx("div",{"data-slot":"dialog-header",className:Ye("flex flex-col gap-2 text-center sm:text-left",e),...t})}function Mc({className:e,showCloseButton:t=!1,children:n,...r}){return v.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&&v.jsx(ey,{asChild:!0,children:v.jsx(At,{variant:"outline",children:"Close"})})]})}function ba({className:e,...t}){return v.jsx(HB,{"data-slot":"dialog-title",className:Ye("text-lg leading-none font-semibold",e),...t})}function El({className:e,...t}){return v.jsx(UB,{"data-slot":"dialog-description",className:Ye("text-sm text-muted-foreground",e),...t})}function Cl(e){const[t,n]=_.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(e).matches);return _.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 eoe({session:e,now:t,disabled:n,loading:r,onClick:i,modeTag:s}){const o=v.jsx(toe,{title:e.title,modeTag:s}),l=v.jsx("span",{className:"text-xs text-muted-foreground tabular-nums",children:q3(e.updatedAt,t)}),u=v.jsxs("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[o,l]});return v.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:v.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,v.jsx(tW,{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 toe({title:e,modeTag:t}){return v.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[v.jsx("span",{className:"text-sm font-normal truncate min-w-0",title:e,children:e}),t&&v.jsx(noe,{mode:t})]})}function noe({mode:e}){const t=e==="json"?"聊天视图":"终端视图",n=e==="json"?p1:g1;return v.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:v.jsx(n,{className:"size-3","aria-hidden":"true"})})}function Y3({providerLabel:e}){return v.jsx("div",{className:"grid min-w-0 gap-4","data-slot":"bypass-permission-warning",role:"alert",children:v.jsxs("div",{className:"flex min-w-0 items-start gap-3 text-sm",children:[v.jsx(B7,{className:"mt-0.5 size-5 shrink-0 text-destructive","aria-hidden":"true"}),v.jsxs("div",{className:"grid min-w-0 gap-2",children:[v.jsxs("p",{className:"font-medium text-foreground",children:[e," 将不再请求工具审批。"]}),v.jsx("p",{className:"text-muted-foreground",children:"Agent 可以直接执行命令、修改或删除文件,并可能绕过部分沙箱保护。"})]})]})})}function roe({now:e}){const t=Ft(X=>X.historySessions),n=Ft(X=>X.historyLoadStatus),[r,i]=_.useState(null),[s,o]=_.useState(null),[l,u]=_.useState("json"),[d,f]=_.useState("default"),[p,y]=_.useState(!1),[g,b]=_.useState(new Set),[w,S]=_.useState(new Set),E=so(),k=_.useMemo(()=>{const X=new Map;for(const z of t){const N=jh(z);let $=X.get(N);$||($=new Map,X.set(N,$));const I=V3(z.projectDir),M=$.get(I);M?M.sessions.push(z):$.set(I,{dir:I,sessions:[z]})}return Array.from(X.entries()).sort(([z],[N])=>W3(z,N)).map(([z,N])=>({provider:z,sessions:Array.from(N.values()).flatMap($=>$.sessions),projects:Array.from(N.values()).map($=>({dir:$.dir,shortDir:Kv($.dir),sessions:$.sessions}))}))},[t]);function T(X){o(X),u(ioe(X)),f(soe(X))}async function R(X,z,N){if(r)return;const $=Ut;if(!$){nt.error("请先连接开发机");return}i(X.id);const I=jh(X);try{const M=await $.createSession({cwd:X.projectDir,mode:z,provider:I,resumeSessionId:X.id,...N?{permissionMode:N}:{}});if(M.error||!M.sessionId){if(M.errorCode===zr.SESSION_ALREADY_ACTIVE){Ft.getState().setCodexActiveWriterConflict({...M.activeWriterPid?{activeWriterPid:M.activeWriterPid}:{}}),o(null);return}nt.error(`恢复失败:${M.error??"未知错误"}`);return}const O={sessionId:M.sessionId,...M.kind!==void 0?{kind:M.kind}:{},...M.name!==void 0?{name:M.name}:{},...M.nameLocked!==void 0?{nameLocked:M.nameLocked}:{},state:"idle",mode:M.mode??z,provider:M.provider??"claude",...M.ptyOwner!==void 0?{ptyOwner:M.ptyOwner}:{}};Ft.getState().addSession(O),E(`/chat/${M.sessionId}?mode=${M.mode??z}`),o(null)}catch(M){nt.error(`恢复失败:${M instanceof Error?M.message:String(M)}`)}finally{i(null)}}function P(){const X=Ut;!X||Ft.getState().historyLoadStatus==="loading"||P1(X).then(z=>{z.status==="failed"&&nt.error(z.error instanceof Error?z.error.message:String(z.error))})}function A(X,z){const N=zN(X,z);S($=>{const I=new Set($);return I.has(N)?I.delete(N):I.add(N),I})}function H(X){b(z=>{const N=new Set(z);return N.has(X)?N.delete(X):N.add(X),N})}const D=t.length>0,K=n==="loading",q=s?K3():[];return v.jsxs("div",{"data-slot":"history-list",className:"flex flex-col",children:[v.jsxs("div",{className:"flex min-h-11 w-full items-center gap-1.5 px-4 py-1.5 md:min-h-[36px]",children:[v.jsxs("button",{type:"button",onClick:()=>D&&y(X=>!X),disabled:!D,"aria-expanded":D?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:[v.jsxs("h3",{className:"min-w-0 text-sm font-semibold text-foreground",children:["全部会话",D?v.jsxs("span",{className:"ml-1 text-muted-foreground/70 font-normal",children:["· ",t.length]}):null]}),D?v.jsx(gh,{className:Ye("size-3.5 shrink-0 text-muted-foreground/80 transition-transform",p&&"rotate-90"),"aria-hidden":"true"}):null]}),v.jsx(At,{type:"button",variant:"ghost",size:"icon-sm","aria-label":"刷新全部会话","aria-busy":K,title:K?"正在加载":"刷新",onClick:P,disabled:K,"data-slot":"history-refresh",className:"size-11 md:size-8",children:v.jsx(m1,{className:Ye("size-3.5",K&&"animate-spin motion-reduce:animate-none"),"aria-hidden":"true"})})]}),!D&&K&&v.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:[v.jsx(fa,{className:"size-3.5 shrink-0 animate-spin motion-reduce:animate-none","aria-hidden":"true"}),v.jsx("span",{children:"正在加载会话记录..."})]}),!D&&n==="idle"&&v.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/80","data-slot":"history-idle",role:"status",children:"会话记录尚未加载"}),!D&&n==="error"&&v.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/80","data-slot":"history-error",role:"status",children:"会话记录加载失败,请点击刷新重试"}),D&&n==="error"&&v.jsx("div",{className:"px-4 pb-2 text-xs text-muted-foreground/80","data-slot":"history-stale",role:"status",children:"刷新失败,当前显示上次加载的结果"}),!D&&n==="loaded"&&v.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/70","data-slot":"history-empty",children:"暂无会话记录"}),D&&p&&v.jsx("ul",{role:"list",className:"flex flex-col",children:k.map(X=>{const z=g.has(X.provider);return v.jsxs("li",{children:[v.jsxs("button",{type:"button",onClick:()=>H(X.provider),"aria-expanded":!z,"data-slot":"history-provider-header","data-expanded":!z,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:[v.jsx("span",{className:"font-mono",children:_y(X.provider)}),v.jsx("span",{className:"h-px flex-1 bg-border/70","aria-hidden":"true"}),v.jsx("span",{className:"tabular-nums",children:X.sessions.length}),v.jsx(gh,{className:Ye("size-3.5 shrink-0 text-muted-foreground/80 transition-transform",!z&&"rotate-90"),"aria-hidden":"true"})]}),!z&&v.jsx("ul",{role:"list",className:"flex flex-col",children:X.projects.map(N=>{const $=zN(X.provider,N.dir),I=w.has($);return v.jsxs("li",{children:[v.jsxs("button",{type:"button",onClick:()=>A(X.provider,N.dir),"aria-expanded":I,"data-slot":"history-group-header","data-expanded":I,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:[v.jsx("span",{className:"text-sm font-mono truncate flex-1 min-w-0",title:N.dir,children:N.shortDir}),v.jsx("span",{className:"text-xs text-muted-foreground/80 tabular-nums shrink-0",children:N.sessions.length}),v.jsx(gh,{className:Ye("size-3.5 shrink-0 text-muted-foreground/80 transition-transform",I&&"rotate-90"),"aria-hidden":"true"})]}),I&&v.jsx("ul",{role:"list",className:"flex flex-col",children:N.sessions.map(M=>v.jsx(eoe,{session:M,now:e,disabled:r!==null,loading:r===M.id,onClick:()=>T(M),modeTag:M.preferredMode},M.id))})]},$)})})]},X.provider)})}),v.jsx(ooe,{session:s,open:s!==null,modes:q,mode:l,permissionMode:d,submitting:r!==null,onOpenChange:X=>{X||o(null)},onModeChange:u,onPermissionModeChange:f,onConfirm:()=>{s&&R(s,l,d)}})]})}function zN(e,t){return`${e}:${V3(t)}`}function V3(e){const t=e.trim();return!t||t==="/"?t||"/":t.replace(/\/+$/,"")||"/"}function K3(){return["json","pty"]}function ioe(e){const t=K3();return e.preferredMode&&t.includes(e.preferredMode)?e.preferredMode:t[0]??"json"}function soe(e){return jh(e)==="codex"?"auto":"default"}function ooe({session:e,open:t,modes:n,mode:r,permissionMode:i,submitting:s,onOpenChange:o,onModeChange:l,onPermissionModeChange:u,onConfirm:d}){const[f,p]=_.useState(!1),y=i==="bypassPermissions",g=Cl("(min-width: 768px)"),b=e?jh(e)==="codex":!1;_.useEffect(()=>{t||p(!1)},[t]);const w=f?v.jsx(Y3,{providerLabel:e?_y(jh(e)):"Agent"}):v.jsxs("div",{className:"grid min-w-0 gap-4",children:[v.jsxs("div",{className:"grid min-w-0 gap-2",children:[v.jsx("span",{className:"text-sm font-medium",children:"模式"}),v.jsxs("div",{role:"radiogroup","aria-label":"恢复模式",className:"grid min-w-0 grid-cols-2 gap-2",children:[n.includes("json")&&v.jsx(jN,{checked:r==="json",label:"聊天",icon:v.jsx(p1,{className:"size-4","aria-hidden":"true"}),disabled:s,onClick:()=>l("json")}),n.includes("pty")&&v.jsx(jN,{checked:r==="pty",label:"终端",icon:v.jsx(g1,{className:"size-4","aria-hidden":"true"}),disabled:s,onClick:()=>l("pty")})]})]}),v.jsxs("div",{className:"grid min-w-0 gap-2",children:[v.jsx("span",{className:"text-sm font-medium",children:"权限模式"}),v.jsxs("div",{role:"radiogroup","aria-label":"权限模式",className:"grid min-w-0 gap-2",children:[!b&&v.jsx(kw,{checked:i==="default",label:"严格审批",description:"所有需要权限的操作都要确认。",disabled:s,onClick:()=>u("default")}),v.jsx(kw,{checked:i==="auto",label:b?"按需审批":"自动判定",description:b?"Codex 在需要时请求确认。":"交给 Agent CLI 的原生策略判断。",disabled:s,onClick:()=>u("auto")}),v.jsx(kw,{checked:i==="bypassPermissions",label:"跳过全部审批",description:"危险模式,会跳过工具审批和部分沙箱保护。",destructive:!0,disabled:s,onClick:()=>u("bypassPermissions")})]})]})]}),S=v.jsxs(v.Fragment,{children:[v.jsx(At,{type:"button",variant:"ghost",disabled:s,onClick:()=>{f?p(!1):o(!1)},children:f?"返回":"取消"}),v.jsx(At,{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?v.jsx(Bl,{open:t,onOpenChange:o,children:v.jsxs(zl,{focusSurfaceOnOpen:!0,className:"min-w-0 sm:max-w-md","data-slot":"history-restore-dialog",children:[v.jsxs(jl,{className:"min-w-0",children:[v.jsx(ba,{children:f?"跳过全部审批?":"恢复会话"}),v.jsx(El,{className:"min-w-0 truncate pr-10 sm:pr-0",title:e==null?void 0:e.title,children:(e==null?void 0:e.title)??""})]}),w,v.jsx(Mc,{children:S})]})}):v.jsx(vy,{open:t,onOpenChange:o,children:v.jsxs(yy,{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:[v.jsxs(gE,{className:"min-w-0 shrink-0 px-4 pb-2 pt-4 text-left",children:[v.jsx(by,{children:f?"跳过全部审批?":"恢复会话"}),v.jsx(qse,{className:"min-w-0 truncate pr-10",title:e==null?void 0:e.title,children:(e==null?void 0:e.title)??""})]}),v.jsx("div",{className:"min-h-0 overflow-y-auto px-4 pb-3","data-slot":"history-restore-body",children:w}),v.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:v.jsx("div",{className:"flex flex-col-reverse gap-2 [&_button]:min-h-11 [&_button]:w-full",children:S})})]})})}function jN({checked:e,label:t,icon:n,disabled:r,onClick:i}){return v.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,v.jsx("span",{className:"min-w-0 text-center",children:t}),v.jsx(pa,{className:Ye("size-3.5 justify-self-end transition-opacity",e?"opacity-100":"opacity-0"),"aria-hidden":"true"})]})}function kw({checked:e,label:t,description:n,destructive:r,disabled:i,onClick:s}){return v.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:[v.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&&v.jsx("span",{className:Ye("size-2 rounded-full",r?"bg-destructive":"bg-primary")})}),v.jsxs("span",{className:"grid min-w-0 gap-1",children:[v.jsx("span",{className:Ye("text-sm font-medium",r?"text-destructive":"text-foreground"),children:t}),v.jsx("span",{className:"min-w-0 break-words text-xs leading-5 text-muted-foreground",children:n})]}),e&&v.jsx(pa,{className:Ye("mt-0.5 size-4 shrink-0",r?"text-destructive":"text-primary"),"aria-hidden":"true"})]})}function aoe({...e}){return v.jsx(rse,{"data-slot":"select",...e})}function loe({...e}){return v.jsx(sse,{"data-slot":"select-value",...e})}function coe({className:e,size:t="default",children:n,...r}){return v.jsxs(ise,{"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,v.jsx(ose,{asChild:!0,children:v.jsx(Al,{className:"size-4 opacity-50"})})]})}function uoe({className:e,children:t,position:n="item-aligned",align:r="center",...i}){return v.jsx(ase,{children:v.jsxs(lse,{"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,...i,children:[v.jsx(foe,{}),v.jsx(cse,{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}),v.jsx(hoe,{})]})})}function doe({className:e,children:t,...n}){return v.jsxs(use,{"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:[v.jsx("span",{"data-slot":"select-item-indicator",className:"absolute right-2 flex size-3.5 items-center justify-center",children:v.jsx(fse,{children:v.jsx(pa,{className:"size-4"})})}),v.jsx(dse,{children:t})]})}function foe({className:e,...t}){return v.jsx(hse,{"data-slot":"select-scroll-up-button",className:Ye("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(f1,{className:"size-4"})})}function hoe({className:e,...t}){return v.jsx(pse,{"data-slot":"select-scroll-down-button",className:Ye("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Al,{className:"size-4"})})}function _E(e){return!e||e.endsWith("/")?e:`${e}/`}function poe(e){const t=e.split("@").pop()??"",n=t.lastIndexOf("/");return n>=0?t.slice(n+1).toLowerCase():t.toLowerCase()}function moe(e){const t=e.split("@").pop()??"",n=t.lastIndexOf("/");return n>=0?t.slice(0,n+1):""}function goe(e,t,n){var o;if(t==="insert")return{currentPath:moe(e)||"./",query:poe(e)};if(!e)return{currentPath:"./",query:""};const r=e.replace(/\/+$/,"")||"/";if(e.endsWith("/")||r===(n==null?void 0:n.baseCwd)||((o=n==null?void 0:n.knownDirs)==null?void 0:o.has(r)))return{currentPath:_E(r),query:""};const s=e.lastIndexOf("/");return{currentPath:s>=0?e.slice(0,s+1):"./",query:s>=0?e.slice(s+1).toLowerCase():e.toLowerCase()}}function voe(e,t){if(t.startsWith("/"))return t.replace(/\/+$/,"")||"/";if(!e)return"";const n=t.replace(/^\.\//,"").replace(/\/+$/,"");return n?`${e}/${n}`:e}function yoe(e,t){return`${_E(e)}${t.name}${t.isDir?"/":""}`}function $N(e,t){const n=e.trim().replace(/\/+$/,"")||"/",r=t.trim().replace(/^\/+|\/+$/g,"");return!n.startsWith("/")||!r||t.trim().startsWith("/")||r.split("/").some(i=>i===""||i==="."||i==="..")?null:n==="/"?`/${r}`:`${n}/${r}`}const G3=_.forwardRef(function({filter:t,onSelect:n,onCreateDirectory:r,mode:i="insert",placement:s="floating",dirsOnly:o=!1,title:l},u){const d=hi(B=>B.tree),f=hi(B=>B.cwd),p=hi(B=>B.homePath),y=i==="insert"?f:p||f,g=_.useMemo(()=>new Set(d.keys()),[d]),b=_.useMemo(()=>goe(t,i,{baseCwd:y,knownDirs:g}),[t,i,y,g]),w=b.currentPath,S=_.useMemo(()=>voe(y,w),[y,w]),E=b.query,k=_.useRef(new Set),[T,R]=_.useState(!1),[P,A]=_.useState(""),[H,D]=_.useState(!1);_.useEffect(()=>{if(!S||d.has(S)||k.current.has(S))return;const B=Ut;if(!B)return;let L=!1;return k.current.add(S),B.requestDirectoryList(S).then(Y=>{L||hi.getState().setDirEntries(Y.path,Y.entries)}).catch(()=>{L||hi.getState().setDirEntries(S,[])}).finally(()=>{k.current.delete(S)}),()=>{L=!0}},[S,d]);const K=!d.has(S),q=_.useMemo(()=>{let B=d.get(S)??[];return o&&(B=B.filter(L=>L.isDir)),E&&(B=B.filter(L=>L.name.toLowerCase().includes(E))),B},[d,S,E,o]),[X,z]=_.useState(0);_.useEffect(()=>z(0),[w,E]),_.useEffect(()=>{R(!1),A("")},[S]),_.useEffect(()=>{X>=q.length&&q.length>0&&z(q.length-1)},[q.length,X]);const N=_.useRef(null),$=_.useRef(!1);_.useEffect(()=>{var L;if(!$.current)return;$.current=!1;const B=(L=N.current)==null?void 0:L.querySelector(`[data-entry-index="${X}"]`);B==null||B.scrollIntoView({block:"nearest"})},[X]);const I=_.useCallback(B=>{const L=yoe(w,B);return i==="insert"?L.replace(/^\.\//,""):L},[w,i]);async function M(){const B=$N(S,P);if(!(!B||!r)){D(!0);try{const L=await r(B);if(!L)return;A(""),R(!1),n(_E(L))}finally{D(!1)}}}_.useImperativeHandle(u,()=>({handleKey(B){return q.length===0?!1:B.key==="ArrowDown"?($.current=!0,z(L=>Math.min(q.length-1,L+1)),!0):B.key==="ArrowUp"?($.current=!0,z(L=>Math.max(0,L-1)),!0):B.key==="Enter"&&!B.nativeEvent.isComposing?(n(I(q[X])),!0):!1}}),[q,X,I,n]);const O=s==="inline"?"relative w-full bg-popover border border-border rounded-md overflow-hidden":i==="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",U=s==="inline"?"h-44 overflow-y-auto overscroll-contain":i==="select"?"max-h-44 overflow-y-auto overscroll-contain":"max-h-60 overflow-y-auto overscroll-contain";return v.jsxs("div",{className:O,"data-slot":"file-path-picker","data-mode":i,"data-placement":s,children:[i==="select"&&l?v.jsxs("div",{className:"border-b border-border/70 px-3 py-2",children:[v.jsxs("div",{className:"flex items-center justify-between gap-3",children:[v.jsx("span",{className:"text-xs text-muted-foreground",children:l}),r?v.jsx("button",{type:"button",className:"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 disabled:cursor-not-allowed disabled:opacity-50",disabled:!S||H,onClick:()=>R(B=>!B),children:"新建目录"}):null]}),T?v.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[v.jsx("input",{type:"text",value:P,onChange:B=>A(B.target.value),onKeyDown:B=>{B.key==="Enter"&&!B.nativeEvent.isComposing&&(B.preventDefault(),M()),B.key==="Escape"&&(R(!1),A(""))},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}),v.jsx("button",{type:"button",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:!$N(S,P)||H,onClick:()=>void M(),children:H?"创建中...":"创建目录"})]}):null]}):null,v.jsx("div",{className:U,children:q.length===0?v.jsx("div",{className:"px-3 py-2 text-xs text-muted-foreground",children:K?"加载中...":"没有匹配的路径"}):v.jsx("ul",{ref:N,role:"list",className:"flex flex-col",children:q.map((B,L)=>v.jsx("li",{children:v.jsx("button",{type:"button",onClick:()=>n(I(B)),onMouseEnter:()=>z(L),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",L===X&&"bg-[color-mix(in_srgb,var(--primary)_15%,transparent)]",B.isDir&&"font-semibold"),"data-slot":"file-entry","data-entry-type":B.isDir?"dir":"file","data-entry-index":L,children:v.jsxs("span",{className:"font-mono text-[13px]",children:[B.name,B.isDir?"/":""]})})},B.name))})})]})}),FN="工作目录不存在或不可访问:",boe=[{value:"default",label:"严格审批"},{value:"auto",label:"自动判定"},{value:"acceptEdits",label:"自动接受编辑"},{value:"plan",label:"只读规划"},{value:"bypassPermissions",label:"跳过全部审批"}],X3=[{value:"auto",label:"按需审批"},{value:"bypassPermissions",label:"跳过全部审批"}],ha={claude:"Claude Code",codex:"Codex"};function _oe(e,t){return t!==zr.PATH_NOT_FOUND||!e.startsWith(FN)?null:e.slice(FN.length).trim()||null}function wv(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 woe(e,t){return t.title?t.disabled?`${ha[e]}:${t.title}`:`${ha[e]} 路径:${t.title}`:`${ha[e]}:${t.label}`}function Soe(e,t){return e!=="codex"||X3.some(n=>n.value===t)?t:"auto"}async function xoe({relay:e,agentCli:t,form:n,timeoutMs:r=N1}){var d,f;const i=n.cwd.trim();if(!i)return{type:"validation_error",message:"请输入工作目录"};if(!e)return{type:"relay_missing",message:"请先连接开发机"};if(wv(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?`${ha[n.provider]} 不可用:${p}`:`${ha[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.error||!p.sessionId){const w=_oe(p.error??"",p.errorCode);return w?{type:"missing_cwd",path:w,message:"找不到这个工作目录"}:{type:"create_error",message:`创建失败:${p.error??"未知错误"}`}}const y=p.mode??o,g=((f=p.name)==null?void 0:f.trim())||void 0;return{type:"success",session:{sessionId:p.sessionId,...p.kind!==void 0?{kind:p.kind}:{},name:g,...p.nameLocked!==void 0?{nameLocked:p.nameLocked}:{},state:"idle",mode:y,provider:p.provider??l,...p.ptyOwner!==void 0?{ptyOwner:p.ptyOwner}:{}},route:`/chat/${p.sessionId}?mode=${y}`}}catch(p){return{type:"exception",message:p instanceof Error?p.message:String(p)}}}async function Eoe({relay:e,timeoutMs:t=N1}){var n;if(!e)return{type:"relay_missing",message:"请先连接开发机"};try{const r=await e.createSession({kind:"terminal",mode:"pty"},t);return r.error||!r.sessionId?{type:"create_error",message:`创建终端失败:${r.error??"未知错误"}`}:{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",mode:"pty",provider:r.provider??"claude",...r.ptyOwner!==void 0?{ptyOwner:r.ptyOwner}:{}},route:`/chat/${r.sessionId}?mode=pty`}}catch(r){return{type:"exception",message:r instanceof Error?r.message:String(r)}}}function Coe({agentCli:e,provider:t,isDesktop:n,editingCliProvider:r,cliPathInput:i,savingCliPath:s,onProviderChange:o,onOpenCliPathEditor:l,onCliPathInputChange:u,onCancelCliPathEditor:d,onSaveCliPath:f}){const p=wv("claude",e),y=wv("codex",e),g=e==null?void 0:e[t];return v.jsxs("section",{"aria-label":"Agent CLI",className:"flex min-w-0 flex-col gap-2",children:[v.jsxs("div",{className:"flex items-center justify-between",children:[v.jsx("span",{className:"text-sm",children:"Agent CLI"}),v.jsx("span",{className:"text-xs text-muted-foreground",children:"选择要启动的 CLI"})]}),v.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-2 sm:grid-cols-2",children:[v.jsx(HN,{provider:"claude",selected:t==="claude",status:p,agentCliLoaded:!!e,onClick:()=>o("claude")}),v.jsx(HN,{provider:"codex",selected:t==="codex",status:y,agentCliLoaded:!!e,onClick:()=>o("codex")})]}),v.jsx("div",{className:"relative min-w-0 rounded-md border border-border bg-muted/20 px-3 py-2.5 md:p-3","data-slot":"agent-cli-path-card",children:r===t?v.jsx(koe,{provider:r,agentCli:e,cliPathInput:i,savingCliPath:s,onCliPathInputChange:u,onCancel:d,onSave:f}):v.jsx(Toe,{provider:t,selectedCli:g,isDesktop:n,onOpenCliPathEditor:l})})]})}function HN({provider:e,selected:t,status:n,agentCliLoaded:r,onClick:i}){return v.jsxs(pp,{children:[v.jsx(mp,{asChild:!0,children:v.jsxs("button",{type:"button","aria-pressed":t,"aria-label":ha[e],onClick:i,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",t?"border-primary/70 bg-primary/10":"border-border bg-muted/20"),children:[v.jsx("span",{className:"text-sm font-medium",children:ha[e]}),v.jsx("span",{className:Ye("text-xs text-muted-foreground",n.disabled&&r&&"text-destructive"),children:n.label})]})}),v.jsx(gp,{side:"top",className:"max-w-[min(520px,calc(100vw-2rem))]",children:v.jsx("span",{className:"break-all font-mono text-xs",children:woe(e,n)})})]})}function koe({provider:e,agentCli:t,cliPathInput:n,savingCliPath:r,onCliPathInputChange:i,onCancel:s,onSave:o}){return v.jsxs(v.Fragment,{children:[v.jsx("p",{className:"mb-1 text-xs text-muted-foreground",children:"CLI 路径"}),v.jsxs("div",{className:"flex min-w-0 flex-col gap-2 sm:flex-row sm:items-center",children:[v.jsxs("label",{className:"min-w-0 flex-1",children:[v.jsx("span",{className:"sr-only",children:"CLI 路径"}),v.jsx("input",{type:"text",list:`agent-cli-path-${e}`,value:n,onChange:l=>i(l.target.value),onKeyDown:l=>{l.key==="Enter"&&(l.preventDefault(),o()),l.key==="Escape"&&(l.preventDefault(),s())},placeholder:e==="claude"?"/path/to/claude":"/path/to/codex",className:"min-h-11 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 md:h-10 md:min-h-0 md:text-sm"}),v.jsx("datalist",{id:`agent-cli-path-${e}`,children:((t==null?void 0:t[e].suggestions)??[]).map(l=>v.jsx("option",{value:l},l))})]}),v.jsxs("div",{className:"flex shrink-0 justify-end gap-2",children:[v.jsx(At,{type:"button",variant:"ghost",className:"min-h-11 shrink-0 rounded px-2.5 text-xs font-medium text-muted-foreground hover:text-foreground md:h-8 md:min-h-0",onClick:s,disabled:r,children:"取消"}),v.jsx(At,{type:"button",className:"min-h-11 shrink-0 rounded px-2.5 text-xs font-medium md:h-8 md:min-h-0",onClick:o,disabled:r||!n.trim(),children:r?"保存中...":"保存路径"})]})]})]})}function Toe({provider:e,selectedCli:t,isDesktop:n,onOpenCliPathEditor:r}){return n?v.jsxs(v.Fragment,{children:[v.jsx("p",{className:"mb-1 text-xs text-muted-foreground",children:"CLI 路径"}),v.jsxs("div",{className:"flex min-w-0 flex-col gap-2 md:flex-row md:items-center",children:[v.jsx("p",{className:Ye("flex h-10 min-w-0 flex-1 items-center truncate font-mono text-sm",t!=null&&t.available?"text-foreground":"text-destructive"),title:(t==null?void 0:t.command)??(t==null?void 0:t.error),children:(t==null?void 0:t.command)??(t==null?void 0:t.error)??"等待检测结果"}),v.jsx(At,{type:"button",variant:"outline",className:"h-8 min-h-0 shrink-0 self-end rounded px-2.5 text-xs font-medium text-muted-foreground hover:text-foreground sm:self-auto",onClick:()=>r(e),children:"指定路径"})]})]}):v.jsxs(v.Fragment,{children:[v.jsx("p",{className:"pr-11 text-xs text-muted-foreground",children:"CLI 路径"}),v.jsx(At,{type:"button",variant:"ghost",size:"icon",className:"absolute right-1 top-1/2 size-11 -translate-y-1/2 rounded-full text-muted-foreground hover:bg-accent/70 hover:text-foreground","aria-label":"指定路径",onClick:()=>r(e),children:v.jsx(f7,{className:"size-4","aria-hidden":"true"})}),v.jsx("p",{className:Ye("mt-1 min-w-0 break-all pr-11 font-mono text-sm leading-5",t!=null&&t.available?"text-foreground":"text-destructive"),title:(t==null?void 0:t.command)??(t==null?void 0:t.error),children:(t==null?void 0:t.command)??(t==null?void 0:t.error)??"等待检测结果"})]})}function ih({open:e,onOpenChange:t}){const[n,r]=_.useState(""),[i,s]=_.useState(""),[o,l]=_.useState("claude"),[u,d]=_.useState("pty"),[f,p]=_.useState("default"),[y,g]=_.useState(!1),[b,w]=_.useState(!1),[S,E]=_.useState(null),[k,T]=_.useState(!1),[R,P]=_.useState(null),[A,H]=_.useState(""),[D,K]=_.useState(!1),q=_.useRef(null),X=_.useRef(e);X.current=e;const z=so(),N=hi(me=>me.homePath),$=hi(me=>me.agentCli),I=Cl("(min-width: 768px)");_.useEffect(()=>{e&&!i&&N&&s(N)},[e,N,i]),_.useEffect(()=>{if(!e||N&&$)return;const me=Ut==null?void 0:Ut.requestProxyInfo();me&&me.then(Ee=>{const Oe=hi.getState();Oe.setHomePath(Ee.homePath),Oe.setAgentCli(Ee.agentCli)}).catch(Ee=>{console.error("[create-session-dialog] requestProxyInfo failed",Ee)})},[e,N,$]),_.useEffect(()=>{if(!k)return;function me(Ee){var Se;const Oe=Ee.target;Oe instanceof Node&&((Se=q.current)!=null&&Se.contains(Oe))||window.setTimeout(()=>T(!1),0)}return document.addEventListener("pointerdown",me,!0),()=>document.removeEventListener("pointerdown",me,!0)},[k]);function M(){r(""),s(""),T(!1),l("claude"),d("pty"),p("default"),g(!1),E(null),P(null),H(""),K(!1)}function O(){if(f==="bypassPermissions"){g(!0);return}j()}async function U(){await j(),X.current&&g(!1)}const B=o==="codex"?X3:boe,L=wv(o,$),Y=b||D||L.disabled;function V(me){const Ee=Soe(me,f);Ee!==f&&p(Ee)}async function j(me){E(null),w(!0);try{const Ee=await xoe({relay:Ut,agentCli:$,form:{cwd:me??i,name:n,provider:o,permissionMode:f,mode:u}});if(Ee.type==="success"){if(Ft.getState().addSession(Ee.session),!X.current)return;t(!1),M(),z(Ee.route);return}if(Ee.type==="missing_cwd"&&E(Ee.path),nt.error(Ee.message),Ee.type==="validation_error"||Ee.type==="relay_missing")return}finally{w(!1)}}async function te(me){const Ee=Ut;if(!Ee)return nt.error("请先连接开发机"),null;try{const Oe=await Ee.createDirectory(me);return Oe.success?(s(Oe.path),E(null),nt.success("目录已创建"),Oe.path):(nt.error(`目录创建失败:${Oe.error??"未知错误"}`),null)}catch(Oe){return nt.error(Oe instanceof Error?Oe.message:String(Oe)),null}}function re(me){var Oe;const Ee=$==null?void 0:$[me];P(me),H((Ee==null?void 0:Ee.command)??((Oe=Ee==null?void 0:Ee.suggestions)==null?void 0:Oe[0])??"")}async function oe(){if(!R)return;const me=A.trim();if(!me){nt.error("请输入 Agent CLI 路径");return}const Ee=Ut;if(!Ee){nt.error("请先连接开发机");return}K(!0);try{const Oe=await Ee.updateAgentCliPath(R,me);if(Oe.error||!Oe.agentCli){nt.error(`路径保存失败:${Oe.error??"未知错误"}`);return}hi.getState().setAgentCli(Oe.agentCli),nt.success(`${ha[R]} 路径已保存`),P(null),H("")}catch(Oe){nt.error(Oe instanceof Error?Oe.message:String(Oe))}finally{K(!1)}}function ee(me){d(me),V(o)}function pe(me){var Oe;const Ee=me.relatedTarget;Ee instanceof Node&&((Oe=q.current)!=null&&Oe.contains(Ee))||window.setTimeout(()=>T(!1),0)}const ae=y?v.jsxs("div",{className:"grid min-w-0 gap-5","data-slot":"bypass-permission-confirmation",children:[v.jsx(Y3,{providerLabel:ha[o]}),v.jsxs(Mc,{children:[v.jsx(At,{type:"button",variant:"ghost",className:"min-h-11 md:min-h-0",onClick:()=>g(!1),disabled:b,children:"返回"}),v.jsx(At,{type:"button",variant:"destructive",className:"min-h-11 md:min-h-0",onClick:()=>void U(),disabled:b,"data-slot":"bypass-permission-confirm",children:b?"创建中...":"确认"})]})]}):v.jsxs("form",{className:"flex min-w-0 flex-col gap-4","data-slot":"create-session-form",autoComplete:"off",onSubmit:me=>{me.preventDefault(),O()},children:[v.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[v.jsx("span",{className:"text-sm",children:"名称(可选)"}),v.jsx("input",{type:"text",name:"dev-anywhere-session-name",autoComplete:"off",autoCorrect:"off",spellCheck:!1,value:n,onChange:me=>r(me.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:"自动生成"})]}),v.jsxs("div",{ref:q,className:"relative flex min-w-0 flex-col gap-2",onBlur:pe,children:[v.jsx("span",{id:"create-session-cwd-label",className:"text-sm",children:"工作目录"}),v.jsx("input",{id:"create-session-cwd",type:"text","aria-labelledby":"create-session-cwd-label",name:"dev-anywhere-session-cwd",autoComplete:"off",autoCorrect:"off",spellCheck:!1,value:i,onFocus:()=>T(!0),onChange:me=>{s(me.target.value),E(null)},placeholder:"输入绝对路径",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 md:h-9 md:min-h-0 md:text-sm"}),k?v.jsx(G3,{mode:"select",dirsOnly:!0,filter:i,title:"选择下一级目录",onCreateDirectory:te,onSelect:me=>{s(me),E(null),T(!0)}}):null]}),S?v.jsxs("section",{role:"status","aria-live":"polite",className:"rounded-md border border-primary/50 bg-primary/10 p-3",children:[v.jsx("p",{className:"text-sm font-medium",children:"工作目录不存在"}),v.jsx("p",{className:"mt-1 break-all font-mono text-xs text-muted-foreground",children:S})]}):null,v.jsxs("section",{"aria-label":"交互方式",className:"flex min-w-0 flex-col gap-2",children:[v.jsx("span",{className:"text-sm",children:"交互方式"}),v.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-2 sm:grid-cols-2",children:[v.jsxs("button",{type:"button","aria-pressed":u==="pty",onClick:()=>ee("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:[v.jsx("span",{className:"text-sm font-medium",children:"终端模式"}),v.jsx("span",{className:"text-xs text-muted-foreground",children:"像本地终端一样操作"})]}),v.jsxs("button",{type:"button","aria-pressed":u==="json",onClick:()=>ee("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:[v.jsx("span",{className:"text-sm font-medium",children:"聊天模式"}),v.jsx("span",{className:"text-xs text-muted-foreground",children:"气泡式对话,支持 Voice Pilot"})]})]})]}),v.jsx(Coe,{agentCli:$,provider:o,isDesktop:I,editingCliProvider:R,cliPathInput:A,savingCliPath:D,onProviderChange:me=>{l(me),V(me)},onOpenCliPathEditor:re,onCliPathInputChange:H,onCancelCliPathEditor:()=>{P(null),H("")},onSaveCliPath:()=>void oe()}),v.jsxs("label",{className:"flex min-w-0 flex-col gap-2",children:[v.jsx("span",{className:"text-sm",children:"权限模式"}),v.jsxs(aoe,{value:f,onValueChange:me=>p(me),children:[v.jsx(coe,{className:"w-full",children:v.jsx(loe,{})}),v.jsx(uoe,{children:B.map(me=>v.jsx(doe,{value:me.value,children:me.label},me.value))})]})]}),v.jsxs(Mc,{children:[v.jsx(At,{type:"button",variant:"ghost",className:"min-h-11 md:min-h-0",onClick:()=>t(!1),disabled:b,children:"取消"}),v.jsx(At,{type:"submit",className:"min-h-11 md:min-h-0",disabled:Y,children:b?"创建中...":"创建"})]})]});return I?v.jsx(Bl,{open:e,onOpenChange:t,children:v.jsxs(zl,{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:[v.jsx(jl,{children:v.jsx(ba,{children:y?"跳过全部审批?":"新建会话"})}),ae]})}):v.jsx(vy,{open:e,onOpenChange:t,children:v.jsxs(yy,{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:[v.jsx(gE,{className:"px-0 pb-1 pt-0 text-left",children:v.jsx(by,{children:y?"跳过全部审批?":"新建会话"})}),ae]})})}function sh({open:e,sessionId:t,initialName:n,onOpenChange:r,onRename:i}){const s=_.useMemo(()=>(n==null?void 0:n.trim())??"",[n]),[o,l]=_.useState(s),[u,d]=_.useState(null),[f,p]=_.useState(!1);_.useEffect(()=>{e&&(l(s),d(null),p(!1))},[s,e]);async function y(g){g.preventDefault();const b=o.trim();if(!b){d("会话标题不能为空");return}if(t){p(!0);try{await i(t,b),r(!1)}catch(w){d(w instanceof Error?w.message:String(w))}finally{p(!1)}}}return v.jsx(Bl,{open:e,onOpenChange:r,children:v.jsx(zl,{className:"sm:max-w-md","data-slot":"session-rename-dialog",children:v.jsxs("form",{className:"grid gap-4",onSubmit:g=>void y(g),children:[v.jsxs(jl,{children:[v.jsx(ba,{children:"重命名会话"}),v.jsx(El,{children:"自定义名称会显示在会话列表和顶部标题中。"})]}),v.jsxs("div",{className:"grid gap-2",children:[v.jsx("label",{htmlFor:"session-rename-title",className:"text-sm font-medium",children:"会话标题"}),v.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?v.jsx("p",{id:"session-rename-error",className:"text-sm text-destructive",children:u}):null]}),v.jsxs(Mc,{children:[v.jsx(At,{type:"button",variant:"outline",onClick:()=>r(!1),children:"取消"}),v.jsx(At,{type:"submit",disabled:f,children:"保存"})]})]})})})}function Roe(e){return(e==null?void 0:e.mode)==="pty"&&e.ptyOwner==="local-terminal"}function Aoe(e){return(e==null?void 0:e.kind)==="terminal"}function Moe(e){return Roe(e)?{title:"断开远程连接?",description:"这只会断开当前页面和本地终端的连接,本地终端里的 Claude Code/Codex 会继续运行。重新接入前,页面不能继续查看或输入这个会话。",confirmLabel:"断开远程连接",destructive:!1}:Aoe(e)?{title:"终止终端?",description:"这会停止当前终端进程,并清理这个终端会话的运行状态。终止后不能继续输入,也无法恢复正在执行的命令。",confirmLabel:"终止终端",destructive:!0}:{title:"终止会话?",description:"这会停止当前 Agent 进程,并清理这个会话的运行状态。终止后不能继续输入,也无法恢复正在执行的任务。",confirmLabel:"终止会话",destructive:!0}}function og({open:e,session:t,onOpenChange:n,onConfirm:r}){const i=Moe(t);function s(){t&&(r(t),n(!1))}return v.jsx(Bl,{open:e,onOpenChange:n,children:v.jsxs(zl,{"data-slot":"session-termination-dialog",children:[v.jsxs(jl,{children:[v.jsx(ba,{children:i.title}),v.jsx(El,{children:i.description})]}),v.jsxs(Mc,{children:[v.jsx(At,{type:"button",variant:"ghost",onClick:()=>n(!1),children:"取消"}),v.jsx(At,{type:"button",variant:i.destructive?"destructive":"default",onClick:s,"data-slot":"session-termination-confirm",children:i.confirmLabel})]})]})})}function Z3(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 Noe(e){if(e.session.state==="error")return"error";const t=Z3(e);return t==="disconnected"?e.session.state:t}function Q3({layout:e}){const t=Ft(te=>te.sessions),n=Ft(te=>te.sessionListLoaded),r=Ft(te=>te.agentStatusBySessionId),i=Ft(te=>te.ptyStateBySessionId),s=Ft(te=>te.renameSession),o=Qt(te=>te.bySessionId),l=N8("/chat/:id"),u=(l==null?void 0:l.params.id)??null,d=De(te=>!!te.selectedProxyId),f=De(te=>te.proxyListLoaded),p=De(te=>te.proxySwitchTarget),y=Ft(te=>te.loadingProxyName),g=p!==null||!f||d&&!n,b=(p==null?void 0:p.name)??y,w=b?`正在连接 ${b}...`:"连接中...",S=so(),[E,k]=_.useState(!1),[T,R]=_.useState(!1),[P,A]=_.useState(null),[H,D]=_.useState(null),{creatingTerminal:K,createTerminal:q}=J3(),[X,z]=_.useState(new Set),[N,$]=_.useState(()=>Date.now());_.useEffect(()=>{const te=setInterval(()=>$(Date.now()),6e4);return()=>clearInterval(te)},[]);function I(te,re){S(`/chat/${te}?mode=${re??"json"}`,{replace:!1})}function M(te){const re=te.sessionId,oe=Ut;if(!oe){nt.error("请先连接开发机");return}oe.sendControl({type:"session_terminate",sessionId:re}),Ft.getState().removeSession(re),Qt.getState().clearSession(re),re===u&&S("/sessions"),(te==null?void 0:te.mode)==="pty"&&te.ptyOwner==="local-terminal"?nt.info("已断开页面连接,本地终端仍在运行"):nt.info("正在终止会话",{duration:1500})}async function O(te,re){const oe=Ut;if(!oe)throw new Error("请先连接开发机");const ee=await oe.renameSession(te,re);if(!ee.success)throw new Error(ee.error??"重命名失败");s(te,ee.name??re),nt.success("已重命名会话")}function U(te){z(re=>{const oe=new Set(re);return oe.has(te)?oe.delete(te):oe.add(te),oe})}function B(te){var ee;const re=te.mode==="json"&&(((ee=o[te.sessionId])==null?void 0:ee.pendingApprovals.some(pe=>pe.status==="pending"))??!1),oe=Noe({session:te,agentStatus:r[te.sessionId],ptyState:i[te.sessionId],hasPendingApproval:re});return oe===te.state?te:{...te,state:oe}}const L=t.length>0;if(e==="sidebar"&&(g||!d))return v.jsxs(v.Fragment,{children:[v.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:"请先连接开发机"}),v.jsx(ih,{open:E,onOpenChange:k}),v.jsx(og,{open:H!==null,session:H,onOpenChange:te=>{te||D(null)},onConfirm:M}),v.jsx(sh,{open:P!==null,sessionId:(P==null?void 0:P.sessionId)??null,initialName:P==null?void 0:P.name,onOpenChange:te=>{te||A(null)},onRename:O})]});if(e==="page"&&g)return v.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:[v.jsx(fa,{className:"h-5 w-5 animate-spin","aria-hidden":!0}),v.jsx("p",{className:"max-w-[min(24rem,calc(100%-2rem))] truncate text-sm",children:w})]});if(e==="page"&&!d)return v.jsxs("div",{className:"flex flex-col h-full",children:[v.jsx("div",{className:"flex-1",children:v.jsx(wc,{variant:"no-proxy"})}),v.jsx(ih,{open:E,onOpenChange:k}),v.jsx(og,{open:H!==null,session:H,onOpenChange:te=>{te||D(null)},onConfirm:M}),v.jsx(sh,{open:P!==null,sessionId:(P==null?void 0:P.sessionId)??null,initialName:P==null?void 0:P.name,onOpenChange:te=>{te||A(null)},onRename:O})]});const Y=v.jsxs("h3",{className:"px-4 pt-3 pb-2 text-sm font-semibold text-foreground","data-slot":"active-section-header",children:["活跃会话",L?v.jsxs("span",{className:"ml-1 text-muted-foreground/70 font-normal",children:["· ",t.length]}):null]}),V=L?v.jsx("ul",{role:"list",className:"flex flex-col w-full min-w-0",children:Poe(t).map(te=>v.jsxs("li",{children:[v.jsxs("button",{type:"button",onClick:()=>U(te.provider),"aria-expanded":!X.has(te.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:[v.jsx("span",{className:"font-mono",children:Loe(te.provider)}),v.jsx("span",{className:"h-px flex-1 bg-border/70","aria-hidden":"true"}),v.jsx("span",{className:"tabular-nums",children:te.sessions.length}),v.jsx(gh,{className:Ye("size-3.5 shrink-0 text-muted-foreground/80 transition-transform",!X.has(te.provider)&&"rotate-90"),"aria-hidden":"true"})]}),X.has(te.provider)?null:v.jsx("ul",{role:"list",className:"flex flex-col",children:te.sessions.map(re=>v.jsx(Xse,{session:B(re),selected:re.sessionId===u,now:N,onClick:()=>I(re.sessionId,re.mode),onRename:()=>A(re),onTerminate:()=>D(re)},re.sessionId))})]},te.provider))}):v.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/70","data-slot":"active-empty",children:"暂无活跃会话"}),j=v.jsx(roe,{now:N});return e==="page"?v.jsxs("div",{className:"flex flex-col h-full",children:[v.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto overscroll-contain",children:[Y,V,j]}),v.jsx("div",{className:"px-4 pt-4 pb-[calc(env(safe-area-inset-bottom)+1rem)] border-t border-border",children:v.jsxs(At,{className:"min-h-11 w-full md:min-h-0","data-slot":"create-session-mobile-trigger",onClick:()=>R(!0),children:[v.jsx(ID,{"aria-hidden":"true"}),"新建"]})}),v.jsx(Doe,{open:T,creatingTerminal:K,onOpenChange:R,onCreateAgent:()=>{R(!1),k(!0)},onCreateTerminal:()=>void q(()=>R(!1))}),v.jsx(ih,{open:E,onOpenChange:k}),v.jsx(og,{open:H!==null,session:H,onOpenChange:te=>{te||D(null)},onConfirm:M}),v.jsx(sh,{open:P!==null,sessionId:(P==null?void 0:P.sessionId)??null,initialName:P==null?void 0:P.name,onOpenChange:te=>{te||A(null)},onRename:O})]}):v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"dev-sidebar-scroll h-full overflow-y-auto overscroll-contain",children:[Y,V,j]}),v.jsx(ih,{open:E,onOpenChange:k}),v.jsx(og,{open:H!==null,session:H,onOpenChange:te=>{te||D(null)},onConfirm:M}),v.jsx(sh,{open:P!==null,sessionId:(P==null?void 0:P.sessionId)??null,initialName:P==null?void 0:P.name,onOpenChange:te=>{te||A(null)},onRename:O})]})}function Poe(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])=>Ooe(n,r)).map(([n,r])=>({provider:n,sessions:r}))}function Loe(e){return e==="terminal"?"终端":_y(e)}function Ooe(e,t){return e===t?0:e==="terminal"?-1:t==="terminal"?1:W3(e,t)}function J3(){const e=so(),[t,n]=_.useState(!1);async function r(i){if(!t){n(!0);try{const s=await Eoe({relay:Ut});if(s.type!=="success"){nt.error(s.message);return}Ft.getState().addSession(s.session),i==null||i(),e(s.route)}finally{n(!1)}}}return{creatingTerminal:t,createTerminal:r}}function UN({compact:e=!1}){const[t,n]=_.useState(!1),[r,i]=_.useState(!1),s=_.useRef(!1),o=De(E=>!!E.selectedProxyId),l=De(E=>E.proxySwitchTarget!==null),u=o&&!l,{creatingTerminal:d,createTerminal:f}=J3();function p(){i(!0),window.setTimeout(()=>i(!1),2e3)}function y(){if(!u){p();return}s.current=!0,n(!0)}function g(){if(!u){p();return}s.current=!0,f()}function b(E){E.preventDefault(),p()}const w=v.jsxs(At,{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",!u&&"opacity-50 hover:bg-background"),"aria-label":"新建会话","aria-disabled":!u,onClick:u?void 0:b,children:[v.jsx(ID,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),!e&&v.jsx("span",{className:"truncate",children:"新建"})]}),S=u?v.jsxs(vE,{children:[v.jsx(yE,{asChild:!0,children:w}),v.jsxs(bE,{align:e?"end":"start",className:"w-52","data-slot":"create-session-type-menu",onCloseAutoFocus:E=>{s.current&&(s.current=!1,E.preventDefault())},children:[v.jsxs(ko,{className:"min-h-9 gap-2.5","data-slot":"create-agent-session-item",onSelect:y,children:[v.jsx(DD,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),"Agent 会话"]}),v.jsxs(ko,{className:"min-h-9 gap-2.5","data-slot":"create-terminal-session-item",disabled:d,onSelect:g,children:[v.jsx(Ah,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),d?"正在创建终端会话...":"终端会话"]})]})]}):w;return v.jsxs(v.Fragment,{children:[u?S:v.jsxs(pp,{open:u?void 0:r,onOpenChange:u?void 0:i,children:[v.jsx(mp,{asChild:!0,children:S}),v.jsx(gp,{side:"top",children:l?"正在切换开发机":"请先连接开发机"})]}),v.jsx(ih,{open:t,onOpenChange:n})]})}function Doe({open:e,creatingTerminal:t,onOpenChange:n,onCreateAgent:r,onCreateTerminal:i}){const s=_.useRef(!1);function o(l){s.current=!0,l()}return v.jsx(vy,{open:e,onOpenChange:n,children:v.jsxs(yy,{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:l=>{s.current&&(s.current=!1,l.preventDefault())},children:[v.jsx(gE,{className:"px-1 pb-1 pt-0 text-left",children:v.jsx(by,{children:"新建"})}),v.jsxs("div",{className:"grid gap-2 pb-1","data-slot":"create-session-type-options",children:[v.jsxs(At,{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:()=>o(r),children:[v.jsx(DD,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),"Agent 会话"]}),v.jsxs(At,{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:()=>o(i),children:[v.jsx(Ah,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),t?"正在创建终端会话...":"终端会话"]})]})]})})}const Ioe="0.6.3",Boe={version:Ioe},zoe={playback:"playback",capture:"play-and-record"};function joe(){return typeof navigator>"u"?null:navigator.audioSession??null}function $oe(){return{setMode:()=>{},release:()=>{}}}class Foe{constructor(t=joe){_t(this,"leases",new Map);_t(this,"session",null);_t(this,"baselineType",null);_t(this,"nextLeaseId",1);_t(this,"nextOrder",1);this.getAudioSession=t}acquire(t){const n=this.getAudioSession();if(!n)return $oe();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(zoe[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 wE=new Foe,ES=64,WN=-60,e5=32;function qN(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-WN)/-WN));return e<0?-r:r}function YN(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 Hoe(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 Uoe(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 t5{constructor(t,n=24e3,r={}){_t(this,"nextStartTime",0);_t(this,"activityEndToken",0);_t(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=Hoe(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*e5/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=Uoe(n.subarray(l,u));this.scheduleTimer(()=>{var g,b,w,S;(b=(g=this.options).onActivityLevel)==null||b.call(g,y),(S=(w=this.options).onPlaybackChunk)==null||S.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 Tw={provider:"aliyun-bailian",configured:!1,region:"cn",asrModel:"qwen3-asr-flash-realtime",ttsModel:"cosyvoice-v3-flash",ttsVoice:"longanyang",turnIdleSeconds:3},VN="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",Woe=800,KN=300,qoe=1600;function CS(e,t){return e.filter(n=>!n.model||n.model===t)}function GN({label:e,children:t,help:n}){return v.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:[v.jsx("span",{className:"block text-[13px] font-medium leading-none text-muted-foreground",children:e}),v.jsx("div",{className:"mt-2 min-w-0",children:t}),n?v.jsx("span",{className:"mt-2 block text-xs leading-relaxed text-muted-foreground",children:n}):null]})}function ag({label:e,value:t,options:n,onChange:r,placeholder:i="请选择",help:s}){const[o,l]=_.useState(!1),u=_.useId(),d=n.find(g=>g.value===t),f=(d==null?void 0:d.label)??(t||i),p=n.filter(g=>!g.disabled),y=!!n5(f).detail;return v.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:[v.jsx("div",{id:u,className:"text-[13px] font-medium leading-none text-muted-foreground",children:e}),v.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:[v.jsx(XN,{label:f,muted:!d&&!t}),v.jsx(Al,{className:`size-4 shrink-0 text-muted-foreground transition-transform ${o?"rotate-180":""}`,"aria-hidden":"true"})]}),o?v.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 b=g.value===t;return v.jsxs("button",{type:"button",role:"option","aria-label":g.label,"aria-selected":b,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:[v.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center text-primary",children:b?v.jsx(pa,{className:"size-4","aria-hidden":"true"}):null}),v.jsx(XN,{label:g.label})]},g.value)})}):null,s?v.jsx("div",{className:"mt-2 text-xs leading-relaxed text-muted-foreground",children:s}):null]})}function XN({label:e,muted:t=!1}){const n=n5(e);return v.jsxs("span",{className:"min-w-0 flex-1",children:[v.jsx("span",{className:`block truncate text-base leading-6 md:text-sm ${t?"text-muted-foreground":"text-foreground"}`,children:n.title}),n.detail?v.jsx("span",{className:"mt-0.5 block truncate text-xs leading-4 text-muted-foreground",children:n.detail}):null]})}function Yoe({scrollRef:e}={}){const[t,n]=_.useState(Tw),[r,i]=_.useState(String(Tw.turnIdleSeconds)),[s,o]=_.useState(()=>Gm()),[l,u]=_.useState(""),[d,f]=_.useState(!1),[p,y]=_.useState(!1),[g,b]=_.useState({kind:"idle"}),w=_.useRef(null),S=_.useRef(null),E=_.useRef(null),k=_.useRef(null),T=_.useRef(null),R=_.useRef(!1);_.useEffect(()=>{const ee=Ut;if(!ee){b({kind:"error",message:"请先连接 Relay 服务器"});return}let pe=!1;return b({kind:"loading"}),ee.requestVoiceConfig().then(ae=>{if(!pe){if(ae.error||!ae.config){b({kind:"error",message:ae.error??"读取语音设置失败"});return}n(ae.config),i(String(ae.config.turnIdleSeconds)),u(""),f(!1),y(!0),b({kind:"idle"})}}).catch(ae=>{pe||b({kind:"error",message:ae instanceof Error?ae.message:"读取语音设置失败"})}),()=>{pe=!0}},[]),_.useEffect(()=>{const ee=Ut;if(!ee||!p)return;let pe=!1;return ee.requestVoiceCapabilities({region:t.region}).then(ae=>{if(!pe){if(ae.error||!ae.capabilities){o(Gm());return}o(ae.capabilities)}}).catch(()=>{pe||o(Gm())}),()=>{pe=!0}},[t.region,p]),_.useEffect(()=>(R.current=!0,()=>{R.current=!1,j(),te()}),[]);const P=_.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]),A=g.kind==="saving"||g.kind==="loading"||g.kind==="testing"||g.kind==="playingTest",H=_.useMemo(()=>CS(s.ttsVoices,t.ttsModel),[s.ttsVoices,t.ttsModel]),K=H.some(ee=>ee.value===t.ttsVoice)?t.ttsVoice:"",q=H.length===0?"当前模型暂无可用音色":K?null:"请选择可用音色",X=_.useMemo(()=>Xoe(r),[r]),z=X?null:"请输入正整数秒数",N=q??z,$=A||!!N,I=_.useMemo(()=>[{value:"cn",label:"中国大陆"},{value:"intl",label:"国际"}],[]),M=_.useMemo(()=>JN(s.asrModels,t.asrModel),[s.asrModels,t.asrModel]),O=_.useMemo(()=>Zoe(s.ttsModels,s.ttsVoices,t.ttsModel),[s.ttsModels,s.ttsVoices,t.ttsModel]),U=_.useMemo(()=>JN(H,K),[H,K]);function B(){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:X??Tw.turnIdleSeconds}}async function L(){if(A)return;if(N){b({kind:"error",message:N});return}const ee=Ut;if(!ee){b({kind:"error",message:"请先连接 Relay 服务器"});return}const pe=B();te(),b({kind:"saving"});const ae=performance.now();try{const me=await ee.updateVoiceConfig(pe);if(!R.current)return;const Ee=performance.now()-ae;if(Ee<KN&&await Goe(KN-Ee),!R.current)return;if(!me.success||me.error||!me.config){b({kind:"error",message:me.error??"保存语音设置失败"});return}n(me.config),i(String(me.config.turnIdleSeconds)),u(""),f(!1),b({kind:"saved"}),T.current=setTimeout(()=>{T.current=null,b(Oe=>Oe.kind==="saved"?{kind:"idle"}:Oe)},qoe),ee.requestVoiceCapabilities({region:me.config.region}).then(Oe=>{R.current&&Oe.capabilities&&o(Oe.capabilities)}).catch(()=>{R.current&&o(Gm())})}catch(me){if(!R.current)return;b({kind:"error",message:me instanceof Error?me.message:"保存语音设置失败"})}}async function Y(){if(A)return;if(N){b({kind:"error",message:N});return}const ee=Ut;if(!ee){b({kind:"error",message:"请先连接 Relay 服务器"});return}let pe;try{pe=V()}catch(ae){b({kind:"error",message:QN(ae)});return}b({kind:"testing"});try{const[ae]=await Promise.all([ee.testVoiceConfig(B()),pe.ready]);if(!ae.success||ae.error){j(),b({kind:"error",message:ae.error??"语音配置测试失败"});return}const me=await re(ae,pe.context);b({kind:"playingTest",transcript:ae.transcript}),k.current=setTimeout(()=>{k.current=null,j(),b({kind:"testPassed",transcript:ae.transcript})},me)}catch(ae){j(),b({kind:"error",message:QN(ae)})}}function V(){j();const ee=wE.acquire("playback");S.current=ee;try{const pe=Koe();return w.current=pe,{context:pe,ready:ZN(pe)}}catch(pe){throw ee.release(),S.current=null,pe}}function j(){var ee,pe,ae;k.current&&(clearTimeout(k.current),k.current=null),(ee=E.current)==null||ee.stop(),E.current=null,(pe=w.current)==null||pe.close(),w.current=null,(ae=S.current)==null||ae.release(),S.current=null}function te(){T.current&&(clearTimeout(T.current),T.current=null)}async function re(ee,pe){if(!ee.audioBase64)throw new Error("语音测试未返回可播放音频");if(ee.audioEncoding&&ee.audioEncoding!=="pcm_s16le")throw new Error("测试音频格式暂不支持");const ae=ee.audioSampleRate??24e3,me=Voe(ee.audioBase64);if(me.byteLength===0||me.byteLength%2!==0)throw new Error("测试音频数据无效");await ZN(pe);const Ee=new t5(pe,ae);E.current=Ee,Ee.enqueue(me);const Oe=Math.ceil(me.byteLength/2/ae*1e3);return Math.max(Woe,Oe)}function oe(ee){var pe;return((pe=CS(s.ttsVoices,ee)[0])==null?void 0:pe.value)??""}return v.jsxs("form",{className:"flex min-h-0 min-w-0 flex-1 flex-col","data-slot":"voice-settings-panel",autoComplete:"off",onSubmit:ee=>{ee.preventDefault(),L()},children:[v.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:v.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:v.jsxs("div",{className:"space-y-3","data-slot":"voice-settings-fields",children:[v.jsx("div",{className:"grid gap-2 rounded-lg border border-border/75 bg-card/55 p-3.5 sm:p-3",children:v.jsxs("div",{className:"flex items-center justify-between gap-3",children:[v.jsxs("div",{className:"min-w-0",children:[v.jsx("div",{className:"text-[13px] font-medium leading-none text-muted-foreground",children:"服务商"}),v.jsx("div",{className:"mt-2 truncate text-base font-medium text-foreground md:text-sm",children:"阿里云百炼"})]}),v.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"})]})}),v.jsx(GN,{label:"阿里云百炼 API Key",help:d?"保存后会清空已保存的 key":null,children:v.jsxs("div",{className:"flex min-w-0 gap-2",children:[v.jsxs("div",{className:"relative min-w-0 flex-1",children:[v.jsx(jD,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":"true"}),v.jsx("input",{"aria-label":"阿里云百炼 API Key",type:"password",name:"dev-anywhere-bailian-api-key",autoComplete:"off",value:l,onChange:ee=>{u(ee.target.value),f(!1)},placeholder:d?"保存后清空":t.configured?"••••••••••••••••":"输入 API Key",className:`${VN} w-full pl-9`})]}),t.configured&&v.jsxs(At,{type:"button",variant:"outline",className:"min-h-11 shrink-0 px-3 md:h-9 md:min-h-0",onClick:()=>{u(""),f(!0)},children:[v.jsx(D7,{className:"size-4","aria-hidden":"true"}),"清空"]})]})}),v.jsx(ag,{label:"地域",value:t.region,options:I,onChange:ee=>n(pe=>({...pe,region:ee==="intl"?"intl":"cn"}))}),v.jsx(ag,{label:"语音识别模型",value:t.asrModel,options:M,onChange:ee=>n(pe=>({...pe,asrModel:ee}))}),v.jsx(ag,{label:"语音合成模型",value:t.ttsModel,options:O,onChange:ee=>n(pe=>({...pe,ttsModel:ee,ttsVoice:oe(ee)}))}),v.jsx(ag,{label:"语音音色",value:K,options:U,placeholder:H.length===0?"暂无可用音色":"请选择音色",onChange:ee=>n(pe=>({...pe,ttsVoice:ee})),help:q}),v.jsx(GN,{label:"结束停顿时间(秒)",help:z,children:v.jsx("input",{"aria-label":"结束停顿时间(秒)",type:"number",min:1,step:1,inputMode:"numeric",value:r,onChange:ee=>i(ee.target.value),className:`${VN} w-full`})})]})})}),v.jsxs("div",{className:"bg-background/95 px-4 pb-3.5 pt-0 backdrop-blur sm:px-5","data-slot":"voice-settings-footer",children:[v.jsx("div",{className:"mr-4 border-t border-border/70","data-slot":"voice-settings-footer-divider"}),v.jsxs("div",{className:"mt-3.5 flex items-center justify-end gap-2",children:[P?v.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,v.jsxs(At,{type:"button",variant:"outline",disabled:$,onClick:()=>void Y(),children:[v.jsx(HD,{className:"size-4","aria-hidden":"true"}),"测试"]}),v.jsxs(At,{type:"submit",disabled:$,children:[v.jsx(S7,{className:"size-4","aria-hidden":"true"}),g.kind==="saving"?"保存中...":"保存"]})]})]})]})}function Voe(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 Koe(){const e=window,t=e.AudioContext??e.webkitAudioContext;if(!t)throw new Error("当前浏览器不支持音频播放");return new t}async function ZN(e){if(e.state!=="running")try{await e.resume()}catch{throw new Error("浏览器阻止了测试音频播放,请再次点击测试")}if(e.state!=="running")throw new Error("浏览器阻止了测试音频播放,请再次点击测试")}function QN(e){return e instanceof Error?e.message:"语音配置测试失败"}function Goe(e){return new Promise(t=>setTimeout(t,e))}function Xoe(e){const t=e.trim();if(!/^[1-9]\d*$/.test(t))return null;const n=Number(t);return Number.isSafeInteger(n)?n:null}function JN(e,t){const n=e.map(r=>({value:r.value,label:r5(r)}));return!t||n.some(r=>r.value===t)?n:[{value:t,label:t},...n]}function Zoe(e,t,n){const r=e.map(i=>{const s=CS(t,i.value).length===0;return{value:i.value,label:`${r5(i)}${s?" · 暂无音色":""}`,disabled:s}});return!n||r.some(i=>i.value===n)?r:[{value:n,label:`${n} · 暂无音色`,disabled:!0},...r]}function n5(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 r5(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 Qoe=[{value:"auto",label:"跟随系统"},{value:"light",label:"浅色"},{value:"dark",label:"深色"}],Joe=[{value:"auto",label:"自动"},{value:"touch",label:"触控优先"},{value:"hardware",label:"实体键盘优先"}],SE="dev-render-scroll min-h-0 space-y-3 overflow-y-auto overscroll-contain pr-4 sm:pr-1";function i5(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 eae(e){const t=e||window.location.origin;return new URL("/health",t).toString()}function tae(e){return e==="version"?"版本":e==="relay-token"?"Relay Token":e==="clients"?"客户端管理":"设置 Voice Pilot"}function nae(e){return e==="version"?"Web 与 Relay 服务器版本。":e==="relay-token"?"连接受保护的 Relay 服务器,保存后立即重连。":e==="clients"?"管理当前连接的 Web 客户端。":"连接语音服务后,即可以语音交互的形式驱动会话。"}function kS({open:e,onOpenChange:t}){const n=De(K=>K.relayUrl),r=De(K=>K.latencyMonitorEnabled),i=De(K=>K.setLatencyMonitorEnabled),s=De(K=>K.sessionIdleNotificationsEnabled),o=De(K=>K.setSessionIdleNotificationsEnabled),l=De(K=>K.inputModePreference),u=De(K=>K.setInputModePreference),d=De(K=>K.themePreference),f=De(K=>K.setThemePreference),p=De(K=>K.ptyScrollTraceEnabled),y=De(K=>K.setPtyScrollTraceEnabled),[g,b]=_.useState("menu"),[w,S]=_.useState({kind:"idle"}),E=_.useRef(null),k=_.useRef(null),T=KJ(),R=_.useMemo(()=>ip().osName==="iPad",[]),P=_.useCallback(async K=>{if(!K){o(!1);return}const q=await EJ();if(q==="granted"){o(!0);return}if(q==="denied"){nt.error("浏览器未授予通知权限,请在浏览器设置中允许通知");return}if(q==="default"){nt.info("未授予通知权限,会话通知保持关闭");return}nt.error("当前浏览器不支持系统通知")},[o]),A=_.useCallback(async K=>{S({kind:"loading"});try{const q=await fetch(eae(n),{cache:"no-store",signal:K});if(!q.ok)throw new Error(`HTTP ${q.status}`);const X=await q.json();if(X.status!=="ok")throw new Error("状态异常");S({kind:"ready",version:X.version??"未知",uptime:X.uptime??0})}catch(q){if(q instanceof DOMException&&q.name==="AbortError")return;S({kind:"error",message:q instanceof Error?"当前 Relay 服务器无法读取版本":"读取失败"})}},[n]);_.useEffect(()=>{if(!e){b("menu");return}},[e]),_.useEffect(()=>{if(!e||g!=="version")return;const K=new AbortController;return A(K.signal),()=>K.abort()},[A,e,g]),_.useEffect(()=>{if(!e||g!=="voice")return;const K=window.requestAnimationFrame(()=>{var q;(q=E.current)==null||q.focus({preventScroll:!0}),k.current&&(k.current.scrollTop=0)});return()=>window.cancelAnimationFrame(K)},[e,g]);const H=w.kind==="ready"?w.version:w.kind==="loading"?"读取中...":w.kind==="error"?"读取失败":"未读取",D=w.kind==="ready"?`运行 ${i5(w.uptime)}`:w.kind==="error"?w.message:"从当前 Relay 服务器 /health 读取";return v.jsx(Bl,{open:e,onOpenChange:t,children:v.jsxs(zl,{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:E,showCloseButton:g==="menu",children:[v.jsx(jl,{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"?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex items-start gap-2",children:[v.jsx(At,{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:()=>b("menu"),children:v.jsx(Uv,{className:"size-4","aria-hidden":"true"})}),v.jsxs("div",{className:"min-w-0 space-y-1.5 pt-0.5 text-left",children:[v.jsx(ba,{children:tae(g)}),v.jsx(El,{className:"max-w-[28rem] leading-5",children:nae(g)})]})]}),g==="voice"?v.jsx("div",{className:"mr-4 mt-3.5 border-t border-border/70","data-slot":"voice-settings-header-divider"}):null]}):v.jsxs(v.Fragment,{children:[v.jsx(ba,{children:"设置"}),v.jsx(El,{children:"连接、外观、通知和高级诊断选项。"})]})}),g==="version"?v.jsx(rae,{relayVersion:H,relayDetail:D,relayMuted:w.kind==="error"}):g==="relay-token"?v.jsx(sae,{saved:T}):g==="clients"?v.jsx(uae,{}):g==="voice"?v.jsx(Yoe,{scrollRef:k}):v.jsx(iae,{relayTokenSaved:T,themePreference:d,onThemePreferenceChange:f,inputModePreference:l,onInputModePreferenceChange:u,showInputModeSetting:R,sessionIdleNotificationsEnabled:s,onSessionIdleNotificationsEnabledChange:P,ptyScrollTraceEnabled:p,onPtyScrollTraceEnabledChange:y,latencyMonitorEnabled:r,onLatencyMonitorEnabledChange:i,onOpenVoice:()=>b("voice"),onOpenRelayToken:()=>b("relay-token"),onOpenClients:()=>b("clients"),onOpenVersion:()=>b("version")})]})})}function rae({relayVersion:e,relayDetail:t,relayMuted:n}){return v.jsxs("div",{className:SE,"data-slot":"settings-dialog-body",children:[v.jsx(t2,{icon:v.jsx(FD,{className:"size-4","aria-hidden":"true"}),label:"Web",value:Boe.version,detail:"当前浏览器加载的版本"}),v.jsx(t2,{icon:v.jsx(UD,{className:"size-4","aria-hidden":"true"}),label:"Relay 服务器",value:e,detail:t,muted:n})]})}function iae({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:b,onOpenVersion:w}){return v.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:[v.jsxs(Au,{title:"服务",children:[v.jsx(lg,{icon:v.jsx(sW,{className:"size-4","aria-hidden":"true"}),label:"Voice Pilot",detail:"用语音输入、听取回复和处理审批",onClick:y}),v.jsx(lg,{icon:v.jsx(jD,{className:"size-4","aria-hidden":"true"}),label:"Relay Token",detail:`${e?"已保存":"未设置"} · 受保护的 Relay 服务器`,onClick:g}),v.jsx(lg,{icon:v.jsx(H7,{className:"size-4","aria-hidden":"true"}),label:"客户端管理",detail:"已连接的浏览器页面和设备",onClick:b})]}),v.jsx(Au,{title:"外观",children:v.jsx(e2,{icon:v.jsx(P7,{className:"size-4","aria-hidden":"true"}),label:"主题",value:t,options:Qoe,onValueChange:n})}),v.jsx(Au,{title:"通知",children:v.jsx(Aw,{icon:v.jsx(aW,{className:"size-4","aria-hidden":"true"}),label:"会话空闲通知",detail:"会话从工作中转为空闲时发送浏览器通知",checked:o,onCheckedChange:l})}),s?v.jsx(Au,{title:"交互",children:v.jsx(e2,{icon:v.jsx($D,{className:"size-4","aria-hidden":"true"}),label:"输入方式",detail:"默认自动识别软键盘和实体键盘;必要时可强制一种方式",value:r,options:Joe,onValueChange:i})}):null,v.jsxs(Au,{title:"高级诊断",children:[v.jsx(Aw,{icon:v.jsx(Ah,{className:"size-4","aria-hidden":"true"}),label:"PTY 滚动追踪",detail:"记录终端滚动和视口同步现场,方便复制诊断报告",checked:u,onCheckedChange:d}),v.jsx(Aw,{icon:v.jsx(LD,{className:"size-4","aria-hidden":"true"}),label:"延迟监控",detail:"显示可拖动的连接延迟浮窗",checked:f,onCheckedChange:p})]}),v.jsx(Au,{title:"关于",children:v.jsx(lg,{icon:v.jsx(UD,{className:"size-4","aria-hidden":"true"}),label:"版本",onClick:w})})]})}function Au({title:e,children:t}){return v.jsxs("section",{className:"space-y-2","data-slot":"settings-section",children:[v.jsx("h3",{className:"px-1 text-xs font-medium text-muted-foreground",children:e}),v.jsx("div",{className:"overflow-hidden rounded-lg border border-border bg-card/55 divide-y divide-border/70",children:t})]})}function e2({icon:e,label:t,detail:n,value:r,options:i,onValueChange:s}){const o=_.useId(),l=_.useId();return v.jsxs("div",{className:"flex w-full items-start gap-3 px-3 py-3 text-left","data-slot":"settings-choice-item",children:[v.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-md bg-background/55 text-muted-foreground",children:e}),v.jsxs("div",{className:"min-w-0 flex-1",children:[v.jsx("div",{id:o,className:"text-sm font-medium text-foreground",children:t}),n?v.jsx("div",{id:l,className:"mt-1 text-xs text-muted-foreground",children:n}):null,v.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 v.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 sae({saved:e}){const t=_.useId(),n=_.useId(),[r,i]=_.useState(""),[s,o]=_.useState(null),l=()=>{cB().catch(f=>{o(f instanceof Error?f.message:"Relay 重连失败。")})},u=()=>{const f=r.trim();if(!f){o("请输入 token。");return}if(!aB(f)){const p="Relay Token 保存失败,请检查浏览器存储权限。";o(p),nt.error(p);return}o(null),nt.success("Relay Token 已保存,正在重新连接"),l()},d=()=>{lB(),l()};return v.jsxs("form",{className:SE,"data-slot":"settings-dialog-body",onSubmit:f=>{f.preventDefault(),u()},children:[v.jsxs("div",{className:"rounded-md border border-border bg-card/70 p-3","data-slot":"relay-token-card",children:[v.jsx("label",{htmlFor:t,className:"text-sm font-medium text-foreground",children:"Token"}),v.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?v.jsx("p",{id:n,className:"mt-2 text-xs text-destructive",children:s}):null]}),v.jsxs("div",{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",children:[e?v.jsx(At,{type:"button",variant:"outline",onClick:d,children:"清空"}):null,v.jsx(At,{type:"submit",disabled:!r.trim(),children:"保存"})]})]})}function oae(e){return e.length<=16?e:`${e.slice(0,8)}...${e.slice(-4)}`}function aae(e,t){var r;return((r=t.get(e))==null?void 0:r.trim())||oae(e)}function lae(e){return VZ(e)}function cae(e){const t=Math.max(0,Math.floor((Date.now()-e)/1e3));return i5(t)}function Rw({label:e,value:t,title:n}){return v.jsxs("div",{className:"grid grid-cols-[3.75rem_minmax(0,1fr)] items-baseline gap-2 text-xs leading-5",children:[v.jsx("span",{className:"shrink-0 text-muted-foreground/80",children:e}),v.jsx("span",{className:"min-w-0 truncate text-muted-foreground",title:n??t,children:t})]})}function uae(){const e=De(y=>y.proxies),[t,n]=_.useState([]),[r,i]=_.useState(!0),[s,o]=_.useState(null),[l,u]=_.useState(null),d=_.useMemo(()=>new Map(e.map(y=>[y.proxyId,y.name]).filter(y=>typeof y[1]=="string")),[e]),f=_.useCallback(async()=>{const y=Ut;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)}},[]);_.useEffect(()=>{f()},[f]);const p=_.useCallback(async y=>{const g=Ut;if(!g){o("Relay 未连接。");return}u(y),o(null);try{const b=await g.kickRelayClient(y);if(!b.success){o(b.error??"断开客户端失败。");return}n(w=>w.filter(S=>S.clientId!==y))}catch(b){o(b instanceof Error?b.message:"断开客户端失败。")}finally{u(null)}},[]);return v.jsxs("div",{className:SE,"data-slot":"settings-dialog-body",children:[v.jsxs("div",{className:"flex min-h-9 items-center gap-2","data-slot":"relay-clients-toolbar",children:[v.jsx("div",{className:"text-sm font-medium text-foreground",children:r?"正在读取客户端":`${t.length} 个在线客户端`}),v.jsx(At,{type:"button",variant:"ghost",size:"icon-sm","aria-label":"刷新客户端列表",title:"刷新",onClick:()=>void f(),disabled:r,"data-slot":"relay-clients-refresh",children:v.jsx(m1,{className:Ye("size-3.5",r&&"animate-spin"),"aria-hidden":"true"})})]}),s?v.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?v.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,b=l===y.clientId;return v.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:v.jsxs("div",{className:"grid gap-3 sm:grid-cols-[minmax(0,1fr)_7.5rem] sm:items-start",children:[v.jsxs("div",{className:"min-w-0 space-y-1.5",children:[v.jsx("div",{className:"min-w-0",children:v.jsx("div",{className:"truncate text-sm font-medium leading-5 text-foreground",children:lae(y)})}),v.jsxs("div",{className:"space-y-1",children:[v.jsx(Rw,{label:"已连接",value:cae(y.connectedAt)}),y.proxyId?v.jsx(Rw,{label:"连接到",value:aae(y.proxyId,d),title:y.proxyId}):null,y.remoteAddress?v.jsx(Rw,{label:"来源 IP",value:y.remoteAddress}):null]})]}),g?v.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:"当前设备"}):v.jsxs(At,{type:"button",variant:"outline",size:"sm",className:"h-9 w-full justify-center",disabled:b,onClick:()=>void p(y.clientId),"data-slot":"relay-client-action",children:[v.jsx(QW,{className:"size-3.5","aria-hidden":"true"}),b?"断开中...":"断开"]})]})},y.clientId)})]})}function Aw({icon:e,label:t,detail:n,checked:r,onCheckedChange:i}){const s=_.useId(),o=_.useId();return v.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:[v.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}),v.jsxs("div",{className:"min-w-0 flex-1",children:[v.jsx("div",{id:s,className:"text-sm font-medium text-foreground",children:t}),v.jsx("div",{id:o,className:"mt-1 text-xs text-muted-foreground",children:n})]}),v.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:v.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 lg({icon:e,label:t,detail:n,onClick:r}){const i=_.useId(),s=_.useId();return v.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:[v.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}),v.jsxs("div",{className:"min-w-0 flex-1",children:[v.jsx("div",{id:i,className:"text-sm font-medium text-foreground",children:t}),n?v.jsx("div",{id:s,className:"mt-1 text-xs text-muted-foreground",children:n}):null]}),v.jsx(gh,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"})]})}function t2({icon:e,label:t,value:n,detail:r,muted:i=!1}){return v.jsxs("div",{className:"flex gap-3 rounded-md border border-border bg-card/70 p-3",children:[v.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}),v.jsxs("div",{className:"min-w-0 flex-1",children:[v.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[v.jsx("div",{className:"text-sm text-muted-foreground",children:t}),v.jsx("div",{className:"min-w-0 truncate font-mono text-sm text-foreground",children:n})]}),v.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:r})]})]})}const dae="xterm-helper-textarea";function fae(e=document.activeElement){return!(e instanceof HTMLElement)||!e.classList.contains(dae)?!1:(e.blur(),!0)}function n2(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&&hae(r,n))return!0;if(r===t)break;r=r.parentElement}return!1}function hae(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 pae({releasePtyFocus:e=!0,containVerticalScroll:t=!0}={}){const n=_.useRef(null),r=_.useCallback(()=>{e&&fae()},[e]),i=_.useCallback(l=>{var u;n.current=((u=l.touches[0])==null?void 0:u.clientY)??null,r()},[r]),s=_.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,n2(l.target,l.currentTarget,f)||l.preventDefault()},[t]),o=_.useCallback(l=>{r(),t&&(n2(l.target,l.currentTarget,l.deltaY)||l.preventDefault())},[t,r]);return{onPointerDownCapture:r,onTouchStartCapture:i,onTouchMoveCapture:s,onWheelCapture:o}}function mae({className:e}){const t=De(o=>o.sidebarCollapsed),n=De(o=>o.toggleSidebarCollapsed),[r,i]=_.useState(!1),s=pae();return t?v.jsxs(v.Fragment,{children:[v.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:[v.jsx(i2,{collapsed:!0,onClick:n}),v.jsx("div",{className:"mt-3 h-px w-5 bg-border/70","aria-hidden":"true"}),v.jsxs("div",{className:"mt-auto flex flex-col gap-2",children:[v.jsx(r2,{compact:!0,tooltipSide:"right",onClick:()=>i(!0)}),v.jsx(UN,{compact:!0})]})]}),v.jsx(kS,{open:r,onOpenChange:i})]}):v.jsxs(v.Fragment,{children:[v.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:[v.jsx("div",{className:"dev-sidebar-fade p-2.5","data-slot":"sidebar-proxy-switcher",children:v.jsxs("div",{className:"dev-sidebar-chrome rounded-lg border p-3",children:[v.jsxs("div",{className:"flex items-center justify-between gap-3",children:[v.jsx(lI,{className:"text-[13px]",slot:"sidebar-brand"}),v.jsx(i2,{collapsed:!1,onClick:n})]}),v.jsx("div",{className:"mt-2.5",children:v.jsx(U3,{layout:"dropdown",variant:"sidebarChrome"})})]})}),v.jsx("div",{className:"dev-sidebar-fade flex min-h-0 flex-1 flex-col overflow-hidden","data-slot":"sidebar-session-list",children:v.jsx("div",{className:"flex-1 min-h-0",children:v.jsx(Q3,{layout:"sidebar"})})}),v.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:[v.jsx("div",{className:"min-w-0 flex-1",children:v.jsx(UN,{})}),v.jsx("div",{className:"min-w-0 flex-1",children:v.jsx(r2,{onClick:()=>i(!0)})})]})]}),v.jsx(kS,{open:r,onOpenChange:i})]})}function r2({compact:e=!1,tooltipSide:t="top",onClick:n}){return v.jsxs(pp,{delayDuration:500,children:[v.jsx(mp,{asChild:!0,children:v.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:[v.jsx(WD,{className:"size-4","aria-hidden":"true"}),!e&&v.jsx("span",{className:"truncate text-sm font-medium",children:"设置"})]})}),v.jsx(gp,{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 i2({collapsed:e,onClick:t}){const n=e?"展开侧边栏":"收起侧边栏",r=e?l7:o7;return v.jsxs(pp,{delayDuration:500,children:[v.jsx(mp,{asChild:!0,children:v.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:v.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"})})}),v.jsx(gp,{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 gae=1500,vae=300,s2=70,o2=35;function s5({texts:e,className:t}){const[n,r]=_.useState(""),[i,s]=_.useState(!0),o=_.useRef("typing"),l=_.useRef(0),u=_.useRef(0);_.useEffect(()=>{const f=setInterval(()=>s(p=>!p),530);return()=>clearInterval(f)},[]),_.useEffect(()=>{let f;const p=()=>e[u.current%e.length],y=()=>{const g=o.current;if(g==="typing"){const b=p();l.current<b.length?(l.current+=1,r(b.slice(0,l.current)),f=setTimeout(y,s2)):(o.current="paused",f=setTimeout(y,gae))}else g==="paused"?(o.current="deleting",f=setTimeout(y,o2)):g==="deleting"?l.current>0?(l.current-=1,r(p().slice(0,l.current)),f=setTimeout(y,o2)):(u.current+=1,o.current="waiting",f=setTimeout(y,vae)):(o.current="typing",f=setTimeout(y,s2))};return f=setTimeout(y,500),()=>clearTimeout(f)},[e]);const d=n.startsWith("DEV")?3:n.length<=3&&"DEV".startsWith(n)?n.length:0;return v.jsxs("div",{className:`font-mono leading-tight select-none ${t??""}`,"data-slot":"brand-typewriter",children:[v.jsx("span",{className:"text-green-500",children:"> "}),v.jsx("span",{className:"text-primary","data-slot":"brand-typewriter-dev",children:n.slice(0,d)}),v.jsx("span",{className:"text-foreground/90",children:n.slice(d)}),v.jsx("span",{className:`text-primary ${i?"opacity-100":"opacity-0"}`,children:"_"})]})}const o5=["DEV Anywhere","/unlimited @anytime"];function yae({subtitle:e,action:t}){return v.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:v.jsxs("div",{className:"dev-mobile-brand-content min-w-0 space-y-3 pr-12",children:[v.jsx(s5,{texts:o5,className:"dev-mobile-brand-typewriter max-w-full overflow-hidden text-ellipsis whitespace-nowrap font-bold tracking-normal"}),v.jsx("p",{className:"dev-mobile-brand-subtitle max-w-[34rem] text-sm leading-5 text-muted-foreground",children:e}),t?v.jsx("div",{className:"dev-mobile-brand-action flex max-w-full min-w-0 pt-1",children:t}):null]})})}const bae=3e3,_ae=1e4,cg=12,wae=4,a2={webRelay:"浏览器 ↔ Relay 服务器",relayProxy:"Relay 服务器 ↔ 开发机",webProxy:"浏览器 ↔ 开发机"},Sae={webRelay:{state:"idle"},relayProxy:{state:"idle"},webProxy:{state:"idle"}};function Mw(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 Mu(e){return{state:"unavailable",error:e,updatedAt:Date.now()}}function oh(e){return e===void 0||!Number.isFinite(e)?"--":`${Math.max(0,Math.round(e))}ms`}function l2(e){switch(e){case"bad":return 4;case"unavailable":return 3;case"warn":return 2;case"measuring":return 1;default:return 0}}function a5(e){return e==="bad"||e==="unavailable"?"bad":e==="warn"?"warn":e==="ok"?"ok":"neutral"}function xae(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 Eae(e){return e.state==="measuring"?"检测中":e.state==="unavailable"?e.error??"不可用":e.rttMs!==void 0?oh(e.rttMs):"等待检测"}function Cae(){const e=Oi("local",Sn.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 c2(e){Er("local",Sn.latencyMonitorPosition,JSON.stringify(e))}function kae(){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 Nw(e,t){const n=kae(),r=cg,i=cg,s=Math.max(r,n.width-t.width-cg),o=Math.max(i,n.height-t.height-cg);return{x:Math.min(s,Math.max(r,Math.round(e.x))),y:Math.min(o,Math.max(i,Math.round(e.y)))}}function Tae(){const e=De(A=>A.latencyMonitorEnabled),t=De(A=>A.connected),n=De(A=>A.proxyOnline),r=De(A=>A.selectedProxyId),[i,s]=_.useState(Sae),[o,l]=_.useState(()=>Cae()),u=_.useRef(!1),d=_.useRef(null),f=_.useRef(null),p=_.useRef(!1),y=_.useMemo(()=>(Object.values(i).sort((A,H)=>l2(H.state)-l2(A.state))[0]??{state:"idle"}).state,[i]),g=a5(y);async function b(){if(u.current)return;const A=Ut;if(!A||!t){const q=Mu("Relay 服务器未连接");s({webRelay:q,relayProxy:q,webProxy:q});return}u.current=!0,s(q=>({webRelay:{...q.webRelay,state:"measuring"},relayProxy:n?{...q.relayProxy,state:"measuring"}:Mu("未连接开发机"),webProxy:n?{...q.webProxy,state:"measuring"}:Mu("未连接开发机")}));const[H,D,K]=await Promise.allSettled([A.measureWebRelayLatency(),n?A.measureRelayProxyLatency():Promise.resolve({success:!1}),n?A.measureWebProxyLatency():Promise.resolve({success:!1})]);s({webRelay:H.status==="fulfilled"?Mw(H.value):Mu(H.reason instanceof Error?H.reason.message:"测速失败"),relayProxy:D.status==="fulfilled"?Mw(D.value):Mu(D.reason instanceof Error?D.reason.message:"测速失败"),webProxy:K.status==="fulfilled"?Mw(K.value):Mu(K.reason instanceof Error?K.reason.message:"测速失败")}),u.current=!1}if(_.useEffect(()=>{if(!e)return;let A=!1,H=null;const D=async()=>{await b(),!A&&(H=setTimeout(D,document.hidden?_ae:bae))};return D(),()=>{A=!0,u.current=!1,H&&clearTimeout(H)}},[e,t,n,r]),_.useEffect(()=>{if(!e||!o)return;const A=d.current;if(!A)return;const H=A.getBoundingClientRect(),D=Nw(o,{width:H.width,height:H.height});D.x===o.x&&D.y===o.y||(l(D),c2(D))},[e,o]),!e)return null;const w=i.webProxy.rttMs!==void 0?i.webProxy:i.relayProxy,S=o!==null?{left:`${o.x}px`,top:`${o.y}px`}:void 0;function E(A){var D,K;if(A.button!==0)return;const H=A.currentTarget.getBoundingClientRect();f.current={pointerId:A.pointerId,startX:A.clientX,startY:A.clientY,originX:H.left,originY:H.top,width:H.width,height:H.height,dragging:!1},(K=(D=A.currentTarget).setPointerCapture)==null||K.call(D,A.pointerId)}function k(A){const H=f.current;if(!H||H.pointerId!==A.pointerId)return;const D=A.clientX-H.startX,K=A.clientY-H.startY;if(!H.dragging&&Math.hypot(D,K)<wae)return;H.dragging=!0,A.preventDefault();const q=Nw({x:H.originX+D,y:H.originY+K},{width:H.width,height:H.height});l(q)}function T(A){var X,z;const H=f.current;if(!H||H.pointerId!==A.pointerId||(f.current=null,(z=(X=A.currentTarget).releasePointerCapture)==null||z.call(X,A.pointerId),!H.dragging))return;A.preventDefault(),p.current=!0,window.setTimeout(()=>{p.current=!1},200);const D=A.clientX-H.startX,K=A.clientY-H.startY,q=Nw({x:H.originX+D,y:H.originY+K},{width:H.width,height:H.height});l(q),c2(q)}function R(A){var D,K;const H=f.current;!H||H.pointerId!==A.pointerId||(f.current=null,(K=(D=A.currentTarget).releasePointerCapture)==null||K.call(D,A.pointerId))}function P(A){p.current&&(p.current=!1,A.preventDefault(),A.stopPropagation())}return v.jsxs(hE,{children:[v.jsx(pE,{asChild:!0,children:v.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",xae(g)),style:S,"data-slot":"latency-monitor-trigger","aria-label":`延迟监控,Relay 服务器 ${oh(i.webRelay.rttMs)},开发机 ${oh(w.rttMs)}`,onPointerDown:E,onPointerMove:k,onPointerUp:T,onPointerCancel:R,onClickCapture:P,children:[v.jsx(LD,{className:"size-3.5","aria-hidden":"true"}),v.jsx("span",{className:"font-medium text-foreground",children:"延迟"}),v.jsxs("span",{className:"hidden text-muted-foreground sm:inline",children:["Relay ",oh(i.webRelay.rttMs)]}),v.jsxs("span",{className:"text-muted-foreground",children:["开发机 ",oh(w.rttMs)]}),v.jsx(Al,{className:"size-3 text-muted-foreground","aria-hidden":"true"})]})}),v.jsxs(mE,{align:"end",className:"w-[320px] p-3","data-slot":"latency-monitor-popover",children:[v.jsxs("div",{className:"flex items-start justify-between gap-3",children:[v.jsxs("div",{children:[v.jsx("div",{className:"text-sm font-medium text-foreground",children:"连接延迟"}),v.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:"数值越低,操作响应通常越快。"})]}),v.jsx(At,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"立即测速",onClick:()=>void b(),children:v.jsx(m1,{className:"size-3","aria-hidden":"true"})})]}),v.jsx("div",{className:"mt-3 space-y-2",children:Object.keys(a2).map(A=>v.jsx(Rae,{label:a2[A],measurement:i[A]},A))})]})]})}function Rae({label:e,measurement:t}){const n=a5(t.state);return v.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:[v.jsx("div",{className:"min-w-0 truncate text-xs font-medium text-foreground",children:e}),v.jsxs("div",{className:"flex items-center gap-2",children:[v.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"}),v.jsx("span",{className:"min-w-[4rem] text-right font-mono text-xs text-foreground",children:Eae(t)})]})]})}const l5="/__dev_anywhere_debug/browser-state-dumps",Aae=1500,Mae=10,Pw=80,xE=500,Nae=["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"],Pae=["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 u2(){if(typeof window>"u")return"off";const e=g5("debugDump");return e==="auto"?"auto":e!==null||Fae("debugInput")?"manual":"off"}function Lae(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:Bae(),document:{title:document.title,readyState:document.readyState,visibilityState:document.visibilityState,activeElement:d2(document.activeElement),selection:zae(),focusedInputs:Array.from(document.querySelectorAll("input, textarea, select, [contenteditable]")).filter(i=>i===document.activeElement||i.matches(":focus")).map(i=>d2(i)).filter(i=>!!i),root:c5(document.documentElement,0,t),truncated:t.truncated,nodeCount:t.count},devAnywhere:{ptyDebug:Nu(()=>{var i;return((i=n.__devAnywherePtyDebug)==null?void 0:i.call(n))??null}),ptyInputDebugSnapshot:Nu(()=>n.__devAnywherePtyInputDebugSnapshot??null),ptyInputDebugText:n.__devAnywherePtyInputDebugText??null,ptyInputDebugEvents:Nu(()=>n.__devAnywherePtyInputDebugEvents??null),ptyScrollTraceTail:Nu(()=>f2(n.__devAnywherePtyScrollTrace)),jsonScrollTraceTail:Nu(()=>f2(n.__devAnywhereJsonScrollTrace)),voicePilotDiagnostics:Nu(()=>{var i;return((i=n.__devAnywhereVoicePilotDiagnostics)==null?void 0:i.snapshot())??null})}};return window.__devAnywhereLastBrowserStateDump=r,r}async function Oae(e="manual"){const t=Lae(e);return Dae(t)}async function Dae(e){const t=JSON.stringify(e,null,2),n=new Blob([t]).size;try{const r=await Iae(t);return{status:"saved",path:r.path,bytes:r.bytes,endpoint:l5}}catch(r){const i=v5(r),s=jae(e.createdAt);return $ae(s,t,"application/json")?{status:"downloaded",filename:s,bytes:n,endpointError:i}:{status:"failed",error:"无法保存或下载诊断包",endpointError:i}}}async function Iae(e){const t=await fetch(l5,{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 c5(e,t,n){if(n.count>=Aae||t>Mae)return n.truncated=!0,{kind:"truncated"};if(n.count+=1,e.nodeType===Node.TEXT_NODE){const u=h2(e.textContent??"");return u?{kind:"text",text:wy(u,xE)}:{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,Pw))u.nodeType===Node.TEXT_NODE&&!h2(u.textContent??"")||r.push(c5(u,t+1,n));s.length>Pw&&(i=s.length-Pw,n.truncated=!0);const o={kind:"element",tag:e.tagName.toLowerCase(),path:m5(e),attrs:u5(e),rect:d5(e),scroll:f5(e),style:h5(e)},l=p5(e);return l&&(o.value=l),r.length>0&&(o.children=r),i>0&&(o.omittedChildren=i),o}function d2(e){if(!(e instanceof HTMLElement))return null;const t=p5(e);return{path:m5(e),tag:e.tagName.toLowerCase(),id:e.id||null,className:e.className||null,attrs:u5(e),rect:d5(e),scroll:f5(e),style:h5(e),...t?{value:t}:{}}}function Bae(){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 u5(e){const t={};for(const n of Nae){const r=e.getAttribute(n);r!==null&&(t[n]=wy(r,500))}return t}function d5(e){const t=e.getBoundingClientRect();return{x:ns(t.x),y:ns(t.y),width:ns(t.width),height:ns(t.height),top:ns(t.top),right:ns(t.right),bottom:ns(t.bottom),left:ns(t.left)}}function f5(e){return{top:ns(e.scrollTop),left:ns(e.scrollLeft),height:ns(e.scrollHeight),width:ns(e.scrollWidth),clientHeight:ns(e.clientHeight),clientWidth:ns(e.clientWidth)}}function h5(e){const t=window.getComputedStyle(e),n={};for(const r of Pae)n[r]=t.getPropertyValue(r);return n}function p5(e){if(!(!(e instanceof HTMLInputElement)&&!(e instanceof HTMLTextAreaElement)))return{length:e.value.length,preview:wy(e.value,xE),selectionStart:e.selectionStart,selectionEnd:e.selectionEnd}}function zae(){var e;try{return wy(((e=window.getSelection())==null?void 0:e.toString())??"",xE)}catch{return null}}function m5(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 jae(e){return`dev-anywhere-browser-state-${e.replace(/[:.]/g,"-")}.json`}function $ae(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 Fae(e){return g5(e)!==null}function g5(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 f2(e){return e?Sv(e.slice(-200)):null}function Nu(e){try{return Sv(e())}catch(t){return{error:v5(t)}}}function Sv(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(Sv);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=Sv(r);return t}return String(e)}function h2(e){return e.replace(/\s+/g," ").trim()}function wy(e,t){return e.length>t?`${e.slice(0,t)}...`:e}function ns(e){return Math.round(e*100)/100}function v5(e){return e instanceof Error?e.message:String(e)}const Hae=500,Uae=1e3,Wae=60;function qae(){const[e,t]=_.useState(()=>u2()),[n,r]=_.useState(!1),[i,s]=_.useState(null),o=_.useRef(null),l=_.useRef(!1),u=_.useRef(0),d=_.useRef(0),f=_.useRef(null);_.useEffect(()=>{const b=()=>t(u2());return window.addEventListener("hashchange",b),window.addEventListener("popstate",b),()=>{window.removeEventListener("hashchange",b),window.removeEventListener("popstate",b)}},[]);const p=_.useCallback(async(b="manual")=>{if(l.current)return o.current??{status:"failed",error:"dump already running"};l.current=!0,r(!0);try{const w=await Oae(b);return o.current=w,s(w),(b==="manual"||w.status==="failed")&&Yae(w),w}finally{l.current=!1,r(!1)}},[]);if(_.useEffect(()=>(window.__devAnywhereDumpBrowserState=p,()=>{window.__devAnywhereDumpBrowserState===p&&delete window.__devAnywhereDumpBrowserState}),[p]),_.useEffect(()=>{var k,T;if(e!=="auto")return;const b=()=>{f.current!==null&&(window.clearTimeout(f.current),f.current=null)},w=R=>{d.current>=Wae||(b(),f.current=window.setTimeout(()=>{f.current=null;const P=Date.now(),A=Uae-(P-u.current);if(A>0){f.current=window.setTimeout(()=>w(R),A);return}u.current=Date.now(),d.current+=1,p(`auto:${d.current}:${R}`)},Hae))};w("initial");const S=["focusin","focusout","beforeinput","input","compositionstart","compositionupdate","compositionend","keydown","keyup","pointerdown","pointerup","resize","visibilitychange"],E=R=>w(R.type);return S.forEach(R=>window.addEventListener(R,E,!0)),(k=window.visualViewport)==null||k.addEventListener("resize",E),(T=window.visualViewport)==null||T.addEventListener("scroll",E),()=>{var R,P;b(),S.forEach(A=>window.removeEventListener(A,E,!0)),(R=window.visualViewport)==null||R.removeEventListener("resize",E),(P=window.visualViewport)==null||P.removeEventListener("scroll",E)}},[p,e]),e==="off")return null;const y=e==="auto"?"自动诊断中":"保存诊断",g=Vae(i);return v.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?v.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,v.jsxs(At,{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?v.jsx(fa,{className:"size-3.5 animate-spin","aria-hidden":"true"}):v.jsx(zW,{className:"size-3.5","aria-hidden":"true"}),v.jsx("span",{children:y})]})]})}function Yae(e){if(e.status==="saved"){nt.success(`诊断已保存: ${e.path}`);return}if(e.status==="downloaded"){nt.info(`诊断已下载: ${e.filename}`);return}nt.error(e.endpointError?`${e.error}: ${e.endpointError}`:e.error)}function Vae(e){return e?e.status==="saved"?`已保存 ${e.path}`:e.status==="downloaded"?`已下载 ${e.filename}`:`失败 ${e.endpointError??e.error}`:null}function Kae(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 EE(e){const{windowKey:t,storageKey:n,maxEntries:r=5e3,dedupeKey:i}=e,s=new Map,o=()=>typeof window>"u"?!1:Kae(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 Bn(e){return Math.round(e*10)/10}function al(e){return e.length===0?"":`${Bn(Math.min(...e))}..${Bn(Math.max(...e))}`}function Ju(e){return[...new Set(e.filter(t=>t!==void 0).map(Bn))]}function y5(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 Gae="dev_anywhere_pty_input_latency_trace",p2=80,Xae=1e4,Zae=new TextDecoder;let Qae=0;const yd=new Map,Wc=EE({windowKey:"__devAnywherePtyInputLatencyTrace",storageKey:Gae,dedupeKey:e=>e.event.startsWith("input")?null:`${e.event}|${e.sessionId}|${e.outputSeq??""}|${e.pendingInputs??""}`});function Jae(){typeof window>"u"||(window.__devAnywherePtyInputLatencyReport=rle)}function ele(e,t){if(!Wc.isEnabled())return null;const n=`pty-in-${Date.now().toString(36)}-${++Qae}`,r=performance.now(),i={inputId:n,sessionId:e,data:t,kind:ole(t),dataLength:t.length,startedAt:r,sentAt:null,firstOutputAt:null,echoMatchedAt:null,xtermWriteAt:null,paintAt:null},s=yd.get(e)??[];return s.push(i),kE(s,r),yd.set(e,s),vp({t:r,event:"input:start",sessionId:e,inputId:n,inputKind:i.kind,dataLength:i.dataLength,pendingInputs:s.length}),{inputId:n,sessionId:e}}function m2(e,t){if(!e||!Wc.isEnabled())return;const n=performance.now(),r=ile(e.sessionId,e.inputId);r&&(r.sentAt=n),vp({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 tle(e,t,n){if(!Wc.isEnabled())return;const r=performance.now(),i=CE(e,r),s=cle(t),o=[],l=[];for(const u of i)u.firstOutputAt===null&&(u.firstOutputAt=r,o.push(u.inputId)),u.echoMatchedAt===null&&lle(u)&&s.includes(u.data)&&(u.echoMatchedAt=r,l.push(u.inputId));vp({t:r,event:"output:received",sessionId:e,outputSeq:n,bytes:t.byteLength,pendingInputs:i.length,deltaFromInputMs:TE(i,r),details:ule([o.length>0?`first=${o.length}`:"",l.length>0?`echo=${l.length}`:""])})}function nle(e,t,n=1){if(!Wc.isEnabled())return;const r=performance.now(),i=CE(e,r),s=[];for(const o of i)o.xtermWriteAt===null&&(o.xtermWriteAt=r,s.push(o.inputId));vp({t:r,event:"output:xterm-write",sessionId:e,bytes:t,chunkCount:n,pendingInputs:i.length,deltaFromInputMs:TE(i,r),details:s.length>0?`firstWrite=${s.length}`:""}),typeof requestAnimationFrame=="function"&&s.length>0&&requestAnimationFrame(()=>sle(e,s))}function rle(){const e=Wc.getAll(),t=e.slice(-200),n=[...yd.values()].flat(),r=n.slice(-80).map(s=>[s.inputId,s.sessionId,s.kind,s.dataLength,s.sentAt===null?"":Bn(s.sentAt-s.startedAt),s.firstOutputAt===null?"":Bn(s.firstOutputAt-s.startedAt),s.echoMatchedAt===null?"":Bn(s.echoMatchedAt-s.startedAt),s.xtermWriteAt===null?"":Bn(s.xtermWriteAt-s.startedAt),s.paintAt===null?"":Bn(s.paintAt-s.startedAt)].join(" ")),i=t.map(s=>[Bn(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?"":Bn(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(`
|
|
534
|
+
For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return _.useEffect(()=>{e&&(document.getElementById(e)||console.error(n))},[n,e]),null},Tte="DialogDescriptionWarning",Rte=({contentRef:e,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${FB(Tte).contentName}}.`;return _.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},W1=TB,Ate=AB,q1=NB,Y1=PB,V1=LB,HB=DB,UB=BB,ey=jB;function Mte(e){const t=_.useRef({value:e,previous:e});return _.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}function Nte(e){const[t,n]=_.useState(void 0);return Di(()=>{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 Pte=["top","right","bottom","left"],Sl=Math.min,vs=Math.max,pv=Math.round,ig=Math.floor,Mo=e=>({x:e,y:e}),Lte={left:"right",right:"left",bottom:"top",top:"bottom"};function cS(e,t,n){return vs(e,Sl(t,n))}function va(e,t){return typeof e=="function"?e(t):e}function ya(e){return e.split("-")[0]}function Rd(e){return e.split("-")[1]}function K1(e){return e==="x"?"y":"x"}function G1(e){return e==="y"?"height":"width"}function Ro(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function X1(e){return K1(Ro(e))}function Ote(e,t,n){n===void 0&&(n=!1);const r=Rd(e),i=X1(e),s=G1(i);let o=i==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[s]>t.floating[s]&&(o=mv(o)),[o,mv(o)]}function Dte(e){const t=mv(e);return[uS(e),t,uS(t)]}function uS(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const _N=["left","right"],wN=["right","left"],Ite=["top","bottom"],Bte=["bottom","top"];function zte(e,t,n){switch(e){case"top":case"bottom":return n?t?wN:_N:t?_N:wN;case"left":case"right":return t?Ite:Bte;default:return[]}}function jte(e,t,n,r){const i=Rd(e);let s=zte(ya(e),n==="start",r);return i&&(s=s.map(o=>o+"-"+i),t&&(s=s.concat(s.map(uS)))),s}function mv(e){const t=ya(e);return Lte[t]+e.slice(t.length)}function $te(e){return{top:0,right:0,bottom:0,left:0,...e}}function WB(e){return typeof e!="number"?$te(e):{top:e,right:e,bottom:e,left:e}}function gv(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 SN(e,t,n){let{reference:r,floating:i}=e;const s=Ro(t),o=X1(t),l=G1(o),u=ya(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(Rd(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 Fte(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}=va(t,e),b=WB(g),S=l[y?p==="floating"?"reference":"floating":p],E=gv(await s.getClippingRect({element:(n=await(s.isElement==null?void 0:s.isElement(S)))==null||n?S:S.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)),R=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=gv(s.convertOffsetParentRelativeRectToViewportRelativeRect?await s.convertOffsetParentRelativeRectToViewportRelativeRect({elements:l,rect:k,offsetParent:T,strategy:u}):k);return{top:(E.top-P.top+b.top)/R.y,bottom:(P.bottom-E.bottom+b.bottom)/R.y,left:(E.left-P.left+b.left)/R.x,right:(P.right-E.right+b.right)/R.x}}const Hte=50,Ute=async(e,t,n)=>{const{placement:r="bottom",strategy:i="absolute",middleware:s=[],platform:o}=n,l=o.detectOverflow?o:{...o,detectOverflow:Fte},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}=SN(d,r,u),y=r,g=0;const b={};for(let w=0;w<s.length;w++){const S=s[w];if(!S)continue;const{name:E,fn:k}=S,{x:T,y:R,data:P,reset:A}=await k({x:f,y:p,initialPlacement:r,placement:y,strategy:i,middlewareData:b,rects:d,platform:l,elements:{reference:e,floating:t}});f=T??f,p=R??p,b[E]={...b[E],...P},A&&g<Hte&&(g++,typeof A=="object"&&(A.placement&&(y=A.placement),A.rects&&(d=A.rects===!0?await o.getElementRects({reference:e,floating:t,strategy:i}):A.rects),{x:f,y:p}=SN(d,y,u)),w=-1)}return{x:f,y:p,placement:y,strategy:i,middlewareData:b}},Wte=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}=va(e,t)||{};if(d==null)return{};const p=WB(f),y={x:n,y:r},g=X1(i),b=G1(g),w=await o.getDimensions(d),S=g==="y",E=S?"top":"left",k=S?"bottom":"right",T=S?"clientHeight":"clientWidth",R=s.reference[b]+s.reference[g]-y[g]-s.floating[b],P=y[g]-s.reference[g],A=await(o.getOffsetParent==null?void 0:o.getOffsetParent(d));let H=A?A[T]:0;(!H||!await(o.isElement==null?void 0:o.isElement(A)))&&(H=l.floating[T]||s.floating[b]);const D=R/2-P/2,K=H/2-w[b]/2-1,q=Sl(p[E],K),X=Sl(p[k],K),z=q,N=H-w[b]-X,$=H/2-w[b]/2+D,I=cS(z,$,N),M=!u.arrow&&Rd(i)!=null&&$!==I&&s.reference[b]/2-($<z?q:X)-w[b]/2<0,O=M?$<z?$-z:$-N:0;return{[g]:y[g]+O,data:{[g]:I,centerOffset:$-I-O,...M&&{alignmentOffset:O}},reset:M}}}),qte=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:b="none",flipAlignment:w=!0,...S}=va(e,t);if((n=s.arrow)!=null&&n.alignmentOffset)return{};const E=ya(i),k=Ro(l),T=ya(l)===l,R=await(u.isRTL==null?void 0:u.isRTL(d.floating)),P=y||(T||!w?[mv(l)]:Dte(l)),A=b!=="none";!y&&A&&P.push(...jte(l,w,b,R));const H=[l,...P],D=await u.detectOverflow(t,S),K=[];let q=((r=s.flip)==null?void 0:r.overflows)||[];if(f&&K.push(D[E]),p){const $=Ote(i,o,R);K.push(D[$[0]],D[$[1]])}if(q=[...q,{placement:i,overflows:K}],!K.every($=>$<=0)){var X,z;const $=(((X=s.flip)==null?void 0:X.index)||0)+1,I=H[$];if(I&&(!(p==="alignment"?k!==Ro(I):!1)||q.every(U=>Ro(U.placement)===k?U.overflows[0]>0:!0)))return{data:{index:$,overflows:q},reset:{placement:I}};let M=(z=q.filter(O=>O.overflows[0]<=0).sort((O,U)=>O.overflows[1]-U.overflows[1])[0])==null?void 0:z.placement;if(!M)switch(g){case"bestFit":{var N;const O=(N=q.filter(U=>{if(A){const B=Ro(U.placement);return B===k||B==="y"}return!0}).map(U=>[U.placement,U.overflows.filter(B=>B>0).reduce((B,L)=>B+L,0)]).sort((U,B)=>U[1]-B[1])[0])==null?void 0:N[0];O&&(M=O);break}case"initialPlacement":M=l;break}if(i!==M)return{reset:{placement:M}}}return{}}}};function xN(e,t){return{top:e.top-t.height,right:e.right-t.width,bottom:e.bottom-t.height,left:e.left-t.width}}function EN(e){return Pte.some(t=>e[t]>=0)}const Yte=function(e){return e===void 0&&(e={}),{name:"hide",options:e,async fn(t){const{rects:n,platform:r}=t,{strategy:i="referenceHidden",...s}=va(e,t);switch(i){case"referenceHidden":{const o=await r.detectOverflow(t,{...s,elementContext:"reference"}),l=xN(o,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:EN(l)}}}case"escaped":{const o=await r.detectOverflow(t,{...s,altBoundary:!0}),l=xN(o,n.floating);return{data:{escapedOffsets:l,escaped:EN(l)}}}default:return{}}}}},qB=new Set(["left","top"]);async function Vte(e,t){const{placement:n,platform:r,elements:i}=e,s=await(r.isRTL==null?void 0:r.isRTL(i.floating)),o=ya(n),l=Rd(n),u=Ro(n)==="y",d=qB.has(o)?-1:1,f=s&&u?-1:1,p=va(t,e);let{mainAxis:y,crossAxis:g,alignmentAxis:b}=typeof p=="number"?{mainAxis:p,crossAxis:0,alignmentAxis:null}:{mainAxis:p.mainAxis||0,crossAxis:p.crossAxis||0,alignmentAxis:p.alignmentAxis};return l&&typeof b=="number"&&(g=l==="end"?b*-1:b),u?{x:g*f,y:y*d}:{x:y*d,y:g*f}}const Kte=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 Vte(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}}}}},Gte=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:E=>{let{x:k,y:T}=E;return{x:k,y:T}}},...d}=va(e,t),f={x:n,y:r},p=await s.detectOverflow(t,d),y=Ro(ya(i)),g=K1(y);let b=f[g],w=f[y];if(o){const E=g==="y"?"top":"left",k=g==="y"?"bottom":"right",T=b+p[E],R=b-p[k];b=cS(T,b,R)}if(l){const E=y==="y"?"top":"left",k=y==="y"?"bottom":"right",T=w+p[E],R=w-p[k];w=cS(T,w,R)}const S=u.fn({...t,[g]:b,[y]:w});return{...S,data:{x:S.x-n,y:S.y-r,enabled:{[g]:o,[y]:l}}}}}},Xte=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}=va(e,t),f={x:n,y:r},p=Ro(i),y=K1(p);let g=f[y],b=f[p];const w=va(l,t),S=typeof w=="number"?{mainAxis:w,crossAxis:0}:{mainAxis:0,crossAxis:0,...w};if(u){const T=y==="y"?"height":"width",R=s.reference[y]-s.floating[T]+S.mainAxis,P=s.reference[y]+s.reference[T]-S.mainAxis;g<R?g=R:g>P&&(g=P)}if(d){var E,k;const T=y==="y"?"width":"height",R=qB.has(ya(i)),P=s.reference[p]-s.floating[T]+(R&&((E=o.offset)==null?void 0:E[p])||0)+(R?0:S.crossAxis),A=s.reference[p]+s.reference[T]+(R?0:((k=o.offset)==null?void 0:k[p])||0)-(R?S.crossAxis:0);b<P?b=P:b>A&&(b=A)}return{[y]:g,[p]:b}}}},Zte=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}=va(e,t),f=await o.detectOverflow(t,d),p=ya(i),y=Rd(i),g=Ro(i)==="y",{width:b,height:w}=s.floating;let S,E;p==="top"||p==="bottom"?(S=p,E=y===(await(o.isRTL==null?void 0:o.isRTL(l.floating))?"start":"end")?"left":"right"):(E=p,S=y==="end"?"top":"bottom");const k=w-f.top-f.bottom,T=b-f.left-f.right,R=Sl(w-f[S],k),P=Sl(b-f[E],T),A=!t.middlewareData.shift;let H=R,D=P;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(D=T),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(H=k),A&&!y){const q=vs(f.left,0),X=vs(f.right,0),z=vs(f.top,0),N=vs(f.bottom,0);g?D=b-2*(q!==0||X!==0?q+X:vs(f.left,f.right)):H=w-2*(z!==0||N!==0?z+N:vs(f.top,f.bottom))}await u({...t,availableWidth:D,availableHeight:H});const K=await o.getDimensions(l.floating);return b!==K.width||w!==K.height?{reset:{rects:!0}}:{}}}};function ty(){return typeof window<"u"}function Ad(e){return YB(e)?(e.nodeName||"").toLowerCase():"#document"}function bs(e){var t;return(e==null||(t=e.ownerDocument)==null?void 0:t.defaultView)||window}function Io(e){var t;return(t=(YB(e)?e.ownerDocument:e.document)||window.document)==null?void 0:t.documentElement}function YB(e){return ty()?e instanceof Node||e instanceof bs(e).Node:!1}function no(e){return ty()?e instanceof Element||e instanceof bs(e).Element:!1}function wa(e){return ty()?e instanceof HTMLElement||e instanceof bs(e).HTMLElement:!1}function CN(e){return!ty()||typeof ShadowRoot>"u"?!1:e instanceof ShadowRoot||e instanceof bs(e).ShadowRoot}function ap(e){const{overflow:t,overflowX:n,overflowY:r,display:i}=ro(e);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&i!=="inline"&&i!=="contents"}function Qte(e){return/^(table|td|th)$/.test(Ad(e))}function ny(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const Jte=/transform|translate|scale|rotate|perspective|filter/,ene=/paint|layout|strict|content/,ac=e=>!!e&&e!=="none";let _w;function Z1(e){const t=no(e)?ro(e):e;return ac(t.transform)||ac(t.translate)||ac(t.scale)||ac(t.rotate)||ac(t.perspective)||!Q1()&&(ac(t.backdropFilter)||ac(t.filter))||Jte.test(t.willChange||"")||ene.test(t.contain||"")}function tne(e){let t=xl(e);for(;wa(t)&&!md(t);){if(Z1(t))return t;if(ny(t))return null;t=xl(t)}return null}function Q1(){return _w==null&&(_w=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),_w}function md(e){return/^(html|body|#document)$/.test(Ad(e))}function ro(e){return bs(e).getComputedStyle(e)}function ry(e){return no(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function xl(e){if(Ad(e)==="html")return e;const t=e.assignedSlot||e.parentNode||CN(e)&&e.host||Io(e);return CN(t)?t.host:t}function VB(e){const t=xl(e);return md(t)?e.ownerDocument?e.ownerDocument.body:e.body:wa(t)&&ap(t)?t:VB(t)}function Dh(e,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const i=VB(e),s=i===((r=e.ownerDocument)==null?void 0:r.body),o=bs(i);if(s){const l=dS(o);return t.concat(o,o.visualViewport||[],ap(i)?i:[],l&&n?Dh(l):[])}else return t.concat(i,Dh(i,[],n))}function dS(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}function KB(e){const t=ro(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=pv(n)!==s||pv(r)!==o;return l&&(n=s,r=o),{width:n,height:r,$:l}}function J1(e){return no(e)?e:e.contextElement}function ad(e){const t=J1(e);if(!wa(t))return Mo(1);const n=t.getBoundingClientRect(),{width:r,height:i,$:s}=KB(t);let o=(s?pv(n.width):n.width)/r,l=(s?pv(n.height):n.height)/i;return(!o||!Number.isFinite(o))&&(o=1),(!l||!Number.isFinite(l))&&(l=1),{x:o,y:l}}const nne=Mo(0);function GB(e){const t=bs(e);return!Q1()||!t.visualViewport?nne:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function rne(e,t,n){return t===void 0&&(t=!1),!n||t&&n!==bs(e)?!1:t}function Tc(e,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const i=e.getBoundingClientRect(),s=J1(e);let o=Mo(1);t&&(r?no(r)&&(o=ad(r)):o=ad(e));const l=rne(s,n,r)?GB(s):Mo(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=bs(s),g=r&&no(r)?bs(r):r;let b=y,w=dS(b);for(;w&&r&&g!==b;){const S=ad(w),E=w.getBoundingClientRect(),k=ro(w),T=E.left+(w.clientLeft+parseFloat(k.paddingLeft))*S.x,R=E.top+(w.clientTop+parseFloat(k.paddingTop))*S.y;u*=S.x,d*=S.y,f*=S.x,p*=S.y,u+=T,d+=R,b=bs(w),w=dS(b)}}return gv({width:f,height:p,x:u,y:d})}function iy(e,t){const n=ry(e).scrollLeft;return t?t.left+n:Tc(Io(e)).left+n}function XB(e,t){const n=e.getBoundingClientRect(),r=n.left+t.scrollLeft-iy(e,n),i=n.top+t.scrollTop;return{x:r,y:i}}function ine(e){let{elements:t,rect:n,offsetParent:r,strategy:i}=e;const s=i==="fixed",o=Io(r),l=t?ny(t.floating):!1;if(r===o||l&&s)return n;let u={scrollLeft:0,scrollTop:0},d=Mo(1);const f=Mo(0),p=wa(r);if((p||!p&&!s)&&((Ad(r)!=="body"||ap(o))&&(u=ry(r)),p)){const g=Tc(r);d=ad(r),f.x=g.x+r.clientLeft,f.y=g.y+r.clientTop}const y=o&&!p&&!s?XB(o,u):Mo(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 sne(e){return Array.from(e.getClientRects())}function one(e){const t=Io(e),n=ry(e),r=e.ownerDocument.body,i=vs(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),s=vs(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let o=-n.scrollLeft+iy(e);const l=-n.scrollTop;return ro(r).direction==="rtl"&&(o+=vs(t.clientWidth,r.clientWidth)-i),{width:i,height:s,x:o,y:l}}const kN=25;function ane(e,t){const n=bs(e),r=Io(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=Q1();(!f||f&&t==="fixed")&&(l=i.offsetLeft,u=i.offsetTop)}const d=iy(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,b=Math.abs(r.clientWidth-p.clientWidth-g);b<=kN&&(s-=b)}else d<=kN&&(s+=d);return{width:s,height:o,x:l,y:u}}function lne(e,t){const n=Tc(e,!0,t==="fixed"),r=n.top+e.clientTop,i=n.left+e.clientLeft,s=wa(e)?ad(e):Mo(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 TN(e,t,n){let r;if(t==="viewport")r=ane(e,n);else if(t==="document")r=one(Io(e));else if(no(t))r=lne(t,n);else{const i=GB(e);r={x:t.x-i.x,y:t.y-i.y,width:t.width,height:t.height}}return gv(r)}function ZB(e,t){const n=xl(e);return n===t||!no(n)||md(n)?!1:ro(n).position==="fixed"||ZB(n,t)}function cne(e,t){const n=t.get(e);if(n)return n;let r=Dh(e,[],!1).filter(l=>no(l)&&Ad(l)!=="body"),i=null;const s=ro(e).position==="fixed";let o=s?xl(e):e;for(;no(o)&&!md(o);){const l=ro(o),u=Z1(o);!u&&l.position==="fixed"&&(i=null),(s?!u&&!i:!u&&l.position==="static"&&!!i&&(i.position==="absolute"||i.position==="fixed")||ap(o)&&!u&&ZB(e,o))?r=r.filter(f=>f!==o):i=l,o=xl(o)}return t.set(e,r),r}function une(e){let{element:t,boundary:n,rootBoundary:r,strategy:i}=e;const o=[...n==="clippingAncestors"?ny(t)?[]:cne(t,this._c):[].concat(n),r],l=TN(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=TN(t,o[y],i);u=vs(g.top,u),d=Sl(g.right,d),f=Sl(g.bottom,f),p=vs(g.left,p)}return{width:d-p,height:f-u,x:p,y:u}}function dne(e){const{width:t,height:n}=KB(e);return{width:t,height:n}}function fne(e,t,n){const r=wa(t),i=Io(t),s=n==="fixed",o=Tc(e,!0,s,t);let l={scrollLeft:0,scrollTop:0};const u=Mo(0);function d(){u.x=iy(i)}if(r||!r&&!s)if((Ad(t)!=="body"||ap(i))&&(l=ry(t)),r){const g=Tc(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?XB(i,l):Mo(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 ww(e){return ro(e).position==="static"}function RN(e,t){if(!wa(e)||ro(e).position==="fixed")return null;if(t)return t(e);let n=e.offsetParent;return Io(e)===n&&(n=n.ownerDocument.body),n}function QB(e,t){const n=bs(e);if(ny(e))return n;if(!wa(e)){let i=xl(e);for(;i&&!md(i);){if(no(i)&&!ww(i))return i;i=xl(i)}return n}let r=RN(e,t);for(;r&&Qte(r)&&ww(r);)r=RN(r,t);return r&&md(r)&&ww(r)&&!Z1(r)?n:r||tne(e)||n}const hne=async function(e){const t=this.getOffsetParent||QB,n=this.getDimensions,r=await n(e.floating);return{reference:fne(e.reference,await t(e.floating),e.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function pne(e){return ro(e).direction==="rtl"}const mne={convertOffsetParentRelativeRectToViewportRelativeRect:ine,getDocumentElement:Io,getClippingRect:une,getOffsetParent:QB,getElementRects:hne,getClientRects:sne,getDimensions:dne,getScale:ad,isElement:no,isRTL:pne};function JB(e,t){return e.x===t.x&&e.y===t.y&&e.width===t.width&&e.height===t.height}function gne(e,t){let n=null,r;const i=Io(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 b=ig(p),w=ig(i.clientWidth-(f+y)),S=ig(i.clientHeight-(p+g)),E=ig(f),T={rootMargin:-b+"px "+-w+"px "+-S+"px "+-E+"px",threshold:vs(0,Sl(1,u))||1};let R=!0;function P(A){const H=A[0].intersectionRatio;if(H!==u){if(!R)return o();H?o(!1,H):r=setTimeout(()=>{o(!1,1e-7)},1e3)}H===1&&!JB(d,e.getBoundingClientRect())&&o(),R=!1}try{n=new IntersectionObserver(P,{...T,root:i.ownerDocument})}catch{n=new IntersectionObserver(P,T)}n.observe(e)}return o(!0),s}function vne(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=J1(e),f=i||s?[...d?Dh(d):[],...t?Dh(t):[]]:[];f.forEach(E=>{i&&E.addEventListener("scroll",n,{passive:!0}),s&&E.addEventListener("resize",n)});const p=d&&l?gne(d,n):null;let y=-1,g=null;o&&(g=new ResizeObserver(E=>{let[k]=E;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 b,w=u?Tc(e):null;u&&S();function S(){const E=Tc(e);w&&!JB(w,E)&&n(),w=E,b=requestAnimationFrame(S)}return n(),()=>{var E;f.forEach(k=>{i&&k.removeEventListener("scroll",n),s&&k.removeEventListener("resize",n)}),p==null||p(),(E=g)==null||E.disconnect(),g=null,u&&cancelAnimationFrame(b)}}const yne=Kte,bne=Gte,_ne=qte,wne=Zte,Sne=Yte,AN=Wte,xne=Xte,Ene=(e,t,n)=>{const r=new Map,i={platform:mne,...n},s={...i.platform,_c:r};return Ute(e,t,{...i,platform:s})};var Cne=typeof document<"u",kne=function(){},Hg=Cne?_.useLayoutEffect:kne;function vv(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(!vv(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)&&!vv(e[s],t[s]))return!1}return!0}return e!==e&&t!==t}function ez(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function MN(e,t){const n=ez(e);return Math.round(t*n)/n}function Sw(e){const t=_.useRef(e);return Hg(()=>{t.current=e}),t}function Tne(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]=_.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[y,g]=_.useState(r);vv(y,r)||g(r);const[b,w]=_.useState(null),[S,E]=_.useState(null),k=_.useCallback(U=>{U!==A.current&&(A.current=U,w(U))},[]),T=_.useCallback(U=>{U!==H.current&&(H.current=U,E(U))},[]),R=s||b,P=o||S,A=_.useRef(null),H=_.useRef(null),D=_.useRef(f),K=u!=null,q=Sw(u),X=Sw(i),z=Sw(d),N=_.useCallback(()=>{if(!A.current||!H.current)return;const U={placement:t,strategy:n,middleware:y};X.current&&(U.platform=X.current),Ene(A.current,H.current,U).then(B=>{const L={...B,isPositioned:z.current!==!1};$.current&&!vv(D.current,L)&&(D.current=L,Fc.flushSync(()=>{p(L)}))})},[y,t,n,X,z]);Hg(()=>{d===!1&&D.current.isPositioned&&(D.current.isPositioned=!1,p(U=>({...U,isPositioned:!1})))},[d]);const $=_.useRef(!1);Hg(()=>($.current=!0,()=>{$.current=!1}),[]),Hg(()=>{if(R&&(A.current=R),P&&(H.current=P),R&&P){if(q.current)return q.current(R,P,N);N()}},[R,P,N,q,K]);const I=_.useMemo(()=>({reference:A,floating:H,setReference:k,setFloating:T}),[k,T]),M=_.useMemo(()=>({reference:R,floating:P}),[R,P]),O=_.useMemo(()=>{const U={position:n,left:0,top:0};if(!M.floating)return U;const B=MN(M.floating,f.x),L=MN(M.floating,f.y);return l?{...U,transform:"translate("+B+"px, "+L+"px)",...ez(M.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:B,top:L}},[n,l,M.floating,f.x,f.y]);return _.useMemo(()=>({...f,update:N,refs:I,elements:M,floatingStyles:O}),[f,N,I,M,O])}const Rne=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?AN({element:r.current,padding:i}).fn(n):{}:r?AN({element:r,padding:i}).fn(n):{}}}},Ane=(e,t)=>{const n=yne(e);return{name:n.name,fn:n.fn,options:[e,t]}},Mne=(e,t)=>{const n=bne(e);return{name:n.name,fn:n.fn,options:[e,t]}},Nne=(e,t)=>({fn:xne(e).fn,options:[e,t]}),Pne=(e,t)=>{const n=_ne(e);return{name:n.name,fn:n.fn,options:[e,t]}},Lne=(e,t)=>{const n=wne(e);return{name:n.name,fn:n.fn,options:[e,t]}},One=(e,t)=>{const n=Sne(e);return{name:n.name,fn:n.fn,options:[e,t]}},Dne=(e,t)=>{const n=Rne(e);return{name:n.name,fn:n.fn,options:[e,t]}};var Ine="Arrow",tz=_.forwardRef((e,t)=>{const{children:n,width:r=10,height:i=5,...s}=e;return v.jsx(hn.svg,{...s,ref:t,width:r,height:i,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:e.asChild?n:v.jsx("polygon",{points:"0,0 30,0 15,10"})})});tz.displayName=Ine;var Bne=tz,eE="Popper",[nz,Ll]=_a(eE),[zne,rz]=nz(eE),iz=e=>{const{__scopePopper:t,children:n}=e,[r,i]=_.useState(null);return v.jsx(zne,{scope:t,anchor:r,onAnchorChange:i,children:n})};iz.displayName=eE;var sz="PopperAnchor",oz=_.forwardRef((e,t)=>{const{__scopePopper:n,virtualRef:r,...i}=e,s=rz(sz,n),o=_.useRef(null),l=Kn(t,o),u=_.useRef(null);return _.useEffect(()=>{const d=u.current;u.current=(r==null?void 0:r.current)||o.current,d!==u.current&&s.onAnchorChange(u.current)}),r?null:v.jsx(hn.div,{...i,ref:l})});oz.displayName=sz;var tE="PopperContent",[jne,$ne]=nz(tE),az=_.forwardRef((e,t)=>{var ee,pe,ae,me,Ee,Oe;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:b,...w}=e,S=rz(tE,n),[E,k]=_.useState(null),T=Kn(t,Se=>k(Se)),[R,P]=_.useState(null),A=Nte(R),H=(A==null?void 0:A.width)??0,D=(A==null?void 0:A.height)??0,K=r+(s!=="center"?"-"+s:""),q=typeof f=="number"?f:{top:0,right:0,bottom:0,left:0,...f},X=Array.isArray(d)?d:[d],z=X.length>0,N={padding:q,boundary:X.filter(Hne),altBoundary:z},{refs:$,floatingStyles:I,placement:M,isPositioned:O,middlewareData:U}=Tne({strategy:"fixed",placement:K,whileElementsMounted:(...Se)=>vne(...Se,{animationFrame:g==="always"}),elements:{reference:S.anchor},middleware:[Ane({mainAxis:i+D,alignmentAxis:o}),u&&Mne({mainAxis:!0,crossAxis:!1,limiter:p==="partial"?Nne():void 0,...N}),u&&Pne({...N}),Lne({...N,apply:({elements:Se,rects:Qe,availableWidth:Ht,availableHeight:ye})=>{const{width:Xe,height:kt}=Qe.reference,gt=Se.floating.style;gt.setProperty("--radix-popper-available-width",`${Ht}px`),gt.setProperty("--radix-popper-available-height",`${ye}px`),gt.setProperty("--radix-popper-anchor-width",`${Xe}px`),gt.setProperty("--radix-popper-anchor-height",`${kt}px`)}}),R&&Dne({element:R,padding:l}),Une({arrowWidth:H,arrowHeight:D}),y&&One({strategy:"referenceHidden",...N})]}),[B,L]=uz(M),Y=Lo(b);Di(()=>{O&&(Y==null||Y())},[O,Y]);const V=(ee=U.arrow)==null?void 0:ee.x,j=(pe=U.arrow)==null?void 0:pe.y,te=((ae=U.arrow)==null?void 0:ae.centerOffset)!==0,[re,oe]=_.useState();return Di(()=>{E&&oe(window.getComputedStyle(E).zIndex)},[E]),v.jsx("div",{ref:$.setFloating,"data-radix-popper-content-wrapper":"",style:{...I,transform:O?I.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:re,"--radix-popper-transform-origin":[(me=U.transformOrigin)==null?void 0:me.x,(Ee=U.transformOrigin)==null?void 0:Ee.y].join(" "),...((Oe=U.hide)==null?void 0:Oe.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:e.dir,children:v.jsx(jne,{scope:n,placedSide:B,onArrowChange:P,arrowX:V,arrowY:j,shouldHideArrow:te,children:v.jsx(hn.div,{"data-side":B,"data-align":L,...w,ref:T,style:{...w.style,animation:O?void 0:"none"}})})})});az.displayName=tE;var lz="PopperArrow",Fne={top:"bottom",right:"left",bottom:"top",left:"right"},cz=_.forwardRef(function(t,n){const{__scopePopper:r,...i}=t,s=$ne(lz,r),o=Fne[s.placedSide];return v.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:v.jsx(Bne,{...i,ref:n,style:{...i.style,display:"block"}})})});cz.displayName=lz;function Hne(e){return e!==null}var Une=e=>({name:"transformOrigin",options:e,fn(t){var S,E,k;const{placement:n,rects:r,middlewareData:i}=t,o=((S=i.arrow)==null?void 0:S.centerOffset)!==0,l=o?0:e.arrowWidth,u=o?0:e.arrowHeight,[d,f]=uz(n),p={start:"0%",center:"50%",end:"100%"}[f],y=(((E=i.arrow)==null?void 0:E.x)??0)+l/2,g=(((k=i.arrow)==null?void 0:k.y)??0)+u/2;let b="",w="";return d==="bottom"?(b=o?p:`${y}px`,w=`${-u}px`):d==="top"?(b=o?p:`${y}px`,w=`${r.floating.height+u}px`):d==="right"?(b=`${-u}px`,w=o?p:`${g}px`):d==="left"&&(b=`${r.floating.width+u}px`,w=o?p:`${g}px`),{data:{x:b,y:w}}}});function uz(e){const[t,n="center"]=e.split("-");return[t,n]}var sy=iz,lp=oz,oy=az,ay=cz,xw="rovingFocusGroup.onEntryFocus",Wne={bubbles:!1,cancelable:!0},cp="RovingFocusGroup",[fS,dz,qne]=j1(cp),[Yne,fz]=_a(cp,[qne]),[Vne,Kne]=Yne(cp),hz=_.forwardRef((e,t)=>v.jsx(fS.Provider,{scope:e.__scopeRovingFocusGroup,children:v.jsx(fS.Slot,{scope:e.__scopeRovingFocusGroup,children:v.jsx(Gne,{...e,ref:t})})}));hz.displayName=cp;var Gne=_.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=_.useRef(null),g=Kn(t,y),b=$1(s),[w,S]=Cc({prop:o,defaultProp:l??null,onChange:u,caller:cp}),[E,k]=_.useState(!1),T=Lo(d),R=dz(n),P=_.useRef(!1),[A,H]=_.useState(0);return _.useEffect(()=>{const D=y.current;if(D)return D.addEventListener(xw,T),()=>D.removeEventListener(xw,T)},[T]),v.jsx(Vne,{scope:n,orientation:r,dir:b,loop:i,currentTabStopId:w,onItemFocus:_.useCallback(D=>S(D),[S]),onItemShiftTab:_.useCallback(()=>k(!0),[]),onFocusableItemAdd:_.useCallback(()=>H(D=>D+1),[]),onFocusableItemRemove:_.useCallback(()=>H(D=>D-1),[]),children:v.jsx(hn.div,{tabIndex:E||A===0?-1:0,"data-orientation":r,...p,ref:g,style:{outline:"none",...e.style},onMouseDown:Mt(e.onMouseDown,()=>{P.current=!0}),onFocus:Mt(e.onFocus,D=>{const K=!P.current;if(D.target===D.currentTarget&&K&&!E){const q=new CustomEvent(xw,Wne);if(D.currentTarget.dispatchEvent(q),!q.defaultPrevented){const X=R().filter(M=>M.focusable),z=X.find(M=>M.active),N=X.find(M=>M.id===w),I=[z,N,...X].filter(Boolean).map(M=>M.ref.current);gz(I,f)}}P.current=!1}),onBlur:Mt(e.onBlur,()=>k(!1))})})}),pz="RovingFocusGroupItem",mz=_.forwardRef((e,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:i=!1,tabStopId:s,children:o,...l}=e,u=Ci(),d=s||u,f=Kne(pz,n),p=f.currentTabStopId===d,y=dz(n),{onFocusableItemAdd:g,onFocusableItemRemove:b,currentTabStopId:w}=f;return _.useEffect(()=>{if(r)return g(),()=>b()},[r,g,b]),v.jsx(fS.ItemSlot,{scope:n,id:d,focusable:r,active:i,children:v.jsx(hn.span,{tabIndex:p?0:-1,"data-orientation":f.orientation,...l,ref:t,onMouseDown:Mt(e.onMouseDown,S=>{r?f.onItemFocus(d):S.preventDefault()}),onFocus:Mt(e.onFocus,()=>f.onItemFocus(d)),onKeyDown:Mt(e.onKeyDown,S=>{if(S.key==="Tab"&&S.shiftKey){f.onItemShiftTab();return}if(S.target!==S.currentTarget)return;const E=Qne(S,f.orientation,f.dir);if(E!==void 0){if(S.metaKey||S.ctrlKey||S.altKey||S.shiftKey)return;S.preventDefault();let T=y().filter(R=>R.focusable).map(R=>R.ref.current);if(E==="last")T.reverse();else if(E==="prev"||E==="next"){E==="prev"&&T.reverse();const R=T.indexOf(S.currentTarget);T=f.loop?Jne(T,R+1):T.slice(R+1)}setTimeout(()=>gz(T))}}),children:typeof o=="function"?o({isCurrentTabStop:p,hasTabStop:w!=null}):o})})});mz.displayName=pz;var Xne={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function Zne(e,t){return t!=="rtl"?e:e==="ArrowLeft"?"ArrowRight":e==="ArrowRight"?"ArrowLeft":e}function Qne(e,t,n){const r=Zne(e.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return Xne[r]}function gz(e,t=!1){const n=document.activeElement;for(const r of e)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function Jne(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var ere=hz,tre=mz,hS=["Enter"," "],nre=["ArrowDown","PageUp","Home"],vz=["ArrowUp","PageDown","End"],rre=[...nre,...vz],ire={ltr:[...hS,"ArrowRight"],rtl:[...hS,"ArrowLeft"]},sre={ltr:["ArrowLeft"],rtl:["ArrowRight"]},up="Menu",[Ih,ore,are]=j1(up),[Hc,yz]=_a(up,[are,Ll,fz]),ly=Ll(),bz=fz(),[lre,Uc]=Hc(up),[cre,dp]=Hc(up),_z=e=>{const{__scopeMenu:t,open:n=!1,children:r,dir:i,onOpenChange:s,modal:o=!0}=e,l=ly(t),[u,d]=_.useState(null),f=_.useRef(!1),p=Lo(s),y=$1(i);return _.useEffect(()=>{const g=()=>{f.current=!0,document.addEventListener("pointerdown",b,{capture:!0,once:!0}),document.addEventListener("pointermove",b,{capture:!0,once:!0})},b=()=>f.current=!1;return document.addEventListener("keydown",g,{capture:!0}),()=>{document.removeEventListener("keydown",g,{capture:!0}),document.removeEventListener("pointerdown",b,{capture:!0}),document.removeEventListener("pointermove",b,{capture:!0})}},[]),v.jsx(sy,{...l,children:v.jsx(lre,{scope:t,open:n,onOpenChange:p,content:u,onContentChange:d,children:v.jsx(cre,{scope:t,onClose:_.useCallback(()=>p(!1),[p]),isUsingKeyboardRef:f,dir:y,modal:o,children:r})})})};_z.displayName=up;var ure="MenuAnchor",nE=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=ly(n);return v.jsx(lp,{...i,...r,ref:t})});nE.displayName=ure;var rE="MenuPortal",[dre,wz]=Hc(rE,{forceMount:void 0}),Sz=e=>{const{__scopeMenu:t,forceMount:n,children:r,container:i}=e,s=Uc(rE,t);return v.jsx(dre,{scope:t,forceMount:n,children:v.jsx(qs,{present:n||s.open,children:v.jsx(Td,{asChild:!0,container:i,children:r})})})};Sz.displayName=rE;var $s="MenuContent",[fre,iE]=Hc($s),xz=_.forwardRef((e,t)=>{const n=wz($s,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,s=Uc($s,e.__scopeMenu),o=dp($s,e.__scopeMenu);return v.jsx(Ih.Provider,{scope:e.__scopeMenu,children:v.jsx(qs,{present:r||s.open,children:v.jsx(Ih.Slot,{scope:e.__scopeMenu,children:o.modal?v.jsx(hre,{...i,ref:t}):v.jsx(pre,{...i,ref:t})})})})}),hre=_.forwardRef((e,t)=>{const n=Uc($s,e.__scopeMenu),r=_.useRef(null),i=Kn(t,r);return _.useEffect(()=>{const s=r.current;if(s)return Qv(s)},[]),v.jsx(sE,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:Mt(e.onFocusOutside,s=>s.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),pre=_.forwardRef((e,t)=>{const n=Uc($s,e.__scopeMenu);return v.jsx(sE,{...e,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),mre=wl("MenuContent.ScrollLock"),sE=_.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:b,...w}=e,S=Uc($s,n),E=dp($s,n),k=ly(n),T=bz(n),R=ore(n),[P,A]=_.useState(null),H=_.useRef(null),D=Kn(t,H,S.onContentChange),K=_.useRef(0),q=_.useRef(""),X=_.useRef(0),z=_.useRef(null),N=_.useRef("right"),$=_.useRef(0),I=b?op:_.Fragment,M=b?{as:mre,allowPinchZoom:!0}:void 0,O=B=>{var ee,pe;const L=q.current+B,Y=R().filter(ae=>!ae.disabled),V=document.activeElement,j=(ee=Y.find(ae=>ae.ref.current===V))==null?void 0:ee.textValue,te=Y.map(ae=>ae.textValue),re=Tre(te,L,j),oe=(pe=Y.find(ae=>ae.textValue===re))==null?void 0:pe.ref.current;(function ae(me){q.current=me,window.clearTimeout(K.current),me!==""&&(K.current=window.setTimeout(()=>ae(""),1e3))})(L),oe&&setTimeout(()=>oe.focus())};_.useEffect(()=>()=>window.clearTimeout(K.current),[]),Xv();const U=_.useCallback(B=>{var Y,V;return N.current===((Y=z.current)==null?void 0:Y.side)&&Are(B,(V=z.current)==null?void 0:V.area)},[]);return v.jsx(fre,{scope:n,searchRef:q,onItemEnter:_.useCallback(B=>{U(B)&&B.preventDefault()},[U]),onItemLeave:_.useCallback(B=>{var L;U(B)||((L=H.current)==null||L.focus(),A(null))},[U]),onTriggerLeave:_.useCallback(B=>{U(B)&&B.preventDefault()},[U]),pointerGraceTimerRef:X,onPointerGraceIntentChange:_.useCallback(B=>{z.current=B},[]),children:v.jsx(I,{...M,children:v.jsx(sp,{asChild:!0,trapped:i,onMountAutoFocus:Mt(s,B=>{var L;B.preventDefault(),(L=H.current)==null||L.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:v.jsx(kd,{asChild:!0,disableOutsidePointerEvents:l,onEscapeKeyDown:d,onPointerDownOutside:f,onFocusOutside:p,onInteractOutside:y,onDismiss:g,children:v.jsx(ere,{asChild:!0,...T,dir:E.dir,orientation:"vertical",loop:r,currentTabStopId:P,onCurrentTabStopIdChange:A,onEntryFocus:Mt(u,B=>{E.isUsingKeyboardRef.current||B.preventDefault()}),preventScrollOnEntryFocus:!0,children:v.jsx(oy,{role:"menu","aria-orientation":"vertical","data-state":jz(S.open),"data-radix-menu-content":"",dir:E.dir,...k,...w,ref:D,style:{outline:"none",...w.style},onKeyDown:Mt(w.onKeyDown,B=>{const Y=B.target.closest("[data-radix-menu-content]")===B.currentTarget,V=B.ctrlKey||B.altKey||B.metaKey,j=B.key.length===1;Y&&(B.key==="Tab"&&B.preventDefault(),!V&&j&&O(B.key));const te=H.current;if(B.target!==te||!rre.includes(B.key))return;B.preventDefault();const oe=R().filter(ee=>!ee.disabled).map(ee=>ee.ref.current);vz.includes(B.key)&&oe.reverse(),Cre(oe)}),onBlur:Mt(e.onBlur,B=>{B.currentTarget.contains(B.target)||(window.clearTimeout(K.current),q.current="")}),onPointerMove:Mt(e.onPointerMove,Bh(B=>{const L=B.target,Y=$.current!==B.clientX;if(B.currentTarget.contains(L)&&Y){const V=B.clientX>$.current?"right":"left";N.current=V,$.current=B.clientX}}))})})})})})})});xz.displayName=$s;var gre="MenuGroup",oE=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return v.jsx(hn.div,{role:"group",...r,ref:t})});oE.displayName=gre;var vre="MenuLabel",Ez=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return v.jsx(hn.div,{...r,ref:t})});Ez.displayName=vre;var yv="MenuItem",NN="menu.itemSelect",cy=_.forwardRef((e,t)=>{const{disabled:n=!1,onSelect:r,...i}=e,s=_.useRef(null),o=dp(yv,e.__scopeMenu),l=iE(yv,e.__scopeMenu),u=Kn(t,s),d=_.useRef(!1),f=()=>{const p=s.current;if(!n&&p){const y=new CustomEvent(NN,{bubbles:!0,cancelable:!0});p.addEventListener(NN,g=>r==null?void 0:r(g),{once:!0}),dB(p,y),y.defaultPrevented?d.current=!1:o.onClose()}};return v.jsx(Cz,{...i,ref:u,disabled:n,onClick:Mt(e.onClick,f),onPointerDown:p=>{var y;(y=e.onPointerDown)==null||y.call(e,p),d.current=!0},onPointerUp:Mt(e.onPointerUp,p=>{var y;d.current||(y=p.currentTarget)==null||y.click()}),onKeyDown:Mt(e.onKeyDown,p=>{const y=l.searchRef.current!=="";n||y&&p.key===" "||hS.includes(p.key)&&(p.currentTarget.click(),p.preventDefault())})})});cy.displayName=yv;var Cz=_.forwardRef((e,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:i,...s}=e,o=iE(yv,n),l=bz(n),u=_.useRef(null),d=Kn(t,u),[f,p]=_.useState(!1),[y,g]=_.useState("");return _.useEffect(()=>{const b=u.current;b&&g((b.textContent??"").trim())},[s.children]),v.jsx(Ih.ItemSlot,{scope:n,disabled:r,textValue:i??y,children:v.jsx(tre,{asChild:!0,...l,focusable:!r,children:v.jsx(hn.div,{role:"menuitem","data-highlighted":f?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...s,ref:d,onPointerMove:Mt(e.onPointerMove,Bh(b=>{r?o.onItemLeave(b):(o.onItemEnter(b),b.defaultPrevented||b.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:Mt(e.onPointerLeave,Bh(b=>o.onItemLeave(b))),onFocus:Mt(e.onFocus,()=>p(!0)),onBlur:Mt(e.onBlur,()=>p(!1))})})})}),yre="MenuCheckboxItem",kz=_.forwardRef((e,t)=>{const{checked:n=!1,onCheckedChange:r,...i}=e;return v.jsx(Nz,{scope:e.__scopeMenu,checked:n,children:v.jsx(cy,{role:"menuitemcheckbox","aria-checked":bv(n)?"mixed":n,...i,ref:t,"data-state":lE(n),onSelect:Mt(i.onSelect,()=>r==null?void 0:r(bv(n)?!0:!n),{checkForDefaultPrevented:!1})})})});kz.displayName=yre;var Tz="MenuRadioGroup",[bre,_re]=Hc(Tz,{value:void 0,onValueChange:()=>{}}),Rz=_.forwardRef((e,t)=>{const{value:n,onValueChange:r,...i}=e,s=Lo(r);return v.jsx(bre,{scope:e.__scopeMenu,value:n,onValueChange:s,children:v.jsx(oE,{...i,ref:t})})});Rz.displayName=Tz;var Az="MenuRadioItem",Mz=_.forwardRef((e,t)=>{const{value:n,...r}=e,i=_re(Az,e.__scopeMenu),s=n===i.value;return v.jsx(Nz,{scope:e.__scopeMenu,checked:s,children:v.jsx(cy,{role:"menuitemradio","aria-checked":s,...r,ref:t,"data-state":lE(s),onSelect:Mt(r.onSelect,()=>{var o;return(o=i.onValueChange)==null?void 0:o.call(i,n)},{checkForDefaultPrevented:!1})})})});Mz.displayName=Az;var aE="MenuItemIndicator",[Nz,wre]=Hc(aE,{checked:!1}),Pz=_.forwardRef((e,t)=>{const{__scopeMenu:n,forceMount:r,...i}=e,s=wre(aE,n);return v.jsx(qs,{present:r||bv(s.checked)||s.checked===!0,children:v.jsx(hn.span,{...i,ref:t,"data-state":lE(s.checked)})})});Pz.displayName=aE;var Sre="MenuSeparator",Lz=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e;return v.jsx(hn.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Lz.displayName=Sre;var xre="MenuArrow",Oz=_.forwardRef((e,t)=>{const{__scopeMenu:n,...r}=e,i=ly(n);return v.jsx(ay,{...i,...r,ref:t})});Oz.displayName=xre;var Ere="MenuSub",[yMe,Dz]=Hc(Ere),nh="MenuSubTrigger",Iz=_.forwardRef((e,t)=>{const n=Uc(nh,e.__scopeMenu),r=dp(nh,e.__scopeMenu),i=Dz(nh,e.__scopeMenu),s=iE(nh,e.__scopeMenu),o=_.useRef(null),{pointerGraceTimerRef:l,onPointerGraceIntentChange:u}=s,d={__scopeMenu:e.__scopeMenu},f=_.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);return _.useEffect(()=>f,[f]),_.useEffect(()=>{const p=l.current;return()=>{window.clearTimeout(p),u(null)}},[l,u]),v.jsx(nE,{asChild:!0,...d,children:v.jsx(Cz,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":i.contentId,"data-state":jz(n.open),...e,ref:ga(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:Mt(e.onPointerMove,Bh(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:Mt(e.onPointerLeave,Bh(p=>{var g,b;f();const y=(g=n.content)==null?void 0:g.getBoundingClientRect();if(y){const w=(b=n.content)==null?void 0:b.dataset.side,S=w==="right",E=S?-5:5,k=y[S?"left":"right"],T=y[S?"right":"left"];s.onPointerGraceIntentChange({area:[{x:p.clientX+E,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:Mt(e.onKeyDown,p=>{var g;const y=s.searchRef.current!=="";e.disabled||y&&p.key===" "||ire[r.dir].includes(p.key)&&(n.onOpenChange(!0),(g=n.content)==null||g.focus(),p.preventDefault())})})})});Iz.displayName=nh;var Bz="MenuSubContent",zz=_.forwardRef((e,t)=>{const n=wz($s,e.__scopeMenu),{forceMount:r=n.forceMount,...i}=e,s=Uc($s,e.__scopeMenu),o=dp($s,e.__scopeMenu),l=Dz(Bz,e.__scopeMenu),u=_.useRef(null),d=Kn(t,u);return v.jsx(Ih.Provider,{scope:e.__scopeMenu,children:v.jsx(qs,{present:r||s.open,children:v.jsx(Ih.Slot,{scope:e.__scopeMenu,children:v.jsx(sE,{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:Mt(e.onFocusOutside,f=>{f.target!==l.trigger&&s.onOpenChange(!1)}),onEscapeKeyDown:Mt(e.onEscapeKeyDown,f=>{o.onClose(),f.preventDefault()}),onKeyDown:Mt(e.onKeyDown,f=>{var g;const p=f.currentTarget.contains(f.target),y=sre[o.dir].includes(f.key);p&&y&&(s.onOpenChange(!1),(g=l.trigger)==null||g.focus(),f.preventDefault())})})})})})});zz.displayName=Bz;function jz(e){return e?"open":"closed"}function bv(e){return e==="indeterminate"}function lE(e){return bv(e)?"indeterminate":e?"checked":"unchecked"}function Cre(e){const t=document.activeElement;for(const n of e)if(n===t||(n.focus(),document.activeElement!==t))return}function kre(e,t){return e.map((n,r)=>e[(t+r)%e.length])}function Tre(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=kre(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 Rre(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 Are(e,t){if(!t)return!1;const n={x:e.clientX,y:e.clientY};return Rre(n,t)}function Bh(e){return t=>t.pointerType==="mouse"?e(t):void 0}var Mre=_z,Nre=nE,Pre=Sz,Lre=xz,Ore=oE,Dre=Ez,Ire=cy,Bre=kz,zre=Rz,jre=Mz,$re=Pz,Fre=Lz,Hre=Oz,Ure=Iz,Wre=zz,uy="DropdownMenu",[qre]=_a(uy,[yz]),Wi=yz(),[Yre,$z]=qre(uy),Fz=e=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:i,defaultOpen:s,onOpenChange:o,modal:l=!0}=e,u=Wi(t),d=_.useRef(null),[f,p]=Cc({prop:i,defaultProp:s??!1,onChange:o,caller:uy});return v.jsx(Yre,{scope:t,triggerId:Ci(),triggerRef:d,contentId:Ci(),open:f,onOpenChange:p,onOpenToggle:_.useCallback(()=>p(y=>!y),[p]),modal:l,children:v.jsx(Mre,{...u,open:f,onOpenChange:p,dir:r,modal:l,children:n})})};Fz.displayName=uy;var Hz="DropdownMenuTrigger",Uz=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...i}=e,s=$z(Hz,n),o=Wi(n);return v.jsx(Nre,{asChild:!0,...o,children:v.jsx(hn.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:ga(t,s.triggerRef),onPointerDown:Mt(e.onPointerDown,l=>{!r&&l.button===0&&l.ctrlKey===!1&&(s.onOpenToggle(),s.open||l.preventDefault())}),onKeyDown:Mt(e.onKeyDown,l=>{r||(["Enter"," "].includes(l.key)&&s.onOpenToggle(),l.key==="ArrowDown"&&s.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(l.key)&&l.preventDefault())})})})});Uz.displayName=Hz;var Vre="DropdownMenuPortal",Wz=e=>{const{__scopeDropdownMenu:t,...n}=e,r=Wi(t);return v.jsx(Pre,{...r,...n})};Wz.displayName=Vre;var qz="DropdownMenuContent",Yz=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=$z(qz,n),s=Wi(n),o=_.useRef(!1);return v.jsx(Lre,{id:i.contentId,"aria-labelledby":i.triggerId,...s,...r,ref:t,onCloseAutoFocus:Mt(e.onCloseAutoFocus,l=>{var u;o.current||(u=i.triggerRef.current)==null||u.focus(),o.current=!1,l.preventDefault()}),onInteractOutside:Mt(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)"}})});Yz.displayName=qz;var Kre="DropdownMenuGroup",Gre=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(Ore,{...i,...r,ref:t})});Gre.displayName=Kre;var Xre="DropdownMenuLabel",Vz=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(Dre,{...i,...r,ref:t})});Vz.displayName=Xre;var Zre="DropdownMenuItem",Kz=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(Ire,{...i,...r,ref:t})});Kz.displayName=Zre;var Qre="DropdownMenuCheckboxItem",Gz=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(Bre,{...i,...r,ref:t})});Gz.displayName=Qre;var Jre="DropdownMenuRadioGroup",eie=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(zre,{...i,...r,ref:t})});eie.displayName=Jre;var tie="DropdownMenuRadioItem",nie=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(jre,{...i,...r,ref:t})});nie.displayName=tie;var rie="DropdownMenuItemIndicator",Xz=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx($re,{...i,...r,ref:t})});Xz.displayName=rie;var iie="DropdownMenuSeparator",Zz=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(Fre,{...i,...r,ref:t})});Zz.displayName=iie;var sie="DropdownMenuArrow",oie=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(Hre,{...i,...r,ref:t})});oie.displayName=sie;var aie="DropdownMenuSubTrigger",lie=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(Ure,{...i,...r,ref:t})});lie.displayName=aie;var cie="DropdownMenuSubContent",uie=_.forwardRef((e,t)=>{const{__scopeDropdownMenu:n,...r}=e,i=Wi(n);return v.jsx(Wre,{...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)"}})});uie.displayName=cie;var die=Fz,fie=Uz,hie=Wz,pie=Yz,mie=Vz,gie=Kz,vie=Gz,yie=Xz,bie=Zz;function PN(e,[t,n]){return Math.min(n,Math.max(t,e))}var dy="Popover",[Qz]=_a(dy,[Ll]),fp=Ll(),[_ie,Ol]=Qz(dy),Jz=e=>{const{__scopePopover:t,children:n,open:r,defaultOpen:i,onOpenChange:s,modal:o=!1}=e,l=fp(t),u=_.useRef(null),[d,f]=_.useState(!1),[p,y]=Cc({prop:r,defaultProp:i??!1,onChange:s,caller:dy});return v.jsx(sy,{...l,children:v.jsx(_ie,{scope:t,contentId:Ci(),triggerRef:u,open:p,onOpenChange:y,onOpenToggle:_.useCallback(()=>y(g=>!g),[y]),hasCustomAnchor:d,onCustomAnchorAdd:_.useCallback(()=>f(!0),[]),onCustomAnchorRemove:_.useCallback(()=>f(!1),[]),modal:o,children:n})})};Jz.displayName=dy;var e3="PopoverAnchor",wie=_.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Ol(e3,n),s=fp(n),{onCustomAnchorAdd:o,onCustomAnchorRemove:l}=i;return _.useEffect(()=>(o(),()=>l()),[o,l]),v.jsx(lp,{...s,...r,ref:t})});wie.displayName=e3;var t3="PopoverTrigger",n3=_.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Ol(t3,n),s=fp(n),o=Kn(t,i.triggerRef),l=v.jsx(hn.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.contentId,"data-state":a3(i.open),...r,ref:o,onClick:Mt(e.onClick,i.onOpenToggle)});return i.hasCustomAnchor?l:v.jsx(lp,{asChild:!0,...s,children:l})});n3.displayName=t3;var cE="PopoverPortal",[Sie,xie]=Qz(cE,{forceMount:void 0}),r3=e=>{const{__scopePopover:t,forceMount:n,children:r,container:i}=e,s=Ol(cE,t);return v.jsx(Sie,{scope:t,forceMount:n,children:v.jsx(qs,{present:n||s.open,children:v.jsx(Td,{asChild:!0,container:i,children:r})})})};r3.displayName=cE;var gd="PopoverContent",i3=_.forwardRef((e,t)=>{const n=xie(gd,e.__scopePopover),{forceMount:r=n.forceMount,...i}=e,s=Ol(gd,e.__scopePopover);return v.jsx(qs,{present:r||s.open,children:s.modal?v.jsx(Cie,{...i,ref:t}):v.jsx(kie,{...i,ref:t})})});i3.displayName=gd;var Eie=wl("PopoverContent.RemoveScroll"),Cie=_.forwardRef((e,t)=>{const n=Ol(gd,e.__scopePopover),r=_.useRef(null),i=Kn(t,r),s=_.useRef(!1);return _.useEffect(()=>{const o=r.current;if(o)return Qv(o)},[]),v.jsx(op,{as:Eie,allowPinchZoom:!0,children:v.jsx(s3,{...e,ref:i,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:Mt(e.onCloseAutoFocus,o=>{var l;o.preventDefault(),s.current||(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:Mt(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:Mt(e.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1})})})}),kie=_.forwardRef((e,t)=>{const n=Ol(gd,e.__scopePopover),r=_.useRef(!1),i=_.useRef(!1);return v.jsx(s3,{...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()}})}),s3=_.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=Ol(gd,n),g=fp(n);return Xv(),v.jsx(sp,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:i,onUnmountAutoFocus:s,children:v.jsx(kd,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:f,onEscapeKeyDown:l,onPointerDownOutside:u,onFocusOutside:d,onDismiss:()=>y.onOpenChange(!1),children:v.jsx(oy,{"data-state":a3(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)"}})})})}),o3="PopoverClose",Tie=_.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=Ol(o3,n);return v.jsx(hn.button,{type:"button",...r,ref:t,onClick:Mt(e.onClick,()=>i.onOpenChange(!1))})});Tie.displayName=o3;var Rie="PopoverArrow",Aie=_.forwardRef((e,t)=>{const{__scopePopover:n,...r}=e,i=fp(n);return v.jsx(ay,{...i,...r,ref:t})});Aie.displayName=Rie;function a3(e){return e?"open":"closed"}var Mie=Jz,Nie=n3,Pie=r3,Lie=i3,Oie=[" ","Enter","ArrowUp","ArrowDown"],Die=[" ","Enter"],Rc="Select",[fy,hy,Iie]=j1(Rc),[Md]=_a(Rc,[Iie,Ll]),py=Ll(),[Bie,Dl]=Md(Rc),[zie,jie]=Md(Rc),l3=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:b}=e,w=py(t),[S,E]=_.useState(null),[k,T]=_.useState(null),[R,P]=_.useState(!1),A=$1(d),[H,D]=Cc({prop:r,defaultProp:i??!1,onChange:s,caller:Rc}),[K,q]=Cc({prop:o,defaultProp:l,onChange:u,caller:Rc}),X=_.useRef(null),z=S?b||!!S.closest("form"):!0,[N,$]=_.useState(new Set),I=Array.from(N).map(M=>M.props.value).join(";");return v.jsx(sy,{...w,children:v.jsxs(Bie,{required:g,scope:t,trigger:S,onTriggerChange:E,valueNode:k,onValueNodeChange:T,valueNodeHasChildren:R,onValueNodeHasChildrenChange:P,contentId:Ci(),value:K,onValueChange:q,open:H,onOpenChange:D,dir:A,triggerPointerDownPosRef:X,disabled:y,children:[v.jsx(fy.Provider,{scope:t,children:v.jsx(zie,{scope:e.__scopeSelect,onNativeOptionAdd:_.useCallback(M=>{$(O=>new Set(O).add(M))},[]),onNativeOptionRemove:_.useCallback(M=>{$(O=>{const U=new Set(O);return U.delete(M),U})},[]),children:n})}),z?v.jsxs(M3,{"aria-hidden":!0,required:g,tabIndex:-1,name:f,autoComplete:p,value:K,onChange:M=>q(M.target.value),disabled:y,form:b,children:[K===void 0?v.jsx("option",{value:""}):null,Array.from(N)]},I):null]})})};l3.displayName=Rc;var c3="SelectTrigger",u3=_.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...i}=e,s=py(n),o=Dl(c3,n),l=o.disabled||r,u=Kn(t,o.onTriggerChange),d=hy(n),f=_.useRef("touch"),[p,y,g]=P3(w=>{const S=d().filter(T=>!T.disabled),E=S.find(T=>T.value===o.value),k=L3(S,w,E);k!==void 0&&o.onValueChange(k.value)}),b=w=>{l||(o.onOpenChange(!0),g()),w&&(o.triggerPointerDownPosRef.current={x:Math.round(w.pageX),y:Math.round(w.pageY)})};return v.jsx(lp,{asChild:!0,...s,children:v.jsx(hn.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":N3(o.value)?"":void 0,...i,ref:u,onClick:Mt(i.onClick,w=>{w.currentTarget.focus(),f.current!=="mouse"&&b(w)}),onPointerDown:Mt(i.onPointerDown,w=>{f.current=w.pointerType;const S=w.target;S.hasPointerCapture(w.pointerId)&&S.releasePointerCapture(w.pointerId),w.button===0&&w.ctrlKey===!1&&w.pointerType==="mouse"&&(b(w),w.preventDefault())}),onKeyDown:Mt(i.onKeyDown,w=>{const S=p.current!=="";!(w.ctrlKey||w.altKey||w.metaKey)&&w.key.length===1&&y(w.key),!(S&&w.key===" ")&&Oie.includes(w.key)&&(b(),w.preventDefault())})})})});u3.displayName=c3;var d3="SelectValue",f3=_.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:i,children:s,placeholder:o="",...l}=e,u=Dl(d3,n),{onValueNodeHasChildrenChange:d}=u,f=s!==void 0,p=Kn(t,u.onValueNodeChange);return Di(()=>{d(f)},[d,f]),v.jsx(hn.span,{...l,ref:p,style:{pointerEvents:"none"},children:N3(u.value)?v.jsx(v.Fragment,{children:o}):s})});f3.displayName=d3;var $ie="SelectIcon",h3=_.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...i}=e;return v.jsx(hn.span,{"aria-hidden":!0,...i,ref:t,children:r||"▼"})});h3.displayName=$ie;var Fie="SelectPortal",p3=e=>v.jsx(Td,{asChild:!0,...e});p3.displayName=Fie;var Ac="SelectContent",m3=_.forwardRef((e,t)=>{const n=Dl(Ac,e.__scopeSelect),[r,i]=_.useState();if(Di(()=>{i(new DocumentFragment)},[]),!n.open){const s=r;return s?Fc.createPortal(v.jsx(g3,{scope:e.__scopeSelect,children:v.jsx(fy.Slot,{scope:e.__scopeSelect,children:v.jsx("div",{children:e.children})})}),s):null}return v.jsx(v3,{...e,ref:t})});m3.displayName=Ac;var Qs=10,[g3,Il]=Md(Ac),Hie="SelectContentImpl",Uie=wl("SelectContent.RemoveScroll"),v3=_.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:b,hideWhenDetached:w,avoidCollisions:S,...E}=e,k=Dl(Ac,n),[T,R]=_.useState(null),[P,A]=_.useState(null),H=Kn(t,ee=>R(ee)),[D,K]=_.useState(null),[q,X]=_.useState(null),z=hy(n),[N,$]=_.useState(!1),I=_.useRef(!1);_.useEffect(()=>{if(T)return Qv(T)},[T]),Xv();const M=_.useCallback(ee=>{const[pe,...ae]=z().map(Oe=>Oe.ref.current),[me]=ae.slice(-1),Ee=document.activeElement;for(const Oe of ee)if(Oe===Ee||(Oe==null||Oe.scrollIntoView({block:"nearest"}),Oe===pe&&P&&(P.scrollTop=0),Oe===me&&P&&(P.scrollTop=P.scrollHeight),Oe==null||Oe.focus(),document.activeElement!==Ee))return},[z,P]),O=_.useCallback(()=>M([D,T]),[M,D,T]);_.useEffect(()=>{N&&O()},[N,O]);const{onOpenChange:U,triggerPointerDownPosRef:B}=k;_.useEffect(()=>{if(T){let ee={x:0,y:0};const pe=me=>{var Ee,Oe;ee={x:Math.abs(Math.round(me.pageX)-(((Ee=B.current)==null?void 0:Ee.x)??0)),y:Math.abs(Math.round(me.pageY)-(((Oe=B.current)==null?void 0:Oe.y)??0))}},ae=me=>{ee.x<=10&&ee.y<=10?me.preventDefault():T.contains(me.target)||U(!1),document.removeEventListener("pointermove",pe),B.current=null};return B.current!==null&&(document.addEventListener("pointermove",pe),document.addEventListener("pointerup",ae,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",pe),document.removeEventListener("pointerup",ae,{capture:!0})}}},[T,U,B]),_.useEffect(()=>{const ee=()=>U(!1);return window.addEventListener("blur",ee),window.addEventListener("resize",ee),()=>{window.removeEventListener("blur",ee),window.removeEventListener("resize",ee)}},[U]);const[L,Y]=P3(ee=>{const pe=z().filter(Ee=>!Ee.disabled),ae=pe.find(Ee=>Ee.ref.current===document.activeElement),me=L3(pe,ee,ae);me&&setTimeout(()=>me.ref.current.focus())}),V=_.useCallback((ee,pe,ae)=>{const me=!I.current&&!ae;(k.value!==void 0&&k.value===pe||me)&&(K(ee),me&&(I.current=!0))},[k.value]),j=_.useCallback(()=>T==null?void 0:T.focus(),[T]),te=_.useCallback((ee,pe,ae)=>{const me=!I.current&&!ae;(k.value!==void 0&&k.value===pe||me)&&X(ee)},[k.value]),re=r==="popper"?pS:y3,oe=re===pS?{side:l,sideOffset:u,align:d,alignOffset:f,arrowPadding:p,collisionBoundary:y,collisionPadding:g,sticky:b,hideWhenDetached:w,avoidCollisions:S}:{};return v.jsx(g3,{scope:n,content:T,viewport:P,onViewportChange:A,itemRefCallback:V,selectedItem:D,onItemLeave:j,itemTextRefCallback:te,focusSelectedItem:O,selectedItemText:q,position:r,isPositioned:N,searchRef:L,children:v.jsx(op,{as:Uie,allowPinchZoom:!0,children:v.jsx(sp,{asChild:!0,trapped:k.open,onMountAutoFocus:ee=>{ee.preventDefault()},onUnmountAutoFocus:Mt(i,ee=>{var pe;(pe=k.trigger)==null||pe.focus({preventScroll:!0}),ee.preventDefault()}),children:v.jsx(kd,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:ee=>ee.preventDefault(),onDismiss:()=>k.onOpenChange(!1),children:v.jsx(re,{role:"listbox",id:k.contentId,"data-state":k.open?"open":"closed",dir:k.dir,onContextMenu:ee=>ee.preventDefault(),...E,...oe,onPlaced:()=>$(!0),ref:H,style:{display:"flex",flexDirection:"column",outline:"none",...E.style},onKeyDown:Mt(E.onKeyDown,ee=>{const pe=ee.ctrlKey||ee.altKey||ee.metaKey;if(ee.key==="Tab"&&ee.preventDefault(),!pe&&ee.key.length===1&&Y(ee.key),["ArrowUp","ArrowDown","Home","End"].includes(ee.key)){let me=z().filter(Ee=>!Ee.disabled).map(Ee=>Ee.ref.current);if(["ArrowUp","End"].includes(ee.key)&&(me=me.slice().reverse()),["ArrowUp","ArrowDown"].includes(ee.key)){const Ee=ee.target,Oe=me.indexOf(Ee);me=me.slice(Oe+1)}setTimeout(()=>M(me)),ee.preventDefault()}})})})})})})});v3.displayName=Hie;var Wie="SelectItemAlignedPosition",y3=_.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...i}=e,s=Dl(Ac,n),o=Il(Ac,n),[l,u]=_.useState(null),[d,f]=_.useState(null),p=Kn(t,H=>f(H)),y=hy(n),g=_.useRef(!1),b=_.useRef(!0),{viewport:w,selectedItem:S,selectedItemText:E,focusSelectedItem:k}=o,T=_.useCallback(()=>{if(s.trigger&&s.valueNode&&l&&d&&w&&S&&E){const H=s.trigger.getBoundingClientRect(),D=d.getBoundingClientRect(),K=s.valueNode.getBoundingClientRect(),q=E.getBoundingClientRect();if(s.dir!=="rtl"){const Ee=q.left-D.left,Oe=K.left-Ee,Se=H.left-Oe,Qe=H.width+Se,Ht=Math.max(Qe,D.width),ye=window.innerWidth-Qs,Xe=PN(Oe,[Qs,Math.max(Qs,ye-Ht)]);l.style.minWidth=Qe+"px",l.style.left=Xe+"px"}else{const Ee=D.right-q.right,Oe=window.innerWidth-K.right-Ee,Se=window.innerWidth-H.right-Oe,Qe=H.width+Se,Ht=Math.max(Qe,D.width),ye=window.innerWidth-Qs,Xe=PN(Oe,[Qs,Math.max(Qs,ye-Ht)]);l.style.minWidth=Qe+"px",l.style.right=Xe+"px"}const X=y(),z=window.innerHeight-Qs*2,N=w.scrollHeight,$=window.getComputedStyle(d),I=parseInt($.borderTopWidth,10),M=parseInt($.paddingTop,10),O=parseInt($.borderBottomWidth,10),U=parseInt($.paddingBottom,10),B=I+M+N+U+O,L=Math.min(S.offsetHeight*5,B),Y=window.getComputedStyle(w),V=parseInt(Y.paddingTop,10),j=parseInt(Y.paddingBottom,10),te=H.top+H.height/2-Qs,re=z-te,oe=S.offsetHeight/2,ee=S.offsetTop+oe,pe=I+M+ee,ae=B-pe;if(pe<=te){const Ee=X.length>0&&S===X[X.length-1].ref.current;l.style.bottom="0px";const Oe=d.clientHeight-w.offsetTop-w.offsetHeight,Se=Math.max(re,oe+(Ee?j:0)+Oe+O),Qe=pe+Se;l.style.height=Qe+"px"}else{const Ee=X.length>0&&S===X[0].ref.current;l.style.top="0px";const Se=Math.max(te,I+w.offsetTop+(Ee?V:0)+oe)+ae;l.style.height=Se+"px",w.scrollTop=pe-te+w.offsetTop}l.style.margin=`${Qs}px 0`,l.style.minHeight=L+"px",l.style.maxHeight=z+"px",r==null||r(),requestAnimationFrame(()=>g.current=!0)}},[y,s.trigger,s.valueNode,l,d,w,S,E,s.dir,r]);Di(()=>T(),[T]);const[R,P]=_.useState();Di(()=>{d&&P(window.getComputedStyle(d).zIndex)},[d]);const A=_.useCallback(H=>{H&&b.current===!0&&(T(),k==null||k(),b.current=!1)},[T,k]);return v.jsx(Yie,{scope:n,contentWrapper:l,shouldExpandOnScrollRef:g,onScrollButtonChange:A,children:v.jsx("div",{ref:u,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:R},children:v.jsx(hn.div,{...i,ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})});y3.displayName=Wie;var qie="SelectPopperPosition",pS=_.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:i=Qs,...s}=e,o=py(n);return v.jsx(oy,{...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)"}})});pS.displayName=qie;var[Yie,uE]=Md(Ac,{}),mS="SelectViewport",b3=_.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...i}=e,s=Il(mS,n),o=uE(mS,n),l=Kn(t,s.onViewportChange),u=_.useRef(0);return v.jsxs(v.Fragment,{children:[v.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}),v.jsx(fy.Slot,{scope:n,children:v.jsx(hn.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:l,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:Mt(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 b=window.innerHeight-Qs*2,w=parseFloat(p.style.minHeight),S=parseFloat(p.style.height),E=Math.max(w,S);if(E<b){const k=E+g,T=Math.min(b,k),R=k-T;p.style.height=T+"px",p.style.bottom==="0px"&&(f.scrollTop=R>0?R:0,p.style.justifyContent="flex-end")}}}u.current=f.scrollTop})})})]})});b3.displayName=mS;var _3="SelectGroup",[Vie,Kie]=Md(_3),Gie=_.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,i=Ci();return v.jsx(Vie,{scope:n,id:i,children:v.jsx(hn.div,{role:"group","aria-labelledby":i,...r,ref:t})})});Gie.displayName=_3;var w3="SelectLabel",Xie=_.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,i=Kie(w3,n);return v.jsx(hn.div,{id:i.id,...r,ref:t})});Xie.displayName=w3;var _v="SelectItem",[Zie,S3]=Md(_v),x3=_.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:i=!1,textValue:s,...o}=e,l=Dl(_v,n),u=Il(_v,n),d=l.value===r,[f,p]=_.useState(s??""),[y,g]=_.useState(!1),b=Kn(t,k=>{var T;return(T=u.itemRefCallback)==null?void 0:T.call(u,k,r,i)}),w=Ci(),S=_.useRef("touch"),E=()=>{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 v.jsx(Zie,{scope:n,value:r,disabled:i,textId:w,isSelected:d,onItemTextChange:_.useCallback(k=>{p(T=>T||((k==null?void 0:k.textContent)??"").trim())},[]),children:v.jsx(fy.ItemSlot,{scope:n,value:r,disabled:i,textValue:f,children:v.jsx(hn.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:b,onFocus:Mt(o.onFocus,()=>g(!0)),onBlur:Mt(o.onBlur,()=>g(!1)),onClick:Mt(o.onClick,()=>{S.current!=="mouse"&&E()}),onPointerUp:Mt(o.onPointerUp,()=>{S.current==="mouse"&&E()}),onPointerDown:Mt(o.onPointerDown,k=>{S.current=k.pointerType}),onPointerMove:Mt(o.onPointerMove,k=>{var T;S.current=k.pointerType,i?(T=u.onItemLeave)==null||T.call(u):S.current==="mouse"&&k.currentTarget.focus({preventScroll:!0})}),onPointerLeave:Mt(o.onPointerLeave,k=>{var T;k.currentTarget===document.activeElement&&((T=u.onItemLeave)==null||T.call(u))}),onKeyDown:Mt(o.onKeyDown,k=>{var R;((R=u.searchRef)==null?void 0:R.current)!==""&&k.key===" "||(Die.includes(k.key)&&E(),k.key===" "&&k.preventDefault())})})})})});x3.displayName=_v;var rh="SelectItemText",E3=_.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:i,...s}=e,o=Dl(rh,n),l=Il(rh,n),u=S3(rh,n),d=jie(rh,n),[f,p]=_.useState(null),y=Kn(t,E=>p(E),u.onItemTextChange,E=>{var k;return(k=l.itemTextRefCallback)==null?void 0:k.call(l,E,u.value,u.disabled)}),g=f==null?void 0:f.textContent,b=_.useMemo(()=>v.jsx("option",{value:u.value,disabled:u.disabled,children:g},u.value),[u.disabled,u.value,g]),{onNativeOptionAdd:w,onNativeOptionRemove:S}=d;return Di(()=>(w(b),()=>S(b)),[w,S,b]),v.jsxs(v.Fragment,{children:[v.jsx(hn.span,{id:u.textId,...s,ref:y}),u.isSelected&&o.valueNode&&!o.valueNodeHasChildren?Fc.createPortal(s.children,o.valueNode):null]})});E3.displayName=rh;var C3="SelectItemIndicator",k3=_.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return S3(C3,n).isSelected?v.jsx(hn.span,{"aria-hidden":!0,...r,ref:t}):null});k3.displayName=C3;var gS="SelectScrollUpButton",T3=_.forwardRef((e,t)=>{const n=Il(gS,e.__scopeSelect),r=uE(gS,e.__scopeSelect),[i,s]=_.useState(!1),o=Kn(t,r.onScrollButtonChange);return Di(()=>{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?v.jsx(A3,{...e,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop-u.offsetHeight)}}):null});T3.displayName=gS;var vS="SelectScrollDownButton",R3=_.forwardRef((e,t)=>{const n=Il(vS,e.__scopeSelect),r=uE(vS,e.__scopeSelect),[i,s]=_.useState(!1),o=Kn(t,r.onScrollButtonChange);return Di(()=>{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?v.jsx(A3,{...e,ref:o,onAutoScroll:()=>{const{viewport:l,selectedItem:u}=n;l&&u&&(l.scrollTop=l.scrollTop+u.offsetHeight)}}):null});R3.displayName=vS;var A3=_.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...i}=e,s=Il("SelectScrollButton",n),o=_.useRef(null),l=hy(n),u=_.useCallback(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return _.useEffect(()=>()=>u(),[u]),Di(()=>{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]),v.jsx(hn.div,{"aria-hidden":!0,...i,ref:t,style:{flexShrink:0,...i.style},onPointerDown:Mt(i.onPointerDown,()=>{o.current===null&&(o.current=window.setInterval(r,50))}),onPointerMove:Mt(i.onPointerMove,()=>{var d;(d=s.onItemLeave)==null||d.call(s),o.current===null&&(o.current=window.setInterval(r,50))}),onPointerLeave:Mt(i.onPointerLeave,()=>{u()})})}),Qie="SelectSeparator",Jie=_.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return v.jsx(hn.div,{"aria-hidden":!0,...r,ref:t})});Jie.displayName=Qie;var yS="SelectArrow",ese=_.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,i=py(n),s=Dl(yS,n),o=Il(yS,n);return s.open&&o.position==="popper"?v.jsx(ay,{...i,...r,ref:t}):null});ese.displayName=yS;var tse="SelectBubbleInput",M3=_.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const i=_.useRef(null),s=Kn(r,i),o=Mte(t);return _.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]),v.jsx(hn.select,{...n,style:{...fB,...n.style},ref:s,defaultValue:t})});M3.displayName=tse;function N3(e){return e===""||e===void 0}function P3(e){const t=Lo(e),n=_.useRef(""),r=_.useRef(0),i=_.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=_.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return _.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,i,s]}function L3(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=nse(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 nse(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var rse=l3,ise=u3,sse=f3,ose=h3,ase=p3,lse=m3,cse=b3,use=x3,dse=E3,fse=k3,hse=T3,pse=R3,[my]=_a("Tooltip",[Ll]),gy=Ll(),O3="TooltipProvider",mse=700,bS="tooltip.open",[gse,dE]=my(O3),D3=e=>{const{__scopeTooltip:t,delayDuration:n=mse,skipDelayDuration:r=300,disableHoverableContent:i=!1,children:s}=e,o=_.useRef(!0),l=_.useRef(!1),u=_.useRef(0);return _.useEffect(()=>{const d=u.current;return()=>window.clearTimeout(d)},[]),v.jsx(gse,{scope:t,isOpenDelayedRef:o,delayDuration:n,onOpen:_.useCallback(()=>{window.clearTimeout(u.current),o.current=!1},[]),onClose:_.useCallback(()=>{window.clearTimeout(u.current),u.current=window.setTimeout(()=>o.current=!0,r)},[r]),isPointerInTransitRef:l,onPointerInTransitChange:_.useCallback(d=>{l.current=d},[]),disableHoverableContent:i,children:s})};D3.displayName=O3;var zh="Tooltip",[vse,hp]=my(zh),I3=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:i,onOpenChange:s,disableHoverableContent:o,delayDuration:l}=e,u=dE(zh,e.__scopeTooltip),d=gy(t),[f,p]=_.useState(null),y=Ci(),g=_.useRef(0),b=o??u.disableHoverableContent,w=l??u.delayDuration,S=_.useRef(!1),[E,k]=Cc({prop:r,defaultProp:i??!1,onChange:H=>{H?(u.onOpen(),document.dispatchEvent(new CustomEvent(bS))):u.onClose(),s==null||s(H)},caller:zh}),T=_.useMemo(()=>E?S.current?"delayed-open":"instant-open":"closed",[E]),R=_.useCallback(()=>{window.clearTimeout(g.current),g.current=0,S.current=!1,k(!0)},[k]),P=_.useCallback(()=>{window.clearTimeout(g.current),g.current=0,k(!1)},[k]),A=_.useCallback(()=>{window.clearTimeout(g.current),g.current=window.setTimeout(()=>{S.current=!0,k(!0),g.current=0},w)},[w,k]);return _.useEffect(()=>()=>{g.current&&(window.clearTimeout(g.current),g.current=0)},[]),v.jsx(sy,{...d,children:v.jsx(vse,{scope:t,contentId:y,open:E,stateAttribute:T,trigger:f,onTriggerChange:p,onTriggerEnter:_.useCallback(()=>{u.isOpenDelayedRef.current?A():R()},[u.isOpenDelayedRef,A,R]),onTriggerLeave:_.useCallback(()=>{b?P():(window.clearTimeout(g.current),g.current=0)},[P,b]),onOpen:R,onClose:P,disableHoverableContent:b,children:n})})};I3.displayName=zh;var _S="TooltipTrigger",B3=_.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=hp(_S,n),s=dE(_S,n),o=gy(n),l=_.useRef(null),u=Kn(t,l,i.onTriggerChange),d=_.useRef(!1),f=_.useRef(!1),p=_.useCallback(()=>d.current=!1,[]);return _.useEffect(()=>()=>document.removeEventListener("pointerup",p),[p]),v.jsx(lp,{asChild:!0,...o,children:v.jsx(hn.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...r,ref:u,onPointerMove:Mt(e.onPointerMove,y=>{y.pointerType!=="touch"&&!f.current&&!s.isPointerInTransitRef.current&&(i.onTriggerEnter(),f.current=!0)}),onPointerLeave:Mt(e.onPointerLeave,()=>{i.onTriggerLeave(),f.current=!1}),onPointerDown:Mt(e.onPointerDown,()=>{i.open&&i.onClose(),d.current=!0,document.addEventListener("pointerup",p,{once:!0})}),onFocus:Mt(e.onFocus,()=>{d.current||i.onOpen()}),onBlur:Mt(e.onBlur,i.onClose),onClick:Mt(e.onClick,i.onClose)})})});B3.displayName=_S;var fE="TooltipPortal",[yse,bse]=my(fE,{forceMount:void 0}),z3=e=>{const{__scopeTooltip:t,forceMount:n,children:r,container:i}=e,s=hp(fE,t);return v.jsx(yse,{scope:t,forceMount:n,children:v.jsx(qs,{present:n||s.open,children:v.jsx(Td,{asChild:!0,container:i,children:r})})})};z3.displayName=fE;var vd="TooltipContent",j3=_.forwardRef((e,t)=>{const n=bse(vd,e.__scopeTooltip),{forceMount:r=n.forceMount,side:i="top",...s}=e,o=hp(vd,e.__scopeTooltip);return v.jsx(qs,{present:r||o.open,children:o.disableHoverableContent?v.jsx($3,{side:i,...s,ref:t}):v.jsx(_se,{side:i,...s,ref:t})})}),_se=_.forwardRef((e,t)=>{const n=hp(vd,e.__scopeTooltip),r=dE(vd,e.__scopeTooltip),i=_.useRef(null),s=Kn(t,i),[o,l]=_.useState(null),{trigger:u,onClose:d}=n,f=i.current,{onPointerInTransitChange:p}=r,y=_.useCallback(()=>{l(null),p(!1)},[p]),g=_.useCallback((b,w)=>{const S=b.currentTarget,E={x:b.clientX,y:b.clientY},k=Ese(E,S.getBoundingClientRect()),T=Cse(E,k),R=kse(w.getBoundingClientRect()),P=Rse([...T,...R]);l(P),p(!0)},[p]);return _.useEffect(()=>()=>y(),[y]),_.useEffect(()=>{if(u&&f){const b=S=>g(S,f),w=S=>g(S,u);return u.addEventListener("pointerleave",b),f.addEventListener("pointerleave",w),()=>{u.removeEventListener("pointerleave",b),f.removeEventListener("pointerleave",w)}}},[u,f,g,y]),_.useEffect(()=>{if(o){const b=w=>{const S=w.target,E={x:w.clientX,y:w.clientY},k=(u==null?void 0:u.contains(S))||(f==null?void 0:f.contains(S)),T=!Tse(E,o);k?y():T&&(y(),d())};return document.addEventListener("pointermove",b),()=>document.removeEventListener("pointermove",b)}},[u,f,o,d,y]),v.jsx($3,{...e,ref:s})}),[wse,Sse]=my(zh,{isInside:!1}),xse=nee("TooltipContent"),$3=_.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":i,onEscapeKeyDown:s,onPointerDownOutside:o,...l}=e,u=hp(vd,n),d=gy(n),{onClose:f}=u;return _.useEffect(()=>(document.addEventListener(bS,f),()=>document.removeEventListener(bS,f)),[f]),_.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]),v.jsx(kd,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:o,onFocusOutside:p=>p.preventDefault(),onDismiss:f,children:v.jsxs(oy,{"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:[v.jsx(xse,{children:r}),v.jsx(wse,{scope:n,isInside:!0,children:v.jsx(pB,{id:u.contentId,role:"tooltip",children:i||r})})]})})});j3.displayName=vd;var F3="TooltipArrow",H3=_.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,i=gy(n);return Sse(F3,n).isInside?null:v.jsx(ay,{...i,...r,ref:t})});H3.displayName=F3;function Ese(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 Cse(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 kse(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 Tse(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 Rse(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),Ase(t)}function Ase(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 Mse=D3,Nse=I3,Pse=B3,Lse=z3,Ose=j3,Dse=H3;function hE({...e}){return v.jsx(Mie,{"data-slot":"popover",...e})}function pE({...e}){return v.jsx(Nie,{"data-slot":"popover-trigger",...e})}function mE({className:e,align:t="center",sideOffset:n=4,...r}){return v.jsx(Pie,{children:v.jsx(Lie,{"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),...r})})}const Ise={"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 wc({variant:e,action:t}){const{heading:n,body:r}=Ise[e];return e==="no-messages"?v.jsx("div",{className:"flex h-full w-full items-center justify-center animate-in fade-in-0 duration-200 motion-reduce:animate-none",children:v.jsx("p",{className:"text-sm text-muted-foreground",children:n})}):v.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:[v.jsx("h2",{className:"text-2xl font-semibold",children:n}),r&&v.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:r}),t&&v.jsx("div",{children:t})]})}const Bse={online:"bg-[var(--color-status-success)]",offline:"bg-[var(--muted-foreground)]",connecting:"bg-[var(--color-status-working)] animate-pulse"},zse={online:"开发机在线",offline:"开发机离线",connecting:"正在连接开发机"};function LN({status:e,className:t}){return v.jsx("span",{className:Ye("inline-block w-2 h-2 rounded-full shrink-0",Bse[e],t),role:"status","aria-label":zse[e]})}function U3({layout:e,variant:t="default"}){const n=De(b=>b.proxies),r=De(b=>b.proxyListLoaded),i=De(b=>b.relayClientAuthIssue),s=De(b=>b.selectedProxyId),o=De(b=>b.proxySwitchTarget),l=Ui(),u=so(),[d,f]=_.useState(!1);async function p(b,w){if(o)return;const S=Ut;if(!S){nt.error("请先连接开发机");return}const E=w??b,k=s!==null&&s!==b;De.getState().setProxySwitchTarget({proxyId:b,name:E});try{const T=await S.selectProxy(b);if(!T.success){nt.error(`无法连接 ${E}:${T.error??"未知错误"}`);return}k&&(Ft.getState().prepareForProxySwitch(E),hi.getState().prepareForProxySwitch()),Er("local",Sn.proxyId,b),De.getState().setProxy(b,w??null),De.getState().setProxyOnline(!0),De.getState().transitionToPhase("session_browsing"),S.sendControl({type:"session_list"}),S.requestProxyInfo().then(R=>{if(De.getState().selectedProxyId!==b)return;const P=hi.getState();P.setHomePath(R.homePath),P.setAgentCli(R.agentCli)}).catch(R=>{console.error("[proxy-switcher] post-bind proxy info fetch failed",R)}),S.requestAgentStatuses().then(R=>{if(De.getState().selectedProxyId!==b)return;const P=Ft.getState();for(const A of R)P.setAgentStatus(A.sessionId,A.payload)}).catch(R=>{console.error("[proxy-switcher] post-bind data fetch failed",R)}),P1(S).then(R=>{R.status==="failed"&&console.error("[proxy-switcher] post-bind data fetch failed",R.error)}),f(!1),(e==="page"||l.pathname.startsWith("/chat/"))&&u("/sessions")}catch(T){const R=T instanceof Error?T.message:"未知错误";nt.error(`无法连接 ${E}:${R}`)}finally{De.getState().setProxySwitchTarget(null)}}if(e==="page")return i==="missing_client_token"?v.jsx(wc,{variant:"client-token-missing"}):i==="invalid_client_token"?v.jsx(wc,{variant:"client-token-invalid"}):r?n.length===0?v.jsx(wc,{variant:"no-proxy"}):v.jsxs("div",{className:"flex flex-col gap-3 p-4 h-full overflow-auto",children:[v.jsx("h3",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"可连接开发机"}),v.jsx("ul",{role:"list",className:"flex flex-col gap-2",children:n.map(b=>{const w=(o==null?void 0:o.proxyId)===b.proxyId,S=o!==null;return v.jsx("li",{children:v.jsxs("button",{type:"button","data-slot":"proxy-item","data-proxy-id":b.proxyId,"data-online":b.online,"data-selecting":w||void 0,disabled:!b.online||S,"aria-busy":w||void 0,onClick:()=>p(b.proxyId,b.name),className:Ye("w-full flex items-center gap-3 px-3 h-11 min-h-[44px] rounded-md border bg-card transition-colors text-left disabled:cursor-not-allowed disabled:hover:bg-card",w?"border-primary/40 bg-accent text-accent-foreground":"border-border hover:bg-accent",S&&!w?"opacity-50":"",b.online?"":"opacity-50"),"aria-pressed":s===b.proxyId,title:b.online?void 0:"这台开发机离线,暂时无法连接",children:[v.jsx(LN,{status:b.online?"online":"offline"}),v.jsx("span",{className:"text-sm font-normal flex-1 truncate min-w-0",children:b.name??b.proxyId}),w?v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:"正在连接"}),v.jsx(fa,{className:"h-4 w-4 animate-spin text-primary shrink-0","aria-hidden":!0})]}):s===b.proxyId?v.jsx(pa,{className:"h-4 w-4 text-primary shrink-0","aria-label":"已选"}):null,!b.online&&!w&&v.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:"离线"})]})},b.proxyId)})})]}):v.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:[v.jsx(fa,{className:"h-5 w-5 animate-spin","aria-hidden":!0}),v.jsx("p",{className:"text-sm",children:"连接中..."})]});const y=n.find(b=>b.proxyId===s),g=(y==null?void 0:y.name)??(y==null?void 0:y.proxyId)??"未选择开发机";return v.jsxs(hE,{open:d,onOpenChange:f,children:[v.jsx(pE,{asChild:!0,children:v.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":`当前连接:${g}`,children:[t==="default"&&v.jsx("span",{className:"h-4 w-4 shrink-0","aria-hidden":!0}),v.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:g}),v.jsx(Al,{className:"h-4 w-4 text-muted-foreground shrink-0 transition-transform group-data-[state=open]:rotate-180","aria-hidden":!0})]})}),v.jsx(mE,{align:"start",className:"w-[260px] p-1",children:n.length===0?v.jsx("div",{className:"text-xs text-muted-foreground p-2",children:"暂无可连接开发机"}):v.jsx("ul",{role:"list",className:"flex flex-col",children:n.map(b=>{const w=(o==null?void 0:o.proxyId)===b.proxyId,S=o!==null;return v.jsx("li",{children:v.jsxs("button",{type:"button","data-slot":"proxy-item","data-proxy-id":b.proxyId,"data-online":b.online,"data-selecting":w||void 0,disabled:!b.online||S,"aria-busy":w||void 0,onClick:()=>p(b.proxyId,b.name),className:Ye("w-full flex items-center gap-2 px-2 h-9 rounded-md transition-colors text-left disabled:cursor-not-allowed disabled:hover:bg-transparent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",w?"bg-accent text-accent-foreground":"hover:bg-accent",S&&!w?"opacity-50":"",b.online?"":"opacity-50"),"aria-pressed":s===b.proxyId,title:b.online?void 0:"这台开发机离线",children:[v.jsx(LN,{status:b.online?"online":"offline"}),v.jsx("span",{className:"text-sm font-normal flex-1 truncate min-w-0",children:b.name??b.proxyId}),w?v.jsx(fa,{className:"h-4 w-4 animate-spin text-primary shrink-0","aria-label":"正在连接"}):s===b.proxyId?v.jsx(pa,{className:"h-4 w-4 text-primary shrink-0","aria-label":"已选"}):null,!b.online&&s!==b.proxyId&&!w&&v.jsx("span",{className:"text-xs text-muted-foreground shrink-0",children:"离线"})]})},b.proxyId)})})})]})}const ON=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,DN=VD,jse=(e,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return DN(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=ON(f)||ON(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(b=>{let[w,S]=b;return Array.isArray(S)?S.includes({...s,...l}[w]):{...s,...l}[w]===S})?[...d,p,y]:d},[]);return DN(e,o,u,n==null?void 0:n.class,n==null?void 0:n.className)},$se=jse("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 At({className:e,variant:t="default",size:n="default",asChild:r=!1,...i}){const s=r?eee:"button";return v.jsx(s,{"data-slot":"button","data-variant":t,"data-size":n,className:Ye($se({variant:t,size:n,className:e})),...i})}function Fse({delayDuration:e=0,...t}){return v.jsx(Mse,{"data-slot":"tooltip-provider",delayDuration:e,...t})}function pp({...e}){return v.jsx(Nse,{"data-slot":"tooltip",...e})}function mp({...e}){return v.jsx(Pse,{"data-slot":"tooltip-trigger",...e})}function gp({className:e,sideOffset:t=0,children:n,hideArrow:r=!1,...i}){return v.jsx(Lse,{children:v.jsxs(Ose,{"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&&v.jsx(Dse,{className:"z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground"})]})})}function vy({...e}){return v.jsx(W1,{"data-slot":"sheet",...e})}function Hse({...e}){return v.jsx(Ate,{"data-slot":"sheet-trigger",...e})}function Use({...e}){return v.jsx(q1,{"data-slot":"sheet-portal",...e})}function Wse({className:e,...t}){return v.jsx(Y1,{"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 yy({className:e,overlayClassName:t,children:n,side:r="right",showCloseButton:i=!0,focusSurfaceOnOpen:s=!1,onOpenAutoFocus:o,...l}){return v.jsxs(Use,{children:[v.jsx(Wse,{className:t}),v.jsxs(V1,{"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:u=>{o==null||o(u),!(!s||u.defaultPrevented)&&(u.preventDefault(),u.currentTarget.focus({preventScroll:!0}))},...l,children:[n,i&&v.jsxs(ey,{"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:[v.jsx(zc,{className:"size-4"}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function gE({className:e,...t}){return v.jsx("div",{"data-slot":"sheet-header",className:Ye("flex flex-col gap-1.5 p-4",e),...t})}function by({className:e,...t}){return v.jsx(HB,{"data-slot":"sheet-title",className:Ye("font-semibold text-foreground",e),...t})}function qse({className:e,...t}){return v.jsx(UB,{"data-slot":"sheet-description",className:Ye("text-sm text-muted-foreground",e),...t})}function vE({...e}){return v.jsx(die,{"data-slot":"dropdown-menu",...e})}function yE({...e}){return v.jsx(fie,{"data-slot":"dropdown-menu-trigger",...e})}function bE({className:e,sideOffset:t=4,...n}){return v.jsx(hie,{children:v.jsx(pie,{"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),...n})})}function ko({className:e,inset:t,variant:n="default",...r}){return v.jsx(gie,{"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 Ew({className:e,children:t,checked:n,...r}){return v.jsxs(vie,{"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:[v.jsx("span",{className:"pointer-events-none absolute left-2 flex size-3.5 items-center justify-center",children:v.jsx(yie,{children:v.jsx(pa,{className:"size-4"})})}),t]})}function sg({className:e,inset:t,...n}){return v.jsx(mie,{"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 Cw({className:e,...t}){return v.jsx(bie,{"data-slot":"dropdown-menu-separator",className:Ye("-mx-1 my-1 h-px bg-border",e),...t})}const Yse={claude:"Claude Code",codex:"Codex"},IN=["claude","codex"];function _y(e){return Yse[e]}function W3(e,t){return IN.indexOf(e)-IN.indexOf(t)}function jh(e){return e.provider??"claude"}const wS=60*1e3,SS=60*wS,Vse=24*SS;function q3(e,t=Date.now()){const n=t-e;if(n<wS)return"刚刚";if(n<SS)return`${Math.floor(n/wS)} 分钟前`;if(n<Vse)return`${Math.floor(n/SS)} 小时前`;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 BN={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 xS(e){return e.kind!=="terminal"?BN[e.state]:e.state==="terminated"?BN.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 Kse({session:e}){const t=xS(e);return v.jsx("span",{className:Ye("inline-block size-2 rounded-full shrink-0",t.dot),"aria-label":`会话状态:${t.label}`,role:"status"})}function Gse({mode:e}){if(e!=="pty"&&e!=="json")return null;const t=e==="json"?"聊天视图":"终端视图",n=e==="json"?p1:g1;return v.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:v.jsx(n,{className:"size-3.5","aria-hidden":"true"})})}function Xse({session:e,selected:t,now:n,onClick:r,onRename:i,onTerminate:s}){const o=e.lastActive,l=e.cwd??e.name??e.sessionId,u=Kv(e.name),d=D1(e),f=e.nameLocked&&e.name?e.name:d||(u==="New Session"?e.sessionId.slice(0,8):u),p=!!e.mode||!!e.provider||o!==void 0,y=o!==void 0?q3(o,n):null,g=e.mode==="pty"&&e.ptyOwner==="local-terminal",b=e.kind==="terminal"?"终止终端":g?"断开远程连接":"终止会话";return v.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&&v.jsx("span",{className:"dev-sidebar-active-indicator absolute left-0 top-0 bottom-0 w-[2px]","aria-hidden":"true"}),v.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:[v.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[v.jsx(Kse,{session:e}),v.jsx("span",{className:"text-sm font-normal truncate flex-1",title:l,children:f})]}),p&&v.jsxs("span",{className:"flex items-center gap-1.5 text-xs leading-5 h-5",children:[e.mode&&v.jsx(Gse,{mode:e.mode}),e.mode&&v.jsx("span",{className:"text-muted-foreground/60 shrink-0","aria-hidden":"true",children:"·"}),e.provider&&e.kind!=="terminal"&&v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"font-mono text-muted-foreground shrink-0",children:_y(e.provider)}),v.jsx("span",{className:"text-muted-foreground/60 shrink-0","aria-hidden":"true",children:"·"})]}),v.jsx("span",{className:Ye("shrink-0",xS(e).text),children:xS(e).label}),y&&v.jsxs(v.Fragment,{children:[v.jsx("span",{className:"text-muted-foreground/60 shrink-0","aria-hidden":"true",children:"·"}),v.jsx("span",{className:"text-muted-foreground shrink-0 tabular-nums",children:y})]})]})]}),(i||s)&&v.jsxs(vE,{children:[v.jsx(yE,{asChild:!0,children:v.jsx(At,{variant:"ghost",size:"icon-xs",className:"size-11 md:size-6","aria-label":"会话操作","data-slot":"session-row-menu-trigger",onClick:w=>w.stopPropagation(),children:v.jsx(AW,{"aria-hidden":"true"})})}),v.jsxs(bE,{align:"end","data-slot":"session-row-menu",children:[i&&v.jsx(ko,{"data-slot":"session-row-rename-item",onSelect:w=>{w.stopPropagation(),i()},children:"重命名"}),s&&v.jsx(ko,{variant:"destructive","data-slot":"session-row-terminate-item",onSelect:w=>{w.stopPropagation(),s()},children:b})]})]})]})}function Bl({...e}){return v.jsx(W1,{"data-slot":"dialog",...e})}function Zse({...e}){return v.jsx(q1,{"data-slot":"dialog-portal",...e})}function Qse({...e}){return v.jsx(ey,{"data-slot":"dialog-close",...e})}function Jse({className:e,...t}){return v.jsx(Y1,{"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 zl({className:e,children:t,showCloseButton:n=!0,focusSurfaceOnOpen:r=!1,onOpenAutoFocus:i,...s}){return v.jsxs(Zse,{"data-slot":"dialog-portal",children:[v.jsx(Jse,{}),v.jsxs(V1,{"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:o=>{i==null||i(o),!(!r||o.defaultPrevented)&&(o.preventDefault(),o.currentTarget.focus({preventScroll:!0}))},...s,children:[t,n&&v.jsxs(ey,{"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:[v.jsx(zc,{}),v.jsx("span",{className:"sr-only",children:"Close"})]})]})]})}function jl({className:e,...t}){return v.jsx("div",{"data-slot":"dialog-header",className:Ye("flex flex-col gap-2 text-center sm:text-left",e),...t})}function Mc({className:e,showCloseButton:t=!1,children:n,...r}){return v.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&&v.jsx(ey,{asChild:!0,children:v.jsx(At,{variant:"outline",children:"Close"})})]})}function ba({className:e,...t}){return v.jsx(HB,{"data-slot":"dialog-title",className:Ye("text-lg leading-none font-semibold",e),...t})}function El({className:e,...t}){return v.jsx(UB,{"data-slot":"dialog-description",className:Ye("text-sm text-muted-foreground",e),...t})}function Cl(e){const[t,n]=_.useState(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia(e).matches);return _.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 eoe({session:e,now:t,disabled:n,loading:r,onClick:i,modeTag:s}){const o=v.jsx(toe,{title:e.title,modeTag:s}),l=v.jsx("span",{className:"text-xs text-muted-foreground tabular-nums",children:q3(e.updatedAt,t)}),u=v.jsxs("span",{className:"flex min-w-0 flex-1 flex-col gap-0.5",children:[o,l]});return v.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:v.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,v.jsx(tW,{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 toe({title:e,modeTag:t}){return v.jsxs("span",{className:"flex min-w-0 items-center gap-1.5",children:[v.jsx("span",{className:"text-sm font-normal truncate min-w-0",title:e,children:e}),t&&v.jsx(noe,{mode:t})]})}function noe({mode:e}){const t=e==="json"?"聊天视图":"终端视图",n=e==="json"?p1:g1;return v.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:v.jsx(n,{className:"size-3","aria-hidden":"true"})})}function Y3({providerLabel:e}){return v.jsx("div",{className:"grid min-w-0 gap-4","data-slot":"bypass-permission-warning",role:"alert",children:v.jsxs("div",{className:"flex min-w-0 items-start gap-3 text-sm",children:[v.jsx(B7,{className:"mt-0.5 size-5 shrink-0 text-destructive","aria-hidden":"true"}),v.jsxs("div",{className:"grid min-w-0 gap-2",children:[v.jsxs("p",{className:"font-medium text-foreground",children:[e," 将不再请求工具审批。"]}),v.jsx("p",{className:"text-muted-foreground",children:"Agent 可以直接执行命令、修改或删除文件,并可能绕过部分沙箱保护。"})]})]})})}function roe({now:e}){const t=Ft(X=>X.historySessions),n=Ft(X=>X.historyLoadStatus),[r,i]=_.useState(null),[s,o]=_.useState(null),[l,u]=_.useState("json"),[d,f]=_.useState("default"),[p,y]=_.useState(!1),[g,b]=_.useState(new Set),[w,S]=_.useState(new Set),E=so(),k=_.useMemo(()=>{const X=new Map;for(const z of t){const N=jh(z);let $=X.get(N);$||($=new Map,X.set(N,$));const I=V3(z.projectDir),M=$.get(I);M?M.sessions.push(z):$.set(I,{dir:I,sessions:[z]})}return Array.from(X.entries()).sort(([z],[N])=>W3(z,N)).map(([z,N])=>({provider:z,sessions:Array.from(N.values()).flatMap($=>$.sessions),projects:Array.from(N.values()).map($=>({dir:$.dir,shortDir:Kv($.dir),sessions:$.sessions}))}))},[t]);function T(X){o(X),u(ioe(X)),f(soe(X))}async function R(X,z,N){if(r)return;const $=Ut;if(!$){nt.error("请先连接开发机");return}i(X.id);const I=jh(X);try{const M=await $.createSession({cwd:X.projectDir,mode:z,provider:I,resumeSessionId:X.id,...N?{permissionMode:N}:{}});if(M.error||!M.sessionId){if(M.errorCode===zr.SESSION_ALREADY_ACTIVE){Ft.getState().setCodexActiveWriterConflict({...M.activeWriterPid?{activeWriterPid:M.activeWriterPid}:{}}),o(null);return}nt.error(`恢复失败:${M.error??"未知错误"}`);return}const O={sessionId:M.sessionId,...M.kind!==void 0?{kind:M.kind}:{},...M.name!==void 0?{name:M.name}:{},...M.nameLocked!==void 0?{nameLocked:M.nameLocked}:{},state:"idle",mode:M.mode??z,provider:M.provider??"claude",...M.ptyOwner!==void 0?{ptyOwner:M.ptyOwner}:{}};Ft.getState().addSession(O),E(`/chat/${M.sessionId}?mode=${M.mode??z}`),o(null)}catch(M){nt.error(`恢复失败:${M instanceof Error?M.message:String(M)}`)}finally{i(null)}}function P(){const X=Ut;!X||Ft.getState().historyLoadStatus==="loading"||P1(X).then(z=>{z.status==="failed"&&nt.error(z.error instanceof Error?z.error.message:String(z.error))})}function A(X,z){const N=zN(X,z);S($=>{const I=new Set($);return I.has(N)?I.delete(N):I.add(N),I})}function H(X){b(z=>{const N=new Set(z);return N.has(X)?N.delete(X):N.add(X),N})}const D=t.length>0,K=n==="loading",q=s?K3():[];return v.jsxs("div",{"data-slot":"history-list",className:"flex flex-col",children:[v.jsxs("div",{className:"flex min-h-11 w-full items-center gap-1.5 px-4 py-1.5 md:min-h-[36px]",children:[v.jsxs("button",{type:"button",onClick:()=>D&&y(X=>!X),disabled:!D,"aria-expanded":D?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:[v.jsxs("h3",{className:"min-w-0 text-sm font-semibold text-foreground",children:["全部会话",D?v.jsxs("span",{className:"ml-1 text-muted-foreground/70 font-normal",children:["· ",t.length]}):null]}),D?v.jsx(gh,{className:Ye("size-3.5 shrink-0 text-muted-foreground/80 transition-transform",p&&"rotate-90"),"aria-hidden":"true"}):null]}),v.jsx(At,{type:"button",variant:"ghost",size:"icon-sm","aria-label":"刷新全部会话","aria-busy":K,title:K?"正在加载":"刷新",onClick:P,disabled:K,"data-slot":"history-refresh",className:"size-11 md:size-8",children:v.jsx(m1,{className:Ye("size-3.5",K&&"animate-spin motion-reduce:animate-none"),"aria-hidden":"true"})})]}),!D&&K&&v.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:[v.jsx(fa,{className:"size-3.5 shrink-0 animate-spin motion-reduce:animate-none","aria-hidden":"true"}),v.jsx("span",{children:"正在加载会话记录..."})]}),!D&&n==="idle"&&v.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/80","data-slot":"history-idle",role:"status",children:"会话记录尚未加载"}),!D&&n==="error"&&v.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/80","data-slot":"history-error",role:"status",children:"会话记录加载失败,请点击刷新重试"}),D&&n==="error"&&v.jsx("div",{className:"px-4 pb-2 text-xs text-muted-foreground/80","data-slot":"history-stale",role:"status",children:"刷新失败,当前显示上次加载的结果"}),!D&&n==="loaded"&&v.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/70","data-slot":"history-empty",children:"暂无会话记录"}),D&&p&&v.jsx("ul",{role:"list",className:"flex flex-col",children:k.map(X=>{const z=g.has(X.provider);return v.jsxs("li",{children:[v.jsxs("button",{type:"button",onClick:()=>H(X.provider),"aria-expanded":!z,"data-slot":"history-provider-header","data-expanded":!z,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:[v.jsx("span",{className:"font-mono",children:_y(X.provider)}),v.jsx("span",{className:"h-px flex-1 bg-border/70","aria-hidden":"true"}),v.jsx("span",{className:"tabular-nums",children:X.sessions.length}),v.jsx(gh,{className:Ye("size-3.5 shrink-0 text-muted-foreground/80 transition-transform",!z&&"rotate-90"),"aria-hidden":"true"})]}),!z&&v.jsx("ul",{role:"list",className:"flex flex-col",children:X.projects.map(N=>{const $=zN(X.provider,N.dir),I=w.has($);return v.jsxs("li",{children:[v.jsxs("button",{type:"button",onClick:()=>A(X.provider,N.dir),"aria-expanded":I,"data-slot":"history-group-header","data-expanded":I,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:[v.jsx("span",{className:"text-sm font-mono truncate flex-1 min-w-0",title:N.dir,children:N.shortDir}),v.jsx("span",{className:"text-xs text-muted-foreground/80 tabular-nums shrink-0",children:N.sessions.length}),v.jsx(gh,{className:Ye("size-3.5 shrink-0 text-muted-foreground/80 transition-transform",I&&"rotate-90"),"aria-hidden":"true"})]}),I&&v.jsx("ul",{role:"list",className:"flex flex-col",children:N.sessions.map(M=>v.jsx(eoe,{session:M,now:e,disabled:r!==null,loading:r===M.id,onClick:()=>T(M),modeTag:M.preferredMode},M.id))})]},$)})})]},X.provider)})}),v.jsx(ooe,{session:s,open:s!==null,modes:q,mode:l,permissionMode:d,submitting:r!==null,onOpenChange:X=>{X||o(null)},onModeChange:u,onPermissionModeChange:f,onConfirm:()=>{s&&R(s,l,d)}})]})}function zN(e,t){return`${e}:${V3(t)}`}function V3(e){const t=e.trim();return!t||t==="/"?t||"/":t.replace(/\/+$/,"")||"/"}function K3(){return["json","pty"]}function ioe(e){const t=K3();return e.preferredMode&&t.includes(e.preferredMode)?e.preferredMode:t[0]??"json"}function soe(e){return jh(e)==="codex"?"auto":"default"}function ooe({session:e,open:t,modes:n,mode:r,permissionMode:i,submitting:s,onOpenChange:o,onModeChange:l,onPermissionModeChange:u,onConfirm:d}){const[f,p]=_.useState(!1),y=i==="bypassPermissions",g=Cl("(min-width: 768px)"),b=e?jh(e)==="codex":!1;_.useEffect(()=>{t||p(!1)},[t]);const w=f?v.jsx(Y3,{providerLabel:e?_y(jh(e)):"Agent"}):v.jsxs("div",{className:"grid min-w-0 gap-4",children:[v.jsxs("div",{className:"grid min-w-0 gap-2",children:[v.jsx("span",{className:"text-sm font-medium",children:"模式"}),v.jsxs("div",{role:"radiogroup","aria-label":"恢复模式",className:"grid min-w-0 grid-cols-2 gap-2",children:[n.includes("json")&&v.jsx(jN,{checked:r==="json",label:"聊天",icon:v.jsx(p1,{className:"size-4","aria-hidden":"true"}),disabled:s,onClick:()=>l("json")}),n.includes("pty")&&v.jsx(jN,{checked:r==="pty",label:"终端",icon:v.jsx(g1,{className:"size-4","aria-hidden":"true"}),disabled:s,onClick:()=>l("pty")})]})]}),v.jsxs("div",{className:"grid min-w-0 gap-2",children:[v.jsx("span",{className:"text-sm font-medium",children:"权限模式"}),v.jsxs("div",{role:"radiogroup","aria-label":"权限模式",className:"grid min-w-0 gap-2",children:[!b&&v.jsx(kw,{checked:i==="default",label:"严格审批",description:"所有需要权限的操作都要确认。",disabled:s,onClick:()=>u("default")}),v.jsx(kw,{checked:i==="auto",label:b?"按需审批":"自动判定",description:b?"Codex 在需要时请求确认。":"交给 Agent CLI 的原生策略判断。",disabled:s,onClick:()=>u("auto")}),v.jsx(kw,{checked:i==="bypassPermissions",label:"跳过全部审批",description:"危险模式,会跳过工具审批和部分沙箱保护。",destructive:!0,disabled:s,onClick:()=>u("bypassPermissions")})]})]})]}),S=v.jsxs(v.Fragment,{children:[v.jsx(At,{type:"button",variant:"ghost",disabled:s,onClick:()=>{f?p(!1):o(!1)},children:f?"返回":"取消"}),v.jsx(At,{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?v.jsx(Bl,{open:t,onOpenChange:o,children:v.jsxs(zl,{focusSurfaceOnOpen:!0,className:"min-w-0 sm:max-w-md","data-slot":"history-restore-dialog",children:[v.jsxs(jl,{className:"min-w-0",children:[v.jsx(ba,{children:f?"跳过全部审批?":"恢复会话"}),v.jsx(El,{className:"min-w-0 truncate pr-10 sm:pr-0",title:e==null?void 0:e.title,children:(e==null?void 0:e.title)??""})]}),w,v.jsx(Mc,{children:S})]})}):v.jsx(vy,{open:t,onOpenChange:o,children:v.jsxs(yy,{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:[v.jsxs(gE,{className:"min-w-0 shrink-0 px-4 pb-2 pt-4 text-left",children:[v.jsx(by,{children:f?"跳过全部审批?":"恢复会话"}),v.jsx(qse,{className:"min-w-0 truncate pr-10",title:e==null?void 0:e.title,children:(e==null?void 0:e.title)??""})]}),v.jsx("div",{className:"min-h-0 overflow-y-auto px-4 pb-3","data-slot":"history-restore-body",children:w}),v.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:v.jsx("div",{className:"flex flex-col-reverse gap-2 [&_button]:min-h-11 [&_button]:w-full",children:S})})]})})}function jN({checked:e,label:t,icon:n,disabled:r,onClick:i}){return v.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,v.jsx("span",{className:"min-w-0 text-center",children:t}),v.jsx(pa,{className:Ye("size-3.5 justify-self-end transition-opacity",e?"opacity-100":"opacity-0"),"aria-hidden":"true"})]})}function kw({checked:e,label:t,description:n,destructive:r,disabled:i,onClick:s}){return v.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:[v.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&&v.jsx("span",{className:Ye("size-2 rounded-full",r?"bg-destructive":"bg-primary")})}),v.jsxs("span",{className:"grid min-w-0 gap-1",children:[v.jsx("span",{className:Ye("text-sm font-medium",r?"text-destructive":"text-foreground"),children:t}),v.jsx("span",{className:"min-w-0 break-words text-xs leading-5 text-muted-foreground",children:n})]}),e&&v.jsx(pa,{className:Ye("mt-0.5 size-4 shrink-0",r?"text-destructive":"text-primary"),"aria-hidden":"true"})]})}function aoe({...e}){return v.jsx(rse,{"data-slot":"select",...e})}function loe({...e}){return v.jsx(sse,{"data-slot":"select-value",...e})}function coe({className:e,size:t="default",children:n,...r}){return v.jsxs(ise,{"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,v.jsx(ose,{asChild:!0,children:v.jsx(Al,{className:"size-4 opacity-50"})})]})}function uoe({className:e,children:t,position:n="item-aligned",align:r="center",...i}){return v.jsx(ase,{children:v.jsxs(lse,{"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,...i,children:[v.jsx(foe,{}),v.jsx(cse,{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}),v.jsx(hoe,{})]})})}function doe({className:e,children:t,...n}){return v.jsxs(use,{"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:[v.jsx("span",{"data-slot":"select-item-indicator",className:"absolute right-2 flex size-3.5 items-center justify-center",children:v.jsx(fse,{children:v.jsx(pa,{className:"size-4"})})}),v.jsx(dse,{children:t})]})}function foe({className:e,...t}){return v.jsx(hse,{"data-slot":"select-scroll-up-button",className:Ye("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(f1,{className:"size-4"})})}function hoe({className:e,...t}){return v.jsx(pse,{"data-slot":"select-scroll-down-button",className:Ye("flex cursor-default items-center justify-center py-1",e),...t,children:v.jsx(Al,{className:"size-4"})})}function _E(e){return!e||e.endsWith("/")?e:`${e}/`}function poe(e){const t=e.split("@").pop()??"",n=t.lastIndexOf("/");return n>=0?t.slice(n+1).toLowerCase():t.toLowerCase()}function moe(e){const t=e.split("@").pop()??"",n=t.lastIndexOf("/");return n>=0?t.slice(0,n+1):""}function goe(e,t,n){var o;if(t==="insert")return{currentPath:moe(e)||"./",query:poe(e)};if(!e)return{currentPath:"./",query:""};const r=e.replace(/\/+$/,"")||"/";if(e.endsWith("/")||r===(n==null?void 0:n.baseCwd)||((o=n==null?void 0:n.knownDirs)==null?void 0:o.has(r)))return{currentPath:_E(r),query:""};const s=e.lastIndexOf("/");return{currentPath:s>=0?e.slice(0,s+1):"./",query:s>=0?e.slice(s+1).toLowerCase():e.toLowerCase()}}function voe(e,t){if(t.startsWith("/"))return t.replace(/\/+$/,"")||"/";if(!e)return"";const n=t.replace(/^\.\//,"").replace(/\/+$/,"");return n?`${e}/${n}`:e}function yoe(e,t){return`${_E(e)}${t.name}${t.isDir?"/":""}`}function $N(e,t){const n=e.trim().replace(/\/+$/,"")||"/",r=t.trim().replace(/^\/+|\/+$/g,"");return!n.startsWith("/")||!r||t.trim().startsWith("/")||r.split("/").some(i=>i===""||i==="."||i==="..")?null:n==="/"?`/${r}`:`${n}/${r}`}const G3=_.forwardRef(function({filter:t,onSelect:n,onCreateDirectory:r,mode:i="insert",placement:s="floating",dirsOnly:o=!1,title:l},u){const d=hi(B=>B.tree),f=hi(B=>B.cwd),p=hi(B=>B.homePath),y=i==="insert"?f:p||f,g=_.useMemo(()=>new Set(d.keys()),[d]),b=_.useMemo(()=>goe(t,i,{baseCwd:y,knownDirs:g}),[t,i,y,g]),w=b.currentPath,S=_.useMemo(()=>voe(y,w),[y,w]),E=b.query,k=_.useRef(new Set),[T,R]=_.useState(!1),[P,A]=_.useState(""),[H,D]=_.useState(!1);_.useEffect(()=>{if(!S||d.has(S)||k.current.has(S))return;const B=Ut;if(!B)return;let L=!1;return k.current.add(S),B.requestDirectoryList(S).then(Y=>{L||hi.getState().setDirEntries(Y.path,Y.entries)}).catch(()=>{L||hi.getState().setDirEntries(S,[])}).finally(()=>{k.current.delete(S)}),()=>{L=!0}},[S,d]);const K=!d.has(S),q=_.useMemo(()=>{let B=d.get(S)??[];return o&&(B=B.filter(L=>L.isDir)),E&&(B=B.filter(L=>L.name.toLowerCase().includes(E))),B},[d,S,E,o]),[X,z]=_.useState(0);_.useEffect(()=>z(0),[w,E]),_.useEffect(()=>{R(!1),A("")},[S]),_.useEffect(()=>{X>=q.length&&q.length>0&&z(q.length-1)},[q.length,X]);const N=_.useRef(null),$=_.useRef(!1);_.useEffect(()=>{var L;if(!$.current)return;$.current=!1;const B=(L=N.current)==null?void 0:L.querySelector(`[data-entry-index="${X}"]`);B==null||B.scrollIntoView({block:"nearest"})},[X]);const I=_.useCallback(B=>{const L=yoe(w,B);return i==="insert"?L.replace(/^\.\//,""):L},[w,i]);async function M(){const B=$N(S,P);if(!(!B||!r)){D(!0);try{const L=await r(B);if(!L)return;A(""),R(!1),n(_E(L))}finally{D(!1)}}}_.useImperativeHandle(u,()=>({handleKey(B){return q.length===0?!1:B.key==="ArrowDown"?($.current=!0,z(L=>Math.min(q.length-1,L+1)),!0):B.key==="ArrowUp"?($.current=!0,z(L=>Math.max(0,L-1)),!0):B.key==="Enter"&&!B.nativeEvent.isComposing?(n(I(q[X])),!0):!1}}),[q,X,I,n]);const O=s==="inline"?"relative w-full bg-popover border border-border rounded-md overflow-hidden":i==="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",U=s==="inline"?"h-44 overflow-y-auto overscroll-contain":i==="select"?"max-h-44 overflow-y-auto overscroll-contain":"max-h-60 overflow-y-auto overscroll-contain";return v.jsxs("div",{className:O,"data-slot":"file-path-picker","data-mode":i,"data-placement":s,children:[i==="select"&&l?v.jsxs("div",{className:"border-b border-border/70 px-3 py-2",children:[v.jsxs("div",{className:"flex items-center justify-between gap-3",children:[v.jsx("span",{className:"text-xs text-muted-foreground",children:l}),r?v.jsx("button",{type:"button",className:"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 disabled:cursor-not-allowed disabled:opacity-50",disabled:!S||H,onClick:()=>R(B=>!B),children:"新建目录"}):null]}),T?v.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[v.jsx("input",{type:"text",value:P,onChange:B=>A(B.target.value),onKeyDown:B=>{B.key==="Enter"&&!B.nativeEvent.isComposing&&(B.preventDefault(),M()),B.key==="Escape"&&(R(!1),A(""))},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}),v.jsx("button",{type:"button",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:!$N(S,P)||H,onClick:()=>void M(),children:H?"创建中...":"创建目录"})]}):null]}):null,v.jsx("div",{className:U,children:q.length===0?v.jsx("div",{className:"px-3 py-2 text-xs text-muted-foreground",children:K?"加载中...":"没有匹配的路径"}):v.jsx("ul",{ref:N,role:"list",className:"flex flex-col",children:q.map((B,L)=>v.jsx("li",{children:v.jsx("button",{type:"button",onClick:()=>n(I(B)),onMouseEnter:()=>z(L),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",L===X&&"bg-[color-mix(in_srgb,var(--primary)_15%,transparent)]",B.isDir&&"font-semibold"),"data-slot":"file-entry","data-entry-type":B.isDir?"dir":"file","data-entry-index":L,children:v.jsxs("span",{className:"font-mono text-[13px]",children:[B.name,B.isDir?"/":""]})})},B.name))})})]})}),FN="工作目录不存在或不可访问:",boe=[{value:"default",label:"严格审批"},{value:"auto",label:"自动判定"},{value:"acceptEdits",label:"自动接受编辑"},{value:"plan",label:"只读规划"},{value:"bypassPermissions",label:"跳过全部审批"}],X3=[{value:"auto",label:"按需审批"},{value:"bypassPermissions",label:"跳过全部审批"}],ha={claude:"Claude Code",codex:"Codex"};function _oe(e,t){return t!==zr.PATH_NOT_FOUND||!e.startsWith(FN)?null:e.slice(FN.length).trim()||null}function wv(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 woe(e,t){return t.title?t.disabled?`${ha[e]}:${t.title}`:`${ha[e]} 路径:${t.title}`:`${ha[e]}:${t.label}`}function Soe(e,t){return e!=="codex"||X3.some(n=>n.value===t)?t:"auto"}async function xoe({relay:e,agentCli:t,form:n,timeoutMs:r=N1}){var d,f;const i=n.cwd.trim();if(!i)return{type:"validation_error",message:"请输入工作目录"};if(!e)return{type:"relay_missing",message:"请先连接开发机"};if(wv(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?`${ha[n.provider]} 不可用:${p}`:`${ha[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.error||!p.sessionId){const w=_oe(p.error??"",p.errorCode);return w?{type:"missing_cwd",path:w,message:"找不到这个工作目录"}:{type:"create_error",message:`创建失败:${p.error??"未知错误"}`}}const y=p.mode??o,g=((f=p.name)==null?void 0:f.trim())||void 0;return{type:"success",session:{sessionId:p.sessionId,...p.kind!==void 0?{kind:p.kind}:{},name:g,...p.nameLocked!==void 0?{nameLocked:p.nameLocked}:{},state:"idle",mode:y,provider:p.provider??l,...p.ptyOwner!==void 0?{ptyOwner:p.ptyOwner}:{}},route:`/chat/${p.sessionId}?mode=${y}`}}catch(p){return{type:"exception",message:p instanceof Error?p.message:String(p)}}}async function Eoe({relay:e,timeoutMs:t=N1}){var n;if(!e)return{type:"relay_missing",message:"请先连接开发机"};try{const r=await e.createSession({kind:"terminal",mode:"pty"},t);return r.error||!r.sessionId?{type:"create_error",message:`创建终端失败:${r.error??"未知错误"}`}:{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",mode:"pty",provider:r.provider??"claude",...r.ptyOwner!==void 0?{ptyOwner:r.ptyOwner}:{}},route:`/chat/${r.sessionId}?mode=pty`}}catch(r){return{type:"exception",message:r instanceof Error?r.message:String(r)}}}function Coe({agentCli:e,provider:t,isDesktop:n,editingCliProvider:r,cliPathInput:i,savingCliPath:s,onProviderChange:o,onOpenCliPathEditor:l,onCliPathInputChange:u,onCancelCliPathEditor:d,onSaveCliPath:f}){const p=wv("claude",e),y=wv("codex",e),g=e==null?void 0:e[t];return v.jsxs("section",{"aria-label":"Agent CLI",className:"flex min-w-0 flex-col gap-2",children:[v.jsxs("div",{className:"flex items-center justify-between",children:[v.jsx("span",{className:"text-sm",children:"Agent CLI"}),v.jsx("span",{className:"text-xs text-muted-foreground",children:"选择要启动的 CLI"})]}),v.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-2 sm:grid-cols-2",children:[v.jsx(HN,{provider:"claude",selected:t==="claude",status:p,agentCliLoaded:!!e,onClick:()=>o("claude")}),v.jsx(HN,{provider:"codex",selected:t==="codex",status:y,agentCliLoaded:!!e,onClick:()=>o("codex")})]}),v.jsx("div",{className:"relative min-w-0 rounded-md border border-border bg-muted/20 px-3 py-2.5 md:p-3","data-slot":"agent-cli-path-card",children:r===t?v.jsx(koe,{provider:r,agentCli:e,cliPathInput:i,savingCliPath:s,onCliPathInputChange:u,onCancel:d,onSave:f}):v.jsx(Toe,{provider:t,selectedCli:g,isDesktop:n,onOpenCliPathEditor:l})})]})}function HN({provider:e,selected:t,status:n,agentCliLoaded:r,onClick:i}){return v.jsxs(pp,{children:[v.jsx(mp,{asChild:!0,children:v.jsxs("button",{type:"button","aria-pressed":t,"aria-label":ha[e],onClick:i,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",t?"border-primary/70 bg-primary/10":"border-border bg-muted/20"),children:[v.jsx("span",{className:"text-sm font-medium",children:ha[e]}),v.jsx("span",{className:Ye("text-xs text-muted-foreground",n.disabled&&r&&"text-destructive"),children:n.label})]})}),v.jsx(gp,{side:"top",className:"max-w-[min(520px,calc(100vw-2rem))]",children:v.jsx("span",{className:"break-all font-mono text-xs",children:woe(e,n)})})]})}function koe({provider:e,agentCli:t,cliPathInput:n,savingCliPath:r,onCliPathInputChange:i,onCancel:s,onSave:o}){return v.jsxs(v.Fragment,{children:[v.jsx("p",{className:"mb-1 text-xs text-muted-foreground",children:"CLI 路径"}),v.jsxs("div",{className:"flex min-w-0 flex-col gap-2 sm:flex-row sm:items-center",children:[v.jsxs("label",{className:"min-w-0 flex-1",children:[v.jsx("span",{className:"sr-only",children:"CLI 路径"}),v.jsx("input",{type:"text",list:`agent-cli-path-${e}`,value:n,onChange:l=>i(l.target.value),onKeyDown:l=>{l.key==="Enter"&&(l.preventDefault(),o()),l.key==="Escape"&&(l.preventDefault(),s())},placeholder:e==="claude"?"/path/to/claude":"/path/to/codex",className:"min-h-11 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 md:h-10 md:min-h-0 md:text-sm"}),v.jsx("datalist",{id:`agent-cli-path-${e}`,children:((t==null?void 0:t[e].suggestions)??[]).map(l=>v.jsx("option",{value:l},l))})]}),v.jsxs("div",{className:"flex shrink-0 justify-end gap-2",children:[v.jsx(At,{type:"button",variant:"ghost",className:"min-h-11 shrink-0 rounded px-2.5 text-xs font-medium text-muted-foreground hover:text-foreground md:h-8 md:min-h-0",onClick:s,disabled:r,children:"取消"}),v.jsx(At,{type:"button",className:"min-h-11 shrink-0 rounded px-2.5 text-xs font-medium md:h-8 md:min-h-0",onClick:o,disabled:r||!n.trim(),children:r?"保存中...":"保存路径"})]})]})]})}function Toe({provider:e,selectedCli:t,isDesktop:n,onOpenCliPathEditor:r}){return n?v.jsxs(v.Fragment,{children:[v.jsx("p",{className:"mb-1 text-xs text-muted-foreground",children:"CLI 路径"}),v.jsxs("div",{className:"flex min-w-0 flex-col gap-2 md:flex-row md:items-center",children:[v.jsx("p",{className:Ye("flex h-10 min-w-0 flex-1 items-center truncate font-mono text-sm",t!=null&&t.available?"text-foreground":"text-destructive"),title:(t==null?void 0:t.command)??(t==null?void 0:t.error),children:(t==null?void 0:t.command)??(t==null?void 0:t.error)??"等待检测结果"}),v.jsx(At,{type:"button",variant:"outline",className:"h-8 min-h-0 shrink-0 self-end rounded px-2.5 text-xs font-medium text-muted-foreground hover:text-foreground sm:self-auto",onClick:()=>r(e),children:"指定路径"})]})]}):v.jsxs(v.Fragment,{children:[v.jsx("p",{className:"pr-11 text-xs text-muted-foreground",children:"CLI 路径"}),v.jsx(At,{type:"button",variant:"ghost",size:"icon",className:"absolute right-1 top-1/2 size-11 -translate-y-1/2 rounded-full text-muted-foreground hover:bg-accent/70 hover:text-foreground","aria-label":"指定路径",onClick:()=>r(e),children:v.jsx(f7,{className:"size-4","aria-hidden":"true"})}),v.jsx("p",{className:Ye("mt-1 min-w-0 break-all pr-11 font-mono text-sm leading-5",t!=null&&t.available?"text-foreground":"text-destructive"),title:(t==null?void 0:t.command)??(t==null?void 0:t.error),children:(t==null?void 0:t.command)??(t==null?void 0:t.error)??"等待检测结果"})]})}function ih({open:e,onOpenChange:t}){const[n,r]=_.useState(""),[i,s]=_.useState(""),[o,l]=_.useState("claude"),[u,d]=_.useState("pty"),[f,p]=_.useState("default"),[y,g]=_.useState(!1),[b,w]=_.useState(!1),[S,E]=_.useState(null),[k,T]=_.useState(!1),[R,P]=_.useState(null),[A,H]=_.useState(""),[D,K]=_.useState(!1),q=_.useRef(null),X=_.useRef(e);X.current=e;const z=so(),N=hi(me=>me.homePath),$=hi(me=>me.agentCli),I=Cl("(min-width: 768px)");_.useEffect(()=>{e&&!i&&N&&s(N)},[e,N,i]),_.useEffect(()=>{if(!e||N&&$)return;const me=Ut==null?void 0:Ut.requestProxyInfo();me&&me.then(Ee=>{const Oe=hi.getState();Oe.setHomePath(Ee.homePath),Oe.setAgentCli(Ee.agentCli)}).catch(Ee=>{console.error("[create-session-dialog] requestProxyInfo failed",Ee)})},[e,N,$]),_.useEffect(()=>{if(!k)return;function me(Ee){var Se;const Oe=Ee.target;Oe instanceof Node&&((Se=q.current)!=null&&Se.contains(Oe))||window.setTimeout(()=>T(!1),0)}return document.addEventListener("pointerdown",me,!0),()=>document.removeEventListener("pointerdown",me,!0)},[k]);function M(){r(""),s(""),T(!1),l("claude"),d("pty"),p("default"),g(!1),E(null),P(null),H(""),K(!1)}function O(){if(f==="bypassPermissions"){g(!0);return}j()}async function U(){await j(),X.current&&g(!1)}const B=o==="codex"?X3:boe,L=wv(o,$),Y=b||D||L.disabled;function V(me){const Ee=Soe(me,f);Ee!==f&&p(Ee)}async function j(me){E(null),w(!0);try{const Ee=await xoe({relay:Ut,agentCli:$,form:{cwd:me??i,name:n,provider:o,permissionMode:f,mode:u}});if(Ee.type==="success"){if(Ft.getState().addSession(Ee.session),!X.current)return;t(!1),M(),z(Ee.route);return}if(Ee.type==="missing_cwd"&&E(Ee.path),nt.error(Ee.message),Ee.type==="validation_error"||Ee.type==="relay_missing")return}finally{w(!1)}}async function te(me){const Ee=Ut;if(!Ee)return nt.error("请先连接开发机"),null;try{const Oe=await Ee.createDirectory(me);return Oe.success?(s(Oe.path),E(null),nt.success("目录已创建"),Oe.path):(nt.error(`目录创建失败:${Oe.error??"未知错误"}`),null)}catch(Oe){return nt.error(Oe instanceof Error?Oe.message:String(Oe)),null}}function re(me){var Oe;const Ee=$==null?void 0:$[me];P(me),H((Ee==null?void 0:Ee.command)??((Oe=Ee==null?void 0:Ee.suggestions)==null?void 0:Oe[0])??"")}async function oe(){if(!R)return;const me=A.trim();if(!me){nt.error("请输入 Agent CLI 路径");return}const Ee=Ut;if(!Ee){nt.error("请先连接开发机");return}K(!0);try{const Oe=await Ee.updateAgentCliPath(R,me);if(Oe.error||!Oe.agentCli){nt.error(`路径保存失败:${Oe.error??"未知错误"}`);return}hi.getState().setAgentCli(Oe.agentCli),nt.success(`${ha[R]} 路径已保存`),P(null),H("")}catch(Oe){nt.error(Oe instanceof Error?Oe.message:String(Oe))}finally{K(!1)}}function ee(me){d(me),V(o)}function pe(me){var Oe;const Ee=me.relatedTarget;Ee instanceof Node&&((Oe=q.current)!=null&&Oe.contains(Ee))||window.setTimeout(()=>T(!1),0)}const ae=y?v.jsxs("div",{className:"grid min-w-0 gap-5","data-slot":"bypass-permission-confirmation",children:[v.jsx(Y3,{providerLabel:ha[o]}),v.jsxs(Mc,{children:[v.jsx(At,{type:"button",variant:"ghost",className:"min-h-11 md:min-h-0",onClick:()=>g(!1),disabled:b,children:"返回"}),v.jsx(At,{type:"button",variant:"destructive",className:"min-h-11 md:min-h-0",onClick:()=>void U(),disabled:b,"data-slot":"bypass-permission-confirm",children:b?"创建中...":"确认"})]})]}):v.jsxs("form",{className:"flex min-w-0 flex-col gap-4","data-slot":"create-session-form",autoComplete:"off",onSubmit:me=>{me.preventDefault(),O()},children:[v.jsxs("label",{className:"flex min-w-0 flex-col gap-1",children:[v.jsx("span",{className:"text-sm",children:"名称(可选)"}),v.jsx("input",{type:"text",name:"dev-anywhere-session-name",autoComplete:"off",autoCorrect:"off",spellCheck:!1,value:n,onChange:me=>r(me.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:"自动生成"})]}),v.jsxs("div",{ref:q,className:"relative flex min-w-0 flex-col gap-2",onBlur:pe,children:[v.jsx("span",{id:"create-session-cwd-label",className:"text-sm",children:"工作目录"}),v.jsx("input",{id:"create-session-cwd",type:"text","aria-labelledby":"create-session-cwd-label",name:"dev-anywhere-session-cwd",autoComplete:"off",autoCorrect:"off",spellCheck:!1,value:i,onFocus:()=>T(!0),onChange:me=>{s(me.target.value),E(null)},placeholder:"输入绝对路径",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 md:h-9 md:min-h-0 md:text-sm"}),k?v.jsx(G3,{mode:"select",dirsOnly:!0,filter:i,title:"选择下一级目录",onCreateDirectory:te,onSelect:me=>{s(me),E(null),T(!0)}}):null]}),S?v.jsxs("section",{role:"status","aria-live":"polite",className:"rounded-md border border-primary/50 bg-primary/10 p-3",children:[v.jsx("p",{className:"text-sm font-medium",children:"工作目录不存在"}),v.jsx("p",{className:"mt-1 break-all font-mono text-xs text-muted-foreground",children:S})]}):null,v.jsxs("section",{"aria-label":"交互方式",className:"flex min-w-0 flex-col gap-2",children:[v.jsx("span",{className:"text-sm",children:"交互方式"}),v.jsxs("div",{className:"grid min-w-0 grid-cols-1 gap-2 sm:grid-cols-2",children:[v.jsxs("button",{type:"button","aria-pressed":u==="pty",onClick:()=>ee("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:[v.jsx("span",{className:"text-sm font-medium",children:"终端模式"}),v.jsx("span",{className:"text-xs text-muted-foreground",children:"像本地终端一样操作"})]}),v.jsxs("button",{type:"button","aria-pressed":u==="json",onClick:()=>ee("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:[v.jsx("span",{className:"text-sm font-medium",children:"聊天模式"}),v.jsx("span",{className:"text-xs text-muted-foreground",children:"气泡式对话,支持 Voice Pilot"})]})]})]}),v.jsx(Coe,{agentCli:$,provider:o,isDesktop:I,editingCliProvider:R,cliPathInput:A,savingCliPath:D,onProviderChange:me=>{l(me),V(me)},onOpenCliPathEditor:re,onCliPathInputChange:H,onCancelCliPathEditor:()=>{P(null),H("")},onSaveCliPath:()=>void oe()}),v.jsxs("label",{className:"flex min-w-0 flex-col gap-2",children:[v.jsx("span",{className:"text-sm",children:"权限模式"}),v.jsxs(aoe,{value:f,onValueChange:me=>p(me),children:[v.jsx(coe,{className:"w-full",children:v.jsx(loe,{})}),v.jsx(uoe,{children:B.map(me=>v.jsx(doe,{value:me.value,children:me.label},me.value))})]})]}),v.jsxs(Mc,{children:[v.jsx(At,{type:"button",variant:"ghost",className:"min-h-11 md:min-h-0",onClick:()=>t(!1),disabled:b,children:"取消"}),v.jsx(At,{type:"submit",className:"min-h-11 md:min-h-0",disabled:Y,children:b?"创建中...":"创建"})]})]});return I?v.jsx(Bl,{open:e,onOpenChange:t,children:v.jsxs(zl,{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:[v.jsx(jl,{children:v.jsx(ba,{children:y?"跳过全部审批?":"新建会话"})}),ae]})}):v.jsx(vy,{open:e,onOpenChange:t,children:v.jsxs(yy,{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:[v.jsx(gE,{className:"px-0 pb-1 pt-0 text-left",children:v.jsx(by,{children:y?"跳过全部审批?":"新建会话"})}),ae]})})}function sh({open:e,sessionId:t,initialName:n,onOpenChange:r,onRename:i}){const s=_.useMemo(()=>(n==null?void 0:n.trim())??"",[n]),[o,l]=_.useState(s),[u,d]=_.useState(null),[f,p]=_.useState(!1);_.useEffect(()=>{e&&(l(s),d(null),p(!1))},[s,e]);async function y(g){g.preventDefault();const b=o.trim();if(!b){d("会话标题不能为空");return}if(t){p(!0);try{await i(t,b),r(!1)}catch(w){d(w instanceof Error?w.message:String(w))}finally{p(!1)}}}return v.jsx(Bl,{open:e,onOpenChange:r,children:v.jsx(zl,{className:"sm:max-w-md","data-slot":"session-rename-dialog",children:v.jsxs("form",{className:"grid gap-4",onSubmit:g=>void y(g),children:[v.jsxs(jl,{children:[v.jsx(ba,{children:"重命名会话"}),v.jsx(El,{children:"自定义名称会显示在会话列表和顶部标题中。"})]}),v.jsxs("div",{className:"grid gap-2",children:[v.jsx("label",{htmlFor:"session-rename-title",className:"text-sm font-medium",children:"会话标题"}),v.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?v.jsx("p",{id:"session-rename-error",className:"text-sm text-destructive",children:u}):null]}),v.jsxs(Mc,{children:[v.jsx(At,{type:"button",variant:"outline",onClick:()=>r(!1),children:"取消"}),v.jsx(At,{type:"submit",disabled:f,children:"保存"})]})]})})})}function Roe(e){return(e==null?void 0:e.mode)==="pty"&&e.ptyOwner==="local-terminal"}function Aoe(e){return(e==null?void 0:e.kind)==="terminal"}function Moe(e){return Roe(e)?{title:"断开远程连接?",description:"这只会断开当前页面和本地终端的连接,本地终端里的 Claude Code/Codex 会继续运行。重新接入前,页面不能继续查看或输入这个会话。",confirmLabel:"断开远程连接",destructive:!1}:Aoe(e)?{title:"终止终端?",description:"这会停止当前终端进程,并清理这个终端会话的运行状态。终止后不能继续输入,也无法恢复正在执行的命令。",confirmLabel:"终止终端",destructive:!0}:{title:"终止会话?",description:"这会停止当前 Agent 进程,并清理这个会话的运行状态。终止后不能继续输入,也无法恢复正在执行的任务。",confirmLabel:"终止会话",destructive:!0}}function og({open:e,session:t,onOpenChange:n,onConfirm:r}){const i=Moe(t);function s(){t&&(r(t),n(!1))}return v.jsx(Bl,{open:e,onOpenChange:n,children:v.jsxs(zl,{"data-slot":"session-termination-dialog",children:[v.jsxs(jl,{children:[v.jsx(ba,{children:i.title}),v.jsx(El,{children:i.description})]}),v.jsxs(Mc,{children:[v.jsx(At,{type:"button",variant:"ghost",onClick:()=>n(!1),children:"取消"}),v.jsx(At,{type:"button",variant:i.destructive?"destructive":"default",onClick:s,"data-slot":"session-termination-confirm",children:i.confirmLabel})]})]})})}function Z3(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 Noe(e){if(e.session.state==="error")return"error";const t=Z3(e);return t==="disconnected"?e.session.state:t}function Q3({layout:e}){const t=Ft(te=>te.sessions),n=Ft(te=>te.sessionListLoaded),r=Ft(te=>te.agentStatusBySessionId),i=Ft(te=>te.ptyStateBySessionId),s=Ft(te=>te.renameSession),o=Qt(te=>te.bySessionId),l=N8("/chat/:id"),u=(l==null?void 0:l.params.id)??null,d=De(te=>!!te.selectedProxyId),f=De(te=>te.proxyListLoaded),p=De(te=>te.proxySwitchTarget),y=Ft(te=>te.loadingProxyName),g=p!==null||!f||d&&!n,b=(p==null?void 0:p.name)??y,w=b?`正在连接 ${b}...`:"连接中...",S=so(),[E,k]=_.useState(!1),[T,R]=_.useState(!1),[P,A]=_.useState(null),[H,D]=_.useState(null),{creatingTerminal:K,createTerminal:q}=J3(),[X,z]=_.useState(new Set),[N,$]=_.useState(()=>Date.now());_.useEffect(()=>{const te=setInterval(()=>$(Date.now()),6e4);return()=>clearInterval(te)},[]);function I(te,re){S(`/chat/${te}?mode=${re??"json"}`,{replace:!1})}function M(te){const re=te.sessionId,oe=Ut;if(!oe){nt.error("请先连接开发机");return}oe.sendControl({type:"session_terminate",sessionId:re}),Ft.getState().removeSession(re),Qt.getState().clearSession(re),re===u&&S("/sessions"),(te==null?void 0:te.mode)==="pty"&&te.ptyOwner==="local-terminal"?nt.info("已断开页面连接,本地终端仍在运行"):nt.info("正在终止会话",{duration:1500})}async function O(te,re){const oe=Ut;if(!oe)throw new Error("请先连接开发机");const ee=await oe.renameSession(te,re);if(!ee.success)throw new Error(ee.error??"重命名失败");s(te,ee.name??re),nt.success("已重命名会话")}function U(te){z(re=>{const oe=new Set(re);return oe.has(te)?oe.delete(te):oe.add(te),oe})}function B(te){var ee;const re=te.mode==="json"&&(((ee=o[te.sessionId])==null?void 0:ee.pendingApprovals.some(pe=>pe.status==="pending"))??!1),oe=Noe({session:te,agentStatus:r[te.sessionId],ptyState:i[te.sessionId],hasPendingApproval:re});return oe===te.state?te:{...te,state:oe}}const L=t.length>0;if(e==="sidebar"&&(g||!d))return v.jsxs(v.Fragment,{children:[v.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:"请先连接开发机"}),v.jsx(ih,{open:E,onOpenChange:k}),v.jsx(og,{open:H!==null,session:H,onOpenChange:te=>{te||D(null)},onConfirm:M}),v.jsx(sh,{open:P!==null,sessionId:(P==null?void 0:P.sessionId)??null,initialName:P==null?void 0:P.name,onOpenChange:te=>{te||A(null)},onRename:O})]});if(e==="page"&&g)return v.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:[v.jsx(fa,{className:"h-5 w-5 animate-spin","aria-hidden":!0}),v.jsx("p",{className:"max-w-[min(24rem,calc(100%-2rem))] truncate text-sm",children:w})]});if(e==="page"&&!d)return v.jsxs("div",{className:"flex flex-col h-full",children:[v.jsx("div",{className:"flex-1",children:v.jsx(wc,{variant:"no-proxy"})}),v.jsx(ih,{open:E,onOpenChange:k}),v.jsx(og,{open:H!==null,session:H,onOpenChange:te=>{te||D(null)},onConfirm:M}),v.jsx(sh,{open:P!==null,sessionId:(P==null?void 0:P.sessionId)??null,initialName:P==null?void 0:P.name,onOpenChange:te=>{te||A(null)},onRename:O})]});const Y=v.jsxs("h3",{className:"px-4 pt-3 pb-2 text-sm font-semibold text-foreground","data-slot":"active-section-header",children:["活跃会话",L?v.jsxs("span",{className:"ml-1 text-muted-foreground/70 font-normal",children:["· ",t.length]}):null]}),V=L?v.jsx("ul",{role:"list",className:"flex flex-col w-full min-w-0",children:Poe(t).map(te=>v.jsxs("li",{children:[v.jsxs("button",{type:"button",onClick:()=>U(te.provider),"aria-expanded":!X.has(te.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:[v.jsx("span",{className:"font-mono",children:Loe(te.provider)}),v.jsx("span",{className:"h-px flex-1 bg-border/70","aria-hidden":"true"}),v.jsx("span",{className:"tabular-nums",children:te.sessions.length}),v.jsx(gh,{className:Ye("size-3.5 shrink-0 text-muted-foreground/80 transition-transform",!X.has(te.provider)&&"rotate-90"),"aria-hidden":"true"})]}),X.has(te.provider)?null:v.jsx("ul",{role:"list",className:"flex flex-col",children:te.sessions.map(re=>v.jsx(Xse,{session:B(re),selected:re.sessionId===u,now:N,onClick:()=>I(re.sessionId,re.mode),onRename:()=>A(re),onTerminate:()=>D(re)},re.sessionId))})]},te.provider))}):v.jsx("div",{className:"px-4 py-3 text-sm text-muted-foreground/70","data-slot":"active-empty",children:"暂无活跃会话"}),j=v.jsx(roe,{now:N});return e==="page"?v.jsxs("div",{className:"flex flex-col h-full",children:[v.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto overscroll-contain",children:[Y,V,j]}),v.jsx("div",{className:"px-4 pt-4 pb-[calc(env(safe-area-inset-bottom)+1rem)] border-t border-border",children:v.jsxs(At,{className:"min-h-11 w-full md:min-h-0","data-slot":"create-session-mobile-trigger",onClick:()=>R(!0),children:[v.jsx(ID,{"aria-hidden":"true"}),"新建"]})}),v.jsx(Doe,{open:T,creatingTerminal:K,onOpenChange:R,onCreateAgent:()=>{R(!1),k(!0)},onCreateTerminal:()=>void q(()=>R(!1))}),v.jsx(ih,{open:E,onOpenChange:k}),v.jsx(og,{open:H!==null,session:H,onOpenChange:te=>{te||D(null)},onConfirm:M}),v.jsx(sh,{open:P!==null,sessionId:(P==null?void 0:P.sessionId)??null,initialName:P==null?void 0:P.name,onOpenChange:te=>{te||A(null)},onRename:O})]}):v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"dev-sidebar-scroll h-full overflow-y-auto overscroll-contain",children:[Y,V,j]}),v.jsx(ih,{open:E,onOpenChange:k}),v.jsx(og,{open:H!==null,session:H,onOpenChange:te=>{te||D(null)},onConfirm:M}),v.jsx(sh,{open:P!==null,sessionId:(P==null?void 0:P.sessionId)??null,initialName:P==null?void 0:P.name,onOpenChange:te=>{te||A(null)},onRename:O})]})}function Poe(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])=>Ooe(n,r)).map(([n,r])=>({provider:n,sessions:r}))}function Loe(e){return e==="terminal"?"终端":_y(e)}function Ooe(e,t){return e===t?0:e==="terminal"?-1:t==="terminal"?1:W3(e,t)}function J3(){const e=so(),[t,n]=_.useState(!1);async function r(i){if(!t){n(!0);try{const s=await Eoe({relay:Ut});if(s.type!=="success"){nt.error(s.message);return}Ft.getState().addSession(s.session),i==null||i(),e(s.route)}finally{n(!1)}}}return{creatingTerminal:t,createTerminal:r}}function UN({compact:e=!1}){const[t,n]=_.useState(!1),[r,i]=_.useState(!1),s=_.useRef(!1),o=De(E=>!!E.selectedProxyId),l=De(E=>E.proxySwitchTarget!==null),u=o&&!l,{creatingTerminal:d,createTerminal:f}=J3();function p(){i(!0),window.setTimeout(()=>i(!1),2e3)}function y(){if(!u){p();return}s.current=!0,n(!0)}function g(){if(!u){p();return}s.current=!0,f()}function b(E){E.preventDefault(),p()}const w=v.jsxs(At,{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",!u&&"opacity-50 hover:bg-background"),"aria-label":"新建会话","aria-disabled":!u,onClick:u?void 0:b,children:[v.jsx(ID,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),!e&&v.jsx("span",{className:"truncate",children:"新建"})]}),S=u?v.jsxs(vE,{children:[v.jsx(yE,{asChild:!0,children:w}),v.jsxs(bE,{align:e?"end":"start",className:"w-52","data-slot":"create-session-type-menu",onCloseAutoFocus:E=>{s.current&&(s.current=!1,E.preventDefault())},children:[v.jsxs(ko,{className:"min-h-9 gap-2.5","data-slot":"create-agent-session-item",onSelect:y,children:[v.jsx(DD,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),"Agent 会话"]}),v.jsxs(ko,{className:"min-h-9 gap-2.5","data-slot":"create-terminal-session-item",disabled:d,onSelect:g,children:[v.jsx(Ah,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),d?"正在创建终端会话...":"终端会话"]})]})]}):w;return v.jsxs(v.Fragment,{children:[u?S:v.jsxs(pp,{open:u?void 0:r,onOpenChange:u?void 0:i,children:[v.jsx(mp,{asChild:!0,children:S}),v.jsx(gp,{side:"top",children:l?"正在切换开发机":"请先连接开发机"})]}),v.jsx(ih,{open:t,onOpenChange:n})]})}function Doe({open:e,creatingTerminal:t,onOpenChange:n,onCreateAgent:r,onCreateTerminal:i}){const s=_.useRef(!1);function o(l){s.current=!0,l()}return v.jsx(vy,{open:e,onOpenChange:n,children:v.jsxs(yy,{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:l=>{s.current&&(s.current=!1,l.preventDefault())},children:[v.jsx(gE,{className:"px-1 pb-1 pt-0 text-left",children:v.jsx(by,{children:"新建"})}),v.jsxs("div",{className:"grid gap-2 pb-1","data-slot":"create-session-type-options",children:[v.jsxs(At,{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:()=>o(r),children:[v.jsx(DD,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),"Agent 会话"]}),v.jsxs(At,{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:()=>o(i),children:[v.jsx(Ah,{className:"size-4 text-muted-foreground","aria-hidden":"true"}),t?"正在创建终端会话...":"终端会话"]})]})]})})}const Ioe="0.7.0",Boe={version:Ioe},zoe={playback:"playback",capture:"play-and-record"};function joe(){return typeof navigator>"u"?null:navigator.audioSession??null}function $oe(){return{setMode:()=>{},release:()=>{}}}class Foe{constructor(t=joe){_t(this,"leases",new Map);_t(this,"session",null);_t(this,"baselineType",null);_t(this,"nextLeaseId",1);_t(this,"nextOrder",1);this.getAudioSession=t}acquire(t){const n=this.getAudioSession();if(!n)return $oe();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(zoe[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 wE=new Foe,ES=64,WN=-60,e5=32;function qN(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-WN)/-WN));return e<0?-r:r}function YN(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 Hoe(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 Uoe(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 t5{constructor(t,n=24e3,r={}){_t(this,"nextStartTime",0);_t(this,"activityEndToken",0);_t(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=Hoe(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*e5/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=Uoe(n.subarray(l,u));this.scheduleTimer(()=>{var g,b,w,S;(b=(g=this.options).onActivityLevel)==null||b.call(g,y),(S=(w=this.options).onPlaybackChunk)==null||S.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 Tw={provider:"aliyun-bailian",configured:!1,region:"cn",asrModel:"qwen3-asr-flash-realtime",ttsModel:"cosyvoice-v3-flash",ttsVoice:"longanyang",turnIdleSeconds:3},VN="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",Woe=800,KN=300,qoe=1600;function CS(e,t){return e.filter(n=>!n.model||n.model===t)}function GN({label:e,children:t,help:n}){return v.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:[v.jsx("span",{className:"block text-[13px] font-medium leading-none text-muted-foreground",children:e}),v.jsx("div",{className:"mt-2 min-w-0",children:t}),n?v.jsx("span",{className:"mt-2 block text-xs leading-relaxed text-muted-foreground",children:n}):null]})}function ag({label:e,value:t,options:n,onChange:r,placeholder:i="请选择",help:s}){const[o,l]=_.useState(!1),u=_.useId(),d=n.find(g=>g.value===t),f=(d==null?void 0:d.label)??(t||i),p=n.filter(g=>!g.disabled),y=!!n5(f).detail;return v.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:[v.jsx("div",{id:u,className:"text-[13px] font-medium leading-none text-muted-foreground",children:e}),v.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:[v.jsx(XN,{label:f,muted:!d&&!t}),v.jsx(Al,{className:`size-4 shrink-0 text-muted-foreground transition-transform ${o?"rotate-180":""}`,"aria-hidden":"true"})]}),o?v.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 b=g.value===t;return v.jsxs("button",{type:"button",role:"option","aria-label":g.label,"aria-selected":b,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:[v.jsx("span",{className:"flex size-4 shrink-0 items-center justify-center text-primary",children:b?v.jsx(pa,{className:"size-4","aria-hidden":"true"}):null}),v.jsx(XN,{label:g.label})]},g.value)})}):null,s?v.jsx("div",{className:"mt-2 text-xs leading-relaxed text-muted-foreground",children:s}):null]})}function XN({label:e,muted:t=!1}){const n=n5(e);return v.jsxs("span",{className:"min-w-0 flex-1",children:[v.jsx("span",{className:`block truncate text-base leading-6 md:text-sm ${t?"text-muted-foreground":"text-foreground"}`,children:n.title}),n.detail?v.jsx("span",{className:"mt-0.5 block truncate text-xs leading-4 text-muted-foreground",children:n.detail}):null]})}function Yoe({scrollRef:e}={}){const[t,n]=_.useState(Tw),[r,i]=_.useState(String(Tw.turnIdleSeconds)),[s,o]=_.useState(()=>Gm()),[l,u]=_.useState(""),[d,f]=_.useState(!1),[p,y]=_.useState(!1),[g,b]=_.useState({kind:"idle"}),w=_.useRef(null),S=_.useRef(null),E=_.useRef(null),k=_.useRef(null),T=_.useRef(null),R=_.useRef(!1);_.useEffect(()=>{const ee=Ut;if(!ee){b({kind:"error",message:"请先连接 Relay 服务器"});return}let pe=!1;return b({kind:"loading"}),ee.requestVoiceConfig().then(ae=>{if(!pe){if(ae.error||!ae.config){b({kind:"error",message:ae.error??"读取语音设置失败"});return}n(ae.config),i(String(ae.config.turnIdleSeconds)),u(""),f(!1),y(!0),b({kind:"idle"})}}).catch(ae=>{pe||b({kind:"error",message:ae instanceof Error?ae.message:"读取语音设置失败"})}),()=>{pe=!0}},[]),_.useEffect(()=>{const ee=Ut;if(!ee||!p)return;let pe=!1;return ee.requestVoiceCapabilities({region:t.region}).then(ae=>{if(!pe){if(ae.error||!ae.capabilities){o(Gm());return}o(ae.capabilities)}}).catch(()=>{pe||o(Gm())}),()=>{pe=!0}},[t.region,p]),_.useEffect(()=>(R.current=!0,()=>{R.current=!1,j(),te()}),[]);const P=_.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]),A=g.kind==="saving"||g.kind==="loading"||g.kind==="testing"||g.kind==="playingTest",H=_.useMemo(()=>CS(s.ttsVoices,t.ttsModel),[s.ttsVoices,t.ttsModel]),K=H.some(ee=>ee.value===t.ttsVoice)?t.ttsVoice:"",q=H.length===0?"当前模型暂无可用音色":K?null:"请选择可用音色",X=_.useMemo(()=>Xoe(r),[r]),z=X?null:"请输入正整数秒数",N=q??z,$=A||!!N,I=_.useMemo(()=>[{value:"cn",label:"中国大陆"},{value:"intl",label:"国际"}],[]),M=_.useMemo(()=>JN(s.asrModels,t.asrModel),[s.asrModels,t.asrModel]),O=_.useMemo(()=>Zoe(s.ttsModels,s.ttsVoices,t.ttsModel),[s.ttsModels,s.ttsVoices,t.ttsModel]),U=_.useMemo(()=>JN(H,K),[H,K]);function B(){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:X??Tw.turnIdleSeconds}}async function L(){if(A)return;if(N){b({kind:"error",message:N});return}const ee=Ut;if(!ee){b({kind:"error",message:"请先连接 Relay 服务器"});return}const pe=B();te(),b({kind:"saving"});const ae=performance.now();try{const me=await ee.updateVoiceConfig(pe);if(!R.current)return;const Ee=performance.now()-ae;if(Ee<KN&&await Goe(KN-Ee),!R.current)return;if(!me.success||me.error||!me.config){b({kind:"error",message:me.error??"保存语音设置失败"});return}n(me.config),i(String(me.config.turnIdleSeconds)),u(""),f(!1),b({kind:"saved"}),T.current=setTimeout(()=>{T.current=null,b(Oe=>Oe.kind==="saved"?{kind:"idle"}:Oe)},qoe),ee.requestVoiceCapabilities({region:me.config.region}).then(Oe=>{R.current&&Oe.capabilities&&o(Oe.capabilities)}).catch(()=>{R.current&&o(Gm())})}catch(me){if(!R.current)return;b({kind:"error",message:me instanceof Error?me.message:"保存语音设置失败"})}}async function Y(){if(A)return;if(N){b({kind:"error",message:N});return}const ee=Ut;if(!ee){b({kind:"error",message:"请先连接 Relay 服务器"});return}let pe;try{pe=V()}catch(ae){b({kind:"error",message:QN(ae)});return}b({kind:"testing"});try{const[ae]=await Promise.all([ee.testVoiceConfig(B()),pe.ready]);if(!ae.success||ae.error){j(),b({kind:"error",message:ae.error??"语音配置测试失败"});return}const me=await re(ae,pe.context);b({kind:"playingTest",transcript:ae.transcript}),k.current=setTimeout(()=>{k.current=null,j(),b({kind:"testPassed",transcript:ae.transcript})},me)}catch(ae){j(),b({kind:"error",message:QN(ae)})}}function V(){j();const ee=wE.acquire("playback");S.current=ee;try{const pe=Koe();return w.current=pe,{context:pe,ready:ZN(pe)}}catch(pe){throw ee.release(),S.current=null,pe}}function j(){var ee,pe,ae;k.current&&(clearTimeout(k.current),k.current=null),(ee=E.current)==null||ee.stop(),E.current=null,(pe=w.current)==null||pe.close(),w.current=null,(ae=S.current)==null||ae.release(),S.current=null}function te(){T.current&&(clearTimeout(T.current),T.current=null)}async function re(ee,pe){if(!ee.audioBase64)throw new Error("语音测试未返回可播放音频");if(ee.audioEncoding&&ee.audioEncoding!=="pcm_s16le")throw new Error("测试音频格式暂不支持");const ae=ee.audioSampleRate??24e3,me=Voe(ee.audioBase64);if(me.byteLength===0||me.byteLength%2!==0)throw new Error("测试音频数据无效");await ZN(pe);const Ee=new t5(pe,ae);E.current=Ee,Ee.enqueue(me);const Oe=Math.ceil(me.byteLength/2/ae*1e3);return Math.max(Woe,Oe)}function oe(ee){var pe;return((pe=CS(s.ttsVoices,ee)[0])==null?void 0:pe.value)??""}return v.jsxs("form",{className:"flex min-h-0 min-w-0 flex-1 flex-col","data-slot":"voice-settings-panel",autoComplete:"off",onSubmit:ee=>{ee.preventDefault(),L()},children:[v.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:v.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:v.jsxs("div",{className:"space-y-3","data-slot":"voice-settings-fields",children:[v.jsx("div",{className:"grid gap-2 rounded-lg border border-border/75 bg-card/55 p-3.5 sm:p-3",children:v.jsxs("div",{className:"flex items-center justify-between gap-3",children:[v.jsxs("div",{className:"min-w-0",children:[v.jsx("div",{className:"text-[13px] font-medium leading-none text-muted-foreground",children:"服务商"}),v.jsx("div",{className:"mt-2 truncate text-base font-medium text-foreground md:text-sm",children:"阿里云百炼"})]}),v.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"})]})}),v.jsx(GN,{label:"阿里云百炼 API Key",help:d?"保存后会清空已保存的 key":null,children:v.jsxs("div",{className:"flex min-w-0 gap-2",children:[v.jsxs("div",{className:"relative min-w-0 flex-1",children:[v.jsx(jD,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground","aria-hidden":"true"}),v.jsx("input",{"aria-label":"阿里云百炼 API Key",type:"password",name:"dev-anywhere-bailian-api-key",autoComplete:"off",value:l,onChange:ee=>{u(ee.target.value),f(!1)},placeholder:d?"保存后清空":t.configured?"••••••••••••••••":"输入 API Key",className:`${VN} w-full pl-9`})]}),t.configured&&v.jsxs(At,{type:"button",variant:"outline",className:"min-h-11 shrink-0 px-3 md:h-9 md:min-h-0",onClick:()=>{u(""),f(!0)},children:[v.jsx(D7,{className:"size-4","aria-hidden":"true"}),"清空"]})]})}),v.jsx(ag,{label:"地域",value:t.region,options:I,onChange:ee=>n(pe=>({...pe,region:ee==="intl"?"intl":"cn"}))}),v.jsx(ag,{label:"语音识别模型",value:t.asrModel,options:M,onChange:ee=>n(pe=>({...pe,asrModel:ee}))}),v.jsx(ag,{label:"语音合成模型",value:t.ttsModel,options:O,onChange:ee=>n(pe=>({...pe,ttsModel:ee,ttsVoice:oe(ee)}))}),v.jsx(ag,{label:"语音音色",value:K,options:U,placeholder:H.length===0?"暂无可用音色":"请选择音色",onChange:ee=>n(pe=>({...pe,ttsVoice:ee})),help:q}),v.jsx(GN,{label:"结束停顿时间(秒)",help:z,children:v.jsx("input",{"aria-label":"结束停顿时间(秒)",type:"number",min:1,step:1,inputMode:"numeric",value:r,onChange:ee=>i(ee.target.value),className:`${VN} w-full`})})]})})}),v.jsxs("div",{className:"bg-background/95 px-4 pb-3.5 pt-0 backdrop-blur sm:px-5","data-slot":"voice-settings-footer",children:[v.jsx("div",{className:"mr-4 border-t border-border/70","data-slot":"voice-settings-footer-divider"}),v.jsxs("div",{className:"mt-3.5 flex items-center justify-end gap-2",children:[P?v.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,v.jsxs(At,{type:"button",variant:"outline",disabled:$,onClick:()=>void Y(),children:[v.jsx(HD,{className:"size-4","aria-hidden":"true"}),"测试"]}),v.jsxs(At,{type:"submit",disabled:$,children:[v.jsx(S7,{className:"size-4","aria-hidden":"true"}),g.kind==="saving"?"保存中...":"保存"]})]})]})]})}function Voe(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 Koe(){const e=window,t=e.AudioContext??e.webkitAudioContext;if(!t)throw new Error("当前浏览器不支持音频播放");return new t}async function ZN(e){if(e.state!=="running")try{await e.resume()}catch{throw new Error("浏览器阻止了测试音频播放,请再次点击测试")}if(e.state!=="running")throw new Error("浏览器阻止了测试音频播放,请再次点击测试")}function QN(e){return e instanceof Error?e.message:"语音配置测试失败"}function Goe(e){return new Promise(t=>setTimeout(t,e))}function Xoe(e){const t=e.trim();if(!/^[1-9]\d*$/.test(t))return null;const n=Number(t);return Number.isSafeInteger(n)?n:null}function JN(e,t){const n=e.map(r=>({value:r.value,label:r5(r)}));return!t||n.some(r=>r.value===t)?n:[{value:t,label:t},...n]}function Zoe(e,t,n){const r=e.map(i=>{const s=CS(t,i.value).length===0;return{value:i.value,label:`${r5(i)}${s?" · 暂无音色":""}`,disabled:s}});return!n||r.some(i=>i.value===n)?r:[{value:n,label:`${n} · 暂无音色`,disabled:!0},...r]}function n5(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 r5(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 Qoe=[{value:"auto",label:"跟随系统"},{value:"light",label:"浅色"},{value:"dark",label:"深色"}],Joe=[{value:"auto",label:"自动"},{value:"touch",label:"触控优先"},{value:"hardware",label:"实体键盘优先"}],SE="dev-render-scroll min-h-0 space-y-3 overflow-y-auto overscroll-contain pr-4 sm:pr-1";function i5(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 eae(e){const t=e||window.location.origin;return new URL("/health",t).toString()}function tae(e){return e==="version"?"版本":e==="relay-token"?"Relay Token":e==="clients"?"客户端管理":"设置 Voice Pilot"}function nae(e){return e==="version"?"Web 与 Relay 服务器版本。":e==="relay-token"?"连接受保护的 Relay 服务器,保存后立即重连。":e==="clients"?"管理当前连接的 Web 客户端。":"连接语音服务后,即可以语音交互的形式驱动会话。"}function kS({open:e,onOpenChange:t}){const n=De(K=>K.relayUrl),r=De(K=>K.latencyMonitorEnabled),i=De(K=>K.setLatencyMonitorEnabled),s=De(K=>K.sessionIdleNotificationsEnabled),o=De(K=>K.setSessionIdleNotificationsEnabled),l=De(K=>K.inputModePreference),u=De(K=>K.setInputModePreference),d=De(K=>K.themePreference),f=De(K=>K.setThemePreference),p=De(K=>K.ptyScrollTraceEnabled),y=De(K=>K.setPtyScrollTraceEnabled),[g,b]=_.useState("menu"),[w,S]=_.useState({kind:"idle"}),E=_.useRef(null),k=_.useRef(null),T=KJ(),R=_.useMemo(()=>ip().osName==="iPad",[]),P=_.useCallback(async K=>{if(!K){o(!1);return}const q=await EJ();if(q==="granted"){o(!0);return}if(q==="denied"){nt.error("浏览器未授予通知权限,请在浏览器设置中允许通知");return}if(q==="default"){nt.info("未授予通知权限,会话通知保持关闭");return}nt.error("当前浏览器不支持系统通知")},[o]),A=_.useCallback(async K=>{S({kind:"loading"});try{const q=await fetch(eae(n),{cache:"no-store",signal:K});if(!q.ok)throw new Error(`HTTP ${q.status}`);const X=await q.json();if(X.status!=="ok")throw new Error("状态异常");S({kind:"ready",version:X.version??"未知",uptime:X.uptime??0})}catch(q){if(q instanceof DOMException&&q.name==="AbortError")return;S({kind:"error",message:q instanceof Error?"当前 Relay 服务器无法读取版本":"读取失败"})}},[n]);_.useEffect(()=>{if(!e){b("menu");return}},[e]),_.useEffect(()=>{if(!e||g!=="version")return;const K=new AbortController;return A(K.signal),()=>K.abort()},[A,e,g]),_.useEffect(()=>{if(!e||g!=="voice")return;const K=window.requestAnimationFrame(()=>{var q;(q=E.current)==null||q.focus({preventScroll:!0}),k.current&&(k.current.scrollTop=0)});return()=>window.cancelAnimationFrame(K)},[e,g]);const H=w.kind==="ready"?w.version:w.kind==="loading"?"读取中...":w.kind==="error"?"读取失败":"未读取",D=w.kind==="ready"?`运行 ${i5(w.uptime)}`:w.kind==="error"?w.message:"从当前 Relay 服务器 /health 读取";return v.jsx(Bl,{open:e,onOpenChange:t,children:v.jsxs(zl,{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:E,showCloseButton:g==="menu",children:[v.jsx(jl,{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"?v.jsxs(v.Fragment,{children:[v.jsxs("div",{className:"flex items-start gap-2",children:[v.jsx(At,{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:()=>b("menu"),children:v.jsx(Uv,{className:"size-4","aria-hidden":"true"})}),v.jsxs("div",{className:"min-w-0 space-y-1.5 pt-0.5 text-left",children:[v.jsx(ba,{children:tae(g)}),v.jsx(El,{className:"max-w-[28rem] leading-5",children:nae(g)})]})]}),g==="voice"?v.jsx("div",{className:"mr-4 mt-3.5 border-t border-border/70","data-slot":"voice-settings-header-divider"}):null]}):v.jsxs(v.Fragment,{children:[v.jsx(ba,{children:"设置"}),v.jsx(El,{children:"连接、外观、通知和高级诊断选项。"})]})}),g==="version"?v.jsx(rae,{relayVersion:H,relayDetail:D,relayMuted:w.kind==="error"}):g==="relay-token"?v.jsx(sae,{saved:T}):g==="clients"?v.jsx(uae,{}):g==="voice"?v.jsx(Yoe,{scrollRef:k}):v.jsx(iae,{relayTokenSaved:T,themePreference:d,onThemePreferenceChange:f,inputModePreference:l,onInputModePreferenceChange:u,showInputModeSetting:R,sessionIdleNotificationsEnabled:s,onSessionIdleNotificationsEnabledChange:P,ptyScrollTraceEnabled:p,onPtyScrollTraceEnabledChange:y,latencyMonitorEnabled:r,onLatencyMonitorEnabledChange:i,onOpenVoice:()=>b("voice"),onOpenRelayToken:()=>b("relay-token"),onOpenClients:()=>b("clients"),onOpenVersion:()=>b("version")})]})})}function rae({relayVersion:e,relayDetail:t,relayMuted:n}){return v.jsxs("div",{className:SE,"data-slot":"settings-dialog-body",children:[v.jsx(t2,{icon:v.jsx(FD,{className:"size-4","aria-hidden":"true"}),label:"Web",value:Boe.version,detail:"当前浏览器加载的版本"}),v.jsx(t2,{icon:v.jsx(UD,{className:"size-4","aria-hidden":"true"}),label:"Relay 服务器",value:e,detail:t,muted:n})]})}function iae({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:b,onOpenVersion:w}){return v.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:[v.jsxs(Au,{title:"服务",children:[v.jsx(lg,{icon:v.jsx(sW,{className:"size-4","aria-hidden":"true"}),label:"Voice Pilot",detail:"用语音输入、听取回复和处理审批",onClick:y}),v.jsx(lg,{icon:v.jsx(jD,{className:"size-4","aria-hidden":"true"}),label:"Relay Token",detail:`${e?"已保存":"未设置"} · 受保护的 Relay 服务器`,onClick:g}),v.jsx(lg,{icon:v.jsx(H7,{className:"size-4","aria-hidden":"true"}),label:"客户端管理",detail:"已连接的浏览器页面和设备",onClick:b})]}),v.jsx(Au,{title:"外观",children:v.jsx(e2,{icon:v.jsx(P7,{className:"size-4","aria-hidden":"true"}),label:"主题",value:t,options:Qoe,onValueChange:n})}),v.jsx(Au,{title:"通知",children:v.jsx(Aw,{icon:v.jsx(aW,{className:"size-4","aria-hidden":"true"}),label:"会话空闲通知",detail:"会话从工作中转为空闲时发送浏览器通知",checked:o,onCheckedChange:l})}),s?v.jsx(Au,{title:"交互",children:v.jsx(e2,{icon:v.jsx($D,{className:"size-4","aria-hidden":"true"}),label:"输入方式",detail:"默认自动识别软键盘和实体键盘;必要时可强制一种方式",value:r,options:Joe,onValueChange:i})}):null,v.jsxs(Au,{title:"高级诊断",children:[v.jsx(Aw,{icon:v.jsx(Ah,{className:"size-4","aria-hidden":"true"}),label:"PTY 滚动追踪",detail:"记录终端滚动和视口同步现场,方便复制诊断报告",checked:u,onCheckedChange:d}),v.jsx(Aw,{icon:v.jsx(LD,{className:"size-4","aria-hidden":"true"}),label:"延迟监控",detail:"显示可拖动的连接延迟浮窗",checked:f,onCheckedChange:p})]}),v.jsx(Au,{title:"关于",children:v.jsx(lg,{icon:v.jsx(UD,{className:"size-4","aria-hidden":"true"}),label:"版本",onClick:w})})]})}function Au({title:e,children:t}){return v.jsxs("section",{className:"space-y-2","data-slot":"settings-section",children:[v.jsx("h3",{className:"px-1 text-xs font-medium text-muted-foreground",children:e}),v.jsx("div",{className:"overflow-hidden rounded-lg border border-border bg-card/55 divide-y divide-border/70",children:t})]})}function e2({icon:e,label:t,detail:n,value:r,options:i,onValueChange:s}){const o=_.useId(),l=_.useId();return v.jsxs("div",{className:"flex w-full items-start gap-3 px-3 py-3 text-left","data-slot":"settings-choice-item",children:[v.jsx("div",{className:"flex size-8 shrink-0 items-center justify-center rounded-md bg-background/55 text-muted-foreground",children:e}),v.jsxs("div",{className:"min-w-0 flex-1",children:[v.jsx("div",{id:o,className:"text-sm font-medium text-foreground",children:t}),n?v.jsx("div",{id:l,className:"mt-1 text-xs text-muted-foreground",children:n}):null,v.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 v.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 sae({saved:e}){const t=_.useId(),n=_.useId(),[r,i]=_.useState(""),[s,o]=_.useState(null),l=()=>{cB().catch(f=>{o(f instanceof Error?f.message:"Relay 重连失败。")})},u=()=>{const f=r.trim();if(!f){o("请输入 token。");return}if(!aB(f)){const p="Relay Token 保存失败,请检查浏览器存储权限。";o(p),nt.error(p);return}o(null),nt.success("Relay Token 已保存,正在重新连接"),l()},d=()=>{lB(),l()};return v.jsxs("form",{className:SE,"data-slot":"settings-dialog-body",onSubmit:f=>{f.preventDefault(),u()},children:[v.jsxs("div",{className:"rounded-md border border-border bg-card/70 p-3","data-slot":"relay-token-card",children:[v.jsx("label",{htmlFor:t,className:"text-sm font-medium text-foreground",children:"Token"}),v.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?v.jsx("p",{id:n,className:"mt-2 text-xs text-destructive",children:s}):null]}),v.jsxs("div",{className:"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",children:[e?v.jsx(At,{type:"button",variant:"outline",onClick:d,children:"清空"}):null,v.jsx(At,{type:"submit",disabled:!r.trim(),children:"保存"})]})]})}function oae(e){return e.length<=16?e:`${e.slice(0,8)}...${e.slice(-4)}`}function aae(e,t){var r;return((r=t.get(e))==null?void 0:r.trim())||oae(e)}function lae(e){return VZ(e)}function cae(e){const t=Math.max(0,Math.floor((Date.now()-e)/1e3));return i5(t)}function Rw({label:e,value:t,title:n}){return v.jsxs("div",{className:"grid grid-cols-[3.75rem_minmax(0,1fr)] items-baseline gap-2 text-xs leading-5",children:[v.jsx("span",{className:"shrink-0 text-muted-foreground/80",children:e}),v.jsx("span",{className:"min-w-0 truncate text-muted-foreground",title:n??t,children:t})]})}function uae(){const e=De(y=>y.proxies),[t,n]=_.useState([]),[r,i]=_.useState(!0),[s,o]=_.useState(null),[l,u]=_.useState(null),d=_.useMemo(()=>new Map(e.map(y=>[y.proxyId,y.name]).filter(y=>typeof y[1]=="string")),[e]),f=_.useCallback(async()=>{const y=Ut;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)}},[]);_.useEffect(()=>{f()},[f]);const p=_.useCallback(async y=>{const g=Ut;if(!g){o("Relay 未连接。");return}u(y),o(null);try{const b=await g.kickRelayClient(y);if(!b.success){o(b.error??"断开客户端失败。");return}n(w=>w.filter(S=>S.clientId!==y))}catch(b){o(b instanceof Error?b.message:"断开客户端失败。")}finally{u(null)}},[]);return v.jsxs("div",{className:SE,"data-slot":"settings-dialog-body",children:[v.jsxs("div",{className:"flex min-h-9 items-center gap-2","data-slot":"relay-clients-toolbar",children:[v.jsx("div",{className:"text-sm font-medium text-foreground",children:r?"正在读取客户端":`${t.length} 个在线客户端`}),v.jsx(At,{type:"button",variant:"ghost",size:"icon-sm","aria-label":"刷新客户端列表",title:"刷新",onClick:()=>void f(),disabled:r,"data-slot":"relay-clients-refresh",children:v.jsx(m1,{className:Ye("size-3.5",r&&"animate-spin"),"aria-hidden":"true"})})]}),s?v.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?v.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,b=l===y.clientId;return v.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:v.jsxs("div",{className:"grid gap-3 sm:grid-cols-[minmax(0,1fr)_7.5rem] sm:items-start",children:[v.jsxs("div",{className:"min-w-0 space-y-1.5",children:[v.jsx("div",{className:"min-w-0",children:v.jsx("div",{className:"truncate text-sm font-medium leading-5 text-foreground",children:lae(y)})}),v.jsxs("div",{className:"space-y-1",children:[v.jsx(Rw,{label:"已连接",value:cae(y.connectedAt)}),y.proxyId?v.jsx(Rw,{label:"连接到",value:aae(y.proxyId,d),title:y.proxyId}):null,y.remoteAddress?v.jsx(Rw,{label:"来源 IP",value:y.remoteAddress}):null]})]}),g?v.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:"当前设备"}):v.jsxs(At,{type:"button",variant:"outline",size:"sm",className:"h-9 w-full justify-center",disabled:b,onClick:()=>void p(y.clientId),"data-slot":"relay-client-action",children:[v.jsx(QW,{className:"size-3.5","aria-hidden":"true"}),b?"断开中...":"断开"]})]})},y.clientId)})]})}function Aw({icon:e,label:t,detail:n,checked:r,onCheckedChange:i}){const s=_.useId(),o=_.useId();return v.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:[v.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}),v.jsxs("div",{className:"min-w-0 flex-1",children:[v.jsx("div",{id:s,className:"text-sm font-medium text-foreground",children:t}),v.jsx("div",{id:o,className:"mt-1 text-xs text-muted-foreground",children:n})]}),v.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:v.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 lg({icon:e,label:t,detail:n,onClick:r}){const i=_.useId(),s=_.useId();return v.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:[v.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}),v.jsxs("div",{className:"min-w-0 flex-1",children:[v.jsx("div",{id:i,className:"text-sm font-medium text-foreground",children:t}),n?v.jsx("div",{id:s,className:"mt-1 text-xs text-muted-foreground",children:n}):null]}),v.jsx(gh,{className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"})]})}function t2({icon:e,label:t,value:n,detail:r,muted:i=!1}){return v.jsxs("div",{className:"flex gap-3 rounded-md border border-border bg-card/70 p-3",children:[v.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}),v.jsxs("div",{className:"min-w-0 flex-1",children:[v.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[v.jsx("div",{className:"text-sm text-muted-foreground",children:t}),v.jsx("div",{className:"min-w-0 truncate font-mono text-sm text-foreground",children:n})]}),v.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:r})]})]})}const dae="xterm-helper-textarea";function fae(e=document.activeElement){return!(e instanceof HTMLElement)||!e.classList.contains(dae)?!1:(e.blur(),!0)}function n2(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&&hae(r,n))return!0;if(r===t)break;r=r.parentElement}return!1}function hae(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 pae({releasePtyFocus:e=!0,containVerticalScroll:t=!0}={}){const n=_.useRef(null),r=_.useCallback(()=>{e&&fae()},[e]),i=_.useCallback(l=>{var u;n.current=((u=l.touches[0])==null?void 0:u.clientY)??null,r()},[r]),s=_.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,n2(l.target,l.currentTarget,f)||l.preventDefault()},[t]),o=_.useCallback(l=>{r(),t&&(n2(l.target,l.currentTarget,l.deltaY)||l.preventDefault())},[t,r]);return{onPointerDownCapture:r,onTouchStartCapture:i,onTouchMoveCapture:s,onWheelCapture:o}}function mae({className:e}){const t=De(o=>o.sidebarCollapsed),n=De(o=>o.toggleSidebarCollapsed),[r,i]=_.useState(!1),s=pae();return t?v.jsxs(v.Fragment,{children:[v.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:[v.jsx(i2,{collapsed:!0,onClick:n}),v.jsx("div",{className:"mt-3 h-px w-5 bg-border/70","aria-hidden":"true"}),v.jsxs("div",{className:"mt-auto flex flex-col gap-2",children:[v.jsx(r2,{compact:!0,tooltipSide:"right",onClick:()=>i(!0)}),v.jsx(UN,{compact:!0})]})]}),v.jsx(kS,{open:r,onOpenChange:i})]}):v.jsxs(v.Fragment,{children:[v.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:[v.jsx("div",{className:"dev-sidebar-fade p-2.5","data-slot":"sidebar-proxy-switcher",children:v.jsxs("div",{className:"dev-sidebar-chrome rounded-lg border p-3",children:[v.jsxs("div",{className:"flex items-center justify-between gap-3",children:[v.jsx(lI,{className:"text-[13px]",slot:"sidebar-brand"}),v.jsx(i2,{collapsed:!1,onClick:n})]}),v.jsx("div",{className:"mt-2.5",children:v.jsx(U3,{layout:"dropdown",variant:"sidebarChrome"})})]})}),v.jsx("div",{className:"dev-sidebar-fade flex min-h-0 flex-1 flex-col overflow-hidden","data-slot":"sidebar-session-list",children:v.jsx("div",{className:"flex-1 min-h-0",children:v.jsx(Q3,{layout:"sidebar"})})}),v.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:[v.jsx("div",{className:"min-w-0 flex-1",children:v.jsx(UN,{})}),v.jsx("div",{className:"min-w-0 flex-1",children:v.jsx(r2,{onClick:()=>i(!0)})})]})]}),v.jsx(kS,{open:r,onOpenChange:i})]})}function r2({compact:e=!1,tooltipSide:t="top",onClick:n}){return v.jsxs(pp,{delayDuration:500,children:[v.jsx(mp,{asChild:!0,children:v.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:[v.jsx(WD,{className:"size-4","aria-hidden":"true"}),!e&&v.jsx("span",{className:"truncate text-sm font-medium",children:"设置"})]})}),v.jsx(gp,{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 i2({collapsed:e,onClick:t}){const n=e?"展开侧边栏":"收起侧边栏",r=e?l7:o7;return v.jsxs(pp,{delayDuration:500,children:[v.jsx(mp,{asChild:!0,children:v.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:v.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"})})}),v.jsx(gp,{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 gae=1500,vae=300,s2=70,o2=35;function s5({texts:e,className:t}){const[n,r]=_.useState(""),[i,s]=_.useState(!0),o=_.useRef("typing"),l=_.useRef(0),u=_.useRef(0);_.useEffect(()=>{const f=setInterval(()=>s(p=>!p),530);return()=>clearInterval(f)},[]),_.useEffect(()=>{let f;const p=()=>e[u.current%e.length],y=()=>{const g=o.current;if(g==="typing"){const b=p();l.current<b.length?(l.current+=1,r(b.slice(0,l.current)),f=setTimeout(y,s2)):(o.current="paused",f=setTimeout(y,gae))}else g==="paused"?(o.current="deleting",f=setTimeout(y,o2)):g==="deleting"?l.current>0?(l.current-=1,r(p().slice(0,l.current)),f=setTimeout(y,o2)):(u.current+=1,o.current="waiting",f=setTimeout(y,vae)):(o.current="typing",f=setTimeout(y,s2))};return f=setTimeout(y,500),()=>clearTimeout(f)},[e]);const d=n.startsWith("DEV")?3:n.length<=3&&"DEV".startsWith(n)?n.length:0;return v.jsxs("div",{className:`font-mono leading-tight select-none ${t??""}`,"data-slot":"brand-typewriter",children:[v.jsx("span",{className:"text-green-500",children:"> "}),v.jsx("span",{className:"text-primary","data-slot":"brand-typewriter-dev",children:n.slice(0,d)}),v.jsx("span",{className:"text-foreground/90",children:n.slice(d)}),v.jsx("span",{className:`text-primary ${i?"opacity-100":"opacity-0"}`,children:"_"})]})}const o5=["DEV Anywhere","/unlimited @anytime"];function yae({subtitle:e,action:t}){return v.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:v.jsxs("div",{className:"dev-mobile-brand-content min-w-0 space-y-3 pr-12",children:[v.jsx(s5,{texts:o5,className:"dev-mobile-brand-typewriter max-w-full overflow-hidden text-ellipsis whitespace-nowrap font-bold tracking-normal"}),v.jsx("p",{className:"dev-mobile-brand-subtitle max-w-[34rem] text-sm leading-5 text-muted-foreground",children:e}),t?v.jsx("div",{className:"dev-mobile-brand-action flex max-w-full min-w-0 pt-1",children:t}):null]})})}const bae=3e3,_ae=1e4,cg=12,wae=4,a2={webRelay:"浏览器 ↔ Relay 服务器",relayProxy:"Relay 服务器 ↔ 开发机",webProxy:"浏览器 ↔ 开发机"},Sae={webRelay:{state:"idle"},relayProxy:{state:"idle"},webProxy:{state:"idle"}};function Mw(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 Mu(e){return{state:"unavailable",error:e,updatedAt:Date.now()}}function oh(e){return e===void 0||!Number.isFinite(e)?"--":`${Math.max(0,Math.round(e))}ms`}function l2(e){switch(e){case"bad":return 4;case"unavailable":return 3;case"warn":return 2;case"measuring":return 1;default:return 0}}function a5(e){return e==="bad"||e==="unavailable"?"bad":e==="warn"?"warn":e==="ok"?"ok":"neutral"}function xae(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 Eae(e){return e.state==="measuring"?"检测中":e.state==="unavailable"?e.error??"不可用":e.rttMs!==void 0?oh(e.rttMs):"等待检测"}function Cae(){const e=Oi("local",Sn.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 c2(e){Er("local",Sn.latencyMonitorPosition,JSON.stringify(e))}function kae(){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 Nw(e,t){const n=kae(),r=cg,i=cg,s=Math.max(r,n.width-t.width-cg),o=Math.max(i,n.height-t.height-cg);return{x:Math.min(s,Math.max(r,Math.round(e.x))),y:Math.min(o,Math.max(i,Math.round(e.y)))}}function Tae(){const e=De(A=>A.latencyMonitorEnabled),t=De(A=>A.connected),n=De(A=>A.proxyOnline),r=De(A=>A.selectedProxyId),[i,s]=_.useState(Sae),[o,l]=_.useState(()=>Cae()),u=_.useRef(!1),d=_.useRef(null),f=_.useRef(null),p=_.useRef(!1),y=_.useMemo(()=>(Object.values(i).sort((A,H)=>l2(H.state)-l2(A.state))[0]??{state:"idle"}).state,[i]),g=a5(y);async function b(){if(u.current)return;const A=Ut;if(!A||!t){const q=Mu("Relay 服务器未连接");s({webRelay:q,relayProxy:q,webProxy:q});return}u.current=!0,s(q=>({webRelay:{...q.webRelay,state:"measuring"},relayProxy:n?{...q.relayProxy,state:"measuring"}:Mu("未连接开发机"),webProxy:n?{...q.webProxy,state:"measuring"}:Mu("未连接开发机")}));const[H,D,K]=await Promise.allSettled([A.measureWebRelayLatency(),n?A.measureRelayProxyLatency():Promise.resolve({success:!1}),n?A.measureWebProxyLatency():Promise.resolve({success:!1})]);s({webRelay:H.status==="fulfilled"?Mw(H.value):Mu(H.reason instanceof Error?H.reason.message:"测速失败"),relayProxy:D.status==="fulfilled"?Mw(D.value):Mu(D.reason instanceof Error?D.reason.message:"测速失败"),webProxy:K.status==="fulfilled"?Mw(K.value):Mu(K.reason instanceof Error?K.reason.message:"测速失败")}),u.current=!1}if(_.useEffect(()=>{if(!e)return;let A=!1,H=null;const D=async()=>{await b(),!A&&(H=setTimeout(D,document.hidden?_ae:bae))};return D(),()=>{A=!0,u.current=!1,H&&clearTimeout(H)}},[e,t,n,r]),_.useEffect(()=>{if(!e||!o)return;const A=d.current;if(!A)return;const H=A.getBoundingClientRect(),D=Nw(o,{width:H.width,height:H.height});D.x===o.x&&D.y===o.y||(l(D),c2(D))},[e,o]),!e)return null;const w=i.webProxy.rttMs!==void 0?i.webProxy:i.relayProxy,S=o!==null?{left:`${o.x}px`,top:`${o.y}px`}:void 0;function E(A){var D,K;if(A.button!==0)return;const H=A.currentTarget.getBoundingClientRect();f.current={pointerId:A.pointerId,startX:A.clientX,startY:A.clientY,originX:H.left,originY:H.top,width:H.width,height:H.height,dragging:!1},(K=(D=A.currentTarget).setPointerCapture)==null||K.call(D,A.pointerId)}function k(A){const H=f.current;if(!H||H.pointerId!==A.pointerId)return;const D=A.clientX-H.startX,K=A.clientY-H.startY;if(!H.dragging&&Math.hypot(D,K)<wae)return;H.dragging=!0,A.preventDefault();const q=Nw({x:H.originX+D,y:H.originY+K},{width:H.width,height:H.height});l(q)}function T(A){var X,z;const H=f.current;if(!H||H.pointerId!==A.pointerId||(f.current=null,(z=(X=A.currentTarget).releasePointerCapture)==null||z.call(X,A.pointerId),!H.dragging))return;A.preventDefault(),p.current=!0,window.setTimeout(()=>{p.current=!1},200);const D=A.clientX-H.startX,K=A.clientY-H.startY,q=Nw({x:H.originX+D,y:H.originY+K},{width:H.width,height:H.height});l(q),c2(q)}function R(A){var D,K;const H=f.current;!H||H.pointerId!==A.pointerId||(f.current=null,(K=(D=A.currentTarget).releasePointerCapture)==null||K.call(D,A.pointerId))}function P(A){p.current&&(p.current=!1,A.preventDefault(),A.stopPropagation())}return v.jsxs(hE,{children:[v.jsx(pE,{asChild:!0,children:v.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",xae(g)),style:S,"data-slot":"latency-monitor-trigger","aria-label":`延迟监控,Relay 服务器 ${oh(i.webRelay.rttMs)},开发机 ${oh(w.rttMs)}`,onPointerDown:E,onPointerMove:k,onPointerUp:T,onPointerCancel:R,onClickCapture:P,children:[v.jsx(LD,{className:"size-3.5","aria-hidden":"true"}),v.jsx("span",{className:"font-medium text-foreground",children:"延迟"}),v.jsxs("span",{className:"hidden text-muted-foreground sm:inline",children:["Relay ",oh(i.webRelay.rttMs)]}),v.jsxs("span",{className:"text-muted-foreground",children:["开发机 ",oh(w.rttMs)]}),v.jsx(Al,{className:"size-3 text-muted-foreground","aria-hidden":"true"})]})}),v.jsxs(mE,{align:"end",className:"w-[320px] p-3","data-slot":"latency-monitor-popover",children:[v.jsxs("div",{className:"flex items-start justify-between gap-3",children:[v.jsxs("div",{children:[v.jsx("div",{className:"text-sm font-medium text-foreground",children:"连接延迟"}),v.jsx("div",{className:"mt-1 text-xs text-muted-foreground",children:"数值越低,操作响应通常越快。"})]}),v.jsx(At,{type:"button",variant:"ghost",size:"icon-xs","aria-label":"立即测速",onClick:()=>void b(),children:v.jsx(m1,{className:"size-3","aria-hidden":"true"})})]}),v.jsx("div",{className:"mt-3 space-y-2",children:Object.keys(a2).map(A=>v.jsx(Rae,{label:a2[A],measurement:i[A]},A))})]})]})}function Rae({label:e,measurement:t}){const n=a5(t.state);return v.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:[v.jsx("div",{className:"min-w-0 truncate text-xs font-medium text-foreground",children:e}),v.jsxs("div",{className:"flex items-center gap-2",children:[v.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"}),v.jsx("span",{className:"min-w-[4rem] text-right font-mono text-xs text-foreground",children:Eae(t)})]})]})}const l5="/__dev_anywhere_debug/browser-state-dumps",Aae=1500,Mae=10,Pw=80,xE=500,Nae=["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"],Pae=["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 u2(){if(typeof window>"u")return"off";const e=g5("debugDump");return e==="auto"?"auto":e!==null||Fae("debugInput")?"manual":"off"}function Lae(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:Bae(),document:{title:document.title,readyState:document.readyState,visibilityState:document.visibilityState,activeElement:d2(document.activeElement),selection:zae(),focusedInputs:Array.from(document.querySelectorAll("input, textarea, select, [contenteditable]")).filter(i=>i===document.activeElement||i.matches(":focus")).map(i=>d2(i)).filter(i=>!!i),root:c5(document.documentElement,0,t),truncated:t.truncated,nodeCount:t.count},devAnywhere:{ptyDebug:Nu(()=>{var i;return((i=n.__devAnywherePtyDebug)==null?void 0:i.call(n))??null}),ptyInputDebugSnapshot:Nu(()=>n.__devAnywherePtyInputDebugSnapshot??null),ptyInputDebugText:n.__devAnywherePtyInputDebugText??null,ptyInputDebugEvents:Nu(()=>n.__devAnywherePtyInputDebugEvents??null),ptyScrollTraceTail:Nu(()=>f2(n.__devAnywherePtyScrollTrace)),jsonScrollTraceTail:Nu(()=>f2(n.__devAnywhereJsonScrollTrace)),voicePilotDiagnostics:Nu(()=>{var i;return((i=n.__devAnywhereVoicePilotDiagnostics)==null?void 0:i.snapshot())??null})}};return window.__devAnywhereLastBrowserStateDump=r,r}async function Oae(e="manual"){const t=Lae(e);return Dae(t)}async function Dae(e){const t=JSON.stringify(e,null,2),n=new Blob([t]).size;try{const r=await Iae(t);return{status:"saved",path:r.path,bytes:r.bytes,endpoint:l5}}catch(r){const i=v5(r),s=jae(e.createdAt);return $ae(s,t,"application/json")?{status:"downloaded",filename:s,bytes:n,endpointError:i}:{status:"failed",error:"无法保存或下载诊断包",endpointError:i}}}async function Iae(e){const t=await fetch(l5,{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 c5(e,t,n){if(n.count>=Aae||t>Mae)return n.truncated=!0,{kind:"truncated"};if(n.count+=1,e.nodeType===Node.TEXT_NODE){const u=h2(e.textContent??"");return u?{kind:"text",text:wy(u,xE)}:{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,Pw))u.nodeType===Node.TEXT_NODE&&!h2(u.textContent??"")||r.push(c5(u,t+1,n));s.length>Pw&&(i=s.length-Pw,n.truncated=!0);const o={kind:"element",tag:e.tagName.toLowerCase(),path:m5(e),attrs:u5(e),rect:d5(e),scroll:f5(e),style:h5(e)},l=p5(e);return l&&(o.value=l),r.length>0&&(o.children=r),i>0&&(o.omittedChildren=i),o}function d2(e){if(!(e instanceof HTMLElement))return null;const t=p5(e);return{path:m5(e),tag:e.tagName.toLowerCase(),id:e.id||null,className:e.className||null,attrs:u5(e),rect:d5(e),scroll:f5(e),style:h5(e),...t?{value:t}:{}}}function Bae(){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 u5(e){const t={};for(const n of Nae){const r=e.getAttribute(n);r!==null&&(t[n]=wy(r,500))}return t}function d5(e){const t=e.getBoundingClientRect();return{x:ns(t.x),y:ns(t.y),width:ns(t.width),height:ns(t.height),top:ns(t.top),right:ns(t.right),bottom:ns(t.bottom),left:ns(t.left)}}function f5(e){return{top:ns(e.scrollTop),left:ns(e.scrollLeft),height:ns(e.scrollHeight),width:ns(e.scrollWidth),clientHeight:ns(e.clientHeight),clientWidth:ns(e.clientWidth)}}function h5(e){const t=window.getComputedStyle(e),n={};for(const r of Pae)n[r]=t.getPropertyValue(r);return n}function p5(e){if(!(!(e instanceof HTMLInputElement)&&!(e instanceof HTMLTextAreaElement)))return{length:e.value.length,preview:wy(e.value,xE),selectionStart:e.selectionStart,selectionEnd:e.selectionEnd}}function zae(){var e;try{return wy(((e=window.getSelection())==null?void 0:e.toString())??"",xE)}catch{return null}}function m5(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 jae(e){return`dev-anywhere-browser-state-${e.replace(/[:.]/g,"-")}.json`}function $ae(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 Fae(e){return g5(e)!==null}function g5(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 f2(e){return e?Sv(e.slice(-200)):null}function Nu(e){try{return Sv(e())}catch(t){return{error:v5(t)}}}function Sv(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(Sv);if(typeof e=="object"){const t={};for(const[n,r]of Object.entries(e))t[n]=Sv(r);return t}return String(e)}function h2(e){return e.replace(/\s+/g," ").trim()}function wy(e,t){return e.length>t?`${e.slice(0,t)}...`:e}function ns(e){return Math.round(e*100)/100}function v5(e){return e instanceof Error?e.message:String(e)}const Hae=500,Uae=1e3,Wae=60;function qae(){const[e,t]=_.useState(()=>u2()),[n,r]=_.useState(!1),[i,s]=_.useState(null),o=_.useRef(null),l=_.useRef(!1),u=_.useRef(0),d=_.useRef(0),f=_.useRef(null);_.useEffect(()=>{const b=()=>t(u2());return window.addEventListener("hashchange",b),window.addEventListener("popstate",b),()=>{window.removeEventListener("hashchange",b),window.removeEventListener("popstate",b)}},[]);const p=_.useCallback(async(b="manual")=>{if(l.current)return o.current??{status:"failed",error:"dump already running"};l.current=!0,r(!0);try{const w=await Oae(b);return o.current=w,s(w),(b==="manual"||w.status==="failed")&&Yae(w),w}finally{l.current=!1,r(!1)}},[]);if(_.useEffect(()=>(window.__devAnywhereDumpBrowserState=p,()=>{window.__devAnywhereDumpBrowserState===p&&delete window.__devAnywhereDumpBrowserState}),[p]),_.useEffect(()=>{var k,T;if(e!=="auto")return;const b=()=>{f.current!==null&&(window.clearTimeout(f.current),f.current=null)},w=R=>{d.current>=Wae||(b(),f.current=window.setTimeout(()=>{f.current=null;const P=Date.now(),A=Uae-(P-u.current);if(A>0){f.current=window.setTimeout(()=>w(R),A);return}u.current=Date.now(),d.current+=1,p(`auto:${d.current}:${R}`)},Hae))};w("initial");const S=["focusin","focusout","beforeinput","input","compositionstart","compositionupdate","compositionend","keydown","keyup","pointerdown","pointerup","resize","visibilitychange"],E=R=>w(R.type);return S.forEach(R=>window.addEventListener(R,E,!0)),(k=window.visualViewport)==null||k.addEventListener("resize",E),(T=window.visualViewport)==null||T.addEventListener("scroll",E),()=>{var R,P;b(),S.forEach(A=>window.removeEventListener(A,E,!0)),(R=window.visualViewport)==null||R.removeEventListener("resize",E),(P=window.visualViewport)==null||P.removeEventListener("scroll",E)}},[p,e]),e==="off")return null;const y=e==="auto"?"自动诊断中":"保存诊断",g=Vae(i);return v.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?v.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,v.jsxs(At,{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?v.jsx(fa,{className:"size-3.5 animate-spin","aria-hidden":"true"}):v.jsx(zW,{className:"size-3.5","aria-hidden":"true"}),v.jsx("span",{children:y})]})]})}function Yae(e){if(e.status==="saved"){nt.success(`诊断已保存: ${e.path}`);return}if(e.status==="downloaded"){nt.info(`诊断已下载: ${e.filename}`);return}nt.error(e.endpointError?`${e.error}: ${e.endpointError}`:e.error)}function Vae(e){return e?e.status==="saved"?`已保存 ${e.path}`:e.status==="downloaded"?`已下载 ${e.filename}`:`失败 ${e.endpointError??e.error}`:null}function Kae(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 EE(e){const{windowKey:t,storageKey:n,maxEntries:r=5e3,dedupeKey:i}=e,s=new Map,o=()=>typeof window>"u"?!1:Kae(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 Bn(e){return Math.round(e*10)/10}function al(e){return e.length===0?"":`${Bn(Math.min(...e))}..${Bn(Math.max(...e))}`}function Ju(e){return[...new Set(e.filter(t=>t!==void 0).map(Bn))]}function y5(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 Gae="dev_anywhere_pty_input_latency_trace",p2=80,Xae=1e4,Zae=new TextDecoder;let Qae=0;const yd=new Map,Wc=EE({windowKey:"__devAnywherePtyInputLatencyTrace",storageKey:Gae,dedupeKey:e=>e.event.startsWith("input")?null:`${e.event}|${e.sessionId}|${e.outputSeq??""}|${e.pendingInputs??""}`});function Jae(){typeof window>"u"||(window.__devAnywherePtyInputLatencyReport=rle)}function ele(e,t){if(!Wc.isEnabled())return null;const n=`pty-in-${Date.now().toString(36)}-${++Qae}`,r=performance.now(),i={inputId:n,sessionId:e,data:t,kind:ole(t),dataLength:t.length,startedAt:r,sentAt:null,firstOutputAt:null,echoMatchedAt:null,xtermWriteAt:null,paintAt:null},s=yd.get(e)??[];return s.push(i),kE(s,r),yd.set(e,s),vp({t:r,event:"input:start",sessionId:e,inputId:n,inputKind:i.kind,dataLength:i.dataLength,pendingInputs:s.length}),{inputId:n,sessionId:e}}function m2(e,t){if(!e||!Wc.isEnabled())return;const n=performance.now(),r=ile(e.sessionId,e.inputId);r&&(r.sentAt=n),vp({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 tle(e,t,n){if(!Wc.isEnabled())return;const r=performance.now(),i=CE(e,r),s=cle(t),o=[],l=[];for(const u of i)u.firstOutputAt===null&&(u.firstOutputAt=r,o.push(u.inputId)),u.echoMatchedAt===null&&lle(u)&&s.includes(u.data)&&(u.echoMatchedAt=r,l.push(u.inputId));vp({t:r,event:"output:received",sessionId:e,outputSeq:n,bytes:t.byteLength,pendingInputs:i.length,deltaFromInputMs:TE(i,r),details:ule([o.length>0?`first=${o.length}`:"",l.length>0?`echo=${l.length}`:""])})}function nle(e,t,n=1){if(!Wc.isEnabled())return;const r=performance.now(),i=CE(e,r),s=[];for(const o of i)o.xtermWriteAt===null&&(o.xtermWriteAt=r,s.push(o.inputId));vp({t:r,event:"output:xterm-write",sessionId:e,bytes:t,chunkCount:n,pendingInputs:i.length,deltaFromInputMs:TE(i,r),details:s.length>0?`firstWrite=${s.length}`:""}),typeof requestAnimationFrame=="function"&&s.length>0&&requestAnimationFrame(()=>sle(e,s))}function rle(){const e=Wc.getAll(),t=e.slice(-200),n=[...yd.values()].flat(),r=n.slice(-80).map(s=>[s.inputId,s.sessionId,s.kind,s.dataLength,s.sentAt===null?"":Bn(s.sentAt-s.startedAt),s.firstOutputAt===null?"":Bn(s.firstOutputAt-s.startedAt),s.echoMatchedAt===null?"":Bn(s.echoMatchedAt-s.startedAt),s.xtermWriteAt===null?"":Bn(s.xtermWriteAt-s.startedAt),s.paintAt===null?"":Bn(s.paintAt-s.startedAt)].join(" ")),i=t.map(s=>[Bn(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?"":Bn(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(`
|
|
535
535
|
`)}function vp(e){Wc.append(e)}function CE(e,t){const n=yd.get(e)??[];return kE(n,t),yd.set(e,n),n}function kE(e,t){for(let n=e.length-1;n>=0;n-=1){const r=e[n],i=r.paintAt!==null,s=t-r.startedAt>Xae;(i||s)&&e.splice(n,1)}e.length>p2&&e.splice(0,e.length-p2)}function ile(e,t){return(yd.get(e)??[]).find(n=>n.inputId===t)??null}function sle(e,t){if(!Wc.isEnabled())return;const n=performance.now(),r=CE(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)}vp({t:n,event:"output:paint",sessionId:e,pendingInputs:r.length,deltaFromInputMs:TE(r,n),details:i>0?`paint=${i}`:""}),kE(r,n)}function TE(e,t){const n=e[0];return n?t-n.startedAt:null}function ole(e){return e==="\r"||e===`
|
|
536
536
|
`?"enter":e.startsWith("\x1B")?"escape":ale(e)?"control":e.length>16?"paste":/[\r\n]/.test(e)?"mixed":"printable"}function ale(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 lle(e){return e.kind==="printable"&&e.data.length>0&&e.data.length<=16}function cle(e){try{return Zae.decode(e)}catch{return""}}function ule(e){return e.filter(Boolean).join(" ")}function eo(e,t){if(!e||!t)return;const n=ele(e,t),r=_c;if(!r){m2(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});m2(n,{sent:s,queueWhenDisconnected:!0,details:s?"sent-open-socket":"queued-or-dropped"})}const g2=-1;function dle({sessionId:e,enabled:t,waiting:n,approvalSeq:r,sendRawInput:i=eo}){const s=_.useRef(void 0),o=_.useRef(e);_.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=g2,i(e,"\r");return}if(s.current===g2){s.current=r;return}s.current!==r&&(s.current=r,i(e,"\r"))},[r,t,i,e,n])}function fle(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=w1(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 hle({target:e,sendRawInput:t}){return dle({sessionId:e.sessionId,enabled:!0,waiting:e.waiting,approvalSeq:e.approvalSeq,sendRawInput:t}),null}function ple({sendRawInput:e=eo}){const t=De(d=>d.connected),n=De(d=>d.proxyOnline),r=De(d=>d.selectedProxyId),i=Ft(d=>d.sessions),s=Ft(d=>d.ptyStateBySessionId),o=Ft(d=>d.agentStatusBySessionId),l=Ft(d=>d.ptyAutoYesBySessionKey),u=i.map(d=>fle({proxyId:r,session:d,ptyState:s[d.sessionId],agentStatus:o[d.sessionId],autoYesBySessionKey:l,connected:t,proxyOnline:n})).filter(d=>d!==null);return v.jsx(v.Fragment,{children:u.map(d=>v.jsx(hle,{target:d,sendRawInput:e},d.key))})}function mle(e,t){return e.some(n=>n.sessionId===t)?e:[...e,{sessionId:t}]}var vc=function(e,t){return Number(e.toFixed(t))},gle=function(e,t){return t},Wn=function(e,t,n){n&&typeof n=="function"&&n(e,t)},vle=function(e){return-Math.cos(e*Math.PI)/2+.5},yle=function(e){return e},ble=function(e){return e*e},_le=function(e){return e*(2-e)},wle=function(e){return e<.5?2*e*e:-1+(4-2*e)*e},Sle=function(e){return e*e*e},xle=function(e){return--e*e*e+1},Ele=function(e){return e<.5?4*e*e*e:(e-1)*(2*e-2)*(2*e-2)+1},Cle=function(e){return e*e*e*e},kle=function(e){return 1- --e*e*e*e},Tle=function(e){return e<.5?8*e*e*e*e:1-8*--e*e*e*e},Rle=function(e){return e*e*e*e*e},Ale=function(e){return 1+--e*e*e*e*e},Mle=function(e){return e<.5?16*e*e*e*e*e:1+16*--e*e*e*e*e},b5={easeOut:vle,linear:yle,easeInQuad:ble,easeOutQuad:_le,easeInOutQuad:wle,easeInCubic:Sle,easeOutCubic:xle,easeInOutCubic:Ele,easeInQuart:Cle,easeOutQuart:kle,easeInOutQuart:Tle,easeInQuint:Rle,easeOutQuint:Ale,easeInOutQuint:Mle},_5=function(e){typeof e=="number"&&cancelAnimationFrame(e)},Js=function(e){e.mounted&&(_5(e.animation),e.isAnimating=!1,e.animation=null,e.velocity=null)};function w5(e,t,n,r){if(e.mounted){var i=new Date().getTime(),s=1;Js(e),e.animation=function(){if(!e.mounted)return _5(e.animation);var o=new Date().getTime()-i,l=o/n,u=b5[t],d=u(l);o>=n?(r(s),e.animation=null):e.animation&&(r(d),requestAnimationFrame(e.animation))},requestAnimationFrame(e.animation)}}function Nle(e){var t=e.scale,n=e.positionX,r=e.positionY;return!(Number.isNaN(t)||Number.isNaN(n)||Number.isNaN(r))}function $l(e,t,n,r){var i=Nle(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):w5(e,r,n,function(g){g!==1?e.isAnimating=!0:e.isAnimating=!1;var b=l+f*g,w=u+p*g,S=d+y*g;s(b,w,S)})}}function Ple(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 Lle=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}},RE=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=Ple(n,r,t),u=l.wrapperWidth,d=l.wrapperHeight,f=l.newContentWidth,p=l.newContentHeight,y=l.newDiffWidth,g=l.newDiffHeight,b=Lle(u,f,y,d,p,g,!!s),w=u>=f&&d>=p;o&&w&&!s&&(b.minPositionX=0,b.maxPositionX=0,b.minPositionY=0,b.maxPositionY=0);var S=e.setup,E=S.minPositionX,k=S.maxPositionX,T=S.minPositionY,R=S.maxPositionY;return E!=null&&(b.minPositionX=u*(1-t)+E*t),k!=null&&(b.maxPositionX=k*t),T!=null&&(b.minPositionY=d*(1-t)+T*t),R!=null&&(b.maxPositionY=R*t),b},$h=function(e,t,n,r){return r?e<t?vc(t,2):e>n?vc(n,2):vc(e,2):vc(e,2)},bd=function(e,t){var n=RE(e,t);return e.bounds=n,n};function yp(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=$h(e,l-p,d+p,r),b=$h(t,u-y,f+y,r);return{x:g,y:b}}function Sy(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=yp(p,y,i,s,0,0,null);return g}var v2=1e-7;function bp(e,t,n,r,i){var s=i?r:0,o=Math.max(t-s,v2),l=n+s;return!Number.isNaN(n)&&e>=l?l:!Number.isNaN(t)&&e<=o?o:Math.max(e,v2)}var y2=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=_p(s,n);return!(d||s.getAttribute("draggable")==="true"||s.getAttribute("contenteditable")==="true"||s.isContentEditable)},b2=function(e){var t=e.isInitialized,n=e.isPanning,r=e.setup,i=r.panning.disabled,s=t&&n&&!i;return!!s},Ole=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}},Dle=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 Ile(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,b=f.minPositionY,w=n>p||n<y,S=r>g||r<b,E=n>p?d.offsetWidth:e.setup.minPositionX||0,k=r>g?d.offsetHeight:e.setup.minPositionY||0,T=Sy(e,E,k,i,e.bounds,l||u),R=T.x,P=T.y;return{scale:i,positionX:w?R:n,positionY:S?P:r}}}function S5(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=yp(t,n,l,s,r,i,o),g=y.x,b=y.y;e.setState(d,g,b)}}var Ble=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}},kl=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},ml;(function(e){e.TRACK_PAD="track_pad",e.MOUSE="mouse",e.TOUCH="touch"})(ml||(ml={}));var zle=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},jle=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 $le(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 _2(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:$h(e,s,o,i)}function Fle(e){var t=1,n=e.offsetWidth/window.innerWidth;return Number.isNaN(n)?t:Math.min(t,n)}var Lw=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 Hle(e,t,n){var r,i,s=zle(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,b=f.sensitivityMouse,w=Date.now();if(o&&l&&d){var S=Fle(d),E=(r={},r[ml.TOUCH]=g,r[ml.MOUSE]=b,r)[n],k=(i={},i[ml.TOUCH]=y,i[ml.MOUSE]=p,i)[n],T=t.x-o.x,R=t.y-o.y,P=Lw(T/S,k,E),A=Lw(R/S,k,E),H=w-l,D=T*T+R*R,K=Lw(Math.sqrt(D)/H,k,E);e.velocity={velocityX:P,velocityY:A,total:K}}e.lastMousePosition=t,e.velocityTime=w}}function Ule(e){var t=e.velocity,n=e.bounds,r=e.setup,i=e.wrapperComponent,s=jle(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,b=r.autoAlignment,w=r.zoomAnimation,S=r.panning,E=S.lockAxisY,k=S.lockAxisX,T=w.animationType,R=b.sizeX,P=b.sizeY,A=b.velocityAlignmentTime,H=A,D=$le(e,u),K=Math.max(D,H),q=kl(e,R),X=kl(e,P),z=q*i.offsetWidth/100,N=X*i.offsetHeight/100,$=d+z,I=f-z,M=p+N,O=y-N,U=e.state,B=new Date().getTime();w5(e,T,K,function(L){var Y=e.state,V=Y.scale,j=Y.positionX,te=Y.positionY,re=new Date().getTime()-B,oe=re/H,ee=b5[b.animationType],pe=1-ee(Math.min(1,oe)),ae=1-L,me=j+o*ae,Ee=te+l*ae,Oe=_2(me,U.positionX,j,k,g,f,d,I,$,pe),Se=_2(Ee,U.positionY,te,E,g,y,p,O,M,pe);if(j!==me||te!==Ee){e.setState(V,Oe,Se);var Qe=e.props.onPanning;Qe&&Qe(zn(e),{})}})}}function w2(e,t){var n=e.state,r=n.scale,i=n.positionX,s=n.positionY;e.panStartPosition={x:i,y:s},Js(e),bd(e,r),window.TouchEvent!==void 0&&t instanceof TouchEvent?Dle(e,t):Ole(e,t)}function x5(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=Ile(e);y&&$l(e,y,d,f)}}function S2(e,t,n,r){var i=e.startCoords,s=e.setup,o=s.autoAlignment,l=o.sizeX,u=o.sizeY;if(i){var d=Ble(e,t,n),f=d.x,p=d.y,y=kl(e,l),g=kl(e,u);Hle(e,{x:f,y:p},r),S5(e,f,p,y,g)}}function Wle(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,b=((i==null?void 0:i.offsetWidth)||0)*u,w=((i==null?void 0:i.offsetHeight)||0)*u,S=!e.setup.limitToBounds||y<b||g<w,E=!t&&n&&n.total>.1&&S;E?Ule(e):x5(e)}}function AE(e,t,n,r){var i=e.setup,s=i.minScale,o=i.maxScale,l=i.limitToBounds,u=bp(vc(t,2),s,o,0,!1),d=bd(e,u),f=Sy(e,n,r,u,d,l),p=f.x,y=f.y;return{scale:u,positionX:p,positionY:y}}function ME(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,b=f||g;if((r>=1||u)&&x5(e),!(b||!i||!e.mounted)){var w=t||i.offsetWidth/2,S=n||i.offsetHeight/2,E=r<o?o:l,k=AE(e,E,w,S);k&&$l(e,k,p,y)}}var zs=function(){return zs=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},zs.apply(this,arguments)};function x2(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 Ow={scale:1,positionX:0,positionY:0},mc={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"}},TS={wrapperClass:"react-transform-wrapper",contentClass:"react-transform-component"},E5=function(e){var t,n,r,i,s,o,l,u,d,f=Math.max((t=e.minScale)!==null&&t!==void 0?t:mc.minScale,1e-7),p=(n=e.maxScale)!==null&&n!==void 0?n:mc.maxScale,y=(r=e.initialScale)!==null&&r!==void 0?r:Ow.scale,g=Math.min(Math.max(y,f),p),b=$h((i=e.initialPositionX)!==null&&i!==void 0?i:Ow.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=$h((l=e.initialPositionY)!==null&&l!==void 0?l:Ow.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:b,positionY:w}},E2=function(e){var t=zs({},mc);return Object.keys(e).forEach(function(n){var r=n,i=typeof e[r]<"u",s=typeof mc[r]<"u";if(s&&i){var o=Object.prototype.toString.call(mc[r]),l=o==="[object Object]",u=o==="[object Array]";l?t[r]=zs(zs({},mc[r]),e[r]):u?t[r]=x2(x2([],mc[r],!0),e[r]):t[r]=e[r]}}),t.minScale<=0&&(t.minScale=1e-7),t},C5=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=bp(vc(p,3),l,o,f,!1);return y};function k5(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,b=l.offsetWidth,w=l.offsetHeight,S=(b/2-f)/d,E=(w/2-p)/d,k=C5(e,t,n),T=AE(e,k,S,E);if(!T)return console.error("Error during zoom event. New transformation state was not calculated.");var R=e.props,P=R.onZoomStart,A=R.onZoom,H=R.onZoomStop,D=new MouseEvent("mousemove",{bubbles:!0}),K=zn(e);Wn(K,D,P),Wn(K,D,A),$l(e,T,g,i);var q=(o=(s=l.ownerDocument)===null||s===void 0?void 0:s.defaultView)!==null&&o!==void 0?o:typeof window<"u"?window:null;q&&q.setTimeout(function(){e.mounted&&Wn(zn(e),D,H)},g)}function T5(e,t,n,r){var i,s,o=e.setup,l=e.wrapperComponent,u=e.contentComponent,d=o.limitToBounds,f=o.centerOnInit,p=E5(e.props),y=e.state,g=y.scale,b=y.positionX,w=y.positionY;if(l){var S=p.positionX,E=p.positionY;if(f&&u){var k=NE(p.scale,l,u);S=k.positionX,E=k.positionY}var T=RE(e,p.scale),R=yp(S,E,T,d,0,0,l),P={scale:p.scale,positionX:R.x,positionY:R.y};if(!(g===p.scale&&b===p.positionX&&w===p.positionY)){r==null||r();var A=e.props,H=A.onZoomStart,D=A.onZoom,K=A.onZoomStop,q=new MouseEvent("mousemove",{bubbles:!0}),X=zn(e);Wn(X,q,H),Wn(X,q,D),$l(e,P,t,n);var z=(s=(i=l.ownerDocument)===null||i===void 0?void 0:i.defaultView)!==null&&s!==void 0?s:typeof window<"u"?window:null;z&&z.setTimeout(function(){e.mounted&&Wn(zn(e),q,K)},t)}}}function qle(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 Yle(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(),b=qle(t,s,o,l),w=b.x,S=b.y,E=g.width/l.scale,k=g.height/l.scale,T=s.offsetWidth/E,R=s.offsetHeight/k,P=bp(n||Math.min(T,R),f,p,0,!1),A=(y.width-E*P)/2,H=(y.height-k*P)/2,D=(y.left-w)*P+A+r,K=(y.top-S)*P+H+i,q=RE(e,P),X=yp(D,K,q,d,0,0,s),z=X.x,N=X.y;return{positionX:z,positionY:N,scale:P}}var Vle=function(e){return function(t,n,r){t===void 0&&(t=.5),n===void 0&&(n=300),r===void 0&&(r="easeOut"),k5(e,1,t,n,r)}},Kle=function(e){return function(t,n,r){t===void 0&&(t=.5),n===void 0&&(n=300),r===void 0&&(r="easeOut"),k5(e,-1,t,n,r)}},Gle=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};$l(e,g,i,s)}}},Xle=function(e){return function(t,n){t===void 0&&(t=200),n===void 0&&(n="easeOut"),T5(e,t,n)}},Zle=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=NE(t||i.scale,s,o);$l(e,l,n,r)}}},Qle=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),Js(e);var l=e.wrapperComponent,u=typeof t=="string"?document.getElementById(t):t;if(l&&u&&l.contains(u)){var d=Yle(e,u,n,s,o);$l(e,d,r,i)}}},RS=function(e){return{instance:e,state:e.state,zoomIn:Vle(e),zoomOut:Kle(e),setTransform:Gle(e),resetTransform:Xle(e),centerView:Zle(e),zoomToElement:Qle(e)}},Jle=function(e){return{instance:e,state:e.state}},zn=function(e){var t={};return Object.assign(t,Jle(e)),Object.assign(t,RS(e)),t},Dw=!1;function Iw(){try{var e={get passive(){return Dw=!0,!1}};return e}catch{return Dw=!1,Dw}}var ug=".".concat(TS.wrapperClass),_p=function(e,t){return t.some(function(n){return e.matches("".concat(ug," ").concat(n,", ").concat(ug," .").concat(n,", ").concat(ug," ").concat(n," *, ").concat(ug," .").concat(n," *"))})},Fh=function(e){e&&clearTimeout(e)},ece=function(e){return Number.parseFloat(e.toFixed(8))},R5=function(e,t,n){var r=ece(n);return"translate(".concat(e,"px, ").concat(t,"px) scale(").concat(r,")")},NE=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 tce(e,t){e!=null&&(typeof e=="function"?e(t):e.current=t)}function nce(e){return function(t){e.forEach(function(n){typeof n=="function"?n(t):n!=null&&(n.current=t)})}}var A5=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=_p(d,o);if(p)return!1;var y=e.isPressingKeys(e.setup.wheel.activationKeys);return!!y},rce=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=A5(e,t);if(l)return!1;var u=t.target,d=_p(u,o);if(d)return!1;var f=e.isPressingKeys(s);return!!f},ice=function(e){return e?e.deltaY<0?1:-1:0};function sce(e,t){var n=ice(e),r=gle(t,n);return r}function M5(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 oce=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 b=s+t*n,w=r?!1:!g,S=bp(b,d,u,y,w&&!p);return S},N5=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},ace=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=_p(o,i);return!u},lce=function(e){var t=e.setup.pinch.disabled,n=e.isInitialized,r=e.pinchStartDistance,i=n&&!t&&r!==null;return!!i},cce=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}},P5=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))},uce=5,dce=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,b=g*n,w=(b-n)*(y/uce),S=n+w,E=S===1/0?0:vc(S,10);return bp(E,o,s,f,!p&&!u)},L5=160,O5=100,fce=function(e,t){var n=e.props,r=n.onWheelStart,i=n.onZoomStart;e.wheelStopEventTimer||(Js(e),Wn(zn(e),t,r),Wn(zn(e),t,i))},hce=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,b=o.smooth,w=p.size,S=p.disabled,E=y.step;if(!s)throw new Error("Component not mounted");t.preventDefault(),t.stopPropagation();var k=sce(t,null),T=b?E*Math.abs(t.deltaY):E,R=oce(e,k,T,!t.ctrlKey);if(u!==R){var P=bd(e,R),A=M5(t,s,u),H=S||w===0||f||g,D=d&&H,K=Sy(e,A.x,A.y,R,P,D),q=K.x,X=K.y;e.previousWheelEvent=t,e.setState(R,q,X),Wn(zn(e),t,r),Wn(zn(e),t,i)}},pce=function(e,t){var n=e.props,r=n.onWheelStop,i=n.onZoomStop;Fh(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(ME(e,t.x,t.y),e.wheelAnimationTimer=null)},O5);var s=N5(e,t);s&&(Fh(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Wn(zn(e),t,r),Wn(zn(e),t,i))},L5))},mce=function(e,t){var n=e.props,r=n.onWheelStart,i=n.onPanningStart;e.wheelStopEventTimer||(Js(e),Wn(zn(e),t,r),Wn(zn(e),t,i))},gce=function(e,t){var n=e.props,r=n.onWheelStop,i=n.onPanningStop;Fh(e.wheelAnimationTimer),e.wheelAnimationTimer=setTimeout(function(){e.mounted&&(ME(e,t.x,t.y),e.wheelAnimationTimer=null)},O5);var s=N5(e,t);s&&(Fh(e.wheelStopEventTimer),e.wheelStopEventTimer=setTimeout(function(){e.mounted&&(e.wheelStopEventTimer=null,Wn(zn(e),t,r),Wn(zn(e),t,i))},L5))},D5=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}},vce=function(e,t){var n=P5(t);e.pinchStartDistance=n,e.lastDistance=n,e.pinchStartScale=e.state.scale,e.isPanning=!1,e.isPinching=!0,e.pinchPreviousCenter=D5(t),Js(e)},yce=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,b=f.disabled,w=f.size,S=y.allowPanning;if(!(r===null||!n)){var E=cce(t,o,n);if(!(!Number.isFinite(E.x)||!Number.isFinite(E.y))){var k=P5(t),T=dce(e,k),R=D5(t),P=o/T,A=(R.x-((s==null?void 0:s.x)||0))*P,H=(R.y-((s==null?void 0:s.y)||0))*P;if(!(T===o&&A===0&&H===0)){e.pinchPreviousCenter=R;var D=bd(e,T),K=b||w===0||d,q=u&&K,X=Sy(e,E.x,E.y,T,D,q),z=X.x,N=X.y;if(e.pinchMidpoint=E,e.lastDistance=k,g.disabled||!S)e.setState(T,z,N);else{var $=p.sizeX,I=p.sizeY,M=kl(e,$,T),O=kl(e,I,T),U=z+A,B=N+H,L=yp(U,B,D,u,M,O,i),Y=L.x,V=L.y;e.setState(T,Y,V)}}}}},bce=function(e){var t=e.pinchMidpoint;e.velocity=null,e.lastDistance=null,e.pinchMidpoint=null,e.pinchStartScale=null,e.pinchStartDistance=null,e.isPinching=!1,ME(e,t==null?void 0:t.x,t==null?void 0:t.y)},I5=function(e,t){var n=e.props.onZoomStop,r=e.setup.doubleClick.animationTime;Fh(e.doubleClickStopEventTimer),e.doubleClickStopEventTimer=setTimeout(function(){e.doubleClickStopEventTimer=null,Wn(zn(e),t,n)},r)},_ce=function(e,t){var n=e.props,r=n.onZoomStart,i=n.onZoom,s=e.setup.doubleClick,o=s.animationTime,l=s.animationType;Wn(zn(e),t,r),T5(e,o,l,function(){return Wn(zn(e),t,i)}),I5(e,t)};function wce(e,t){return e==="toggle"?t===1?1:-1:e==="zoomOut"?-1:1}function Sce(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,b=f.animationTime,w=f.animationType;if(!p&&!r){if(y==="reset")return _ce(e,t);if(!s)return console.error("No ContentComponent found");var S=wce(y,e.state.scale),E=C5(e,S,g);if(o!==E){Wn(zn(e),t,u);var k=M5(t,s,o),T=AE(e,E,k.x,k.y);if(!T)return console.error("Error during zoom event. New transformation state was not calculated.");Wn(zn(e),t,d),$l(e,T,b,w),I5(e,t)}}}var xce=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=_p(u,l);return!p},Ece=(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&&bd(n,n.state.scale),n.setup=E2(r)},this.initializeWindowEvents=function(){var r,i,s,o,l=Iw(),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=Iw(),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),Js(n),(l=n.observer)===null||l===void 0||l.disconnect()},this.handleInitializeWrapperEvents=function(r){var i=Iw();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(zn(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(zn(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=A5(n,r);s&&(fce(n,r),hce(n,r),pce(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=rce(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,b=o?f:y,w=l?p:g,S=n.setup.autoAlignment,E=S.sizeX,k=S.sizeY,T=kl(n,E),R=kl(n,k);b===f&&w===p||(mce(n,r),S5(n,b,w,T,R),Wn(zn(n),r,i),gce(n,r))}},this.onPanningStart=function(r){var i=n.setup.disabled,s=n.props.onPanningStart;if(!i){n.syncModifierKeys(r);var o=y2(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(),Js(n),w2(n,r),Wn(zn(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=b2(n);if(o){var l=n.isPressingKeys(n.setup.panning.activationKeys);l&&(r.preventDefault(),r.stopPropagation(),S2(n,r.clientX,r.clientY,ml.MOUSE),Wn(zn(n),r,s))}}},this.onPanningStop=function(r){var i=n.setup.panning.velocityDisabled,s=n.props.onPanningStop;n.isPanning&&(Wle(n,i),Wn(zn(n),r,s))},this.onPinchStart=function(r){var i=n.setup.disabled,s=n.props.onPinchStart;if(!i){var o=ace(n,r);o&&(vce(n,r),Js(n),Wn(zn(n),r,s))}},this.onPinch=function(r){var i=n.setup.disabled,s=n.props.onPinch;if(!i){var o=lce(n);o&&(r.preventDefault(),r.stopPropagation(),yce(n,r),Wn(zn(n),r,s))}},this.onPinchStop=function(r){var i=n.props.onPinchStop;n.pinchStartScale&&(bce(n),Wn(zn(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,Js(n);var f=r.touches,p=f.length===1,y=f.length===2,g=y2(n,r);if(p){if(!g)return;Js(n),w2(n,r),Wn(zn(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=b2(n);if(!o)return;r.cancelable&&r.preventDefault(),r.stopPropagation();var l=r.touches[0];S2(n,l.clientX,l.clientY,ml.TOUCH),Wn(zn(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=xce(n,r);s&&Sce(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=NE(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):R5(r,i,s)},this.getContext=function(){return zn(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:zn(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=zn(n);n.onChangeCallbacks.forEach(function(d){return d(u)}),Wn(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,bd(n,n.state.scale),n.handleInitializeWrapperEvents(r),n.handleInitialize(i),n.initializeWindowEvents(),n.isInitialized=!0;var s=zn(n);Wn(s,void 0,n.props.onInit),tce(n.props.ref,s)},this.props=t,this.setup=E2(this.props),this.state=E5(this.props)}return e})(),xy=et.createContext(null),Cce=function(e,t){return typeof e=="function"?e(t):e},kce=et.forwardRef(function(e,t){var n=_.useRef(new Ece(e)).current,r=Cce(e.children,RS(n));return _.useImperativeHandle(t,function(){return RS(n)},[n]),_.useEffect(function(){n.update(e)},[n,e]),v.jsx(xy.Provider,zs({value:n},{children:r}))});et.forwardRef(function(e,t){var n=_.useRef(null),r=_.useContext(xy);return _.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]),v.jsx("div",zs({},e,{ref:nce([n,t])}))});function Tce(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 Rce=`.transform-component-module_wrapper__SPB86 {
|
|
537
537
|
position: relative;
|
|
@@ -669,7 +669,7 @@ WARNING: This link could potentially be dangerous`)){let n=window.open();if(n){t
|
|
|
669
669
|
`))return null;const n=Mye(t);return!n||/^[a-z][a-z0-9+.-]*:\/\//i.test(n)||rC(n)||n.split("/").includes("...")?null:n}function Pye(e){return e.includes("/")?!1:oC(e)}function Lye(e){const t=e.split("/").pop()??e;if(/^\d+(?:\.\d+)+$/.test(t))return!1;if(e.includes("/"))return!0;const n=e.replace(U4,""),r=n.split("/").pop()??n;return/[A-Za-z_-]/.test(r)}function Oye(e){const t=Nye(e);return!t||Pye(t)||!Lye(t)?null:Aye.test(t)?{kind:"image-preview",path:t}:U4.test(t)?{kind:"file-download",path:t}:null}const Dye=16,Iye=24,Uf=6,Bye=425,hh=-1;function Iu(e,t){return e.pointerId===t||t===hh&&e.touchIdentifier!==null}function dc(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 Sg(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 Bu(e){return Math.hypot(e.lastX-e.startX,e.lastY-e.startY)}function Ri(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 zye({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=_.useRef(null),g=_.useRef(null);_.useEffect(()=>{const O=B=>{const L=g.current;L&&(L.touchIdentifier!==null&&!dc(B.changedTouches,L.touchIdentifier)||(g.current=null,(L.kind==="longpress"||L.kind==="link")&&B.cancelable&&B.preventDefault()))},U=()=>{g.current=null};return document.addEventListener("touchend",O,{capture:!0,passive:!1}),document.addEventListener("touchcancel",U,{capture:!0}),()=>{document.removeEventListener("touchend",O,{capture:!0}),document.removeEventListener("touchcancel",U,{capture:!0})}},[]);const b=_.useCallback(O=>{O.longPressTimer!==null&&(window.clearTimeout(O.longPressTimer),O.longPressTimer=null)},[]),w=_.useCallback(O=>{O.longPressed||O.moved||(O.longPressed=!0,O.longPressArmed=!1,b(O),t(),l==null||l({clientX:O.startX,clientY:O.startY}))},[b,l,t]),S=_.useCallback(O=>{if(!(O.longPressed||O.longPressArmed||O.moved)){if(Bu(O)>Uf){b(O),Ri("longpress:cancel-drift",{distance:Bu(O),threshold:Uf});return}if(o!=null&&o({clientX:O.startX,clientY:O.startY})){O.longPressArmed=!0,b(O),Ri("longpress:arm-link",{clientX:O.startX,clientY:O.startY});return}w(O)}},[b,o,w]),E=_.useCallback((O,U=!0)=>{if(O.longPressDelivered||!O.longPressed||O.moved)return;O.longPressDelivered=!0;const B={clientX:O.lastX,clientY:O.lastY};U?window.setTimeout(()=>d==null?void 0:d(B),0):d==null||d(B)},[d]),k=_.useCallback((O,U,B,L=!1,Y=null)=>{g.current=null;const V={pointerId:O,touchIdentifier:Y,startX:U,startY:B,lastX:U,lastY:B,moved:!1,longPressArmed:!1,longPressed:!1,longPressDelivered:!1,touchEventStream:L,longPressTimer:null,scrollPositionAtStart:(p==null?void 0:p())??null};V.longPressTimer=window.setTimeout(()=>{y.current===V&&S(V)},Bye),y.current=V,Ri("start",{pointerId:O,clientX:U,clientY:B,touchEventStream:L}),i==null||i({clientX:U,clientY:B})},[p,S,i]),T=_.useCallback(O=>{const U=O.scrollPositionAtStart,B=(p==null?void 0:p())??null;return!U||!B?!1:Math.abs(B.scrollLeft-U.scrollLeft)>.5||Math.abs(B.scrollTop-U.scrollTop)>.5},[p]),R=_.useCallback((O,U,B)=>{const L=y.current;if(!L||!Iu(L,O))return!1;L.lastX=U,L.lastY=B;const Y=Bu(L);if(L.longPressArmed&&Y>Uf&&(L.longPressArmed=!1,Ri("longpress:cancel-armed-drift",{pointerId:O,clientX:U,clientY:B,distance:Y,threshold:Uf})),L.longPressed)return Ri("move",{pointerId:O,clientX:U,clientY:B,distance:Y,moved:L.moved,longPressed:!0}),u==null||u({clientX:U,clientY:B}),!0;const V=U-L.startX,j=B-L.startY;return!L.moved&&Y>=Dye&&(L.moved=!0,b(L)),Ri("move",{pointerId:O,clientX:U,clientY:B,dx:V,dy:j,distance:Y,moved:L.moved,longPressed:!1}),L.moved},[b,u]),P=_.useCallback((O,U)=>{var V;const B=y.current;if(!B||!Iu(B,O))return null;U&&(B.lastX=U.clientX,B.lastY=U.clientY),y.current=null,b(B);const L=Bu(B);let Y;if(B.longPressArmed){if(L<=Uf)return w(B),E(B),Y="longpress",Ri("finish",{pointerId:O,result:Y,point:U,moved:B.moved,distance:L,longPressed:!0,longPressArmed:!0}),f==null||f(Y),Y;B.longPressArmed=!1}return B.longPressed?(E(B),Y="longpress",Ri("finish",{pointerId:O,result:Y,point:U,moved:B.moved,longPressArmed:B.longPressArmed,distance:L,longPressed:!0}),f==null||f(Y),Y):T(B)?(t(),Y="scroll",Ri("finish",{pointerId:O,result:Y,point:U,moved:B.moved,distance:L,longPressed:!1,containerScrolled:!0}),f==null||f(Y),Y):B.moved?U&&Bu(B)<=Iye&&(s!=null&&s(U))?(t(),Y="link",Ri("finish",{pointerId:O,result:Y,point:U,moved:!0,distance:L,longPressed:!1}),f==null||f(Y),Y):(t(),Y="scroll",Ri("finish",{pointerId:O,result:Y,point:U,moved:!0,distance:L,longPressed:!1}),f==null||f(Y),Y):U&&(s!=null&&s(U))?(t(),Y="link",Ri("finish",{pointerId:O,result:Y,point:U,moved:!1,distance:L,longPressed:!1}),f==null||f(Y),Y):(n?n():(V=e.current)==null||V.focus(),Y="tap",Ri("finish",{pointerId:O,result:Y,point:U,moved:!1,distance:L,longPressed:!1}),f==null||f(Y),Y)},[b,E,T,n,f,s,w,t,e]),A=_.useCallback((O,U={})=>{const B=y.current;return!B||!Iu(B,O)?null:(b(B),y.current=null,B.longPressed?(E(B,U.immediateLongPressEnd!==!0),Ri("cancel",{pointerId:O,result:"longpress"}),f==null||f("longpress"),"longpress"):(B.longPressArmed&&Ri("cancel",{pointerId:O,result:"armed"}),t(),Ri("cancel",{pointerId:O,result:"scroll",moved:B.moved,distance:Bu(B)}),f==null||f("scroll"),"scroll"))},[b,E,f,t]),H=_.useRef(A);H.current=A,_.useEffect(()=>{const O=()=>{g.current=null;const B=y.current;B&&H.current(B.pointerId,{immediateLongPressEnd:!0})},U=()=>{document.visibilityState==="hidden"&&O()};return window.addEventListener("blur",O),window.addEventListener("pagehide",O),document.addEventListener("visibilitychange",U),()=>{window.removeEventListener("blur",O),window.removeEventListener("pagehide",O),document.removeEventListener("visibilitychange",U);const B=y.current;B&&b(B),y.current=null,g.current=null}},[b]);const D=_.useCallback(O=>{if(O.pointerType!=="touch")return;const U=O.target;if(!(U instanceof Element&&U.closest('[data-slot="pty-selection-handle"]'))&&!(!(U instanceof Element)||!U.closest(".xterm")&&!(r!=null&&r({clientX:O.clientX,clientY:O.clientY})))){if(y.current){O.stopPropagation();return}k(O.pointerId,O.clientX,O.clientY),O.stopPropagation()}},[r,k]),K=_.useCallback(O=>{if(O.pointerType!=="touch")return;const U=y.current;if(U&&!Iu(U,O.pointerId)){O.stopPropagation();return}if(U!=null&&U.touchEventStream&&Iu(U,O.pointerId)){O.stopPropagation();return}const B=R(O.pointerId,O.clientX,O.clientY),L=y.current;L&&B&&(O.stopPropagation(),L.longPressed&&O.preventDefault())},[R]),q=_.useCallback(O=>{const U=y.current,B=P(O.pointerId,{clientX:O.clientX,clientY:O.clientY});B&&(O.pointerType==="touch"&&(g.current={kind:B,touchIdentifier:(U==null?void 0:U.touchIdentifier)??null}),O.stopPropagation(),B==="link"&&O.cancelable&&O.preventDefault())},[P]),X=_.useCallback(O=>{const U=y.current;if(O.pointerType==="touch"&&U&&Iu(U,O.pointerId)&&U.touchEventStream&&!U.longPressed){O.stopPropagation();return}const B=A(O.pointerId);B&&(O.pointerType==="touch"&&(g.current={kind:B,touchIdentifier:(U==null?void 0:U.touchIdentifier)??null}),O.stopPropagation())},[A]),z=_.useCallback(O=>{const U=O.target;if(!(U instanceof Element)||U.closest('[data-slot="pty-selection-handle"]'))return;const B=O.changedTouches[0]??O.touches[0];if(B&&!(!U.closest(".xterm")&&!(r!=null&&r({clientX:B.clientX,clientY:B.clientY})))){if(y.current){if(y.current.touchIdentifier===null){const L=Sg(O.changedTouches,{clientX:y.current.lastX,clientY:y.current.lastY});if(!L)return;y.current.touchIdentifier=L.identifier,y.current.touchEventStream=!0}return}k(hh,B.clientX,B.clientY,!0,B.identifier)}},[r,k]),N=_.useCallback(O=>{const U=y.current;if(!U)return;if(U.touchIdentifier===null){const j=Sg(O.changedTouches.length>0?O.changedTouches:O.touches,{clientX:U.lastX,clientY:U.lastY});if(!j)return;U.touchIdentifier=j.identifier,U.touchEventStream=!0}const B=dc(O.changedTouches,U.touchIdentifier);if(!B&&O.changedTouches.length>0)return;const L=B??dc(O.touches,U.touchIdentifier);if(!L)return;const Y=R(hh,L.clientX,L.clientY),V=y.current;V&&Y&&V.longPressed&&(O.stopPropagation(),O.preventDefault())},[R]),$=_.useCallback(O=>{var V;const U=y.current;if((U==null?void 0:U.touchIdentifier)===null&&O.changedTouches.length>0){const j=Sg(O.changedTouches,{clientX:U.lastX,clientY:U.lastY});j&&(U.touchIdentifier=j.identifier)}const B=U?dc(O.changedTouches,U.touchIdentifier):null;if(U&&!B&&dc(O.touches,U.touchIdentifier))return;const L=B?{clientX:B.clientX,clientY:B.clientY}:U?{clientX:U.lastX,clientY:U.lastY}:void 0,Y=P(hh,L)??((V=g.current)==null?void 0:V.kind);g.current=null,(Y==="longpress"||Y==="link")&&(O.stopPropagation(),O.cancelable&&O.preventDefault())},[P]),I=_.useCallback(O=>{var L;const U=y.current;if((U==null?void 0:U.touchIdentifier)===null&&O.changedTouches.length>0){const Y=Sg(O.changedTouches,{clientX:U.lastX,clientY:U.lastY});Y&&(U.touchIdentifier=Y.identifier)}if(U&&!dc(O.changedTouches,U.touchIdentifier)&&dc(O.touches,U.touchIdentifier))return;const B=A(hh)??((L=g.current)==null?void 0:L.kind);g.current=null,B==="longpress"&&O.stopPropagation()},[A]),M=_.useCallback(O=>{const U=y.current;U&&(O.preventDefault(),O.stopPropagation(),S(U))},[S]);return{onPointerDownCapture:D,onPointerMoveCapture:K,onPointerUpCapture:q,onPointerCancelCapture:X,onTouchStartCapture:z,onTouchMoveCapture:N,onTouchEndCapture:$,onTouchCancelCapture:I,onContextMenuCapture:M}}function jye({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:b,onHorizontalScrollIntent:w,onSelectionAutoscroll:S,onHandleDragStart:E,onHandleDragMove:k,onHandleDragEnd:T,onHandleDragCancel:R}){const P=_.useRef(null),A=_.useRef(null),H=_.useRef(null),D=_.useRef(!1),K=_.useRef(!1),q=_.useRef(null),X=_.useRef(null),z=_.useCallback(()=>{A.current=null,H.current=null,D.current=!1,P.current!==null&&(cancelAnimationFrame(P.current),P.current=null)},[]),N=_.useCallback(()=>{var V;(V=q.current)==null||V.call(q),q.current=null,X.current=null,K.current=!1,z()},[z]),$=_.useCallback(()=>{var oe;P.current=null;const V=A.current;if(!V||!t||!i())return;const j=t.getBoundingClientRect(),{dx:te,dy:re}=$4({pointerX:V.clientX,pointerY:V.clientY,rect:j,scrollLeft:t.scrollLeft,scrollTop:t.scrollTop,scrollWidth:t.scrollWidth,scrollHeight:t.scrollHeight,clientWidth:t.clientWidth,clientHeight:t.clientHeight,edgePx:44,maxSpeedPx:18});te!==0&&(w==null||w(`selectionGestureAutoscroll dx=${Math.round(te)}`),t.scrollLeft+=te),re!==0&&(D.current||(b==null||b(`selectionGestureAutoscroll dy=${Math.round(re)}`),D.current=!0),t.scrollTop+=re),(te!==0||re!==0)&&(S==null||S({scrollLeft:t.scrollLeft,scrollTop:t.scrollTop}),(oe=H.current)==null||oe.call(H,V)),P.current=requestAnimationFrame($)},[t,i,w,S,b]),I=_.useCallback((V,j)=>{A.current=V,H.current=j,P.current===null&&(P.current=requestAnimationFrame($))},[$]);_.useEffect(()=>N,[N]),_.useEffect(()=>{const V=()=>{const te=X.current;te?te():N()},j=()=>{document.visibilityState==="hidden"&&V()};return window.addEventListener("blur",V),window.addEventListener("pagehide",V),document.addEventListener("visibilitychange",j),()=>{window.removeEventListener("blur",V),window.removeEventListener("pagehide",V),document.removeEventListener("visibilitychange",j)}},[N]),_.useEffect(()=>{if(!t)return;const V=j=>{K.current&&j.preventDefault()};return t.addEventListener("touchmove",V,{capture:!0,passive:!1}),document.addEventListener("touchmove",V,{capture:!0,passive:!1}),()=>{t.removeEventListener("touchmove",V,{capture:!0}),document.removeEventListener("touchmove",V,{capture:!0})}},[t]);const M=_.useCallback(V=>{N(),K.current=!0,d(V)},[d,N]),O=_.useCallback(V=>{if(!f(V)){z();return}I(V,f)},[f,z,I]),U=_.useCallback(V=>{N(),p(V)},[p,N]),B=zye({terminalRef:e,suppressPtyFocus:n,focusTerminal:r,isGestureTarget:s,onTap:o,isTapCandidate:l,onLongPressCandidateStart:u,onLongPressStart:M,onLongPressMove:O,onLongPressEnd:U,onGestureFinish:y,getScrollPosition:g}),L=_.useCallback((V,j)=>{if(j.preventDefault(),j.stopPropagation(),q.current)return;N(),K.current=!0,E(V);const te=j.pointerId,re=j.currentTarget.getBoundingClientRect(),oe={x:j.clientX-(re.left+re.width/2),y:j.clientY-(re.top+re.height/2)},ee=(Oe,Se)=>({clientX:Oe-oe.x,clientY:Se-oe.y});let pe=()=>{};const ae=Oe=>{if(Oe.pointerId!==te)return;Oe.cancelable&&Oe.preventDefault();const Se=ee(Oe.clientX,Oe.clientY);k(V,Se),I(Se,Qe=>k(V,Qe))},me=Oe=>{if(Oe.pointerId!==te)return;const Se=ee(Oe.clientX,Oe.clientY);pe(),q.current=null,N(),T(V,Se)},Ee=Oe=>{Oe.pointerId===te&&(pe(),q.current=null,N(),R(V))};pe=()=>{window.removeEventListener("pointermove",ae),window.removeEventListener("pointerup",me),window.removeEventListener("pointercancel",Ee)},q.current=pe,X.current=()=>{N(),R(V)},window.addEventListener("pointermove",ae,{passive:!1}),window.addEventListener("pointerup",me),window.addEventListener("pointercancel",Ee)},[R,T,k,E,N,I]),Y=_.useCallback((V,j)=>{if(q.current)return;const te=j.touches[0]??j.changedTouches[0];if(!te)return;j.preventDefault(),j.stopPropagation(),K.current=!0,D.current=!1,E(V);const re=te.identifier,oe=j.currentTarget.getBoundingClientRect(),ee={x:te.clientX-(oe.left+oe.width/2),y:te.clientY-(oe.top+oe.height/2)},pe=Qe=>{for(let Ht=0;Ht<Qe.length;Ht+=1){const ye=Qe[Ht];if((ye==null?void 0:ye.identifier)===re)return ye}return null},ae=(Qe,Ht)=>({clientX:Qe-ee.x,clientY:Ht-ee.y});let me=()=>{};const Ee=Qe=>{const Ht=pe(Qe.touches)??pe(Qe.changedTouches);if(!Ht)return;Qe.cancelable&&Qe.preventDefault();const ye=ae(Ht.clientX,Ht.clientY);k(V,ye),I(ye,Xe=>k(V,Xe))},Oe=Qe=>{const Ht=pe(Qe.changedTouches);if(!Ht)return;const ye=Ht?ae(Ht.clientX,Ht.clientY):A.current;me(),q.current=null,N(),T(V,ye)},Se=Qe=>{pe(Qe.changedTouches)&&(me(),q.current=null,N(),R(V))};me=()=>{window.removeEventListener("touchmove",Ee),window.removeEventListener("touchend",Oe),window.removeEventListener("touchcancel",Se)},q.current=me,X.current=()=>{N(),R(V)},window.addEventListener("touchmove",Ee,{passive:!1}),window.addEventListener("touchend",Oe),window.addEventListener("touchcancel",Se)},[R,T,k,E,N,I]);return{pointerHandlers:B,stopPtySelectionGesture:N,handlePtySelectionHandlePointerDown:L,handlePtySelectionHandleTouchStart:Y}}const $ye=2,oL=600,Fye=160;function cC(){return/^(Macintosh|MacIntel|MacPPC|Mac68K)$/u.test(navigator.platform)}function W4(e,t){return cC()?t.altKey&&e.options.macOptionClickForcesSelection===!0:t.shiftKey}function Hye(e,t){return e.modes.mouseTrackingMode==="none"||W4(e,t)}function Uye(e,t){return t.altKey&&!(cC()&&e.options.macOptionClickForcesSelection===!0)}function bc(e,t){return e.row===t.row?e.column-t.column:e.row-t.row}function nv(e){const t=ms(e.anchor),n=ms(e.focus);return bc(t,n)<=0?{start:t,end:n}:{start:n,end:t}}function Wye(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}=nv(e);return bc(t,n)>=0&&bc(t,r)<=0}function qye(e){return e.key.toLowerCase()==="c"&&(cC()?e.metaKey:e.ctrlKey)}function ms(e){return{row:e.row,column:e.column}}function g0(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 Yye(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(bye()),w=_.useRef(null),S=_.useRef(null),E=_.useRef(new Map),k=_.useRef(null),T=_.useRef(null),R=_.useRef(""),P=_.useRef(!1),A=_.useRef(null),H=_.useRef(null),D=_.useRef(null),K=_.useRef(null),q=_.useRef("hide"),X=_.useRef(!1),z=_.useRef(0),N=_.useRef(0),$=_.useRef(null),I=_.useRef(null),M=_.useRef(0),O=_.useRef(o),[U,B]=_.useState(null),[L,Y]=_.useState(null),[V,j]=_.useState(null),te=_.useMemo(()=>kye(l),[l]),re=_.useCallback(W=>{q.current=W,X.current=!1,z.current+=1,window.clearTimeout(N.current),N.current=0},[]),oe=_.useCallback((W,ne)=>{const G=window.visualViewport;return H4({clientX:W,clientY:ne,viewportWidth:(G==null?void 0:G.width)??window.innerWidth,viewportHeight:(G==null?void 0:G.height)??window.innerHeight,viewportOffsetLeft:(G==null?void 0:G.offsetLeft)??0,viewportOffsetTop:(G==null?void 0:G.offsetTop)??0})},[]),ee=_.useCallback(W=>{const ne=r.current;if(!ne||!s)return null;const G=ne.getBoundingClientRect(),de=s.getBoundingClientRect(),xe=window.visualViewport,Q=Math.max(de.left+s.clientLeft,(xe==null?void 0:xe.offsetLeft)??0),ie=Math.max(de.top+s.clientTop,(xe==null?void 0:xe.offsetTop)??0),le=Math.min(de.left+s.clientLeft+s.clientWidth,((xe==null?void 0:xe.offsetLeft)??0)+((xe==null?void 0:xe.width)??window.innerWidth)),he=Math.min(de.top+s.clientTop+s.clientHeight,((xe==null?void 0:xe.offsetTop)??0)+((xe==null?void 0:xe.height)??window.innerHeight)),Z={anchor:{left:W.anchor.left+G.left,top:W.anchor.top+G.top},focus:{left:W.focus.left+G.left,top:W.focus.top+G.top}},se=ce=>ce.left>=Q&&ce.left<=le&&ce.top>=ie&&ce.top<=he;return{clientHandles:Z,visible:{anchor:se(Z.anchor),focus:se(Z.focus)}}},[s,r]),pe=_.useCallback(W=>{const ne=ee(W);if(!ne)return null;const G=["anchor","focus"].filter(ie=>ne.visible[ie]);if(G.length===0)return null;const de=ne.clientHandles[G[0]],xe=ne.clientHandles[G[1]??G[0]],Q=window.visualViewport;return Rye({handles:{anchor:de,focus:xe},viewportWidth:(Q==null?void 0:Q.width)??window.innerWidth,viewportHeight:(Q==null?void 0:Q.height)??window.innerHeight,viewportOffsetLeft:(Q==null?void 0:Q.offsetLeft)??0,viewportOffsetTop:(Q==null?void 0:Q.offsetTop)??0})},[ee]),ae=_.useCallback(W=>{const ne=t.current,G=n.current;return!ne||!G?null:Nv(G,W)??E.current.get(W)??ne.buffer.active.getLine(W)},[t,n]),me=_.useCallback(W=>{const ne=t.current,G=n.current,de=r.current;return!ne||!G||!de?null:Tye({terminal:ne,host:G,coordinateSpace:de,anchor:ms(W.anchor),focus:ms(W.focus),columnMode:W.columnMode,getLine:ae})},[ae,r,t,n]),Ee=_.useCallback(()=>{var ne;const W=t.current;return!W||!s||!W.element?null:(w.current&&S.current===W||((ne=w.current)==null||ne.dispose(),w.current=b4({terminal:W,container:s,getLine:ae}),S.current=W),w.current)},[s,ae,t]),Oe=_.useCallback((W,ne=!1)=>{const G=t.current,de=n.current;if(!G||!de)return;ne&&(E.current=new Map);const xe=Math.min(W.anchor.row,W.focus.row),Q=Math.max(W.anchor.row,W.focus.row),ie=v4(de);for(const[Z,se]of ie)Z>=xe&&Z<=Q&&E.current.set(Z,p4(se,G.cols));const le=Math.max(xe,G.buffer.active.viewportY),he=Math.min(Q,G.buffer.active.viewportY+G.rows-1);for(let Z=le;Z<=he;Z+=1)ie.has(Z)||E.current.delete(Z)},[t,n]),Se=_.useCallback(W=>{const ne=Math.min(W.anchor.row,W.focus.row),G=Math.max(W.anchor.row,W.focus.row);E.current=new Map(Array.from(E.current).filter(([de])=>de>=ne&&de<=G))},[]),Qe=_.useCallback(()=>{const W=t.current,ne=n.current;if(!W||!ne)return null;const G=W.buffer.active,de=new Proxy(G,{get(Q,ie){if(ie==="getLine")return le=>E.current.get(le)??Nv(ne,le)??Q.getLine(le);if(ie==="length"){let le=0;for(const he of E.current.keys())le=Math.max(le,he+1);return Math.max(Q.length,le)}return Reflect.get(Q,ie,Q)}}),xe=new Proxy(W.buffer,{get(Q,ie){return ie==="active"?de:Reflect.get(Q,ie,Q)}});return new Proxy(W,{get(Q,ie){return ie==="buffer"?xe:Reflect.get(Q,ie,Q)}})},[t,n]),Ht=_.useCallback((W,ne)=>{const G=ne??Oye(W);return T.current=G,j(G),G},[]),ye=_.useCallback((W,ne)=>{Oe(W);const G=Qe();if(!G)return null;const de=Ay({terminal:G,anchor:ms(W.anchor),focus:ms(W.focus),columnMode:W.columnMode});return de?(R.current=de.text,Ht(de.text,ne),de):null},[Oe,Qe,Ht]),Xe=_.useCallback(()=>{const W=Ti(b.current);return W?ye(W):null},[ye]),kt=_.useCallback((W,ne)=>{var xe;ne.toolbar==="hide"&&re("hide");let G=null;if(ne.toolbar==="hide"){Oe(W);const Q=Qe();if(!Q||W.anchor.column>=Q.cols||W.focus.column>=Q.cols||!Q.buffer.active.getLine(W.anchor.row)||!Q.buffer.active.getLine(W.focus.row))return!1;R.current="",T.current=null,j(null)}else{if(!ye(W,ne.explicitPathAction))return!1;G=T.current}(xe=Ee())==null||xe.render(W),P.current=ne.handles;const de=ne.handles?me(W):null;return Y(de),ne.toolbar==="hide"?B(null):ne.toolbar==="path-only"&&!G?(re("hide"),B(null)):de?(re(ne.toolbar),B(pe(de))):ne.clientPoint?(re(ne.toolbar),B(oe(ne.clientPoint.clientX,ne.clientPoint.clientY))):(re("hide"),B(null)),!0},[Ee,Oe,Qe,me,oe,pe,ye,re]),gt=_.useCallback(()=>{var ne,G;const W=k.current;if(W){k.current=null;for(const de of W.subscriptions)de.dispose();(ne=W.anchor)==null||ne.dispose(),(G=W.focus)==null||G.dispose()}},[]),Lt=_.useCallback(()=>{var W;(W=w.current)==null||W.render(null),P.current=!1,T.current=null,R.current="",re("hide"),B(null),Y(null),j(null)},[re]),an=_.useCallback(()=>{var W,ne,G;(W=I.current)==null||W.call(I),(ne=$.current)==null||ne.call($),b.current=ia(b.current,{type:"clear-selection"}),E.current=new Map,gt(),A.current=null,H.current=null,D.current=null,K.current=null,(G=w.current)==null||G.dispose(),w.current=null,S.current=null,Lt()},[Lt,gt]),ut=_.useCallback(()=>{var W;an(),(W=t.current)==null||W.clearSelection()},[an,t]),Le=_.useCallback((W,ne,G=!1)=>{const de=t.current,xe=n.current;return!de||!xe?null:vye({terminal:de,host:xe,clientX:W,clientY:ne,clampToBuffer:G})},[t,n]),Ke=_.useCallback(()=>{var de;if(!P.current)return;const W=Ti(b.current);if(!W){Y(null),B(null);return}Oe(W),(de=Ee())==null||de.render(W);const ne=me(W);if(Y(ne),!ne){B(null);return}const G=q.current;B(G!=="hide"&&!X.current&&(G!=="path-only"||T.current)?pe(ne):null)},[Oe,Ee,me,pe]),lt=_.useCallback(W=>{gt();const ne=t.current;if(!ne)return!1;const G=ne.buffer.active,de=ne.cols,xe=ne.rows;if(G.type==="alternate"){const Z={terminal:ne,buffer:G,cols:de,rows:xe,anchor:null,focus:null,subscriptions:[],sync:()=>{}},se=()=>{k.current===Z&&(gt(),ut())};return Z.sync=()=>{k.current===Z&&(t.current!==ne||ne.buffer.active!==G||ne.cols!==de||ne.rows!==xe)&&se()},k.current=Z,Z.subscriptions.push(ne.onResize(Z.sync),ne.buffer.onBufferChange(se)),!0}const Q=g0(ne,W.anchor.row);if(!Q)return!1;const ie=g0(ne,W.focus.row);if(!ie||ne.buffer.active!==G||Q.isDisposed||Q.line!==W.anchor.row||ie.isDisposed||ie.line!==W.focus.row)return Q.dispose(),ie==null||ie.dispose(),!1;const le={terminal:ne,buffer:G,cols:de,rows:xe,anchor:Q,focus:ie,subscriptions:[],sync:()=>{}},he=()=>{k.current===le&&(gt(),ut())};return le.sync=()=>{var ze;if(k.current!==le)return;if(t.current!==ne||ne.buffer.active!==G||ne.cols!==de||Q.isDisposed||ie.isDisposed||Q.line<0||ie.line<0){he();return}const Z=b.current;if(Z.phase!=="selected"||Z.range.anchor.row===Q.line&&Z.range.focus.row===ie.line)return;const se=Q.line-Z.range.anchor.row,ce=ie.line-Z.range.focus.row;if(se!==ce){he();return}const Me={...Z.range,anchor:{...Z.range.anchor,row:Q.line},focus:{...Z.range.focus,row:ie.line}};if(b.current=ia(Z,{type:"set-selection",range:Me}),E.current=$f(E.current,se),H.current&&(H.current={...H.current,row:H.current.row+se}),D.current){const Ze=aa(D.current.range,se);if(!Ze){he();return}D.current={range:Ze,lines:$f(D.current.lines,se)}}(ze=Ee())==null||ze.render(Me),Ke()},k.current=le,le.subscriptions.push(Q.onDispose(he),ie.onDispose(he),ne.onWriteParsed(le.sync),ne.onResize(le.sync),ne.buffer.onBufferChange(he)),!0},[ut,Ee,Ke,gt,t]),ve=_.useCallback(()=>{if(!P.current)return;const W=Ti(b.current),ne=r.current,G=W?me(W):null;if(!ne)return;const de=G?ee(G):null;for(const xe of["anchor","focus"]){const Q=ne.querySelector(`[data-slot="pty-selection-handle"][data-kind="${xe}"]`);if(!Q)continue;const ie=G==null?void 0:G[xe];if(!ie){Q.style.visibility!=="hidden"&&(Q.style.visibility="hidden"),Q.style.pointerEvents!=="none"&&(Q.style.pointerEvents="none");continue}const le=(de==null?void 0:de.visible[xe])===!0||K.current===xe,he=`translate3d(${ie.left}px, ${ie.top}px, 0) translate(-50%, -50%)`,Z=le?"visible":"hidden",se=le?"auto":"none";Q.style.transform!==he&&(Q.style.transform=he),Q.style.visibility!==Z&&(Q.style.visibility=Z),Q.style.pointerEvents!==se&&(Q.style.pointerEvents=se)}},[ee,me,r]),$e=_.useCallback((W,ne,G=!1)=>{const de={anchor:ms(W.anchor),focus:ms(W.focus),columnMode:W.columnMode};return b.current=ia(b.current,{type:"set-selection",range:de}),G&&(E.current=new Map),!kt(de,ne)||!lt(de)?(ut(),null):de},[lt,ut,kt]);_.useEffect(()=>()=>{gt()},[gt]),_.useEffect(()=>{var W;return(W=w.current)==null||W.dispose(),w.current=null,S.current=null,()=>{var ne;(ne=w.current)==null||ne.dispose(),w.current=null,S.current=null}},[s]),_.useEffect(()=>{if(!s)return;const W=s.ownerDocument,ne=t.current;let G=null,de=1,xe=null,Q=!1,ie=null,le=()=>{};const he=()=>{var bt;const Pe=ie;if(Pe){ie=null;for(const xt of Pe.subscriptions)xt.dispose();(bt=Pe.marker)==null||bt.dispose()}},Z=()=>{xe!==null&&(cancelAnimationFrame(xe),xe=null)},se=()=>{G=null,Z(),he()};I.current=se;const ce=(Pe,bt)=>{const xt=Ti(b.current);xt&&(G&&(E.current=G.selectionLines),kt(xt,{handles:!1,toolbar:"hide",clientPoint:{clientX:Pe,clientY:bt}}))},Me=(Pe,bt)=>{he();const xt=Pe.buffer.active,Te=xt.type==="normal"?g0(Pe,bt):null;if(xt.type==="normal"&&!Te)return!1;const tt={terminal:Pe,buffer:xt,cols:Pe.cols,rows:Pe.rows,marker:Te,markerLine:(Te==null?void 0:Te.line)??bt,subscriptions:[]},St=()=>{ie===tt&&(he(),le())},Yt=()=>{if(ie!==tt||!G)return;if(t.current!==Pe||Pe.buffer.active!==xt||Pe.cols!==tt.cols||xt.type==="alternate"&&Pe.rows!==tt.rows||Te!=null&&Te.isDisposed||Te!==null&&Te.line<0){St();return}if(!Te)return;const on=Te.line-tt.markerLine;if(on!==0){if(tt.markerLine=Te.line,b.current=wye(b.current,on),G.initialRange=G.initialRange?aa(G.initialRange,on):null,G.selectionLines=$f(G.selectionLines,on),G.selectionLinesBeforePress=$f(G.selectionLinesBeforePress,on),E.current=$f(E.current,on),b.current.phase!=="pressed"&&b.current.phase!=="selecting"){St();return}ce(G.lastX,G.lastY)}};return ie=tt,tt.subscriptions.push(Pe.onWriteParsed(Yt),Pe.onResize(Yt),Pe.buffer.onBufferChange(St)),Te&&tt.subscriptions.push(Te.onDispose(St)),!0},ze=(Pe,bt)=>{const xt=Qe();return xt?bt==="line"?yye({terminal:xt,point:Pe}):bt==="word"?h0({terminal:xt,point:Pe})??f0({terminal:xt,point:Pe}):null:null},Ze=Pe=>{if(!G||!Pe||G.unit==="cell"||!G.initialRange)return null;const bt=ze(Pe,G.unit);if(!bt)return G.initialRange;const xt=nv(G.initialRange),Te=nv({anchor:bt.anchor,focus:bt.focus});return bc(Te.end,xt.start)<0?{anchor:xt.end,focus:Te.start}:bc(Te.start,xt.end)>0?{anchor:xt.start,focus:Te.end}:G.initialRange},Ve=()=>{if(!G)return;const Pe=Le(G.lastX,G.lastY,!0);b.current=ia(b.current,{type:"selection-autoscroll",pointerId:G.id,bufferPoint:Pe,range:Ze(Pe)}),ce(G.lastX,G.lastY)},mt=()=>{var St,Yt;if(xe=null,!G||!Nx(b.current))return;const Pe=s.getBoundingClientRect(),{dx:bt,dy:xt}=$4({pointerX:G.lastX,pointerY:G.lastY,rect:Pe,scrollLeft:s.scrollLeft,scrollTop:s.scrollTop,scrollWidth:s.scrollWidth,scrollHeight:s.scrollHeight,clientWidth:s.clientWidth,clientHeight:s.clientHeight}),Te=s.scrollLeft,tt=s.scrollTop;bt!==0&&((St=i.current)==null||St.markHorizontalScrollIntent(`managedSelectionAutoscroll dx=${Math.round(bt)}`),s.scrollLeft+=bt),xt!==0&&((Yt=i.current)==null||Yt.markSelectionAutoscrollIntent(`managedSelectionAutoscroll dy=${Math.round(xt)}`),s.scrollTop+=xt),(s.scrollLeft!==Te||s.scrollTop!==tt)&&Ve(),xe=requestAnimationFrame(mt)},vt=()=>{xe===null&&Nx(b.current)&&(xe=requestAnimationFrame(mt))},Je=(Pe,bt,xt)=>{var Bt;if(!G)return;const Te=G,tt=b.current,St=Pe==="cancel"?"preserve-selection":tt.phase==="pressed"?Te.shiftExtend||Te.unit!=="cell"?"commit-selection":"clear-on-click":"commit-selection";b.current=ia(tt,{type:"gesture-finish",pointerId:Te.id,result:St}),E.current=St==="preserve-selection"?Te.selectionLinesBeforePress:St==="commit-selection"?Te.selectionLines:new Map,se(),St==="preserve-selection"&&((Bt=k.current)==null||Bt.sync());const Yt=Ti(b.current);if(!Yt){E.current=new Map,gt(),Lt();return}if(Se(Yt),!kt(Yt,{handles:!1,toolbar:"path-only",clientPoint:{clientX:bt,clientY:xt}})){ut();return}St==="commit-selection"&&!lt(Yt)&&ut()};le=()=>{var Pe;G&&((Pe=t.current)==null||Pe.clearSelection(),Je("cancel",G.lastX,G.lastY))};const Nt=Pe=>{if(Pe.button!==0)return;const bt=t.current,xt=Pe.target;if(!bt||!(xt instanceof Element))return;const Te=Le(Pe.clientX,Pe.clientY,!1);if(!xt.closest(".xterm")&&!Te)return;const tt=W4(bt,Pe),St=Ave(bt,Pe),Yt=bt.modes.mouseTrackingMode!=="none"&&!tt&&(Pe.metaKey||Pe.ctrlKey)&&St!==null;if(!Hye(bt,Pe)&&!Yt)return;G&&Je("cancel",G.lastX,G.lastY),Pe.preventDefault(),Pe.stopImmediatePropagation(),bt.focus(),bt.clearSelection();const on=Ti(b.current),Bt=new Map(E.current),ue=de++,we=Pe.shiftKey&&on!==null&&Te!==null,be=on&&we?on.columnMode:Uye(bt,Pe),Re=we?"cell":Pe.detail===3?"line":Pe.detail===2?"word":"cell",ot=we?new Map(Bt):new Map;E.current=ot;const Et=Te?ze(Te,Re):null,dt=we?{anchor:on.anchor,focus:Te,columnMode:on.columnMode}:Et?{anchor:ms(Et.anchor),focus:ms(Et.focus)}:null;if(b.current=ia(b.current,{type:"pointer-press",candidate:{pointerId:ue,client:{x:Pe.clientX,y:Pe.clientY},bufferPoint:Te,columnMode:be}}),dt&&(b.current=ia(b.current,{type:"resolve-press-range",pointerId:ue,range:dt}),ce(Pe.clientX,Pe.clientY)),G={id:ue,startX:Pe.clientX,startY:Pe.clientY,lastX:Pe.clientX,lastY:Pe.clientY,shiftExtend:we,unit:Re,initialRange:dt,linkCandidate:Pe.detail===1&&!we&&!tt&&!be?St:null,selectionLinesBeforePress:Bt,selectionLines:ot},Te&&!Me(bt,Te.row)){le();return}(we||Re!=="cell")&&queueMicrotask(()=>{t.current===bt&&bt.clearSelection()})},wt=Pe=>{var Te,tt;if(!G)return;if(Pe.buttons===0){(Te=t.current)==null||Te.clearSelection(),Je("release",Pe.clientX,Pe.clientY);return}Pe.preventDefault(),Pe.stopImmediatePropagation(),G.lastX=Pe.clientX,G.lastY=Pe.clientY;const bt=b.current;if(bt.phase==="pressed"&&Math.hypot(Pe.clientX-G.startX,Pe.clientY-G.startY)<$ye)return;(tt=t.current)==null||tt.clearSelection(),G.linkCandidate=null;const xt=Le(Pe.clientX,Pe.clientY,!0);b.current=ia(bt,{type:"pointer-move",pointerId:G.id,client:{x:Pe.clientX,y:Pe.clientY},bufferPoint:xt,range:Ze(xt)}),b.current.phase==="selecting"&&(ce(Pe.clientX,Pe.clientY),vt())},Xt=Pe=>{var tt,St;if(!G||Pe.button!==0)return;const bt=b.current.phase==="pressed"&&G.unit==="cell"&&!G.shiftExtend,xt=bt?G.linkCandidate:null;Pe.preventDefault(),Pe.stopImmediatePropagation(),(tt=t.current)==null||tt.clearSelection(),Je("release",Pe.clientX,Pe.clientY),!((xt==null?void 0:xt.activateOnMouseUp(Pe))===!0)&&bt&&xt===null&&(f==null||f({clientX:Pe.clientX,clientY:Pe.clientY,pointerType:"mouse",altKey:Pe.altKey,ctrlKey:Pe.ctrlKey,metaKey:Pe.metaKey,shiftKey:Pe.shiftKey})),(St=t.current)==null||St.focus()},sn=()=>{var Pe;G&&((Pe=t.current)==null||Pe.clearSelection(),Je("cancel",G.lastX,G.lastY))},ke=Pe=>{var bt;!G||Pe.pointerType!=="mouse"||((bt=t.current)==null||bt.clearSelection(),Je("cancel",Pe.clientX,Pe.clientY))},je=()=>{var Pe;!G||W.visibilityState!=="hidden"||((Pe=t.current)==null||Pe.clearSelection(),Je("cancel",G.lastX,G.lastY))},Ge=()=>{var Pe;G&&((Pe=t.current)==null||Pe.clearSelection(),Je("cancel",G.lastX,G.lastY))},st=Pe=>{var xt;const bt=((xt=Xe())==null?void 0:xt.text)??"";!bt||!Pe.clipboardData||(Q=!0,Pe.clipboardData.setData("text/plain",bt),Pe.preventDefault(),Pe.stopImmediatePropagation())},Rt=Pe=>{var bt;if(Ti(b.current)){if(qye(Pe)){const xt=((bt=Xe())==null?void 0:bt.text)??"";if(!xt)return;Pe.preventDefault(),Pe.stopImmediatePropagation(),Q=!1;try{W.execCommand("copy")}catch{}if(!Q){const Te=W.activeElement instanceof HTMLElement?W.activeElement:null;Ax(xt,{allowLegacyFallback:!0}).finally(()=>{Te!=null&&Te.isConnected&&(W.activeElement===W.body||W.activeElement===null)&&Te.focus({preventScroll:!0})})}return}Pe.key==="Shift"||Pe.key==="Control"||Pe.key==="Meta"||Pe.key==="Alt"||ut()}},Kt=Pe=>{var we,be,Re;const bt=t.current,xt=Pe.target,Te=Le(Pe.clientX,Pe.clientY,!1);if(!bt||!(xt instanceof Element)||!xt.closest(".xterm")&&!Te)return;const tt=Ti(b.current);if(Te&&(!tt||!Wye(tt,Te))){const ot=E.current;E.current=new Map;const Et=Qe();if(!Et){E.current=ot;return}const dt=h0({terminal:Et,point:Te}),wn=dt??f0({terminal:Et,point:Te});wn?$e(wn,{handles:!1,toolbar:"hide",clientPoint:{clientX:Pe.clientX,clientY:Pe.clientY},explicitPathAction:dt==null?void 0:dt.pathAction},!0):E.current=ot}if(!Ti(b.current))return;const Yt=((we=Xe())==null?void 0:we.text)??"",on=(be=bt.element)==null?void 0:be.querySelector(".xterm-helper-textarea"),Bt=(Re=bt.element)==null?void 0:Re.querySelector(".xterm-screen");if(!on||!Bt)return;Pe.stopImmediatePropagation();const ue=Bt.getBoundingClientRect();Object.assign(on.style,{width:"20px",height:"20px",left:`${Pe.clientX-ue.left-10}px`,top:`${Pe.clientY-ue.top-10}px`,zIndex:"1000"}),on.value=Yt,on.focus({preventScroll:!0}),on.select()};return s.addEventListener("mousedown",Nt,!0),s.addEventListener("copy",st,!0),s.addEventListener("keydown",Rt,!0),s.addEventListener("contextmenu",Kt,!0),W.addEventListener("mousemove",wt,!0),W.addEventListener("mouseup",Xt,!0),W.addEventListener("pointercancel",ke,!0),W.addEventListener("visibilitychange",je),window.addEventListener("blur",sn),window.addEventListener("pagehide",Ge),()=>{G?(ne==null||ne.clearSelection(),Je("cancel",G.lastX,G.lastY)):se(),I.current===se&&(I.current=null),s.removeEventListener("mousedown",Nt,!0),s.removeEventListener("copy",st,!0),s.removeEventListener("keydown",Rt,!0),s.removeEventListener("contextmenu",Kt,!0),W.removeEventListener("mousemove",wt,!0),W.removeEventListener("mouseup",Xt,!0),W.removeEventListener("pointercancel",ke,!0),W.removeEventListener("visibilitychange",je),window.removeEventListener("blur",sn),window.removeEventListener("pagehide",Ge)}},[lt,ut,Lt,s,Le,Qe,f,kt,Se,Xe,gt,i,$e,t]),_.useLayoutEffect(()=>{if(!U&&!L&&!V)return;const W=ne=>{const G=ne.target;if(G instanceof Element&&G.closest('[data-slot="pty-selection-toolbar"], [data-slot="pty-selection-handle"]'))return;const de="pointerType"in ne&&typeof ne.pointerType=="string"?ne.pointerType:null,xe=G instanceof Element&&G.closest(".xterm")!==null,Q=xe||G instanceof Element&&G.closest('[data-slot="pty-spacer"], [data-slot="pty-host"]')!==null,ie=!xe&&Q&&"clientX"in ne&&typeof ne.clientX=="number"&&"clientY"in ne&&typeof ne.clientY=="number"&&Le(ne.clientX,ne.clientY,!1)!==null,le=G instanceof Element&&G.closest('[data-slot="pty-scrollbar"], [data-slot="pty-horizontal-scrollbar"]')!==null;Eye({hasManagedSelection:Ti(b.current)!==null,eventType:ne.type,pointerType:de,targetIsScrollSurface:le||Q&&(ne.type==="touchstart"||de==="touch")})||de==="mouse"&&(xe||ie)||ut()};return document.addEventListener("pointerdown",W,!0),document.addEventListener("touchstart",W,!0),()=>{document.removeEventListener("pointerdown",W,!0),document.removeEventListener("touchstart",W,!0)}},[ut,Le,L,V,U]);const at=L!==null;_.useLayoutEffect(()=>{at&&ve()},[at,L,ve]),_.useLayoutEffect(()=>{if(!at||!s)return;const W=t.current;ve(),s.addEventListener("scroll",ve,{passive:!0});const ne=W==null?void 0:W.onScroll(ve),G=W==null?void 0:W.onRender(ve),de=W==null?void 0:W.onResize(ve),xe=new ResizeObserver(ve);xe.observe(s);const Q=r.current;Q&&xe.observe(Q);const ie=n.current;return ie&&xe.observe(ie),()=>{s.removeEventListener("scroll",ve),ne==null||ne.dispose(),G==null||G.dispose(),de==null||de.dispose(),xe.disconnect()}},[s,at,r,ve,t,n]),_.useLayoutEffect(()=>{var ne;const W=O.current!==o;O.current=o,W&&(M.current=performance.now()+oL),at&&((ne=i.current)==null||ne.relayout(),Ke(),ve())},[at,o,Ke,i,ve]),_.useEffect(()=>{if(!at)return;const W=window.visualViewport;let ne=0,G=0;const de=()=>{M.current=performance.now()+oL,cancelAnimationFrame(ne),window.clearTimeout(G),ne=requestAnimationFrame(()=>{Ke(),ve(),G=window.setTimeout(()=>{ne=requestAnimationFrame(()=>{Ke(),ve()})},160)})};return Ke(),ve(),window.addEventListener("resize",de),W==null||W.addEventListener("resize",de),W==null||W.addEventListener("scroll",de),()=>{cancelAnimationFrame(ne),window.clearTimeout(G),window.removeEventListener("resize",de),W==null||W.removeEventListener("resize",de),W==null||W.removeEventListener("scroll",de)}},[at,Ke,ve]);const yt=_.useCallback(({clientX:W,clientY:ne})=>{u({blur:!1}),A.current=Le(W,ne,!1)},[Le,u]),pt=_.useCallback(({clientX:W,clientY:ne})=>{const G=t.current;if(!G)return;const de=Le(W,ne,!1)??A.current;if(G.clearSelection(),!de){ut();return}E.current=new Map;const xe=Qe();if(!xe)return;const Q=h0({terminal:xe,point:de}),ie=Q??f0({terminal:xe,point:de});if(!ie){ut();return}H.current=null,$e(ie,{handles:!0,toolbar:"hide",clientPoint:{clientX:W,clientY:ne},explicitPathAction:Q==null?void 0:Q.pathAction},!0)},[ut,Le,Qe,$e,t]),cn=_.useCallback(({clientX:W,clientY:ne})=>{const G=Le(W,ne,!0),de=Ti(b.current);if(!G||!de)return!1;if(!H.current){const{start:Q,end:ie}=nv(de),le=bc(G,Q),he=bc(G,ie);if(le>=0&&he<=0)return!1;H.current=ms(le<0?ie:Q)}const xe={anchor:H.current,focus:G,text:""};return $e(xe,{handles:!0,toolbar:"hide",clientPoint:{clientX:W,clientY:ne}})!==null},[Le,$e]),qt=_.useCallback(W=>{const ne=Ti(b.current);ne&&(Se(ne),kt(ne,{handles:!0,toolbar:"show",clientPoint:W}))},[kt,Se]),Gt=_.useCallback(()=>{const W=q.current;if(W==="hide"||K.current!==null)return;const ne=Ti(b.current);if(!ne||!Xe()||W==="path-only"&&!T.current)return;const G=me(ne);B(G?pe(G):null)},[me,pe,Xe]);_.useLayoutEffect(()=>{if(!s)return;const W=s.ownerDocument,ne=W.defaultView??window;let G=!1;const de=()=>{window.clearTimeout(N.current),N.current=0},xe=()=>{if(de(),G||!X.current||q.current==="hide"||W.visibilityState==="hidden")return;const ce=++z.current;N.current=window.setTimeout(()=>{N.current=0,!(ce!==z.current||G||q.current==="hide"||W.visibilityState==="hidden")&&(X.current=!1,Gt())},Fye)},Q=()=>{q.current!=="hide"&&(X.current=!0,B(null),xe())},ie=ce=>{ce.touches.length!==0&&(G=!0,z.current+=1,de())},le=ce=>{ce.touches.length>0||(G=!1,xe())},he=()=>{G=!1,z.current+=1,de()},Z=()=>{W.visibilityState==="hidden"?he():xe()},se=()=>xe();return s.addEventListener("scroll",Q,{passive:!0}),s.addEventListener("touchstart",ie,{passive:!0,capture:!0}),W.addEventListener("touchend",le,{passive:!0,capture:!0}),W.addEventListener("touchcancel",le,{passive:!0,capture:!0}),W.addEventListener("visibilitychange",Z),ne.addEventListener("blur",he),ne.addEventListener("focus",se),ne.addEventListener("pagehide",he),ne.addEventListener("pageshow",se),()=>{z.current+=1,X.current=!1,de(),s.removeEventListener("scroll",Q),s.removeEventListener("touchstart",ie,!0),W.removeEventListener("touchend",le,!0),W.removeEventListener("touchcancel",le,!0),W.removeEventListener("visibilitychange",Z),ne.removeEventListener("blur",he),ne.removeEventListener("focus",se),ne.removeEventListener("pagehide",he),ne.removeEventListener("pageshow",se)}},[s,Gt]);const vn=_.useCallback(({clientX:W,clientY:ne})=>{A.current=null,H.current=null,qt({clientX:W,clientY:ne})},[qt]),dn=_.useCallback(()=>{var ne;const W=((ne=Xe())==null?void 0:ne.text)??"";W&&Ax(W,{allowLegacyFallback:!0}).then(G=>{ut(),G==="failed"?nt.error("复制失败"):nt.success("已复制")})},[ut,Xe]),$t=_.useCallback(()=>{if(!Xe())return;const W=T.current;W&&(W.kind==="image-preview"?g(W.path):y(W.path),ut())},[ut,y,g,Xe]),nn=_.useCallback(()=>Ti(b.current)!==null,[]),rn=_.useCallback(()=>!s||performance.now()<=M.current?null:{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop},[s]),qn=_.useCallback(W=>{K.current=W;const ne=Ti(b.current);D.current=ne?{range:{...ne,anchor:{...ne.anchor},focus:{...ne.focus}},lines:new Map(E.current)}:null,re("hide"),B(null)},[re]),Fn=_.useCallback((W,{clientX:ne,clientY:G})=>{const de=Le(ne,G,!0),xe=Ti(b.current);if(!de||!xe)return;const Q={anchor:W==="anchor"?de:ms(xe.anchor),focus:W==="focus"?de:ms(xe.focus),columnMode:xe.columnMode,text:""};$e(Q,{handles:!0,toolbar:"hide",clientPoint:{clientX:ne,clientY:G}})},[Le,$e]),Jn=_.useCallback((W,ne)=>{K.current=null,D.current=null,qt(ne??void 0)},[qt]),lr=_.useCallback(()=>{K.current=null;const W=D.current;if(D.current=null,!W){qt();return}if(E.current=W.lines,b.current=ia(b.current,{type:"set-selection",range:W.range}),!kt(W.range,{handles:!0,toolbar:"show"})){ut();return}lt(W.range)||ut()},[lt,ut,kt,qt]),fn=jye({terminalRef:t,containerEl:s,suppressPtyFocus:u,focusPtyInput:d,isSelectionActive:nn,isGestureTarget:({clientX:W,clientY:ne})=>Le(W,ne,!1)!==null,onTap:f,isTapCandidate:p,onLongPressCandidateStart:yt,onLongPressStart:pt,onLongPressMove:cn,onLongPressEnd:vn,getTouchScrollPosition:rn,onGestureFinish:W=>{Cye(W)&&ut()},onVerticalScrollIntent:W=>{var ne;return(ne=i.current)==null?void 0:ne.markSelectionAutoscrollIntent(W)},onHorizontalScrollIntent:W=>{var ne;return(ne=i.current)==null?void 0:ne.markHorizontalScrollIntent(W)},onHandleDragStart:qn,onHandleDragMove:Fn,onHandleDragEnd:Jn,onHandleDragCancel:lr});return $.current=fn.stopPtySelectionGesture,{pointerHandlers:fn.pointerHandlers,ptySelectionToolbar:U,ptySelectionHandles:L,ptySelectionPathAction:V,ptySelectionHandleMetrics:te,hasPtySelection:nn,clearManagedPtySelection:an,clearPtySelection:ut,copyPtySelection:dn,openPtySelectionPathAction:$t,handlePtySelectionHandlePointerDown:fn.handlePtySelectionHandlePointerDown,handlePtySelectionHandleTouchStart:fn.handlePtySelectionHandleTouchStart}}function Vye(){return De(e=>e.ptyScrollTraceEnabled)}const Kye=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function aL(e){return Kye.has(e)}function uC(e){if(!e)return null;const t=Array.from(e.items??[]);for(const r of t){if(r.kind!=="file"||!aL(r.type))continue;const i=r.getAsFile();if(i)return i}return Array.from(e.files??[]).find(r=>aL(r.type))??null}function Gye(e){return`${e.startsWith("@")?e:`@${e}`} `}async function q4(e){const t=uC(e.clipboardData);if(!t)return null;if(!e.relay)throw new Error("请先连接开发机");const n=await z4(t),r=await e.relay.uploadClipboardImage(e.sessionId,n);if(!r.success||!r.path)throw new Error(r.error??"剪贴板图片上传失败");return{path:r.path,pathMention:Gye(r.path)}}function Xye(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 Zye({sessionId:e,terminalRef:t,onAfterPaste:n}){return _.useCallback(async r=>{var u;const i=r.clipboardData,s=!!uC(i),o=s?null:Xye(i);if(!s&&!o)return;r.preventDefault(),r.stopPropagation();const l=Ut;if(!l){nt.error("请先连接开发机");return}if(s){const d=nt.loading("图片上传中...");try{const f=await q4({clipboardData:i,relay:l,sessionId:e});if(nt.dismiss(d),!f)return;eo(e,f.pathMention)}catch(f){nt.error(f instanceof Error?f.message:String(f),{id:d});return}}else if(o){const d=await Vh({relay:l,sessionId:e,file:o});if(!d)return;eo(e,`@${d} `)}n==null||n(),(u=t.current)==null||u.focus()},[e,t,n])}const Qye=new Set(["Enter","Backspace","Tab","Escape","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Delete","Home","End"]),lL={caseSensitive:!1,regex:!1,wholeWord:!1,decorations:Cx};function Jye({softKeyboardEditingSurface:e,ptyInputFocused:t,keyboardOpen:n}){return e&&t&&n}function ebe({controlsVisible:e,keyboardOpen:t,previous:n}){return e?!n.controlsVisible||t&&!n.keyboardOpen:!1}function tbe({touchEditingSurface:e,inputModePreference:t,detectedPhysicalKeyboard:n,softKeyboardDetected:r}){return!e||t==="hardware"?!0:t==="touch"?!1:n&&!r}function nbe({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:Qye.has(n)}const cL=8,rbe=32;function ibe({showMobilePtyControls:e,horizontalScrollable:t,mobileControlsHeight:n}){return e?Math.ceil(Math.max(0,n))+cL:t?rbe:cL}function sbe(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"?fh("\x1B[A",t):e.key==="ArrowDown"?fh("\x1B[B",t):e.key==="ArrowRight"?fh("\x1B[C",t):e.key==="ArrowLeft"?fh("\x1B[D",t):e.key==="Delete"?"\x1B[3~":e.key==="Home"?"\x1B[H":e.key==="End"?"\x1B[F":null}function obe(e){const{sessionId:t,active:n=!0,containerEl:r,spacerRef:i,xtermHostRef:s,selectionHandleLayerRef:o,mobileControlsHeight:l}=e,u=tye(),d=u.markDisconnected,f=sye(),p=Vye(),{openImagePreview:y}=LE(),g=_.useRef(null),b=_.useRef(null),w=_.useRef(null),S=_.useRef(!1),E=_.useRef([]),k=_.useRef(null),T=_.useRef(null),R=_.useRef(n),P=_.useRef(n),A=_.useRef(!1),H=_.useRef(!1),D=_.useRef(!1),K=_.useRef(!1),q=_.useRef(null),X=_.useRef(null),z=_.useRef(null),N=_.useRef(null),$=_.useRef({keyboardOpen:!1,controlsVisible:!1}),I=_.useRef(!1),M=_.useRef(!1),O=_.useRef(!1),U=_.useRef({keyboardOffset:0,hasSeenSoftKeyboard:!1,showMobilePtyControls:!1,touchEditingSurface:!1,ptyInputFocused:!1,containerPaddingBottom:0,mobileControlsBottomInset:0}),[B,L]=_.useState({scrollTop:0,scrollLeft:0,scrollHeight:0,scrollWidth:0,clientHeight:0,clientWidth:0,scrollable:!1,horizontalScrollable:!1}),[Y,V]=_.useState(!1),[j,te]=_.useState(!1),[re,oe]=_.useState({resultIndex:-1,resultCount:0}),ee=De(ke=>ke.connected),pe=De(ke=>ke.proxyOnline),ae=De(ke=>ke.ptyFontSize),me=De(ke=>ke.inputModePreference),Ee=De(ke=>ke.adaptiveInputModality),Oe=De(ke=>ke.setAdaptiveInputModality),Se=Ee==="hardware",Qe=Cl("(pointer: coarse), (hover: none)"),{bottomOffset:Ht,layoutBottomInset:ye}=lC(),Xe=me==="hardware",kt=tbe({touchEditingSurface:Qe,inputModePreference:me,detectedPhysicalKeyboard:Se,softKeyboardDetected:Ht>0}),gt=Qe&&!kt,Lt=kt?0:Ht,an=Lt>0,ut=kt?0:ye,[Le,Ke]=_.useState(()=>ee&&pe);I.current=kt,R.current=n,A.current=u.ready,H.current=ee&&pe;const lt=_.useCallback(()=>R.current&&A.current&&H.current,[]);_.useEffect(()=>{ee&&pe&&Ke(!0)},[ee,pe]),_.useEffect(()=>{Lt>0&&V(!0)},[Lt]);const ve=iye({containerEl:r,xtermHostRef:s,terminalRef:g}),{ptyInputFocused:$e,suppressPtyFocus:at,focusPtyInput:yt,handleFocusCapture:pt,handleBlurCapture:cn}=ve,qt=Jye({softKeyboardEditingSurface:gt,ptyInputFocused:$e,keyboardOpen:an});U.current={keyboardOffset:Lt,hasSeenSoftKeyboard:Y,showMobilePtyControls:qt,touchEditingSurface:Qe,ptyInputFocused:$e,containerPaddingBottom:U.current.containerPaddingBottom,mobileControlsBottomInset:ut};const Gt=f.clearNewFramesWhileAway;X.current||(X.current=KP(()=>{var ke;(ke=T.current)==null||ke.relayout()}));const vn=_.useCallback(()=>{O.current=!1},[]);z.current||(z.current=KP(()=>{var je,Ge;const ke=N.current??{reason:"rawInput",force:!1};N.current=null,ke.force&&vn(),(je=T.current)==null||je.traceRawInputFollowFire(),(Ge=T.current)==null||Ge.scrollToBottom(ke.reason,ke.force?{force:!0}:void 0),Gt()}));const dn=_.useCallback(()=>{if(O.current)return;const ke=T.current;ke&&ke.preparePageResumeRestore(),O.current=!0},[]),$t=_.useCallback(()=>{if(!O.current||document.visibilityState==="hidden"||!R.current||!A.current)return;const ke=T.current;ke&&(ke.restorePageResume(),Gt(),O.current=!1)},[Gt]);_.useEffect(()=>()=>{var ke,je;(ke=X.current)==null||ke.dispose(),(je=z.current)==null||je.dispose(),X.current=null,z.current=null},[]),_.useEffect(()=>{const ke=()=>{dn()},je=()=>{if(document.visibilityState==="hidden"){ke();return}$t()};return document.addEventListener("visibilitychange",je),window.addEventListener("pagehide",ke),window.addEventListener("pageshow",$t),window.addEventListener("focus",$t),()=>{document.removeEventListener("visibilitychange",je),window.removeEventListener("pagehide",ke),window.removeEventListener("pageshow",$t),window.removeEventListener("focus",$t)}},[dn,$t]),_.useLayoutEffect(()=>{const ke=P.current;if(P.current=n,!n){ke&&dn();return}(!ke||O.current)&&u.ready&&$t()},[n,u.ready,dn,$t]);const nn=_.useCallback((ke="rawInput",je)=>{var Rt,Kt;const Ge=N.current,st=(Ge==null?void 0:Ge.force)===!0||(je==null?void 0:je.force)===!0;N.current={reason:(je==null?void 0:je.force)===!0||!Ge?ke:Ge.reason,force:st},(Rt=T.current)==null||Rt.traceRawInputFollowScheduled(ke),(Kt=z.current)==null||Kt.schedule()},[]),rn=_.useCallback((ke,je)=>{var Ge;!ke.includes("\r")&&!ke.includes(`
|
|
670
670
|
`)||(Ge=T.current)==null||Ge.resetHorizontalScroll(je,{holdUntilCursorVisible:!0})},[]),qn=_.useCallback(()=>I.current?"submit":"linefeed",[]),Fn=_.useCallback(()=>I.current,[]);_.useEffect(()=>{if(!n||me!=="auto"||!Qe)return;const ke=Ge=>{const st=s.current,Rt=r;return Ge instanceof Node?st!=null&&st.contains(Ge)||Ge===document.body||Ge===document.documentElement?!0:Rt!=null&&Rt.contains(Ge)?Ge instanceof HTMLElement?Ge.closest('a,button,input,textarea,select,[contenteditable="true"],[role="button"],[role="textbox"]')===null:!0:!1:Ge===window},je=Ge=>{var Kt,Pe;if(!nbe({active:R.current,touchEditingSurface:Qe,key:Ge.key,code:Ge.code,altKey:Ge.altKey,ctrlKey:Ge.ctrlKey,metaKey:Ge.metaKey,isComposing:Ge.isComposing,targetAcceptsPtyInput:ke(Ge.target)}))return;Oe("hardware"),I.current=!0,(Kt=g.current)==null||Kt.focus();const st=s.current;if(Ge.target instanceof Node&&(st!=null&&st.contains(Ge.target)))return;const Rt=sbe(Ge,(Pe=g.current)==null?void 0:Pe.modes);!Rt||!lt()||(Ge.preventDefault(),Ge.stopPropagation(),eo(t,Rt),nn("physicalKeyboard"),rn(Rt,"physicalKeyboardEnter"))};return window.addEventListener("keydown",je,!0),()=>window.removeEventListener("keydown",je,!0)},[n,lt,r,me,rn,nn,t,Oe,Qe,s]);const Jn=_.useCallback(ke=>{const je=Ut;if(!je){nt.error("请先连接开发机");return}const Ge=nt.loading(`下载 ${ke} ...`);PE({relay:je,sessionId:t,path:ke}).then(st=>{st.ok?nt.success(`已开始下载 ${ke}`,{id:Ge}):nt.error(st.error,{id:Ge})}).catch(st=>{nt.error(st instanceof Error?st.message:String(st),{id:Ge})})},[t]),lr=_.useCallback(ke=>{const je=g.current;return je?Pve(je,E.current,ke):!1},[]),fn=_.useCallback(ke=>{const je=g.current;return je?Nve(je,E.current,ke):!1},[]),W=Yye({terminalRef:g,xtermHostRef:s,selectionHandleLayerRef:o,scrollControllerRef:T,containerEl:r,keyboardOffset:Lt,ptyFontSize:ae,suppressPtyFocus:at,focusPtyInput:yt,onTap:lr,isTapCandidate:fn,onDownloadPath:Jn,onPreviewPath:y}),ne=W.clearManagedPtySelection,G=W.clearPtySelection;M.current=W.hasPtySelection();const de=_.useCallback(()=>{const ke=g.current,je=w.current,Ge=S.current&&ke?zP(ke.getSelectionPosition(),ke.cols):null;je==null||je.render(Ge)},[]),xe=Zye({sessionId:t,terminalRef:g,onAfterPaste:()=>nn("paste")}),Q=_.useCallback(ke=>{if(!lt()){ke.preventDefault();return}xe(ke)},[lt,xe]),[ie,le]=_.useState(!1),he=_.useCallback(ke=>{ke.dataTransfer.types.includes("Files")&&(ke.preventDefault(),le(je=>je||!0))},[]),Z=_.useCallback(ke=>{ke.currentTarget.contains(ke.relatedTarget)||le(!1)},[]),se=_.useCallback(async ke=>{var Rt;const je=(Rt=ke.dataTransfer.files)==null?void 0:Rt[0];if(!je||(ke.preventDefault(),le(!1),!lt()))return;const Ge=Ut;if(!Ge){nt.error("请先连接开发机");return}const st=await Vh({relay:Ge,sessionId:t,file:je});st&&(eo(t,`@${st} `),nn("dropUpload"))},[lt,nn,t]),ce=_.useCallback(ke=>{var Ge;if(!lt()){ke.preventDefault();return}const je=ke.target;je instanceof Element&&je.closest(".xterm")||(ke.preventDefault(),(Ge=g.current)==null||Ge.focus())},[lt]);_.useEffect(()=>{if(!Le)return;const ke=s.current,je=_c,Ge=Ut,st=r,Rt=i.current;if(!ke||!je||!Ge||!st||!Rt)return;let Kt=null,Pe=null,bt=null,xt=null,Te=null,tt=null,St=null,Yt=null;const we=Yge({host:ke,sessionId:t,ws:je,relay:Ge,scheduleAutoFocus:gt?()=>{}:be=>{requestAnimationFrame(()=>{JP(s.current)&&be()})},createTerminal:async be=>{const Re=await h4(be,{fontSize:De.getState().ptyFontSize});return Yt=Re.serializeAddon,Re},attachRawInput:(be,Re,ot)=>Jme(be,Re,{...ot,getPlainEnterBehavior:qn,isPhysicalKeyboardMode:Fn,physicalKeyboardMode:Xe}),isInputEnabled:lt,canFocus:lt,onTerminalReady:be=>{G();const Re=be;g.current=Re;const ot=new Kue({highlightLimit:1e3});Re.loadAddon(ot),b.current=ot,Te=ot.onDidChangeResults(Nn=>{oe(Nn),de()}),te(!0);const Et=uve(Re,y);Kt=Et.dispose;const dt=Eve(Re,Jn);Pe=dt.dispose,E.current=[Et.provider,dt.provider],Gve(()=>g.current);const wn=xme(Re),sr=Nme(ke,{serializeRangeAsHtml:(Nn,br)=>(Yt==null?void 0:Yt.serializeAsHTML({range:{startLine:Nn,endLine:Math.min(br,Math.max(0,Re.buffer.active.length-1)),startCol:0},includeGlobalBackground:!0,onlySelection:!1,scrollback:0}))??"",getSerializedCell:(Nn,br)=>{var mi;const Tn=(mi=Re.buffer.active.getLine(Nn))==null?void 0:mi.getCell(br);return Tn?{text:Tn.getWidth()===0?"":Tn.getChars()||" ",isDim:!!Tn.isDim(),isRenderedFgRGB:Tn.isInverse()?Tn.isBgRGB():Tn.isFgRGB()}:null},getSelectionLine:Nn=>Re.buffer.active.getLine(Nn)??null,getBufferRowIdentityOffset:wn.getOffset});xt=()=>{sr.dispose(),wn.dispose()};const Gn=O.current;Gn&&(K.current=!1);const ni=zge({container:st,spacer:Rt,host:ke,term:Re,hasNewFrame:()=>D.current,consumeNewFrame:()=>{D.current=!1},hasNewFramesWhileAway:()=>f.hasNewFramesWhileAwayRef.current,setNewFramesWhileAway:f.setHasNewFramesWhileAway,onAtBottomChange:f.handleAtBottomChange,onScrollStateChange:L,initialUserHasVerticalScrollIntent:Gn?!1:K.current,onUserVerticalScrollIntentChange:Nn=>{K.current=Nn},onTouchReviewStart:at,onHistoryProjectionChange:Nn=>{const br=sr.render(Nn);return br&&de(),br},getBufferRowIdentityOffset:wn.getOffset});T.current=ni,bt=ni.dispose,St=b4({terminal:Re,container:st,getLine:Nn=>Nv(ke,Nn)??Re.buffer.active.getLine(Nn)??null,resolveRange:()=>S.current?zP(Re.getSelectionPosition(),Re.cols):null,projectionOnly:!0,overlaySlot:"pty-search-selection-overlay",segmentSlot:"pty-search-selection-segment",selectionBackground:Cx.activeMatchBackground,borderColor:Cx.activeMatchBorder,opacity:"0.62"}),w.current=St,tt=Re.onSelectionChange(de),de(),Gn&&(ni.restorePageResume(),Gt(),O.current=!1),Zve(()=>{var Hl;const Nn=_r=>{if(!_r)return null;const Pn=_r.getBoundingClientRect();return{top:Pn.top,bottom:Pn.bottom,height:Pn.height,left:Pn.left,right:Pn.right,width:Pn.width}},br=document.querySelector('[data-slot="pty-mobile-controls"]'),Tn=document.querySelector("[data-keyboard-offset]"),mi=window.visualViewport,ao=Nn(br),Zt=(mi==null?void 0:mi.height)??window.innerHeight;return{...Jve(ni.getDebugProbe,{container:st,spacer:Rt,host:ke,term:Re}),mobileLayout:{...U.current,window:{innerHeight:window.innerHeight,outerHeight:window.outerHeight,documentClientHeight:document.documentElement.clientHeight},visualViewport:mi?{height:mi.height,width:mi.width,offsetTop:mi.offsetTop,pageTop:mi.pageTop,scale:mi.scale}:null,chatRoot:{dataKeyboardOffset:(Tn==null?void 0:Tn.getAttribute("data-keyboard-offset"))??null,rect:Nn(Tn)},ptyViewRect:Nn(st.parentElement),containerRect:Nn(st),controlsRect:ao,controlsOverflowBelowVisualViewport:ao===null?null:ao.bottom-Zt,activeElement:document.activeElement instanceof HTMLElement?{tag:document.activeElement.tagName,ariaLabel:document.activeElement.getAttribute("aria-label"),slot:(Hl=document.activeElement.closest("[data-slot]"))==null?void 0:Hl.getAttribute("data-slot")}:null},frame:{lastWriteAt:q.current,pendingNewFrame:D.current}}})},onFramePending:()=>{var be;D.current=!0,(be=T.current)==null||be.markHorizontalLiveFramePending(),K.current&&!f.hasNewFramesWhileAwayRef.current&&f.setHasNewFramesWhileAway(!0)},onFrameWritten:()=>{var be;q.current=performance.now(),(be=X.current)==null||be.schedule()},onRawInput:be=>{ege(be)||(nn("rawInput",{force:!0}),rn(be,"rawInputEnter"))},onError:be=>{const Re=be instanceof Error?be.message:String(be);nt.error(`终端初始化失败:${Re}`)},connectTransportInitially:ee&&pe,...u.transport});return k.current=we,()=>{S.current=!1,tt==null||tt.dispose(),St==null||St.dispose(),w.current===St&&(w.current=null),G(),bt==null||bt(),xt==null||xt(),Te==null||Te.dispose(),Qve(),Kt==null||Kt(),Pe==null||Pe(),E.current=[],Xve(),b.current=null,te(!1),oe({resultIndex:-1,resultCount:0}),we.dispose(),g.current=null,T.current=null,k.current=null}},[t,Le,r,i,s,u.transport,f.handleAtBottomChange,f.hasNewFramesWhileAwayRef,f.setHasNewFramesWhileAway,lt,Xe,qn,Fn,Jn,y,at,nn,rn,G,de]),_.useEffect(()=>{if(!Le)return;const ke=k.current;if(ke){if(!ee||!pe){d(),ke.setTransportActive(!1);return}return Kge(t,n?"active":"background",()=>{var je;(je=k.current)==null||je.setTransportActive(!0)})}},[n,ee,d,pe,t,Le]),_.useEffect(()=>{const ke=g.current,je=T.current;!ke||!je||Sme(ke,ae,je.relayout)},[ae]),_.useEffect(()=>{if(!n||!u.ready||gt)return;const ke=requestAnimationFrame(()=>{var je;JP(s.current)&&((je=g.current)==null||je.focus())});return()=>cancelAnimationFrame(ke)},[n,u.ready,gt,s]);const Me=_.useCallback((ke="viewExternal",je)=>{var Ge;je!=null&&je.force&&vn(),(Ge=T.current)==null||Ge.scrollToBottom(ke,je)},[vn]),ze=_.useCallback(ke=>{var je;(je=T.current)==null||je.scrollToRatio(ke)},[]),Ze=_.useCallback(ke=>{var je;(je=T.current)==null||je.scrollToXRatio(ke)},[]),Ve=_.useCallback(ke=>{var Pe;const je=g.current,Ge=je==null?void 0:je.getSelectionPosition();if(!je||!Ge)return;const st=Ge.start.y;if(st>=ke&&st<ke+je.rows)return;const Rt=Math.max(0,je.buffer.active.length-je.rows);if(Rt===0)return;const Kt=Math.max(0,Math.min(Rt,st-Math.floor(je.rows/2)));(Pe=T.current)==null||Pe.scrollToRatio(Kt/Rt)},[]),mt=_.useCallback((ke,je=!1)=>{const Ge=g.current,st=b.current;if(!Ge||!st||!ke)return ke||(S.current=!1,st==null||st.clearDecorations(),Ge==null||Ge.clearSelection(),ne(),de(),oe({resultIndex:-1,resultCount:0})),!1;ne(),S.current=!0;const Rt=Ge.buffer.active.viewportY,Kt=st.findNext(ke,{...lL,incremental:je});return Kt&&Ve(Rt),de(),Kt},[ne,de,Ve]),vt=_.useCallback(ke=>{const je=g.current,Ge=b.current;if(!je||!Ge||!ke)return!1;ne(),S.current=!0;const st=je.buffer.active.viewportY,Rt=Ge.findPrevious(ke,lL);return Rt&&Ve(st),de(),Rt},[ne,de,Ve]),Je=_.useCallback(()=>{var ke,je;S.current=!1,(ke=b.current)==null||ke.clearDecorations(),(je=g.current)==null||je.clearSelection(),ne(),de(),oe({resultIndex:-1,resultCount:0})},[ne,de]),Nt=_.useCallback(ke=>{var Ge,st;if(!lt())return;const je=fh(ke,(Ge=g.current)==null?void 0:Ge.modes);eo(t,je),nn("mobileControl",{force:!0}),rn(ke,"mobileControlEnter"),(st=g.current)==null||st.focus()},[lt,rn,nn,t]),wt=_.useCallback(()=>{var je,Ge,st;if(!lt())return;const ke=(Ge=(je=navigator.clipboard)==null?void 0:je.readText)==null?void 0:Ge.bind(navigator.clipboard);if(!window.isSecureContext||!ke){nt.error("无法读取剪贴板"),(st=g.current)==null||st.focus();return}ke().then(Rt=>{if(!Rt)return;const Kt=g.current;if(Kt){Kt.paste(Rt);return}eo(t,Rt),nn("paste"),rn(Rt,"pasteEnter")}).catch(Rt=>{const Kt=Rt instanceof Error&&Rt.message?Rt.message:"无法读取剪贴板";nt.error(Kt)}).finally(()=>{var Rt;return(Rt=g.current)==null?void 0:Rt.focus()})},[lt,rn,nn,t]),Xt=ibe({showMobilePtyControls:qt,horizontalScrollable:B.horizontalScrollable,mobileControlsHeight:l});U.current.containerPaddingBottom=Xt,_.useEffect(()=>{var Ge,st;M.current?(Ge=T.current)==null||Ge.relayout():(st=X.current)==null||st.schedule();const ke=$.current,je=ebe({controlsVisible:qt,keyboardOpen:an,previous:ke});$.current={keyboardOpen:an,controlsVisible:qt},qt&&(M.current?Gt():je&&nn("keyboardOffset",{force:!0}))},[Lt,an,qt,Xt,Gt,nn]);const sn=_.useMemo(()=>({onFocusCapture:pt,onBlurCapture:cn}),[pt,cn]);return{scrollState:B,isAtBottom:f.isAtBottom,hasNewFramesWhileAway:f.hasNewFramesWhileAway,ptyInputFocused:$e,showMobilePtyControls:qt,touchEditingSurface:Qe,keyboardOffset:Lt,physicalKeyboardMode:kt,softKeyboardEditingSurface:gt,mobileControlsBottomInset:ut,connectionReady:u.ready,connectionOverlay:u.overlay,containerPaddingBottom:Xt,traceEnabled:p,findReady:j,findResultIndex:re.resultIndex,findResultCount:re.resultCount,findNext:mt,findPrevious:vt,clearFind:Je,scrollToBottom:Me,scrollToRatio:ze,scrollToXRatio:Ze,clearNewFramesWhileAway:Gt,sendMobileInput:Nt,pasteMobileClipboard:wt,handleTerminalContainerMouseDown:ce,handlePasteCapture:Q,pointerHandlers:W.pointerHandlers,focusHandlers:sn,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:ie,handlePtyDragOver:he,handlePtyDragLeave:Z,handlePtyDrop:se}}function abe({sessionId:e,sessionKind:t,provider:n,active:r=!0,findRequest:i}){const[s,o]=_.useState(null),[l,u]=_.useState(0),[d,f]=_.useState(!1),[p,y]=_.useState(""),g=_.useRef(null),b=_.useRef(null),w=_.useRef(null),S=obe({sessionId:e,active:r,containerEl:s,spacerRef:g,xtermHostRef:b,selectionHandleLayerRef:w,mobileControlsHeight:l}),E=S.ptySelectionHandleMetrics,{clearFind:k,findNext:T,findPrevious:R,findReady:P,findResultCount:A,findResultIndex:H}=S,D=_.useCallback(()=>{R(p)},[R,p]),K=_.useCallback(()=>{T(p)},[T,p]),q=_.useCallback(()=>f(!0),[]),X=_.useCallback(()=>{f(!1),k()},[k]),z=U5({enabled:r,open:d,openRequest:i,onOpen:q,onClose:X,onPrevious:D,onNext:K});return _.useEffect(()=>{!d||!P||(p?T(p,!0):k())},[k,T,d,p,P]),v.jsxs("div",{className:"flex flex-col h-full relative","data-slot":"chat-pty-view","data-connection-ready":S.connectionReady?"true":"false","aria-busy":!S.connectionReady,children:[d?v.jsx(AS,{query:p,resultIndex:H,resultCount:A,focusRequest:z.focusRequest,loading:!!p&&!P,onQueryChange:y,onPrevious:D,onNext:K,onClose:z.closeFind}):null,v.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) + ${S.containerPaddingBottom}px)`,touchAction:"pan-x pan-y",overflowAnchor:"none"},onMouseDownCapture:S.handleTerminalContainerMouseDown,onPointerDownCapture:N=>{S.pointerHandlers.onPointerDownCapture(N)},onPointerMoveCapture:S.pointerHandlers.onPointerMoveCapture,onPointerUpCapture:S.pointerHandlers.onPointerUpCapture,onPointerCancelCapture:S.pointerHandlers.onPointerCancelCapture,onTouchStartCapture:S.pointerHandlers.onTouchStartCapture,onTouchMoveCapture:S.pointerHandlers.onTouchMoveCapture,onTouchEndCapture:S.pointerHandlers.onTouchEndCapture,onTouchCancelCapture:S.pointerHandlers.onTouchCancelCapture,onContextMenuCapture:S.pointerHandlers.onContextMenuCapture,onPasteCapture:S.handlePasteCapture,onDragOver:S.handlePtyDragOver,onDragLeave:S.handlePtyDragLeave,onDrop:S.handlePtyDrop,onFocusCapture:S.focusHandlers.onFocusCapture,onBlurCapture:S.focusHandlers.onBlurCapture,"data-slot":"pty-terminal","data-drag-over":S.isPtyDragOver?"true":void 0,children:[v.jsx("div",{ref:g,style:{position:"relative",overflowAnchor:"none"},"data-slot":"pty-spacer",children:v.jsx("div",{ref:b,style:{position:"absolute",left:0,top:0,overflow:"hidden",overflowAnchor:"none",boxSizing:"border-box"},"data-slot":"pty-host"})}),v.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}})]}),v.jsx($5,{visible:!S.isAtBottom,hasNewMessages:S.hasNewFramesWhileAway,className:d?"top-14":"top-10",onClick:()=>{S.scrollToBottom("backToBottomBtn",{force:!0}),S.clearNewFramesWhileAway()}}),S.showMobilePtyControls?v.jsx(oue,{sessionKind:t,provider:n,bottomInset:S.mobileControlsBottomInset,onInput:S.sendMobileInput,onPaste:S.pasteMobileClipboard,onHeightChange:u}):null,S.ptySelectionHandles&&w.current?Fc.createPortal(v.jsxs(v.Fragment,{children:[v.jsx(uL,{kind:"anchor",metrics:E,"aria-label":"调整选区起点",onPointerDown:N=>S.handlePtySelectionHandlePointerDown("anchor",N),onTouchStart:N=>S.handlePtySelectionHandleTouchStart("anchor",N)}),v.jsx(uL,{kind:"focus",metrics:E,"aria-label":"调整选区终点",onPointerDown:N=>S.handlePtySelectionHandlePointerDown("focus",N),onTouchStart:N=>S.handlePtySelectionHandleTouchStart("focus",N)})]}),w.current):null,S.ptySelectionToolbar?v.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:S.ptySelectionToolbar.left,top:S.ptySelectionToolbar.top},"data-slot":"pty-selection-toolbar",children:[v.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:N=>N.preventDefault(),onClick:S.copyPtySelection,"aria-label":"复制终端选区",children:"复制"}),S.ptySelectionPathAction?v.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:N=>N.preventDefault(),onClick:S.openPtySelectionPathAction,"aria-label":S.ptySelectionPathAction.kind==="image-preview"?"预览终端选区图片":"下载终端选区文件",children:S.ptySelectionPathAction.kind==="image-preview"?"预览":"下载"}):null]}):null,v.jsx(pue,{state:S.scrollState,onScrollRatio:S.scrollToRatio}),v.jsx(mue,{state:S.scrollState,onScrollRatio:S.scrollToXRatio}),v.jsx(Vce,{...S.connectionOverlay}),v.jsx(Gce,{ptyInputFocused:S.ptyInputFocused,touchEditingSurface:S.touchEditingSurface,softKeyboardEditingSurface:S.softKeyboardEditingSurface,physicalKeyboardMode:S.physicalKeyboardMode,keyboardOffset:S.keyboardOffset,showMobilePtyControls:S.showMobilePtyControls,mobileControlsBottomInset:S.mobileControlsBottomInset}),S.traceEnabled?v.jsx(lbe,{}):null]})}function uL({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 v.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:[v.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"}),v.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 lbe(){const[e,t]=_.useState(!1);async function n(){const r=qce();try{await navigator.clipboard.writeText(r),t(!0),window.setTimeout(()=>t(!1),1200)}catch{window.prompt("Copy PTY scroll trace",r)}}return v.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 cbe=1024,ube=720,xg=.5,Y4=_.createContext(null);function dbe({children:e}){const[t,n]=_.useState([]),[r,i]=_.useState(null),[s,o]=_.useState(null),l=De(k=>k.selectedProxyId),u=Ft(k=>k.sessions),d=Ft(k=>k.sessionListLoaded),f=_.useRef(l),p=_.useRef(null),y=_.useMemo(()=>u.filter(k=>k.mode==="pty").map(k=>k.sessionId).sort().join(`
|
|
671
671
|
`),[u]),g=_.useCallback(k=>{p.current=k.sessionId,i(k),n(T=>mle(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=_.useCallback((k,T)=>{p.current===k&&o(R=>!T||R&&pbe(R,T)?R:T)},[]),S=_.useCallback((k,T)=>{T!==void 0&&n(R=>R.map(P=>P.sessionId===k?{...P,findRequest:T}:P))},[]);_.useEffect(()=>{if(!d)return;const k=new Set(y?y.split(`
|
|
672
|
-
`):[]);n(T=>T.filter(R=>k.has(R.sessionId))),i(T=>T&&k.has(T.sessionId)?T:null),p.current&&!k.has(p.current)&&(p.current=null,o(null))},[y,d]),_.useEffect(()=>{const k=f.current;f.current=l,!(!k||k===l)&&(p.current=null,n([]),i(null),o(null))},[l]);const E=_.useMemo(()=>({activate:g,deactivate:b,updateFindRequest:S,updateViewportRect:w}),[g,b,S,w]);return v.jsxs(Y4.Provider,{value:E,children:[e,v.jsx(hbe,{entries:t,activeView:r,viewportRect:s})]})}function fbe({sessionId:e,sessionKind:t,provider:n,findRequest:r}){const i=_.useContext(Y4),s=_.useRef(null);if(!i)throw new Error("PtyKeepAliveViewport must be used within PtyKeepAliveProvider");const{activate:o,deactivate:l,updateFindRequest:u,updateViewportRect:d}=i;return _.useLayoutEffect(()=>(o({sessionId:e,sessionKind:t,provider:n}),()=>l(e)),[o,l,e,t,n]),_.useLayoutEffect(()=>{u(e,r)},[r,e,u]),_.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]),v.jsx("div",{ref:s,className:"h-full w-full bg-background","data-slot":"pty-keepalive-viewport","data-session-id":e})}function hbe({entries:e,activeView:t,viewportRect:n}){return e.length===0?null:v.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)??cbe,height:(n==null?void 0:n.height)??ube};return v.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:v.jsx(j5,{sessionId:r.sessionId,children:v.jsx(abe,{sessionId:r.sessionId,sessionKind:r.sessionKind,provider:r.provider,active:i,findRequest:r.findRequest})})},r.sessionId)})})}function pbe(e,t){return Math.abs(e.top-t.top)<=xg&&Math.abs(e.left-t.left)<=xg&&Math.abs(e.width-t.width)<=xg&&Math.abs(e.height-t.height)<=xg}function mbe(){const e=Ft(r=>r.codexActiveWriterConflict),t=Ft(r=>r.setCodexActiveWriterConflict),n=()=>t(null);return v.jsx(Bl,{open:e!==null,onOpenChange:r=>!r&&n(),children:v.jsxs(zl,{focusSurfaceOnOpen:!0,className:"min-w-0 sm:max-w-md",children:[v.jsxs(jl,{children:[v.jsx(ba,{children:"该 Codex 会话仍在运行"}),v.jsxs(El,{className:"space-y-2 text-left leading-6",children:[v.jsxs("span",{className:"block",children:["另一个 Codex 进程正在使用此会话",e!=null&&e.activeWriterPid?v.jsxs(v.Fragment,{children:["(PID"," ",v.jsx("span",{className:"font-mono text-foreground",children:e.activeWriterPid}),")"]}):null,"。"]}),v.jsx("span",{className:"block",children:"它可能来自本机终端、Codex App 或另一条 DEV Anywhere 会话。请先回到或结束原会话后再重试。"}),v.jsx("span",{className:"block text-muted-foreground/80",children:"DEV Anywhere 不会自动终止该进程。"})]})]}),v.jsx(Mc,{children:v.jsx(At,{type:"button",onClick:n,autoFocus:!0,children:"知道了"})})]})})}function dC({route:e,surface:t,proxiesLength:n,hasProxy:r,sessionCount:i,relayClientAuthIssue:s=null}){return s==="missing_client_token"?"Relay 服务器需要 client token。请在设置里填写。":s==="invalid_client_token"?"当前浏览器保存的 client token 无效或已过期。请在设置里更新。":n===0?"在开发机上启动 DEV Anywhere,本页会显示可连接的开发机。":t==="mobile"&&e==="proxy-select"||!r?"选择要连接的开发机。":i===0?"还没有会话。可以从本地终端接入,也可以新建会话。":t==="desktop"?"从左侧打开会话,或新建会话开始新的任务。":"打开会话,或新建会话开始新的任务。"}const fC="dev-anywhere:last-chat-route",V4="dev-anywhere:route-restored",Px="dev-anywhere:restored-target";function gbe(e){return e.alreadyRestored||e.pathname!=="/"||!e.lastRoute||!e.lastRoute.startsWith("/chat/")?null:e.lastRoute}function vbe(){var e;try{return((e=globalThis.localStorage)==null?void 0:e.getItem(fC))??null}catch{return null}}function ybe(e){var t;try{(t=globalThis.localStorage)==null||t.setItem(fC,e)}catch{}}function K4(){var e;try{(e=globalThis.localStorage)==null||e.removeItem(fC)}catch{}}function bbe(){var e;try{return((e=globalThis.sessionStorage)==null?void 0:e.getItem(V4))==="1"}catch{return!1}}function _be(){var e;try{(e=globalThis.sessionStorage)==null||e.setItem(V4,"1")}catch{}}function wbe(e){var t;try{(t=globalThis.sessionStorage)==null||t.setItem(Px,e)}catch{}}function Sbe(){var e,t;try{const n=((e=globalThis.sessionStorage)==null?void 0:e.getItem(Px))??null;return n!==null&&((t=globalThis.sessionStorage)==null||t.removeItem(Px)),n}catch{return null}}function xbe(e){const t=JI(e);return t.osName!=="iPad"?{supported:!0}:e.standalone||t.browserName==="Safari"?{supported:!0}:{supported:!1,reason:"ipad-safari-required",browserName:t.browserName}}function rv(){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 Ebe(){return typeof navigator>"u"?{supported:!0}:xbe({userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints,standalone:rv()})}function Cbe(){Uve(),Wve();const e=Ui(),t=so(),n=e.pathname.startsWith("/chat/"),r=e.pathname==="/"||e.pathname==="/sessions",[i,s]=_.useState(!1),[o,l]=_.useState(()=>rv()),u=De(D=>D.proxies.length),d=De(D=>D.proxyListLoaded),f=De(D=>D.relayClientAuthIssue),p=De(D=>!!D.selectedProxyId),y=De(D=>D.selectedProxyId),g=De(D=>D.selectedProxyName),b=Ft(D=>D.sessions.length),w=De(D=>D.pendingToast),S=De(D=>D.setPendingToast),E=e.pathname==="/"?"proxy-select":"sessions",k=dC({route:E,surface:"mobile",proxiesLength:u,hasProxy:p,sessionCount:b,relayClientAuthIssue:f}),T=g??y,P=e.pathname==="/sessions"&&d&&u>0?v.jsxs(At,{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":T?`切换开发机,当前 ${T}`:"切换开发机",onClick:()=>t("/"),children:[v.jsx(FD,{className:"size-4 text-primary","aria-hidden":"true"}),v.jsxs("span",{className:"min-w-0 truncate",children:[v.jsx("span",{className:"text-foreground",children:"切换开发机"}),T?v.jsxs("span",{className:"ml-1 text-muted-foreground/75",children:["· ",T]}):null]})]}):null;_.useEffect(()=>{if(!w)return;({error:nt.error,info:nt.info,success:nt.success})[w.kind](w.message),S(null)},[w,S]),_.useEffect(()=>{if(typeof window.matchMedia!="function"){l(rv());return}const D=window.matchMedia("(display-mode: standalone)"),K=window.matchMedia("(display-mode: fullscreen)"),q=()=>l(rv());return q(),D.addEventListener("change",q),K.addEventListener("change",q),()=>{D.removeEventListener("change",q),K.removeEventListener("change",q)}},[]);const A=_.useRef(!1);_.useEffect(()=>{if(A.current)return;A.current=!0;const D=gbe({pathname:e.pathname,alreadyRestored:bbe(),lastRoute:vbe()});_be(),D&&(wbe(D),t(D,{replace:!0}))},[]);const H=_.useRef(!1);return _.useEffect(()=>{n?(H.current=!0,ybe(`${e.pathname}${e.search}`)):H.current&&(H.current=!1,K4())},[n,e.pathname,e.search]),v.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":o?"true":void 0,children:[!n&&v.jsx(At,{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:()=>s(!0),children:v.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:v.jsx(WD,{className:"size-4","aria-hidden":"true"})})}),!n&&v.jsx(yae,{subtitle:k,action:P}),v.jsx(ple,{}),v.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[v.jsx(mae,{className:"hidden md:flex"}),v.jsx("main",{className:"relative flex-1 overflow-hidden",role:"main",children:v.jsx(dbe,{children:v.jsx("div",{className:Ye("h-full",!r&&"animate-in fade-in-0 duration-200 motion-reduce:animate-none"),children:v.jsx(i9,{})},r?"top-level":e.pathname)})})]}),v.jsx(kS,{open:i,onOpenChange:s}),v.jsx(mbe,{}),v.jsx(qae,{}),v.jsx(Tae,{}),v.jsx($Q,{})]})}function G4({subtitle:e,action:t}){return v.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-6 px-6 text-center",children:[v.jsx(s5,{texts:o5,className:"text-2xl md:text-3xl font-bold"}),v.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:e}),t&&v.jsx("div",{children:t})]})}function kbe(){const e=De(o=>o.proxies),t=De(o=>!!o.selectedProxyId),n=De(o=>o.relayClientAuthIssue),r=Ft(o=>o.sessions.length),i=dC({route:"proxy-select",surface:"desktop",proxiesLength:e.length,hasProxy:t,sessionCount:r,relayClientAuthIssue:n}),s=n==="missing_client_token"?"client-token-missing":n==="invalid_client_token"?"client-token-invalid":null;return v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"h-full md:hidden",children:v.jsx(U3,{layout:"page"})}),v.jsx("div",{className:"hidden md:block h-full",children:s?v.jsx(wc,{variant:s}):v.jsx(G4,{subtitle:i})})]})}function Tbe(){const e=De(o=>o.proxies),t=De(o=>!!o.selectedProxyId),n=De(o=>o.relayClientAuthIssue),r=Ft(o=>o.sessions.length),i=Oi("local",Sn.proxyId)!==null;if(!t&&!i)return v.jsx(r9,{to:"/",replace:!0});const s=dC({route:"sessions",surface:"desktop",proxiesLength:e.length,hasProxy:t,sessionCount:r,relayClientAuthIssue:n});return v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"h-full md:hidden",children:v.jsx(Q3,{layout:"page"})}),v.jsx("div",{className:"hidden md:block h-full",children:v.jsx(G4,{subtitle:s})})]})}function X4(){if(!(typeof navigator>"u"))return navigator.wakeLock}function Rbe(e,t){return e===!1?"insecure-context":t?null:"unsupported"}function Z4(){var t;const e=typeof window>"u"?void 0:window.isSecureContext;return Rbe(e,typeof((t=X4())==null?void 0:t.request)=="function")}function Abe(e){return e==="insecure-context"?"屏幕常亮需要 HTTPS":"当前浏览器不支持屏幕常亮"}function Mbe(){const e=X4();if(typeof(e==null?void 0:e.request)!="function")throw new Error(Abe(Z4()));return e.request("screen")}function Nbe(e){return e instanceof Error&&e.message.trim()?e.message:"无法开启屏幕常亮"}class Pbe{constructor(t={}){_t(this,"activeScopes",new Set);_t(this,"pendingScopes",new Set);_t(this,"listeners",new Map);_t(this,"sentinel",null);_t(this,"requestInFlight",null);_t(this,"requestWakeLock");_t(this,"documentRef");_t(this,"windowRef");_t(this,"unavailableReason");_t(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(()=>{})});_t(this,"handlePageHide",()=>{this.releaseSentinel().catch(()=>{})});var n,r;this.requestWakeLock=t.request??Mbe,this.unavailableReason=typeof t.request=="function"?null:Z4(),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(Nbe(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 cl=new Pbe;function Q4(e){const[t,n]=_.useState(()=>cl.getSnapshot(e));_.useEffect(()=>cl.subscribe(e,n),[e]),_.useEffect(()=>()=>{cl.disable(e).catch(()=>{})},[e]);const r=_.useCallback(()=>cl.enable(e),[e]),i=_.useCallback(()=>cl.disable(e),[e]),s=_.useCallback(()=>cl.toggle(e),[e]);return{...t,enable:r,disable:i,toggle:s}}function Lbe(){return new AudioContext}class Obe{constructor(t=Lbe){_t(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 iv=new Obe,dL=400,nd=[];let J4=1;function Dbe(){return typeof performance>"u"?0:Math.round(performance.now()*10)/10}function ph(e){const t={sequence:J4++,timestamp:new Date().toISOString(),monotonicMs:Dbe(),sessionId:e.sessionId,scope:e.scope,event:e.event,...e.attemptId?{attemptId:e.attemptId}:{},...e.requestId?{requestId:e.requestId}:{},...e.details?{details:{...e.details}}:{}};nd.push(t),nd.length>dL&&nd.splice(0,nd.length-dL)}function Ibe(){return nd.map(e=>({...e,...e.details?{details:{...e.details}}:{}}))}function Bbe(){nd.length=0,J4=1}typeof window<"u"&&(window.__devAnywhereVoicePilotDiagnostics={snapshot:Ibe,clear:Bbe});function e$(e){return`voice-pilot:${e}`}function zbe(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 jbe="modulepreload",$be=function(e){return"/"+e},fL={},Fbe=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=$be(d),d in fL)return;fL[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":jbe,f||(y.as="script"),y.crossOrigin="",y.href=d,u&&y.setAttribute("nonce",u),document.head.appendChild(y),f)return new Promise((g,b)=>{y.addEventListener("load",g),y.addEventListener("error",()=>b(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)})},Hbe="/assets/fvad-DYxbW2my.wasm",wd=16e3,Ube=20,ul=wd*Ube/1e3,v0=ul*Int16Array.BYTES_PER_ELEMENT;let hL=null;async function Wbe(){return hL??(hL=Fbe(async()=>{const{default:e}=await import("./fvad-BQ0eMlem.js");return{default:e}},[]).then(({default:e})=>e({locateFile:t=>t.endsWith(".wasm")?Hbe:t}))),hL}class hC{constructor(t,n,r){_t(this,"destroyed",!1);this.module=t,this.handle=n,this.framePointer=r}static async create(t=3){const n=await Wbe(),r=n._fvad_new();if(!r)throw new Error("无法初始化浏览器语音活动检测器");const i=n._malloc(v0);if(!i)throw n._fvad_free(r),new Error("无法分配浏览器语音活动检测缓冲区");if(n._fvad_set_sample_rate(r,wd)!==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 hC(n,r,i)}process(t){if(this.destroyed)throw new Error("浏览器语音活动检测器已释放");if(t.byteLength!==v0)throw new Error(`语音活动检测帧必须为 ${v0} 字节`);this.module.HEAPU8.set(t,this.framePointer);const n=this.module._fvad_process(this.handle,this.framePointer,ul);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 qbe{constructor(t={}){_t(this,"startSpeechFrames");_t(this,"endSilenceFrames");_t(this,"active",!1);_t(this,"speechFrames",0);_t(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 Ybe{constructor(){_t(this,"pending",new Float32Array(ul));_t(this,"pendingLength",0)}push(t,n){let r=0;if(this.pendingLength>0){const i=ul-this.pendingLength,s=Math.min(i,t.length);this.pending.set(t.subarray(0,s),this.pendingLength),this.pendingLength+=s,r+=s,this.pendingLength===ul&&(n(this.pending.slice()),this.pendingLength=0)}for(;r+ul<=t.length;)n(t.slice(r,r+ul)),r+=ul;if(r<t.length){const i=t.subarray(r);this.pending.set(i,0),this.pendingLength=i.length}}reset(){this.pendingLength=0}}const Vbe="/__dev_anywhere_debug/voice-fixture",Kbe=wd*e5/1e3;function Gbe(){return hC.create(3)}const Xbe={createVad:Gbe,getUserMedia:e=>navigator.mediaDevices.getUserMedia(e),createAudioContext:e=>new AudioContext(e),fetch:e=>fetch(e)};function Zbe(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 Qbe(e){for(const t of e.getTracks())t.stop()}function t$(e){const t=e.createAudioContext({sampleRate:wd});if(t.sampleRate!==wd)throw t.close().catch(()=>{}),new Error("浏览器无法提供 Voice Pilot 所需的 16 kHz 音频输入");return t}async function Jbe(e){const t=t$(e);let n;try{n=await e.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:wd}})}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(),Qbe(n),t.state!=="closed"&&await t.close()}}}async function e_e(e,t){const n=t$(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 n$(e=window.location.search,t=!1){return t&&new URLSearchParams(e).get("voice-fixture")==="default"?{kind:"fixture",url:Vbe}:{kind:"microphone"}}async function t_e(e,t=Xbe){const n=await t.createVad();let r;try{r=e.source.kind==="fixture"?await e_e(e.source.url,t):await Jbe(t)}catch(f){throw n.destroy(),f}const i=new qbe,s=new Ybe,o=r.context.createScriptProcessor(Kbe,1,1);let l=!1,u=null,d=null;return o.onaudioprocess=f=>{l&&s.push(f.inputBuffer.getChannelData(0),p=>{const y=zbe(p),g=n.process(y);e.onFrame({pcm:y,speechProbability:g?1:0,activityLevel:Zbe(p)});const b=i.push(g);b==="speech-start"&&e.onSpeechStart(),b==="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 r$(e=ip().osName){return{mediaAccept:"image/*,video/*",fileAccept:e==="Android"?"application/*,text/*":void 0}}function n_e(e){const[t,n,...r]=Array.from(e);return t&&n===" "&&r.length>0?{indicator:t,label:r.join("")}:{label:e}}function r_e({title:e,isPtyTitle:t}){if(!t)return v.jsx(v.Fragment,{children:e});const{indicator:n,label:r}=n_e(e);return v.jsxs("span",{className:"inline-flex items-center justify-center max-w-full min-w-0 font-mono font-normal",children:[n&&v.jsx("span",{className:"inline-block w-[1.25ch] shrink-0 text-center","aria-hidden":"true",children:n}),v.jsx("span",{className:"truncate",children:n?` ${r}`:r})]})}function i_e(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 s_e(){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(i_e(n),{cause:n})}finally{e==null||e.getTracks().forEach(n=>n.stop())}}const zu="min-h-9 gap-2.5",Eg="px-2 pb-1 pt-2 text-xs font-semibold text-muted-foreground";function wo({children:e,className:t}){return v.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 o_e({label:e}){return v.jsxs(wo,{className:"relative",children:[v.jsx($D,{className:"size-4","aria-hidden":"true"}),v.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 a_e({sessionId:e,mode:t,onFind:n}){const r=r$(),i=so(),s=Ft(ye=>ye.sessions.find(Xe=>Xe.sessionId===e)),o=Ft(ye=>ye.ptyTitles[e]),l=De(ye=>ye.ptyFontSize),u=De(ye=>ye.chatContentFontSize),d=De(ye=>ye.selectedProxyId),f=De(ye=>ye.adjustPtyFontSize),p=De(ye=>ye.adjustChatContentFontSize),y=De(ye=>ye.setChatContentFontSize),g=De(ye=>ye.resetPtyFontSize),b=De(ye=>ye.resetChatContentFontSize),w=De(ye=>ye.inputModePreference==="hardware"),S=Ft(ye=>ye.renameSession),E=w1(d,e),k=Ft(ye=>E?!!ye.ptyAutoYesBySessionKey[E]:!1),T=Ft(ye=>ye.setPtyAutoYes),P=Cl("(pointer: coarse), (hover: none)")&&!w,A=t==="pty"||(s==null?void 0:s.mode)==="pty",H=(s==null?void 0:s.kind)==="terminal",D=Q4(e),K=_n(ye=>ye.bySessionId[e]??Ry),q=_n(ye=>ye.enable),X=_n(ye=>ye.disable),z=!!(s!=null&&s.nameLocked&&(s!=null&&s.name)),N=D1(s),$=z&&(s==null?void 0:s.name)||N||A&&o||(s==null?void 0:s.name)||e.slice(0,8),I=!!(A&&!H&&o&&!z),M=A?l:b1(u,P),O=!A&&P?dI:cI,U=A?g:b,[B,L]=_.useState(!1),[Y,V]=_.useState(!1),j=K.enabled,te=D.active||j,re=D.pending||!D.supported||j;function oe(ye){if(A){f(ye);return}if(P){y(M+ye);return}p(ye)}function ee(){D.toggle().catch(ye=>{nt.error(ye instanceof Error?ye.message:String(ye))})}async function pe(ye){var kt;if(A||H){nt.info("Voice Pilot 目前适用于聊天会话。");return}if(ye!==!0){X(e);return}const Xe=Ut;if(!Xe){nt.error("请先连接开发机");return}try{if(!((kt=(await Xe.requestVoiceConfig()).config)!=null&&kt.configured)){nt.info("请先在设置里配置 Voice Pilot。");return}L(!0)}catch(gt){nt.error(gt instanceof Error?gt.message:String(gt))}}async function ae(){var gt;V(!0);let ye=null,Xe=!1;const kt=e$(e);try{ph({sessionId:e,scope:"runtime",event:"wake-lock-requested",details:{userActivationActive:((gt=navigator.userActivation)==null?void 0:gt.isActive)??!1,visibilityState:document.visibilityState,secureContext:window.isSecureContext}});const Lt=cl.enable(kt).then(()=>{ph({sessionId:e,scope:"runtime",event:"wake-lock-acquired"})},Ke=>{throw ph({sessionId:e,scope:"runtime",event:"wake-lock-failed",details:{error:Ke instanceof Error?Ke.message:String(Ke)}}),new Error("屏幕常亮请求被浏览器拒绝,Voice Pilot 未开启。",{cause:Ke})});ye=wE.acquire("capture");const an=iv.prepare(),Le=n$().kind==="microphone"?s_e():Promise.resolve();await Promise.all([Lt,an,Le]),q(e),Xe=!0,L(!1)}catch(Lt){ph({sessionId:e,scope:"runtime",event:"startup-failed",details:{error:Lt instanceof Error?Lt.message:String(Lt)}}),nt.error(Lt instanceof Error?Lt.message:String(Lt))}finally{ye==null||ye.release(),Xe||await cl.disable(kt).catch(()=>{}),V(!1)}}const me=_.useRef(null),Ee=_.useRef(null),[Oe,Se]=_.useState(!1);async function Qe(ye){var Lt;const Xe=(Lt=ye.target.files)==null?void 0:Lt[0];if(ye.target.value="",!Xe)return;const kt=Ut;if(!kt){nt.error("请先连接开发机");return}const gt=await Vh({relay:kt,sessionId:e,file:Xe});gt&&eo(e,`@${gt} `)}async function Ht(ye,Xe){const kt=Ut;if(!kt)throw new Error("请先连接开发机");const gt=await kt.renameSession(ye,Xe);if(!gt.success)throw new Error(gt.error??"重命名失败");S(ye,gt.name??Xe),nt.success("已重命名会话")}return v.jsxs("div",{className:"border-b border-border bg-card pt-[env(safe-area-inset-top)] shrink-0","data-slot":"chat-header",children:[v.jsx("div",{className:"dev-chat-shell-rail-inset","data-slot":"chat-header-rail-inset",children:v.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:[v.jsx("div",{className:"flex justify-start",children:v.jsx(At,{variant:"ghost",size:"icon-sm",className:"md:hidden",onClick:()=>i("/sessions"),"aria-label":"返回会话列表","data-slot":"chat-back-button",children:v.jsx(Uv,{"aria-hidden":"true"})})}),v.jsx("span",{className:"text-sm font-semibold truncate text-center px-2","data-slot":"chat-session-title",children:v.jsx(r_e,{title:$,isPtyTitle:I})}),v.jsxs(vE,{modal:!1,children:[v.jsx(yE,{asChild:!0,children:v.jsx(At,{variant:"ghost",size:"icon-sm",className:"justify-self-end","aria-label":"会话操作","data-slot":"chat-overflow-trigger",children:v.jsx(TW,{"aria-hidden":"true"})})}),v.jsxs(bE,{align:"end",className:"w-max min-w-44 max-w-[calc(100vw-1rem)]","data-slot":"chat-overflow-menu",children:[v.jsx(sg,{className:Eg,children:"会话"}),v.jsxs(ko,{className:zu,"data-slot":"chat-menu-find",onSelect:n,children:[v.jsx(wo,{children:v.jsx(av,{"aria-hidden":"true"})}),"在会话中查找"]}),v.jsxs(ko,{className:zu,"data-slot":"chat-menu-rename",onSelect:()=>Se(!0),children:[v.jsx(wo,{children:v.jsx(p7,{"aria-hidden":"true"})}),"重命名"]}),v.jsxs(Ew,{checked:te,className:"min-h-9 justify-start gap-2.5 pl-2 pr-8 [&>span:first-child]:left-auto [&>span:first-child]:right-2",disabled:re,"data-slot":"chat-menu-screen-wake-lock-item",onCheckedChange:ee,children:[v.jsx(wo,{children:v.jsx(GW,{"aria-hidden":"true"})}),v.jsx("span",{className:"min-w-0 flex-1",children:D.supported?j?"屏幕常亮(Voice Pilot 控制)":"屏幕常亮":D.unavailableReason==="insecure-context"?"屏幕常亮(需要 HTTPS)":"屏幕常亮(浏览器不支持)"})]}),A&&!H&&v.jsxs(Ew,{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:!E,"data-slot":"chat-menu-pty-auto-yes-item",onCheckedChange:ye=>{E&&T(E,ye===!0)},children:[v.jsx(wo,{children:v.jsx(pa,{"aria-hidden":"true"})}),v.jsx("span",{className:"min-w-0 flex-1",children:"Always yes"})]}),!A&&!H&&v.jsxs(Ew,{checked:K.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:pe,children:[v.jsx(wo,{children:v.jsx(t7,{"aria-hidden":"true"})}),v.jsx("span",{className:"min-w-0 flex-1",children:"Voice Pilot"})]}),v.jsx(Cw,{}),A&&!H?v.jsxs(v.Fragment,{children:[v.jsx(sg,{className:Eg,children:"快捷键"}),v.jsxs(ko,{className:zu,"data-slot":"chat-menu-send-ctrl-o",onClick:()=>eo(e,""),children:[v.jsx(o_e,{label:"^O"}),"发送 Ctrl+O"]}),v.jsx(Cw,{}),v.jsx(sg,{className:Eg,children:"文件"}),v.jsxs(ko,{className:zu,"data-slot":"chat-menu-upload-image",onClick:()=>{var ye;return(ye=Ee.current)==null?void 0:ye.click()},children:[v.jsx(wo,{children:v.jsx(np,{"aria-hidden":"true"})}),"上传照片或视频"]}),v.jsxs(ko,{className:zu,"data-slot":"chat-menu-upload-file",onClick:()=>{var ye;return(ye=me.current)==null?void 0:ye.click()},children:[v.jsx(wo,{children:v.jsx(qD,{"aria-hidden":"true"})}),"上传文件"]}),v.jsx(Cw,{})]}):null,v.jsx(sg,{className:Eg,children:"字号"}),v.jsx("div",{className:"px-2 pb-1","data-slot":"chat-menu-font-control",children:v.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:[v.jsx(wo,{children:v.jsx(j7,{"aria-hidden":"true"})}),v.jsxs("div",{className:"col-start-2 inline-flex w-fit shrink-0 items-center gap-2","data-slot":"chat-menu-font-stepper",children:[v.jsx(At,{variant:"ghost",size:"icon-sm",className:"size-[22px] rounded-[5px] bg-muted/45 text-muted-foreground hover:bg-accent hover:text-accent-foreground",disabled:M<=O,"aria-label":"字号变小","data-slot":"chat-menu-font-smaller",onClick:ye=>{ye.stopPropagation(),oe(-1)},children:v.jsx(r7,{"aria-hidden":"true"})}),v.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:[M,"px"]}),v.jsx(At,{variant:"ghost",size:"icon-sm",className:"size-[22px] rounded-[5px] bg-muted/45 text-muted-foreground hover:bg-accent hover:text-accent-foreground",disabled:M>=uI,"aria-label":"字号变大","data-slot":"chat-menu-font-larger",onClick:ye=>{ye.stopPropagation(),oe(1)},children:v.jsx(v7,{"aria-hidden":"true"})})]})]})}),v.jsxs(ko,{className:zu,"data-slot":"chat-menu-font-reset",onClick:U,children:[v.jsx(wo,{children:v.jsx(_7,{"aria-hidden":"true"})}),v.jsx("span",{"data-slot":"chat-menu-font-reset-label",children:"恢复默认"})]})]})]})]})}),v.jsx(sh,{open:Oe,sessionId:e,initialName:s==null?void 0:s.name,onOpenChange:Se,onRename:Ht}),v.jsx(Bl,{open:B&&!K.enabled,onOpenChange:ye=>{Y||L(ye)},children:v.jsxs(zl,{className:"sm:max-w-md","data-slot":"voice-pilot-wake-lock-dialog",focusSurfaceOnOpen:!0,children:[v.jsxs(jl,{children:[v.jsx(ba,{children:"开启 Voice Pilot?"}),v.jsx(El,{children:"开启后会持续聆听并保持屏幕常亮,停止后自动恢复。"})]}),v.jsxs(Mc,{children:[v.jsx(At,{type:"button",variant:"outline",disabled:Y,onClick:()=>L(!1),children:"取消"}),v.jsx(At,{type:"button","data-slot":"voice-pilot-confirm-start",disabled:Y,onClick:()=>{ae()},children:Y?"正在开启...":"开启 Voice Pilot"})]})]})}),A?v.jsxs(v.Fragment,{children:[v.jsx("input",{ref:Ee,type:"file",accept:r.mediaAccept,className:"hidden","data-slot":"chat-menu-upload-image-input",onChange:ye=>{Qe(ye)}}),v.jsx("input",{ref:me,type:"file",accept:r.fileAccept,className:"hidden","data-slot":"chat-menu-upload-file-input",onChange:ye=>{Qe(ye)}})]}):null]})}function ju(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((b,w)=>r[w]!==b)))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 b=Math.round((Date.now()-f)*100)/100,w=Math.round((Date.now()-g)*100)/100,S=w/16,E=(k,T)=>{for(k=String(k);k.length<T;)k=" "+k;return k};console.info(`%c⏱ ${E(w,5)} /${E(b,5)} ms`,`
|
|
672
|
+
`):[]);n(T=>T.filter(R=>k.has(R.sessionId))),i(T=>T&&k.has(T.sessionId)?T:null),p.current&&!k.has(p.current)&&(p.current=null,o(null))},[y,d]),_.useEffect(()=>{const k=f.current;f.current=l,!(!k||k===l)&&(p.current=null,n([]),i(null),o(null))},[l]);const E=_.useMemo(()=>({activate:g,deactivate:b,updateFindRequest:S,updateViewportRect:w}),[g,b,S,w]);return v.jsxs(Y4.Provider,{value:E,children:[e,v.jsx(hbe,{entries:t,activeView:r,viewportRect:s})]})}function fbe({sessionId:e,sessionKind:t,provider:n,findRequest:r}){const i=_.useContext(Y4),s=_.useRef(null);if(!i)throw new Error("PtyKeepAliveViewport must be used within PtyKeepAliveProvider");const{activate:o,deactivate:l,updateFindRequest:u,updateViewportRect:d}=i;return _.useLayoutEffect(()=>(o({sessionId:e,sessionKind:t,provider:n}),()=>l(e)),[o,l,e,t,n]),_.useLayoutEffect(()=>{u(e,r)},[r,e,u]),_.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]),v.jsx("div",{ref:s,className:"h-full w-full bg-background","data-slot":"pty-keepalive-viewport","data-session-id":e})}function hbe({entries:e,activeView:t,viewportRect:n}){return e.length===0?null:v.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)??cbe,height:(n==null?void 0:n.height)??ube};return v.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:v.jsx(j5,{sessionId:r.sessionId,children:v.jsx(abe,{sessionId:r.sessionId,sessionKind:r.sessionKind,provider:r.provider,active:i,findRequest:r.findRequest})})},r.sessionId)})})}function pbe(e,t){return Math.abs(e.top-t.top)<=xg&&Math.abs(e.left-t.left)<=xg&&Math.abs(e.width-t.width)<=xg&&Math.abs(e.height-t.height)<=xg}function mbe(){const e=Ft(r=>r.codexActiveWriterConflict),t=Ft(r=>r.setCodexActiveWriterConflict),n=()=>t(null);return v.jsx(Bl,{open:e!==null,onOpenChange:r=>!r&&n(),children:v.jsxs(zl,{focusSurfaceOnOpen:!0,className:"min-w-0 sm:max-w-md",children:[v.jsxs(jl,{children:[v.jsx(ba,{children:"该 Codex 会话仍在运行"}),v.jsxs(El,{className:"space-y-2 text-left leading-6",children:[v.jsxs("span",{className:"block",children:["另一个 Codex 进程正在使用此会话",e!=null&&e.activeWriterPid?v.jsxs(v.Fragment,{children:["(PID"," ",v.jsx("span",{className:"font-mono text-foreground",children:e.activeWriterPid}),")"]}):null,"。"]}),v.jsx("span",{className:"block",children:"它可能来自本机终端、Codex App 或另一条 DEV Anywhere 会话。请先回到或结束原会话后再重试。"}),v.jsx("span",{className:"block text-muted-foreground/80",children:"DEV Anywhere 不会自动终止该进程。"})]})]}),v.jsx(Mc,{children:v.jsx(At,{type:"button",onClick:n,autoFocus:!0,children:"知道了"})})]})})}function dC({route:e,surface:t,proxiesLength:n,hasProxy:r,sessionCount:i,relayClientAuthIssue:s=null}){return s==="missing_client_token"?"Relay 服务器需要 client token。请在设置里填写。":s==="invalid_client_token"?"当前浏览器保存的 client token 无效或已过期。请在设置里更新。":n===0?"在开发机上启动 DEV Anywhere,本页会显示可连接的开发机。":t==="mobile"&&e==="proxy-select"||!r?"选择要连接的开发机。":i===0?"还没有会话。可以从本地终端接入,也可以新建会话。":t==="desktop"?"从左侧打开会话,或新建会话开始新的任务。":"打开会话,或新建会话开始新的任务。"}const fC="dev-anywhere:last-chat-route",V4="dev-anywhere:route-restored",Px="dev-anywhere:restored-target";function gbe(e){return e.alreadyRestored||e.pathname!=="/"||!e.lastRoute||!e.lastRoute.startsWith("/chat/")?null:e.lastRoute}function vbe(){var e;try{return((e=globalThis.localStorage)==null?void 0:e.getItem(fC))??null}catch{return null}}function ybe(e){var t;try{(t=globalThis.localStorage)==null||t.setItem(fC,e)}catch{}}function K4(){var e;try{(e=globalThis.localStorage)==null||e.removeItem(fC)}catch{}}function bbe(){var e;try{return((e=globalThis.sessionStorage)==null?void 0:e.getItem(V4))==="1"}catch{return!1}}function _be(){var e;try{(e=globalThis.sessionStorage)==null||e.setItem(V4,"1")}catch{}}function wbe(e){var t;try{(t=globalThis.sessionStorage)==null||t.setItem(Px,e)}catch{}}function Sbe(){var e,t;try{const n=((e=globalThis.sessionStorage)==null?void 0:e.getItem(Px))??null;return n!==null&&((t=globalThis.sessionStorage)==null||t.removeItem(Px)),n}catch{return null}}function xbe(e){const t=JI(e);return t.osName!=="iPad"?{supported:!0}:e.standalone||t.browserName==="Safari"?{supported:!0}:{supported:!1,reason:"ipad-safari-required",browserName:t.browserName}}function rv(){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 Ebe(){return typeof navigator>"u"?{supported:!0}:xbe({userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints,standalone:rv()})}function Cbe(){Uve(),Wve();const e=Ui(),t=so(),n=e.pathname.startsWith("/chat/"),r=e.pathname==="/"||e.pathname==="/sessions",[i,s]=_.useState(!1),[o,l]=_.useState(()=>rv()),u=De(D=>D.proxies.length),d=De(D=>D.proxyListLoaded),f=De(D=>D.relayClientAuthIssue),p=De(D=>!!D.selectedProxyId),y=De(D=>D.selectedProxyId),g=De(D=>D.selectedProxyName),b=Ft(D=>D.sessions.length),w=De(D=>D.pendingToast),S=De(D=>D.setPendingToast),E=e.pathname==="/"?"proxy-select":"sessions",k=dC({route:E,surface:"mobile",proxiesLength:u,hasProxy:p,sessionCount:b,relayClientAuthIssue:f}),T=g??y,P=e.pathname==="/sessions"&&d&&u>0?v.jsxs(At,{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":T?`切换开发机,当前 ${T}`:"切换开发机",onClick:()=>t("/"),children:[v.jsx(FD,{className:"size-4 text-primary","aria-hidden":"true"}),v.jsxs("span",{className:"min-w-0 truncate",children:[v.jsx("span",{className:"text-foreground",children:"切换开发机"}),T?v.jsxs("span",{className:"ml-1 text-muted-foreground/75",children:["· ",T]}):null]})]}):null;_.useEffect(()=>{if(!w)return;({error:nt.error,info:nt.info,success:nt.success})[w.kind](w.message),S(null)},[w,S]),_.useEffect(()=>{if(typeof window.matchMedia!="function"){l(rv());return}const D=window.matchMedia("(display-mode: standalone)"),K=window.matchMedia("(display-mode: fullscreen)"),q=()=>l(rv());return q(),D.addEventListener("change",q),K.addEventListener("change",q),()=>{D.removeEventListener("change",q),K.removeEventListener("change",q)}},[]);const A=_.useRef(!1);_.useEffect(()=>{if(A.current)return;A.current=!0;const D=gbe({pathname:e.pathname,alreadyRestored:bbe(),lastRoute:vbe()});_be(),D&&(wbe(D),t(D,{replace:!0}))},[]);const H=_.useRef(!1);return _.useEffect(()=>{n?(H.current=!0,ybe(`${e.pathname}${e.search}`)):H.current&&(H.current=!1,K4())},[n,e.pathname,e.search]),v.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":o?"true":void 0,children:[!n&&v.jsx(At,{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:()=>s(!0),children:v.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:v.jsx(WD,{className:"size-4","aria-hidden":"true"})})}),!n&&v.jsx(yae,{subtitle:k,action:P}),v.jsx(ple,{}),v.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[v.jsx(mae,{className:"hidden md:flex"}),v.jsx("main",{className:"relative flex-1 overflow-hidden",role:"main",children:v.jsx(dbe,{children:v.jsx("div",{className:Ye("h-full",!r&&"animate-in fade-in-0 duration-200 motion-reduce:animate-none"),children:v.jsx(i9,{})},r?"top-level":e.pathname)})})]}),v.jsx(kS,{open:i,onOpenChange:s}),v.jsx(mbe,{}),v.jsx(qae,{}),v.jsx(Tae,{}),v.jsx($Q,{})]})}function G4({subtitle:e,action:t}){return v.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-6 px-6 text-center",children:[v.jsx(s5,{texts:o5,className:"text-2xl md:text-3xl font-bold"}),v.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:e}),t&&v.jsx("div",{children:t})]})}function kbe(){const e=De(o=>o.proxies),t=De(o=>!!o.selectedProxyId),n=De(o=>o.relayClientAuthIssue),r=Ft(o=>o.sessions.length),i=dC({route:"proxy-select",surface:"desktop",proxiesLength:e.length,hasProxy:t,sessionCount:r,relayClientAuthIssue:n}),s=n==="missing_client_token"?"client-token-missing":n==="invalid_client_token"?"client-token-invalid":null;return v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"h-full md:hidden",children:v.jsx(U3,{layout:"page"})}),v.jsx("div",{className:"hidden md:block h-full",children:s?v.jsx(wc,{variant:s}):v.jsx(G4,{subtitle:i})})]})}function Tbe(){const e=De(o=>o.proxies),t=De(o=>!!o.selectedProxyId),n=De(o=>o.relayClientAuthIssue),r=Ft(o=>o.sessions.length),i=Oi("local",Sn.proxyId)!==null;if(!t&&!i)return v.jsx(r9,{to:"/",replace:!0});const s=dC({route:"sessions",surface:"desktop",proxiesLength:e.length,hasProxy:t,sessionCount:r,relayClientAuthIssue:n});return v.jsxs(v.Fragment,{children:[v.jsx("div",{className:"h-full md:hidden",children:v.jsx(Q3,{layout:"page"})}),v.jsx("div",{className:"hidden md:block h-full",children:v.jsx(G4,{subtitle:s})})]})}function X4(){if(!(typeof navigator>"u"))return navigator.wakeLock}function Rbe(e,t){return e===!1?"insecure-context":t?null:"unsupported"}function Z4(){var t;const e=typeof window>"u"?void 0:window.isSecureContext;return Rbe(e,typeof((t=X4())==null?void 0:t.request)=="function")}function Abe(e){return e==="insecure-context"?"屏幕常亮需要 HTTPS":"当前浏览器不支持屏幕常亮"}function Mbe(){const e=X4();if(typeof(e==null?void 0:e.request)!="function")throw new Error(Abe(Z4()));return e.request("screen")}function Nbe(e){return e instanceof Error&&e.message.trim()?e.message:"无法开启屏幕常亮"}class Pbe{constructor(t={}){_t(this,"activeScopes",new Set);_t(this,"pendingScopes",new Set);_t(this,"listeners",new Map);_t(this,"sentinel",null);_t(this,"requestInFlight",null);_t(this,"requestWakeLock");_t(this,"documentRef");_t(this,"windowRef");_t(this,"unavailableReason");_t(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(()=>{})});_t(this,"handlePageHide",()=>{this.releaseSentinel().catch(()=>{})});var n,r;this.requestWakeLock=t.request??Mbe,this.unavailableReason=typeof t.request=="function"?null:Z4(),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(Nbe(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 cl=new Pbe;function Q4(e){const[t,n]=_.useState(()=>cl.getSnapshot(e));_.useEffect(()=>cl.subscribe(e,n),[e]),_.useEffect(()=>()=>{cl.disable(e).catch(()=>{})},[e]);const r=_.useCallback(()=>cl.enable(e),[e]),i=_.useCallback(()=>cl.disable(e),[e]),s=_.useCallback(()=>cl.toggle(e),[e]);return{...t,enable:r,disable:i,toggle:s}}function Lbe(){return new AudioContext}class Obe{constructor(t=Lbe){_t(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 iv=new Obe,dL=400,nd=[];let J4=1;function Dbe(){return typeof performance>"u"?0:Math.round(performance.now()*10)/10}function ph(e){const t={sequence:J4++,timestamp:new Date().toISOString(),monotonicMs:Dbe(),sessionId:e.sessionId,scope:e.scope,event:e.event,...e.attemptId?{attemptId:e.attemptId}:{},...e.requestId?{requestId:e.requestId}:{},...e.details?{details:{...e.details}}:{}};nd.push(t),nd.length>dL&&nd.splice(0,nd.length-dL)}function Ibe(){return nd.map(e=>({...e,...e.details?{details:{...e.details}}:{}}))}function Bbe(){nd.length=0,J4=1}typeof window<"u"&&(window.__devAnywhereVoicePilotDiagnostics={snapshot:Ibe,clear:Bbe});function e$(e){return`voice-pilot:${e}`}function zbe(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 jbe="modulepreload",$be=function(e){return"/"+e},fL={},Fbe=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=$be(d),d in fL)return;fL[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":jbe,f||(y.as="script"),y.crossOrigin="",y.href=d,u&&y.setAttribute("nonce",u),document.head.appendChild(y),f)return new Promise((g,b)=>{y.addEventListener("load",g),y.addEventListener("error",()=>b(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)})},Hbe="/assets/fvad-DYxbW2my.wasm",wd=16e3,Ube=20,ul=wd*Ube/1e3,v0=ul*Int16Array.BYTES_PER_ELEMENT;let hL=null;async function Wbe(){return hL??(hL=Fbe(async()=>{const{default:e}=await import("./fvad-DQYOSZdE.js");return{default:e}},[]).then(({default:e})=>e({locateFile:t=>t.endsWith(".wasm")?Hbe:t}))),hL}class hC{constructor(t,n,r){_t(this,"destroyed",!1);this.module=t,this.handle=n,this.framePointer=r}static async create(t=3){const n=await Wbe(),r=n._fvad_new();if(!r)throw new Error("无法初始化浏览器语音活动检测器");const i=n._malloc(v0);if(!i)throw n._fvad_free(r),new Error("无法分配浏览器语音活动检测缓冲区");if(n._fvad_set_sample_rate(r,wd)!==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 hC(n,r,i)}process(t){if(this.destroyed)throw new Error("浏览器语音活动检测器已释放");if(t.byteLength!==v0)throw new Error(`语音活动检测帧必须为 ${v0} 字节`);this.module.HEAPU8.set(t,this.framePointer);const n=this.module._fvad_process(this.handle,this.framePointer,ul);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 qbe{constructor(t={}){_t(this,"startSpeechFrames");_t(this,"endSilenceFrames");_t(this,"active",!1);_t(this,"speechFrames",0);_t(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 Ybe{constructor(){_t(this,"pending",new Float32Array(ul));_t(this,"pendingLength",0)}push(t,n){let r=0;if(this.pendingLength>0){const i=ul-this.pendingLength,s=Math.min(i,t.length);this.pending.set(t.subarray(0,s),this.pendingLength),this.pendingLength+=s,r+=s,this.pendingLength===ul&&(n(this.pending.slice()),this.pendingLength=0)}for(;r+ul<=t.length;)n(t.slice(r,r+ul)),r+=ul;if(r<t.length){const i=t.subarray(r);this.pending.set(i,0),this.pendingLength=i.length}}reset(){this.pendingLength=0}}const Vbe="/__dev_anywhere_debug/voice-fixture",Kbe=wd*e5/1e3;function Gbe(){return hC.create(3)}const Xbe={createVad:Gbe,getUserMedia:e=>navigator.mediaDevices.getUserMedia(e),createAudioContext:e=>new AudioContext(e),fetch:e=>fetch(e)};function Zbe(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 Qbe(e){for(const t of e.getTracks())t.stop()}function t$(e){const t=e.createAudioContext({sampleRate:wd});if(t.sampleRate!==wd)throw t.close().catch(()=>{}),new Error("浏览器无法提供 Voice Pilot 所需的 16 kHz 音频输入");return t}async function Jbe(e){const t=t$(e);let n;try{n=await e.getUserMedia({audio:{channelCount:1,echoCancellation:!0,autoGainControl:!0,noiseSuppression:!0,sampleRate:wd}})}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(),Qbe(n),t.state!=="closed"&&await t.close()}}}async function e_e(e,t){const n=t$(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 n$(e=window.location.search,t=!1){return t&&new URLSearchParams(e).get("voice-fixture")==="default"?{kind:"fixture",url:Vbe}:{kind:"microphone"}}async function t_e(e,t=Xbe){const n=await t.createVad();let r;try{r=e.source.kind==="fixture"?await e_e(e.source.url,t):await Jbe(t)}catch(f){throw n.destroy(),f}const i=new qbe,s=new Ybe,o=r.context.createScriptProcessor(Kbe,1,1);let l=!1,u=null,d=null;return o.onaudioprocess=f=>{l&&s.push(f.inputBuffer.getChannelData(0),p=>{const y=zbe(p),g=n.process(y);e.onFrame({pcm:y,speechProbability:g?1:0,activityLevel:Zbe(p)});const b=i.push(g);b==="speech-start"&&e.onSpeechStart(),b==="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 r$(e=ip().osName){return{mediaAccept:"image/*,video/*",fileAccept:e==="Android"?"application/*,text/*":void 0}}function n_e(e){const[t,n,...r]=Array.from(e);return t&&n===" "&&r.length>0?{indicator:t,label:r.join("")}:{label:e}}function r_e({title:e,isPtyTitle:t}){if(!t)return v.jsx(v.Fragment,{children:e});const{indicator:n,label:r}=n_e(e);return v.jsxs("span",{className:"inline-flex items-center justify-center max-w-full min-w-0 font-mono font-normal",children:[n&&v.jsx("span",{className:"inline-block w-[1.25ch] shrink-0 text-center","aria-hidden":"true",children:n}),v.jsx("span",{className:"truncate",children:n?` ${r}`:r})]})}function i_e(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 s_e(){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(i_e(n),{cause:n})}finally{e==null||e.getTracks().forEach(n=>n.stop())}}const zu="min-h-9 gap-2.5",Eg="px-2 pb-1 pt-2 text-xs font-semibold text-muted-foreground";function wo({children:e,className:t}){return v.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 o_e({label:e}){return v.jsxs(wo,{className:"relative",children:[v.jsx($D,{className:"size-4","aria-hidden":"true"}),v.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 a_e({sessionId:e,mode:t,onFind:n}){const r=r$(),i=so(),s=Ft(ye=>ye.sessions.find(Xe=>Xe.sessionId===e)),o=Ft(ye=>ye.ptyTitles[e]),l=De(ye=>ye.ptyFontSize),u=De(ye=>ye.chatContentFontSize),d=De(ye=>ye.selectedProxyId),f=De(ye=>ye.adjustPtyFontSize),p=De(ye=>ye.adjustChatContentFontSize),y=De(ye=>ye.setChatContentFontSize),g=De(ye=>ye.resetPtyFontSize),b=De(ye=>ye.resetChatContentFontSize),w=De(ye=>ye.inputModePreference==="hardware"),S=Ft(ye=>ye.renameSession),E=w1(d,e),k=Ft(ye=>E?!!ye.ptyAutoYesBySessionKey[E]:!1),T=Ft(ye=>ye.setPtyAutoYes),P=Cl("(pointer: coarse), (hover: none)")&&!w,A=t==="pty"||(s==null?void 0:s.mode)==="pty",H=(s==null?void 0:s.kind)==="terminal",D=Q4(e),K=_n(ye=>ye.bySessionId[e]??Ry),q=_n(ye=>ye.enable),X=_n(ye=>ye.disable),z=!!(s!=null&&s.nameLocked&&(s!=null&&s.name)),N=D1(s),$=z&&(s==null?void 0:s.name)||N||A&&o||(s==null?void 0:s.name)||e.slice(0,8),I=!!(A&&!H&&o&&!z),M=A?l:b1(u,P),O=!A&&P?dI:cI,U=A?g:b,[B,L]=_.useState(!1),[Y,V]=_.useState(!1),j=K.enabled,te=D.active||j,re=D.pending||!D.supported||j;function oe(ye){if(A){f(ye);return}if(P){y(M+ye);return}p(ye)}function ee(){D.toggle().catch(ye=>{nt.error(ye instanceof Error?ye.message:String(ye))})}async function pe(ye){var kt;if(A||H){nt.info("Voice Pilot 目前适用于聊天会话。");return}if(ye!==!0){X(e);return}const Xe=Ut;if(!Xe){nt.error("请先连接开发机");return}try{if(!((kt=(await Xe.requestVoiceConfig()).config)!=null&&kt.configured)){nt.info("请先在设置里配置 Voice Pilot。");return}L(!0)}catch(gt){nt.error(gt instanceof Error?gt.message:String(gt))}}async function ae(){var gt;V(!0);let ye=null,Xe=!1;const kt=e$(e);try{ph({sessionId:e,scope:"runtime",event:"wake-lock-requested",details:{userActivationActive:((gt=navigator.userActivation)==null?void 0:gt.isActive)??!1,visibilityState:document.visibilityState,secureContext:window.isSecureContext}});const Lt=cl.enable(kt).then(()=>{ph({sessionId:e,scope:"runtime",event:"wake-lock-acquired"})},Ke=>{throw ph({sessionId:e,scope:"runtime",event:"wake-lock-failed",details:{error:Ke instanceof Error?Ke.message:String(Ke)}}),new Error("屏幕常亮请求被浏览器拒绝,Voice Pilot 未开启。",{cause:Ke})});ye=wE.acquire("capture");const an=iv.prepare(),Le=n$().kind==="microphone"?s_e():Promise.resolve();await Promise.all([Lt,an,Le]),q(e),Xe=!0,L(!1)}catch(Lt){ph({sessionId:e,scope:"runtime",event:"startup-failed",details:{error:Lt instanceof Error?Lt.message:String(Lt)}}),nt.error(Lt instanceof Error?Lt.message:String(Lt))}finally{ye==null||ye.release(),Xe||await cl.disable(kt).catch(()=>{}),V(!1)}}const me=_.useRef(null),Ee=_.useRef(null),[Oe,Se]=_.useState(!1);async function Qe(ye){var Lt;const Xe=(Lt=ye.target.files)==null?void 0:Lt[0];if(ye.target.value="",!Xe)return;const kt=Ut;if(!kt){nt.error("请先连接开发机");return}const gt=await Vh({relay:kt,sessionId:e,file:Xe});gt&&eo(e,`@${gt} `)}async function Ht(ye,Xe){const kt=Ut;if(!kt)throw new Error("请先连接开发机");const gt=await kt.renameSession(ye,Xe);if(!gt.success)throw new Error(gt.error??"重命名失败");S(ye,gt.name??Xe),nt.success("已重命名会话")}return v.jsxs("div",{className:"border-b border-border bg-card pt-[env(safe-area-inset-top)] shrink-0","data-slot":"chat-header",children:[v.jsx("div",{className:"dev-chat-shell-rail-inset","data-slot":"chat-header-rail-inset",children:v.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:[v.jsx("div",{className:"flex justify-start",children:v.jsx(At,{variant:"ghost",size:"icon-sm",className:"md:hidden",onClick:()=>i("/sessions"),"aria-label":"返回会话列表","data-slot":"chat-back-button",children:v.jsx(Uv,{"aria-hidden":"true"})})}),v.jsx("span",{className:"text-sm font-semibold truncate text-center px-2","data-slot":"chat-session-title",children:v.jsx(r_e,{title:$,isPtyTitle:I})}),v.jsxs(vE,{modal:!1,children:[v.jsx(yE,{asChild:!0,children:v.jsx(At,{variant:"ghost",size:"icon-sm",className:"justify-self-end","aria-label":"会话操作","data-slot":"chat-overflow-trigger",children:v.jsx(TW,{"aria-hidden":"true"})})}),v.jsxs(bE,{align:"end",className:"w-max min-w-44 max-w-[calc(100vw-1rem)]","data-slot":"chat-overflow-menu",children:[v.jsx(sg,{className:Eg,children:"会话"}),v.jsxs(ko,{className:zu,"data-slot":"chat-menu-find",onSelect:n,children:[v.jsx(wo,{children:v.jsx(av,{"aria-hidden":"true"})}),"在会话中查找"]}),v.jsxs(ko,{className:zu,"data-slot":"chat-menu-rename",onSelect:()=>Se(!0),children:[v.jsx(wo,{children:v.jsx(p7,{"aria-hidden":"true"})}),"重命名"]}),v.jsxs(Ew,{checked:te,className:"min-h-9 justify-start gap-2.5 pl-2 pr-8 [&>span:first-child]:left-auto [&>span:first-child]:right-2",disabled:re,"data-slot":"chat-menu-screen-wake-lock-item",onCheckedChange:ee,children:[v.jsx(wo,{children:v.jsx(GW,{"aria-hidden":"true"})}),v.jsx("span",{className:"min-w-0 flex-1",children:D.supported?j?"屏幕常亮(Voice Pilot 控制)":"屏幕常亮":D.unavailableReason==="insecure-context"?"屏幕常亮(需要 HTTPS)":"屏幕常亮(浏览器不支持)"})]}),A&&!H&&v.jsxs(Ew,{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:!E,"data-slot":"chat-menu-pty-auto-yes-item",onCheckedChange:ye=>{E&&T(E,ye===!0)},children:[v.jsx(wo,{children:v.jsx(pa,{"aria-hidden":"true"})}),v.jsx("span",{className:"min-w-0 flex-1",children:"Always yes"})]}),!A&&!H&&v.jsxs(Ew,{checked:K.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:pe,children:[v.jsx(wo,{children:v.jsx(t7,{"aria-hidden":"true"})}),v.jsx("span",{className:"min-w-0 flex-1",children:"Voice Pilot"})]}),v.jsx(Cw,{}),A&&!H?v.jsxs(v.Fragment,{children:[v.jsx(sg,{className:Eg,children:"快捷键"}),v.jsxs(ko,{className:zu,"data-slot":"chat-menu-send-ctrl-o",onClick:()=>eo(e,""),children:[v.jsx(o_e,{label:"^O"}),"发送 Ctrl+O"]}),v.jsx(Cw,{}),v.jsx(sg,{className:Eg,children:"文件"}),v.jsxs(ko,{className:zu,"data-slot":"chat-menu-upload-image",onClick:()=>{var ye;return(ye=Ee.current)==null?void 0:ye.click()},children:[v.jsx(wo,{children:v.jsx(np,{"aria-hidden":"true"})}),"上传照片或视频"]}),v.jsxs(ko,{className:zu,"data-slot":"chat-menu-upload-file",onClick:()=>{var ye;return(ye=me.current)==null?void 0:ye.click()},children:[v.jsx(wo,{children:v.jsx(qD,{"aria-hidden":"true"})}),"上传文件"]}),v.jsx(Cw,{})]}):null,v.jsx(sg,{className:Eg,children:"字号"}),v.jsx("div",{className:"px-2 pb-1","data-slot":"chat-menu-font-control",children:v.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:[v.jsx(wo,{children:v.jsx(j7,{"aria-hidden":"true"})}),v.jsxs("div",{className:"col-start-2 inline-flex w-fit shrink-0 items-center gap-2","data-slot":"chat-menu-font-stepper",children:[v.jsx(At,{variant:"ghost",size:"icon-sm",className:"size-[22px] rounded-[5px] bg-muted/45 text-muted-foreground hover:bg-accent hover:text-accent-foreground",disabled:M<=O,"aria-label":"字号变小","data-slot":"chat-menu-font-smaller",onClick:ye=>{ye.stopPropagation(),oe(-1)},children:v.jsx(r7,{"aria-hidden":"true"})}),v.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:[M,"px"]}),v.jsx(At,{variant:"ghost",size:"icon-sm",className:"size-[22px] rounded-[5px] bg-muted/45 text-muted-foreground hover:bg-accent hover:text-accent-foreground",disabled:M>=uI,"aria-label":"字号变大","data-slot":"chat-menu-font-larger",onClick:ye=>{ye.stopPropagation(),oe(1)},children:v.jsx(v7,{"aria-hidden":"true"})})]})]})}),v.jsxs(ko,{className:zu,"data-slot":"chat-menu-font-reset",onClick:U,children:[v.jsx(wo,{children:v.jsx(_7,{"aria-hidden":"true"})}),v.jsx("span",{"data-slot":"chat-menu-font-reset-label",children:"恢复默认"})]})]})]})]})}),v.jsx(sh,{open:Oe,sessionId:e,initialName:s==null?void 0:s.name,onOpenChange:Se,onRename:Ht}),v.jsx(Bl,{open:B&&!K.enabled,onOpenChange:ye=>{Y||L(ye)},children:v.jsxs(zl,{className:"sm:max-w-md","data-slot":"voice-pilot-wake-lock-dialog",focusSurfaceOnOpen:!0,children:[v.jsxs(jl,{children:[v.jsx(ba,{children:"开启 Voice Pilot?"}),v.jsx(El,{children:"开启后会持续聆听并保持屏幕常亮,停止后自动恢复。"})]}),v.jsxs(Mc,{children:[v.jsx(At,{type:"button",variant:"outline",disabled:Y,onClick:()=>L(!1),children:"取消"}),v.jsx(At,{type:"button","data-slot":"voice-pilot-confirm-start",disabled:Y,onClick:()=>{ae()},children:Y?"正在开启...":"开启 Voice Pilot"})]})]})}),A?v.jsxs(v.Fragment,{children:[v.jsx("input",{ref:Ee,type:"file",accept:r.mediaAccept,className:"hidden","data-slot":"chat-menu-upload-image-input",onChange:ye=>{Qe(ye)}}),v.jsx("input",{ref:me,type:"file",accept:r.fileAccept,className:"hidden","data-slot":"chat-menu-upload-file-input",onChange:ye=>{Qe(ye)}})]}):null]})}function ju(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((b,w)=>r[w]!==b)))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 b=Math.round((Date.now()-f)*100)/100,w=Math.round((Date.now()-g)*100)/100,S=w/16,E=(k,T)=>{for(k=String(k);k.length<T;)k=" "+k;return k};console.info(`%c⏱ ${E(w,5)} /${E(b,5)} ms`,`
|
|
673
673
|
font-size: .6rem;
|
|
674
674
|
font-weight: bold;
|
|
675
675
|
color: hsl(${Math.max(0,Math.min(120-120*S,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 pL(e,t){if(e===void 0)throw new Error("Unexpected undefined");return e}const l_e=(e,t)=>Math.abs(e-t)<1.01,c_e=(e,t,n)=>{let r;return function(...i){e.clearTimeout(r),r=e.setTimeout(()=>t.apply(this,i),n)}},mL=e=>{const{offsetWidth:t,offsetHeight:n}=e;return{width:t,height:n}},u_e=e=>e,d_e=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},f_e=(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(mL(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(mL(n))};e.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(l):l()});return s.observe(n,{box:"border-box"}),()=>{s.unobserve(n)}},gL={passive:!0},vL=typeof window>"u"?!0:"onscrollend"in window,h_e=(e,t)=>{const n=e.scrollElement;if(!n)return;const r=e.targetWindow;if(!r)return;let i=0;const s=e.options.useScrollendEvent&&vL?()=>{}:c_e(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,gL);const d=e.options.useScrollendEvent&&vL;return d&&n.addEventListener("scrollend",u,gL),()=>{n.removeEventListener("scroll",l),d&&n.removeEventListener("scrollend",u)}},p_e=(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"]},m_e=(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 g_e{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:u_e,rangeExtractor:d_e,onChange:()=>{},measureElement:p_e,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=ju(()=>(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=ju(()=>[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=ju(()=>[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 b=p[g];b&&(y[b.lane]=g)}for(let g=f;g<n;g++){const b=s(g),w=this.laneAssignments.get(g);let S,E;const k=u==="estimate"||d.has(b);if(w!==void 0&&this.options.lanes>1){S=w;const A=y[S],H=A!==void 0?p[A]:void 0;E=H?H.end+this.options.gap:r+i}else{const A=this.options.lanes===1?p[g-1]:this.getFurthestMeasurement(p,g);E=A?A.end+this.options.gap:r+i,S=A?A.lane:g%this.options.lanes,this.options.lanes>1&&k&&this.laneAssignments.set(g,S)}const T=d.get(b),R=typeof T=="number"?T:this.options.estimateSize(g),P=E+R;p[g]={index:g,start:E,size:R,end:P,key:b,lane:S},y[S]=g}return this.measurementsCache=p,p},{key:!1,debug:()=>this.options.debug}),this.calculateRange=ju(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,r,i,s)=>this.range=n.length>0&&r>0?v_e({measurements:n,outerSize:r,scrollOffset:i,lanes:s}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=ju(()=>{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=ju(()=>[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 pL(r[i$(0,r.length-1,i=>pL(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&&l_e(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 i$=(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 v_e({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=i$(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 yL=typeof document<"u"?_.useLayoutEffect:_.useEffect;function y_e({useFlushSync:e=!0,...t}){const n=_.useReducer(()=>({}),{})[1],r={...t,onChange:(s,o)=>{var l;e&&o?Fc.flushSync(n):n(),(l=t.onChange)==null||l.call(t,s,o)}},[i]=_.useState(()=>new g_e(r));return i.setOptions(r),yL(()=>i._didMount(),[]),yL(()=>i._willUpdate()),i}function b_e(e){return y_e({observeElementRect:f_e,observeElementOffset:h_e,scrollToFn:m_e,...e})}function __e(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=iC(i)?"image":aC(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 w_e(e){const t=__e(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 S_e(e){return e.kind==="diff"}const x_e=12e4;function bL(e){return e?e.replace(/\r\n?/gu,`
|