diff --git a/desktop-tauri/ui-islands/src/islands/models-page.tsx b/desktop-tauri/ui-islands/src/islands/models-page.tsx index 95207e7f..ebff8ef6 100644 --- a/desktop-tauri/ui-islands/src/islands/models-page.tsx +++ b/desktop-tauri/ui-islands/src/islands/models-page.tsx @@ -312,7 +312,9 @@ function matches(model: ManageModel, keyword: string, provider: string, stateFil if (stateFilter === 'enabled' && !rowEnabled(model)) return false if (stateFilter === 'disabled' && rowEnabled(model)) return false if (stateFilter === 'mapped' && !(model.aliases || []).length) return false - if (provider !== 'all' && (model.provider || '') !== provider) return false + // 「自定义 · 全部」视图:数据已只含自定义家(viewData 的聚合分支给),不再按家过滤 —— + // 行上的 provider 是各家真实 id,拿哨兵 'custom-all' 精确匹配会把整张表筛光 + if (provider !== 'all' && provider !== 'custom-all' && (model.provider || '') !== provider) return false if (!keyword) return true const hay = [model.id, model.name, ...(model.aliases || [])].join(' ').toLowerCase() return hay.includes(keyword) diff --git a/desktop-tauri/ui-islands/src/islands/models-panel-state.ts b/desktop-tauri/ui-islands/src/islands/models-panel-state.ts index 45d28f98..b2e7f98f 100644 --- a/desktop-tauri/ui-islands/src/islands/models-panel-state.ts +++ b/desktop-tauri/ui-islands/src/islands/models-panel-state.ts @@ -435,8 +435,11 @@ function aggregateView(): ManageView { /** 当前视图的数据(两个数据源在这里合流,下游渲染 / 搜索 / 候选自动跟着选中的家走) */ export function viewData(): ManageView { const provider = currentProvider() - if (customSource.isCustom(provider)) return customViewOf(provider) + // 哨兵必须先于 isCustom 判定:'custom-all' 也以 custom- 开头,isCustom 会把它当成 + // 一家真实记录查(record 为 null → 空视图),聚合分支永远走不到 —— v3.0.4~v3.0.6 + // 「全部视图恒为空」的根因就是这两行的先后顺序 if (provider === ALL_CUSTOM) return aggregateView() + if (customSource.isCustom(provider)) return customViewOf(provider) return snapshot.data || EMPTY_VIEW } @@ -886,8 +889,10 @@ export function closeMapping(): void { export function openCustomModel(): void { const provider = currentProvider() // 「自定义 · 全部」不预选:模型要登记到某一家名下,聚合视图说明用户没定到哪一家, - // 交给弹窗自己选(与内置「全部」视图同一行为);单家视图锁定那一家 - const custom = customSource.isCustom(provider) + // 交给弹窗自己选(与内置「全部」视图同一行为);单家视图锁定那一家。 + // 哨兵要先从 isCustom 里豁免:'custom-all' 过不了前缀判定的话,这里会 locked=true + // 且把不存在的 'custom-all' 预选进弹窗(保存必然报「该提供商已不存在」) + const custom = provider !== ALL_CUSTOM && customSource.isCustom(provider) const preselect = custom || (provider !== 'all' && provider !== ALL_CUSTOM) ? provider : '' patch({ customModel: { provider: preselect, locked: custom } }) } @@ -945,14 +950,18 @@ export function providerLabelOf(provider: string): string { */ export function refreshModels(): void { const provider = currentProvider() - const custom = customSource.isCustom(provider) + // 哨兵不算单家(同 openCustomModel:'custom-all' 会被 isCustom 的前缀判定误中, + // 把 name 顶成哨兵原文、custom 布尔置真) + const custom = provider !== ALL_CUSTOM && customSource.isCustom(provider) const name = custom ? (customSource.record(provider)?.name || provider) : t('内置提供商') shared().wbModelsFetchModal?.open({ - // 「自定义 · 全部」聚合视图没有单一的上游可拉(各家 Base URL 都不同), - // 把 providerId 置空,弹窗按内置家的「多家范围」模式组装刷新名单 - providerId: provider === ALL_CUSTOM ? '' : provider, + // 「自定义 · 全部」聚合视图没有单一的上游可拉(各家 Base URL 都不同),按内置家的 + // 「多家范围」模式打开弹窗。providerId 传 'all' 而不是空串:弹窗入口对空 providerId + // 直接 return(点了没反应),而内置分支的刷新请求体只带 {accounts, providers}, + // 不会把这个值发给后端 —— 它只在弹窗没拿到 name 时做标题回落,这里已显式给了 + providerId: provider === ALL_CUSTOM ? 'all' : provider, custom, name, // 自定义家:导入成功 → 目录缓存已刷新,重绘即可(数据源是本地缓存) diff --git a/desktop-tauri/ui/islands/ui.js b/desktop-tauri/ui/islands/ui.js index 60d68d69..d62d313b 100644 --- a/desktop-tauri/ui/islands/ui.js +++ b/desktop-tauri/ui/islands/ui.js @@ -1,23 +1,23 @@ -var kse=Object.defineProperty;var Cse=(xi,gl,to)=>gl in xi?kse(xi,gl,{enumerable:!0,configurable:!0,writable:!0,value:to}):xi[gl]=to;var ln=(xi,gl,to)=>Cse(xi,typeof gl!="symbol"?gl+"":gl,to);(function(){"use strict";function xi(e,t){for(var a=0;ao[c]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}function gl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var to={exports:{}},Bd={};var eC;function D5(){if(eC)return Bd;eC=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function a(o,c,d){var f=null;if(d!==void 0&&(f=""+d),c.key!==void 0&&(f=""+c.key),"key"in c){d={};for(var p in c)p!=="key"&&(d[p]=c[p])}else d=c;return c=d.ref,{$$typeof:e,type:o,key:f,ref:c!==void 0?c:null,props:d}}return Bd.Fragment=t,Bd.jsx=a,Bd.jsxs=a,Bd}var tC;function I5(){return tC||(tC=1,to.exports=D5()),to.exports}var s=I5(),xv={exports:{}},ct={};var nC;function P5(){if(nC)return ct;nC=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),a=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),c=Symbol.for("react.profiler"),d=Symbol.for("react.consumer"),f=Symbol.for("react.context"),p=Symbol.for("react.forward_ref"),g=Symbol.for("react.suspense"),v=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),b=Symbol.for("react.activity"),j=Symbol.for("react.view_transition"),w=Symbol.iterator;function S(M){return M===null||typeof M!="object"?null:(M=w&&M[w]||M["@@iterator"],typeof M=="function"?M:null)}var N={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},k=Object.assign,E={};function D(M,U,Z){this.props=M,this.context=U,this.refs=E,this.updater=Z||N}D.prototype.isReactComponent={},D.prototype.setState=function(M,U){if(typeof M!="object"&&typeof M!="function"&&M!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,M,U,"setState")},D.prototype.forceUpdate=function(M){this.updater.enqueueForceUpdate(this,M,"forceUpdate")};function C(){}C.prototype=D.prototype;function A(M,U,Z){this.props=M,this.context=U,this.refs=E,this.updater=Z||N}var R=A.prototype=new C;R.constructor=A,k(R,D.prototype),R.isPureReactComponent=!0;var I=Array.isArray;function P(){}var O={H:null,A:null,T:null,S:null},_=Object.prototype.hasOwnProperty;function L(M,U,Z){var ae=Z.ref;return{$$typeof:e,type:M,key:U,ref:ae!==void 0?ae:null,props:Z}}function H(M,U){return L(M.type,U,M.props)}function B(M){return typeof M=="object"&&M!==null&&M.$$typeof===e}function z(M){var U={"=":"=0",":":"=2"};return"$"+M.replace(/[=:]/g,function(Z){return U[Z]})}var Q=/\/+/g;function K(M,U){return typeof M=="object"&&M!==null&&M.key!=null?z(""+M.key):U.toString(36)}function X(M){switch(M.status){case"fulfilled":return M.value;case"rejected":throw M.reason;default:switch(typeof M.status=="string"?M.then(P,P):(M.status="pending",M.then(function(U){M.status==="pending"&&(M.status="fulfilled",M.value=U)},function(U){M.status==="pending"&&(M.status="rejected",M.reason=U)})),M.status){case"fulfilled":return M.value;case"rejected":throw M.reason}}throw M}function q(M,U,Z,ae,ce){var J=typeof M;(J==="undefined"||J==="boolean")&&(M=null);var ie=!1;if(M===null)ie=!0;else switch(J){case"bigint":case"string":case"number":ie=!0;break;case"object":switch(M.$$typeof){case e:case t:ie=!0;break;case y:return ie=M._init,q(ie(M._payload),U,Z,ae,ce)}}if(ie)return ce=ce(M),ie=ae===""?"."+K(M,0):ae,I(ce)?(Z="",ie!=null&&(Z=ie.replace(Q,"$&/")+"/"),q(ce,U,Z,"",function(fe){return fe})):ce!=null&&(B(ce)&&(ce=H(ce,Z+(ce.key==null||M&&M.key===ce.key?"":(""+ce.key).replace(Q,"$&/")+"/")+ie)),U.push(ce)),1;ie=0;var ge=ae===""?".":ae+":";if(I(M))for(var ee=0;ee"u"?!1:e instanceof ShadowRoot||e instanceof Sn(e).ShadowRoot}function Ud(e){const{overflow:t,overflowX:a,overflowY:o,display:c}=xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+o+a)&&c!=="inline"&&c!=="contents"}function L5(e){return/^(table|td|th)$/.test(Bs(e))}function Rm(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const z5=/transform|translate|scale|rotate|perspective|filter/,B5=/paint|layout|strict|content/,bi=e=>!!e&&e!=="none";let vv;function yv(e){const t=At(e)?xr(e):e;return bi(t.transform)||bi(t.translate)||bi(t.scale)||bi(t.rotate)||bi(t.perspective)||!jv()&&(bi(t.backdropFilter)||bi(t.filter))||z5.test(t.willChange||"")||B5.test(t.contain||"")}function H5(e){let t=so(e);for(;dn(t)&&!no(t);){if(yv(t))return t;if(Rm(t))return null;t=so(t)}return null}function jv(){return vv==null&&(vv=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),vv}function no(e){return/^(html|body|#document)$/.test(Bs(e))}function xr(e){return Sn(e).getComputedStyle(e)}function Om(e){return At(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function so(e){if(Bs(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Bc(e)&&e.host||xl(e);return Bc(t)?t.host:t}function rC(e){const t=so(e);return no(t)?(e.ownerDocument||e).body:dn(t)&&Ud(t)?t:rC(t)}function Hc(e,t,a){var o;t===void 0&&(t=[]),a===void 0&&(a=!0);const c=rC(e),d=c===((o=e.ownerDocument)==null?void 0:o.body),f=Sn(c);if(d){const p=wv(f);return t.concat(f,f.visualViewport||[],Ud(c)?c:[],p&&a?Hc(p):[])}else return t.concat(c,Hc(c,[],a))}function wv(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}const Sv={..._5},aC={};function Ms(e,t){const a=x.useRef(aC);return a.current===aC&&(a.current=e(t)),a}const Nv=Sv.useInsertionEffect,U5=Nv&&Nv!==Sv.useLayoutEffect?Nv:e=>e();function Ie(e){const t=Ms(V5).current;return t.next=e,U5(t.effect),t.trampoline}function V5(){const e={next:void 0,callback:F5,trampoline:(...t)=>e.callback?.(...t),effect:()=>{e.callback=e.next}};return e}function F5(){}const De=typeof document<"u"?x.useLayoutEffect:()=>{};function kv(e,t){if(e&&!t)return e;if(!e&&t)return t;if(e||t)return{...e,...t}}const Cv={};function Wr(e,t,a,o,c){if(!a&&!o&&!c&&!e)return Mm(t);let d=Mm(e);return t&&(d=Vd(d,t)),a&&(d=Vd(d,a)),o&&(d=Vd(d,o)),c&&(d=Vd(d,c)),d}function $5(e){if(e.length===0)return Cv;if(e.length===1)return Mm(e[0]);let t=Mm(e[0]);for(let a=1;a=65&&c<=90&&(typeof t=="function"||typeof t>"u")}function Tv(e){return typeof e=="function"}function oC(e,t){return Tv(e)?e(t):e??Cv}function K5(e,t){return t?e?(...a)=>{const o=a[0];if(uC(o)){const d=o;Dm(d);const f=t(...a);return d.baseUIHandlerPrevented||e?.(...a),f}const c=t(...a);return e?.(...a),c}:iC(t):e}function iC(e){return e&&((...t)=>{const a=t[0];return uC(a)&&Dm(a),e(...t)})}function Dm(e){return e.preventBaseUIHandler=()=>{e.baseUIHandlerPrevented=!0},e}function cC(e,t){return t?e?t+" "+e:t:e}function uC(e){return e!=null&&typeof e=="object"&&"nativeEvent"in e}function Y5(e,t){return function(o,...c){const d=new URL(e);return d.searchParams.set("code",o.toString()),c.forEach(f=>d.searchParams.append("args[]",f)),`${t} error #${o}; visit ${d} for the full message.`}}const on=Y5("https://base-ui.com/production-error","Base UI"),dC=x.createContext(void 0);function fC(e=!1){const t=x.useContext(dC);if(t===void 0&&!e)throw new Error(on(16));return t}function X5(e){const{focusableWhenDisabled:t,disabled:a,composite:o=!1,tabIndex:c=0,isNativeButton:d}=e,f=o&&t!==!1,p=o&&t===!1;return{props:x.useMemo(()=>{const v={onKeyDown(y){a&&t&&y.key!=="Tab"&&y.preventDefault()}};return o||(v.tabIndex=c,!d&&a&&(v.tabIndex=t?c:-1)),(d&&(t||f)||!d&&a)&&(v["aria-disabled"]=a),d&&(!t||p)&&(v.disabled=a),v},[o,a,t,f,p,d,c])}}function $t(e){return e?.ownerDocument||document}function Uc(e,t,{detail:a=0}={}){e.dispatchEvent(new(Sn(e)).PointerEvent("click",{bubbles:!0,cancelable:!0,composed:!0,detail:a,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey,metaKey:t.metaKey}))}function Jr(e={}){const{disabled:t=!1,focusableWhenDisabled:a,tabIndex:o=0,native:c=!0,composite:d}=e,f=x.useRef(null),p=fC(!0),g=d??p!==void 0,{props:v}=X5({focusableWhenDisabled:a,disabled:t,composite:g,tabIndex:o,isNativeButton:c}),y=x.useCallback(()=>{const w=f.current;Ev(w)&&g&&t&&v.disabled===void 0&&w.disabled&&(w.disabled=!1)},[t,v.disabled,g]);De(y,[y]);const b=x.useCallback((w={})=>{const{onClick:S,onMouseDown:N,onKeyUp:k,onKeyDown:E,onPointerDown:D,...C}=w;return Wr({onClick(A){if(t){A.preventDefault();return}S?.(A)},onMouseDown(A){t||N?.(A)},onKeyDown(A){if(t||(Dm(A),E?.(A),A.baseUIHandlerPrevented))return;const R=A.target===A.currentTarget,I=A.currentTarget,P=Ev(I),O=!c&&Q5(I),_=R&&(c?P:!O),L=A.key==="Enter",H=A.key===" ",B=I.getAttribute("role"),z=B?.startsWith("menuitem")||B==="option"||B==="gridcell";if(R&&g&&H){if(A.defaultPrevented&&z)return;A.preventDefault(),(!c||P)&&(A.preventBaseUIHandler(),Uc(I,A));return}if(!_||c||!H&&!L){R&&O&&H&&A.preventDefault();return}A.defaultPrevented||(A.preventDefault(),L&&(A.preventBaseUIHandler(),Uc(I,A)))},onKeyUp(A){if(!t){if(Dm(A),k?.(A),A.target===A.currentTarget&&c&&g&&Ev(A.currentTarget)&&A.key===" "){A.preventDefault();return}A.baseUIHandlerPrevented||A.target===A.currentTarget&&!c&&!g&&!A.defaultPrevented&&A.key===" "&&(A.preventBaseUIHandler(),Uc(A.currentTarget,A))}},onPointerDown(A){if(t){A.preventDefault();return}D?.(A)}},c?{type:"button"}:{role:"button"},v,C)},[t,v,g,c]),j=Ie(w=>{f.current=w,y()});return{getButtonProps:b,buttonRef:j}}function Ev(e){return dn(e)&&e.tagName==="BUTTON"}function Q5(e){return dn(e)&&e.tagName==="A"&&!!e.href}function ea(e,t,a,o){const c=Ms(pC).current;return W5(c,e,t,a,o)&&mC(c,[e,t,a,o]),c.callback}function Z5(e){const t=Ms(pC).current;return J5(t,e)&&mC(t,e),t.callback}function pC(){return{callback:null,cleanup:null,refs:[]}}function W5(e,t,a,o,c){return e.refs[0]!==t||e.refs[1]!==a||e.refs[2]!==o||e.refs[3]!==c}function J5(e,t){return e.refs.length!==t.length||e.refs.some((a,o)=>a!==t[o])}function mC(e,t){if(e.refs=t,t.every(a=>a==null)){e.callback=null;return}e.callback=a=>{if(e.cleanup&&(e.cleanup(),e.cleanup=null),a!=null){const o=Array(t.length).fill(null);for(let c=0;c{for(let c=0;c=e}function hC(e){if(!x.isValidElement(e))return null;const t=e,a=t.props;return(Av(19)?a?.ref:t.ref)??null}function qt(){}const Rr=Object.freeze([]),fn=Object.freeze({});function tz(e,t){const a={};for(const o in e){const c=e[o];if(t?.hasOwnProperty(o)){const d=t[o](c);d!=null&&Object.assign(a,d);continue}c===!0?a[`data-${o.toLowerCase()}`]="":c&&(a[`data-${o.toLowerCase()}`]=c.toString())}return a}function nz(e,t){return typeof e=="function"?e(t):e}function sz(e,t){return typeof e=="function"?e(t):e}function vt(e,t,a={}){let o=t.render;a.enabled!==!1&&(o=oz(o));const c=rz(t,a,o);if(a.enabled===!1)return null;const d=a.state??fn;return iz(e,o,c,d)}function rz(e,t,a){const{className:o,style:c}=e,{state:d=fn,ref:f,props:p,stateAttributesMapping:g,enabled:v=!0}=t,y=v?nz(o,d):void 0,b=v?sz(c,d):void 0,j=v?tz(d,g):fn,w=v&&p?az(p):void 0,S=v?kv(j,w)??{}:fn;return typeof document<"u"&&(v?Array.isArray(f)?S.ref=Z5([S.ref,hC(a),...f]):S.ref=ea(S.ref,hC(a),f):ea(null,null)),v?(y!==void 0&&(S.className=cC(S.className,y)),b!==void 0&&(S.style=kv(S.style,b)),S):fn}function az(e){return Array.isArray(e)?$5(e):Wr(void 0,e)}const lz=Symbol.for("react.lazy");function oz(e){if(e?.$$typeof!==lz)return e;const t=x.Children.toArray(e)[0];return x.isValidElement(t)?t:e}function iz(e,t,a,o){if(t){if(typeof t=="function")return t(a,o);const c=Wr(a,t.props);return c.ref=a.ref,x.cloneElement(t,c)}if(e&&typeof e=="string")return cz(e,a);throw new Error(on(8))}function cz(e,t){return e==="button"?x.createElement("button",{type:"button",...t,key:t.key}):e==="img"?x.createElement("img",{alt:"",...t,key:t.key}):x.createElement(e,t)}const uz=x.forwardRef(function(t,a){const{render:o,className:c,disabled:d=!1,focusableWhenDisabled:f=!1,nativeButton:p=!0,style:g,...v}=t,{getButtonProps:y,buttonRef:b}=Jr({disabled:d,focusableWhenDisabled:f,native:p});return vt("button",t,{state:{disabled:d},ref:[a,b],props:[v,y]})});function gC(e){var t,a,o="";if(typeof e=="string"||typeof e=="number")o+=e;else if(typeof e=="object")if(Array.isArray(e)){var c=e.length;for(t=0;ttypeof e=="boolean"?`${e}`:e===0?"0":e,vC=xC,Vc=(e,t)=>a=>{var o;if(t?.variants==null)return vC(e,a?.class,a?.className);const{variants:c,defaultVariants:d}=t,f=Object.keys(c).map(v=>{const y=a?.[v],b=d?.[v];if(y===null)return null;const j=bC(y)||bC(b);return c[v][j]}),p=a&&Object.entries(a).reduce((v,y)=>{let[b,j]=y;return j===void 0||(v[b]=j),v},{}),g=t==null||(o=t.compoundVariants)===null||o===void 0?void 0:o.reduce((v,y)=>{let{class:b,className:j,...w}=y;return Object.entries(w).every(S=>{let[N,k]=S;return Array.isArray(k)?k.includes({...d,...p}[N]):{...d,...p}[N]===k})?[...v,b,j]:v},[]);return vC(e,f,g,a?.class,a?.className)},dz=(e,t)=>{const a=new Array(e.length+t.length);for(let o=0;o({classGroupId:e,validator:t}),yC=(e=new Map,t=null,a)=>({nextPart:e,validators:t,classGroupId:a}),Im="-",jC=[],pz="arbitrary..",mz=e=>{const t=gz(e),{conflictingClassGroups:a,conflictingClassGroupModifiers:o}=e;return{getClassGroupId:f=>{if(f.startsWith("[")&&f.endsWith("]"))return hz(f);const p=f.split(Im),g=p[0]===""&&p.length>1?1:0;return wC(p,g,t)},getConflictingClassGroupIds:(f,p)=>{if(p){const g=o[f],v=a[f];return g?v?dz(v,g):g:v||jC}return a[f]||jC}}},wC=(e,t,a)=>{if(e.length-t===0)return a.classGroupId;const c=e[t],d=a.nextPart.get(c);if(d){const v=wC(e,t+1,d);if(v)return v}const f=a.validators;if(f===null)return;const p=t===0?e.join(Im):e.slice(t).join(Im),g=f.length;for(let v=0;ve.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),a=t.indexOf(":"),o=t.slice(0,a);return o?pz+o:void 0})(),gz=e=>{const{theme:t,classGroups:a}=e;return xz(a,t)},xz=(e,t)=>{const a=yC();for(const o in e){const c=e[o];Rv(c,a,o,t)}return a},Rv=(e,t,a,o)=>{const c=e.length;for(let d=0;d{if(typeof e=="string"){vz(e,t,a);return}if(typeof e=="function"){yz(e,t,a,o);return}jz(e,t,a,o)},vz=(e,t,a)=>{const o=e===""?t:SC(t,e);o.classGroupId=a},yz=(e,t,a,o)=>{if(wz(e)){Rv(e(o),t,a,o);return}t.validators===null&&(t.validators=[]),t.validators.push(fz(a,e))},jz=(e,t,a,o)=>{const c=Object.entries(e),d=c.length;for(let f=0;f{let a=e;const o=t.split(Im),c=o.length;for(let d=0;d"isThemeGetter"in e&&e.isThemeGetter===!0,Sz=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,a=Object.create(null),o=Object.create(null);const c=(d,f)=>{a[d]=f,t++,t>e&&(t=0,o=a,a=Object.create(null))};return{get(d){let f=a[d];if(f!==void 0)return f;if((f=o[d])!==void 0)return c(d,f),f},set(d,f){d in a?a[d]=f:c(d,f)}}},Ov="!",NC=":",Nz=[],kC=(e,t,a,o,c)=>({modifiers:e,hasImportantModifier:t,baseClassName:a,maybePostfixModifierPosition:o,isExternal:c}),kz=e=>{const{prefix:t,experimentalParseClassName:a}=e;let o=c=>{const d=[];let f=0,p=0,g=0,v;const y=c.length;for(let N=0;Ng?v-g:void 0;return kC(d,w,j,S)};if(t){const c=t+NC,d=o;o=f=>f.startsWith(c)?d(f.slice(c.length)):kC(Nz,!1,f,void 0,!0)}if(a){const c=o;o=d=>a({className:d,parseClassName:c})}return o},Cz=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((a,o)=>{t.set(a,1e6+o)}),a=>{const o=[];let c=[];for(let d=0;d0&&(c.sort(),o.push(...c),c=[]),o.push(f)):c.push(f)}return c.length>0&&(c.sort(),o.push(...c)),o}},Tz=e=>({cache:Sz(e.cacheSize),parseClassName:kz(e),sortModifiers:Cz(e),postfixLookupClassGroupIds:Ez(e),...mz(e)}),Ez=e=>{const t=Object.create(null),a=e.postfixLookupClassGroups;if(a)for(let o=0;o{const{parseClassName:a,getClassGroupId:o,getConflictingClassGroupIds:c,sortModifiers:d,postfixLookupClassGroupIds:f}=t,p=[],g=e.trim().split(Az);let v="";for(let y=g.length-1;y>=0;y-=1){const b=g[y],{isExternal:j,modifiers:w,hasImportantModifier:S,baseClassName:N,maybePostfixModifierPosition:k}=a(b);if(j){v=b+(v.length>0?" "+v:v);continue}let E=!!k,D;if(E){const P=N.substring(0,k);D=o(P);const O=D&&f[D]?o(N):void 0;O&&O!==D&&(D=O,E=!1)}else D=o(N);if(!D){if(!E){v=b+(v.length>0?" "+v:v);continue}if(D=o(N),!D){v=b+(v.length>0?" "+v:v);continue}E=!1}const C=w.length===0?"":w.length===1?w[0]:d(w).join(":"),A=S?C+Ov:C,R=A+D;if(p.indexOf(R)>-1)continue;p.push(R);const I=c(D,E);for(let P=0;P0?" "+v:v)}return v},Oz=(...e)=>{let t=0,a,o,c="";for(;t{if(typeof e=="string")return e;let t,a="";for(let o=0;o{let a,o,c,d;const f=g=>{const v=t.reduce((y,b)=>b(y),e());return a=Tz(v),o=a.cache.get,c=a.cache.set,d=p,p(g)},p=g=>{const v=o(g);if(v)return v;const y=Rz(g,a);return c(g,y),y};return d=f,(...g)=>d(Oz(...g))},Dz=[],Ss=e=>{const t=a=>a[e]||Dz;return t.isThemeGetter=!0,t.themeKey=e,t},TC=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,EC=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Iz=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,Pz=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,_z=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Lz=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix|color|light-dark)\(.+\)$/,zz=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Bz=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,ro=e=>Iz.test(e),Nt=e=>!!e&&!Number.isNaN(Number(e)),Fa=e=>!!e&&Number.isInteger(Number(e)),Mv=e=>e.endsWith("%")&&Nt(e.slice(0,-1)),bl=e=>Pz.test(e),AC=()=>!0,Hz=e=>_z.test(e)&&!Lz.test(e),Dv=()=>!1,Uz=e=>zz.test(e),Vz=e=>Bz.test(e),Fz=e=>!Ke(e)&&!Xe(e),$z=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),qz=e=>ao(e,PC,Dv),Ke=e=>TC.test(e),vi=e=>ao(e,_C,Hz),RC=e=>ao(e,Jz,Nt),Gz=e=>ao(e,zC,AC),Kz=e=>ao(e,LC,Dv),OC=e=>ao(e,DC,Dv),Yz=e=>ao(e,IC,Vz),Pm=e=>ao(e,BC,Uz),Xe=e=>EC.test(e),Fd=e=>yi(e,_C),Xz=e=>yi(e,LC),MC=e=>yi(e,DC),Qz=e=>yi(e,PC),Zz=e=>yi(e,IC),_m=e=>yi(e,BC,!0),Wz=e=>yi(e,zC,!0),ao=(e,t,a)=>{const o=TC.exec(e);return o?o[1]?t(o[1]):a(o[2]):!1},yi=(e,t,a=!1)=>{const o=EC.exec(e);return o?o[1]?t(o[1]):a:!1},DC=e=>e==="position"||e==="percentage",IC=e=>e==="image"||e==="url",PC=e=>e==="length"||e==="size"||e==="bg-size",_C=e=>e==="length",Jz=e=>e==="number",LC=e=>e==="family-name",zC=e=>e==="number"||e==="weight",BC=e=>e==="shadow",e4=Mz(()=>{const e=Ss("color"),t=Ss("font"),a=Ss("text"),o=Ss("font-weight"),c=Ss("tracking"),d=Ss("leading"),f=Ss("breakpoint"),p=Ss("container"),g=Ss("spacing"),v=Ss("radius"),y=Ss("shadow"),b=Ss("inset-shadow"),j=Ss("text-shadow"),w=Ss("drop-shadow"),S=Ss("blur"),N=Ss("perspective"),k=Ss("aspect"),E=Ss("ease"),D=Ss("animate"),C=()=>["auto","avoid","all","avoid-page","page","left","right","column"],A=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],R=()=>[...A(),Xe,Ke],I=()=>["auto","hidden","clip","visible","scroll"],P=()=>["auto","contain","none"],O=()=>[Xe,Ke,g],_=()=>[ro,"full","auto",...O()],L=()=>[Fa,"none","subgrid",Xe,Ke],H=()=>["auto",{span:["full",Fa,Xe,Ke]},Fa,Xe,Ke],B=()=>[Fa,"auto",Xe,Ke],z=()=>["auto","min","max","fr",Xe,Ke],Q=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],K=()=>["start","end","center","stretch","center-safe","end-safe"],X=()=>["auto",...O()],q=()=>[ro,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...O()],$=()=>[p,ro,"screen","full","dvw","lvw","svw","min","max","fit",...O()],Y=()=>[ro,"screen","full","lh","dvh","lvh","svh","min","max","fit",...O()],F=()=>[e,Xe,Ke],G=()=>[...A(),MC,OC,{position:[Xe,Ke]}],W=()=>["no-repeat",{repeat:["","x","y","space","round"]}],le=()=>["auto","cover","contain",Qz,qz,{size:[Xe,Ke]}],M=()=>[Mv,Fd,vi],U=()=>["","none","full",v,Xe,Ke],Z=()=>["",Nt,Fd,vi],ae=()=>["solid","dashed","dotted","double"],ce=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>[Nt,Mv,MC,OC],ie=()=>["","none",S,Xe,Ke],ge=()=>["none",Nt,Xe,Ke],ee=()=>["none",Nt,Xe,Ke],fe=()=>[Nt,Xe,Ke],te=()=>[ro,"full",...O()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[bl],breakpoint:[bl],color:[AC],container:[bl],"drop-shadow":[bl],ease:["in","out","in-out"],font:[Fz],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[bl],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[bl],shadow:[bl],spacing:["px",Nt],text:[bl],"text-shadow":[bl],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",ro,Ke,Xe,k]}],container:["container"],"container-type":[{"@container":["","normal","size",Xe,Ke]}],"container-named":[$z],columns:[{columns:[Nt,"auto",Ke,Xe,p]}],"break-after":[{"break-after":C()}],"break-before":[{"break-before":C()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:R()}],overflow:[{overflow:I()}],"overflow-x":[{"overflow-x":I()}],"overflow-y":[{"overflow-y":I()}],overscroll:[{overscroll:P()}],"overscroll-x":[{"overscroll-x":P()}],"overscroll-y":[{"overscroll-y":P()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:_()}],"inset-x":[{"inset-x":_()}],"inset-y":[{"inset-y":_()}],start:[{"inset-s":_(),start:_()}],end:[{"inset-e":_(),end:_()}],"inset-bs":[{"inset-bs":_()}],"inset-be":[{"inset-be":_()}],top:[{top:_()}],right:[{right:_()}],bottom:[{bottom:_()}],left:[{left:_()}],visibility:["visible","invisible","collapse"],z:[{z:[Fa,"auto",Xe,Ke]}],basis:[{basis:[ro,"full","auto",p,...O()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Nt,ro,"auto","initial","none",Ke]}],grow:[{grow:["",Nt,Xe,Ke]}],shrink:[{shrink:["",Nt,Xe,Ke]}],order:[{order:[Fa,"first","last","none",Xe,Ke]}],"grid-cols":[{"grid-cols":L()}],"col-start-end":[{col:H()}],"col-start":[{"col-start":B()}],"col-end":[{"col-end":B()}],"grid-rows":[{"grid-rows":L()}],"row-start-end":[{row:H()}],"row-start":[{"row-start":B()}],"row-end":[{"row-end":B()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":z()}],"auto-rows":[{"auto-rows":z()}],gap:[{gap:O()}],"gap-x":[{"gap-x":O()}],"gap-y":[{"gap-y":O()}],"justify-content":[{justify:[...Q(),"normal"]}],"justify-items":[{"justify-items":[...K(),"normal"]}],"justify-self":[{"justify-self":["auto",...K()]}],"align-content":[{content:["normal",...Q()]}],"align-items":[{items:[...K(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...K(),{baseline:["","last"]}]}],"place-content":[{"place-content":Q()}],"place-items":[{"place-items":[...K(),"baseline"]}],"place-self":[{"place-self":["auto",...K()]}],p:[{p:O()}],px:[{px:O()}],py:[{py:O()}],ps:[{ps:O()}],pe:[{pe:O()}],pbs:[{pbs:O()}],pbe:[{pbe:O()}],pt:[{pt:O()}],pr:[{pr:O()}],pb:[{pb:O()}],pl:[{pl:O()}],m:[{m:X()}],mx:[{mx:X()}],my:[{my:X()}],ms:[{ms:X()}],me:[{me:X()}],mbs:[{mbs:X()}],mbe:[{mbe:X()}],mt:[{mt:X()}],mr:[{mr:X()}],mb:[{mb:X()}],ml:[{ml:X()}],"space-x":[{"space-x":O()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":O()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],"inline-size":[{inline:["auto",...$()]}],"min-inline-size":[{"min-inline":["auto",...$()]}],"max-inline-size":[{"max-inline":["none",...$()]}],"block-size":[{block:["auto",...Y()]}],"min-block-size":[{"min-block":["auto",...Y()]}],"max-block-size":[{"max-block":["none",...Y()]}],w:[{w:[p,"screen",...q()]}],"min-w":[{"min-w":[p,"screen","none",...q()]}],"max-w":[{"max-w":[p,"screen","none","prose",{screen:[f]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh","none",...q()]}],"font-size":[{text:["base",a,Fd,vi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[o,Wz,Gz]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Mv,Ke]}],"font-family":[{font:[Xz,Kz,t]}],"font-features":[{"font-features":[Ke]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[c,Xe,Ke]}],"line-clamp":[{"line-clamp":[Nt,"none",Xe,RC]}],leading:[{leading:["none",d,...O()]}],"list-image":[{"list-image":["none",Xe,Ke]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Xe,Ke]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:F()}],"text-color":[{text:F()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ae(),"wavy"]}],"text-decoration-thickness":[{decoration:[Nt,"from-font","auto",Xe,vi]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[Nt,"auto",Xe,Ke]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:O()}],"tab-size":[{tab:[Fa,Xe,Ke]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Xe,Ke]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Xe,Ke]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:G()}],"bg-repeat":[{bg:W()}],"bg-size":[{bg:le()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Fa,Xe,Ke],radial:["",Xe,Ke],conic:["",Fa,Xe,Ke]},Zz,Yz]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:M()}],"gradient-via-pos":[{via:M()}],"gradient-to-pos":[{to:M()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:U()}],"rounded-s":[{"rounded-s":U()}],"rounded-e":[{"rounded-e":U()}],"rounded-t":[{"rounded-t":U()}],"rounded-r":[{"rounded-r":U()}],"rounded-b":[{"rounded-b":U()}],"rounded-l":[{"rounded-l":U()}],"rounded-ss":[{"rounded-ss":U()}],"rounded-se":[{"rounded-se":U()}],"rounded-ee":[{"rounded-ee":U()}],"rounded-es":[{"rounded-es":U()}],"rounded-tl":[{"rounded-tl":U()}],"rounded-tr":[{"rounded-tr":U()}],"rounded-br":[{"rounded-br":U()}],"rounded-bl":[{"rounded-bl":U()}],"border-w":[{border:Z()}],"border-w-x":[{"border-x":Z()}],"border-w-y":[{"border-y":Z()}],"border-w-s":[{"border-s":Z()}],"border-w-e":[{"border-e":Z()}],"border-w-bs":[{"border-bs":Z()}],"border-w-be":[{"border-be":Z()}],"border-w-t":[{"border-t":Z()}],"border-w-r":[{"border-r":Z()}],"border-w-b":[{"border-b":Z()}],"border-w-l":[{"border-l":Z()}],"divide-x":[{"divide-x":Z()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Z()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...ae(),"hidden","none"]}],"divide-style":[{divide:[...ae(),"hidden","none"]}],"border-color":[{border:F()}],"border-color-x":[{"border-x":F()}],"border-color-y":[{"border-y":F()}],"border-color-s":[{"border-s":F()}],"border-color-e":[{"border-e":F()}],"border-color-bs":[{"border-bs":F()}],"border-color-be":[{"border-be":F()}],"border-color-t":[{"border-t":F()}],"border-color-r":[{"border-r":F()}],"border-color-b":[{"border-b":F()}],"border-color-l":[{"border-l":F()}],"divide-color":[{divide:F()}],"outline-style":[{outline:[...ae(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Nt,Xe,Ke]}],"outline-w":[{outline:["",Nt,Fd,vi]}],"outline-color":[{outline:F()}],shadow:[{shadow:["","inner","none",y,_m,Pm]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":["none",b,_m,Pm]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:Z()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[Nt,vi]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":Z()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":["none",j,_m,Pm]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[Nt,Xe,Ke]}],"mix-blend":[{"mix-blend":[...ce(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ce()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Nt]}],"mask-image-linear-from-pos":[{"mask-linear-from":J()}],"mask-image-linear-to-pos":[{"mask-linear-to":J()}],"mask-image-linear-from-color":[{"mask-linear-from":F()}],"mask-image-linear-to-color":[{"mask-linear-to":F()}],"mask-image-t-from-pos":[{"mask-t-from":J()}],"mask-image-t-to-pos":[{"mask-t-to":J()}],"mask-image-t-from-color":[{"mask-t-from":F()}],"mask-image-t-to-color":[{"mask-t-to":F()}],"mask-image-r-from-pos":[{"mask-r-from":J()}],"mask-image-r-to-pos":[{"mask-r-to":J()}],"mask-image-r-from-color":[{"mask-r-from":F()}],"mask-image-r-to-color":[{"mask-r-to":F()}],"mask-image-b-from-pos":[{"mask-b-from":J()}],"mask-image-b-to-pos":[{"mask-b-to":J()}],"mask-image-b-from-color":[{"mask-b-from":F()}],"mask-image-b-to-color":[{"mask-b-to":F()}],"mask-image-l-from-pos":[{"mask-l-from":J()}],"mask-image-l-to-pos":[{"mask-l-to":J()}],"mask-image-l-from-color":[{"mask-l-from":F()}],"mask-image-l-to-color":[{"mask-l-to":F()}],"mask-image-x-from-pos":[{"mask-x-from":J()}],"mask-image-x-to-pos":[{"mask-x-to":J()}],"mask-image-x-from-color":[{"mask-x-from":F()}],"mask-image-x-to-color":[{"mask-x-to":F()}],"mask-image-y-from-pos":[{"mask-y-from":J()}],"mask-image-y-to-pos":[{"mask-y-to":J()}],"mask-image-y-from-color":[{"mask-y-from":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"mask-image-radial":[{"mask-radial":[Xe,Ke]}],"mask-image-radial-from-pos":[{"mask-radial-from":J()}],"mask-image-radial-to-pos":[{"mask-radial-to":J()}],"mask-image-radial-from-color":[{"mask-radial-from":F()}],"mask-image-radial-to-color":[{"mask-radial-to":F()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":A()}],"mask-image-conic-pos":[{"mask-conic":[Nt]}],"mask-image-conic-from-pos":[{"mask-conic-from":J()}],"mask-image-conic-to-pos":[{"mask-conic-to":J()}],"mask-image-conic-from-color":[{"mask-conic-from":F()}],"mask-image-conic-to-color":[{"mask-conic-to":F()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:G()}],"mask-repeat":[{mask:W()}],"mask-size":[{mask:le()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Xe,Ke]}],filter:[{filter:["","none",Xe,Ke]}],blur:[{blur:ie()}],brightness:[{brightness:[Nt,Xe,Ke]}],contrast:[{contrast:[Nt,Xe,Ke]}],"drop-shadow":[{"drop-shadow":["","none",w,_m,Pm]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:["",Nt,Xe,Ke]}],"hue-rotate":[{"hue-rotate":[Nt,Xe,Ke]}],invert:[{invert:["",Nt,Xe,Ke]}],saturate:[{saturate:[Nt,Xe,Ke]}],sepia:[{sepia:["",Nt,Xe,Ke]}],"backdrop-filter":[{"backdrop-filter":["","none",Xe,Ke]}],"backdrop-blur":[{"backdrop-blur":ie()}],"backdrop-brightness":[{"backdrop-brightness":[Nt,Xe,Ke]}],"backdrop-contrast":[{"backdrop-contrast":[Nt,Xe,Ke]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Nt,Xe,Ke]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Nt,Xe,Ke]}],"backdrop-invert":[{"backdrop-invert":["",Nt,Xe,Ke]}],"backdrop-opacity":[{"backdrop-opacity":[Nt,Xe,Ke]}],"backdrop-saturate":[{"backdrop-saturate":[Nt,Xe,Ke]}],"backdrop-sepia":[{"backdrop-sepia":["",Nt,Xe,Ke]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":O()}],"border-spacing-x":[{"border-spacing-x":O()}],"border-spacing-y":[{"border-spacing-y":O()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Xe,Ke]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Nt,"initial",Xe,Ke]}],ease:[{ease:["linear","initial",E,Xe,Ke]}],delay:[{delay:[Nt,Xe,Ke]}],animate:[{animate:["none",D,Xe,Ke]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[N,Xe,Ke]}],"perspective-origin":[{"perspective-origin":R()}],rotate:[{rotate:ge()}],"rotate-x":[{"rotate-x":ge()}],"rotate-y":[{"rotate-y":ge()}],"rotate-z":[{"rotate-z":ge()}],scale:[{scale:ee()}],"scale-x":[{"scale-x":ee()}],"scale-y":[{"scale-y":ee()}],"scale-z":[{"scale-z":ee()}],"scale-3d":["scale-3d"],skew:[{skew:fe()}],"skew-x":[{"skew-x":fe()}],"skew-y":[{"skew-y":fe()}],transform:[{transform:[Xe,Ke,"","none","gpu","cpu"]}],"transform-origin":[{origin:R()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:te()}],"translate-x":[{"translate-x":te()}],"translate-y":[{"translate-y":te()}],"translate-z":[{"translate-z":te()}],"translate-none":["translate-none"],zoom:[{zoom:[Fa,Xe,Ke]}],accent:[{accent:F()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:F()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Xe,Ke]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":F()}],"scrollbar-track-color":[{"scrollbar-track":F()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":O()}],"scroll-mx":[{"scroll-mx":O()}],"scroll-my":[{"scroll-my":O()}],"scroll-ms":[{"scroll-ms":O()}],"scroll-me":[{"scroll-me":O()}],"scroll-mbs":[{"scroll-mbs":O()}],"scroll-mbe":[{"scroll-mbe":O()}],"scroll-mt":[{"scroll-mt":O()}],"scroll-mr":[{"scroll-mr":O()}],"scroll-mb":[{"scroll-mb":O()}],"scroll-ml":[{"scroll-ml":O()}],"scroll-p":[{"scroll-p":O()}],"scroll-px":[{"scroll-px":O()}],"scroll-py":[{"scroll-py":O()}],"scroll-ps":[{"scroll-ps":O()}],"scroll-pe":[{"scroll-pe":O()}],"scroll-pbs":[{"scroll-pbs":O()}],"scroll-pbe":[{"scroll-pbe":O()}],"scroll-pt":[{"scroll-pt":O()}],"scroll-pr":[{"scroll-pr":O()}],"scroll-pb":[{"scroll-pb":O()}],"scroll-pl":[{"scroll-pl":O()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Xe,Ke]}],fill:[{fill:["none",...F()]}],"stroke-w":[{stroke:[Nt,Fd,vi,RC]}],stroke:[{stroke:["none",...F()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["start","end","right","left"],"inset-y":["inset-bs","inset-be","top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["ps","pe","pr","pl"],py:["pbs","pbe","pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["ms","me","mr","ml"],my:["mbs","mbe","mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-s","border-w-e","border-w-r","border-w-l"],"border-w-y":["border-w-bs","border-w-be","border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-s","border-color-e","border-color-r","border-color-l"],"border-color-y":["border-color-bs","border-color-be","border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-ms","scroll-me","scroll-mr","scroll-ml"],"scroll-my":["scroll-mbs","scroll-mbe","scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-ps","scroll-pe","scroll-pr","scroll-pl"],"scroll-py":["scroll-pbs","scroll-pbe","scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}});function Ue(...e){return e4(xC(e))}const t4=Vc(["group/button inline-flex shrink-0 items-center justify-center gap-1.5 whitespace-nowrap border","font-medium transition-[background-color,border-color,color,transform,box-shadow] duration-150 ease-out","outline-none select-none active:translate-y-[0.5px]","disabled:pointer-events-none disabled:opacity-45 disabled:shadow-none","[&_svg]:pointer-events-none [&_svg]:shrink-0"],{variants:{variant:{default:"border-primary bg-primary font-semibold text-primary-on shadow-glow hover:border-primary-hover hover:bg-primary-hover",outline:"border-control-border bg-control text-foreground shadow-1 hover:border-control-border-hover hover:bg-control-hover",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"border-transparent bg-transparent text-subtle shadow-none hover:bg-control-hover hover:text-foreground",destructive:"border-destructive-bd bg-destructive-soft text-destructive hover:bg-destructive-hover",dashed:"border-dashed border-border-strong bg-transparent text-muted-foreground shadow-none hover:border-primary hover:text-primary-fg",link:"border-transparent bg-transparent text-primary shadow-none underline-offset-4 hover:underline"},size:{default:"h-[30px] rounded-md px-3 text-[12.5px]","2xs":"h-4 rounded-pill px-1.5 text-[10px]",xs:"h-6 rounded-sm px-2 text-[11.5px]",sm:"h-[26px] rounded-sm px-2.5 text-[12px]",lg:"h-9 rounded-md px-4 text-[13px]",icon:"h-[30px] w-[30px] rounded-md p-0","icon-2xs":"size-4 rounded-pill p-0","icon-xs":"size-6 rounded-sm p-0","icon-sm":"h-[26px] w-[26px] rounded-sm p-0","icon-lg":"size-9 rounded-md p-0"}},defaultVariants:{variant:"default",size:"default"}});function se({className:e,variant:t,size:a,...o}){return s.jsx(uz,{className:Ue(t4({variant:t,size:a}),e),...o})}const n4="data-valid",s4="data-invalid",r4={badInput:!1,customError:!1,patternMismatch:!1,rangeOverflow:!1,rangeUnderflow:!1,stepMismatch:!1,tooLong:!1,tooShort:!1,typeMismatch:!1,valid:null,valueMissing:!1},HC={valid:null,touched:!1,dirty:!1,filled:!1,focused:!1},a4={disabled:!1,...HC},ji={valid(e){return e===null?null:e?{[n4]:""}:{[s4]:""}}},UC={invalid:void 0,name:void 0,validityData:{state:r4,errors:[],error:"",value:"",initialValue:null},setValidityData:qt,disabled:void 0,setTouched:qt,setDirty:qt,setFilled:qt,setFocused:qt,validationMode:"onSubmit",shouldValidateOnChange:()=>!1,state:a4,registerFieldControl:qt,validation:{getValidationProps:(e,t=fn)=>t,inputRef:{current:null},registeredInputs:new Map,registerInput:qt,getInputControl:()=>null,commit:async()=>{},change:qt}},VC=x.createContext(UC);function Sa(e=!0){const t=x.useContext(VC);if(t.setValidityData===qt&&!e)throw new Error(on(28));return t}const l4=x.createContext(void 0);function o4(e=!1){const t=x.useContext(l4);if(!t&&!e)throw new Error(on(86));return t}const i4=x.createContext({elementRef:{current:null},formRef:{current:{fields:new Map}},errors:{},clearErrors:qt,validationMode:"onSubmit",submitCountRef:{current:0}});function Fc(){return x.useContext(i4)}let FC=0;function c4(e,t="mui"){const[a,o]=x.useState(e),c=e||a;return x.useEffect(()=>{a==null&&(FC+=1,o(`${t}-${FC}`))},[a,t]),c}const $C=Sv.useId;function $d(e,t){if($C!==void 0){const a=$C();return e??(t?`${t}-${a}`:a)}return c4(e,t)}function Na(e){return $d(e,"base-ui")}const u4=x.createContext({controlId:void 0,registerControlId:qt,resetControlId:qt,labelId:void 0,setLabelId:qt,messageIds:[],setMessageIds:qt,getDescriptionProps:e=>e});function vl(){return x.useContext(u4)}function Iv(e,t,a,o=!0,c){const[d,f]=x.useState(),p=Na(c?`${c}-label`:void 0),g=e??t??d;return De(()=>{const v=e||t||!o?void 0:d4(a.current,p);d!==v&&f(v)}),g}function d4(e,t){const a=f4(e);if(a)return!a.id&&t&&(a.id=t),a.id||void 0}function f4(e){if(!e)return;const t=e.parentElement;if(t&&t.tagName==="LABEL")return t;const a=e.id;if(a){const c=e.nextElementSibling;if(c&&c.htmlFor===a)return c}const o=e.labels;return o&&o[0]}function lo(e={}){const{id:t,enabled:a=!0}=e,{controlId:o,registerControlId:c,resetControlId:d}=vl(),f=Na(),p=Ms(()=>Symbol()),g=x.useRef(!1),v=x.useRef(!1),y=Ie(()=>{!g.current||c===qt||(g.current=!1,c(p.current,void 0))});return De(()=>{if(!a||c===qt){y();return}let b;if(t!==void 0)v.current=!0,b=t;else if(v.current)b=f;else{d();return}if(b===void 0){y();return}g.current=!0,c(p.current,b)},[t,a,c,d,f,p,y]),De(()=>y,[y]),(a?o:void 0)??t??f}function p4(){return typeof navigator>"u"?{userAgent:"",platform:"",maxTouchPoints:0}:{userAgent:navigator.userAgent,platform:navigator.platform??"",maxTouchPoints:navigator.maxTouchPoints??0}}const{userAgent:m4,platform:h4,maxTouchPoints:g4}=p4(),Lm=m4.toLowerCase(),qd=h4.toLowerCase(),Gd=/^i(os$|p)/.test(qd)||qd==="macintel"&&g4>1,qC="android",zm=qd===qC||Lm.includes(qC),GC=!Gd&&qd.startsWith("mac");qd.startsWith("win");const x4=GC||Gd,yl=typeof CSS<"u"&&!!CSS.supports?.("-webkit-backdrop-filter:none"),KC=!yl&&Lm.includes("firefox");!yl&&Lm.includes("chrom");const b4=x4,Pv=/jsdom|happydom/.test(Lm);function or(e){let t=e.activeElement;for(;t?.shadowRoot?.activeElement!=null;)t=t.shadowRoot.activeElement;return t}function Qe(e,t){if(!e||!t)return!1;const a=t.getRootNode?.();if(e.contains(t))return!0;if(a&&Bc(a)){let o=t;for(;o;){if(e===o)return!0;o=o.parentNode||o.host}}return!1}function is(e){return"composedPath"in e?e.composedPath()[0]??e.target:e.target}const _v="data-base-ui-focusable",YC="input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])",wi="ArrowLeft",Si="ArrowRight",Lv="ArrowUp",Bm="ArrowDown",XC="data-starting-style",v4="data-ending-style",y4={[XC]:""},j4={[v4]:""},oo={transitionStatus(e){return e==="starting"?y4:e==="ending"?j4:null}},w4="data-open",S4="data-closed",N4="data-anchor-hidden",QC="data-popup-open",k4="data-pressed",C4={[QC]:""},T4={[QC]:"",[k4]:""},E4={[w4]:""},A4={[S4]:""},R4={[N4]:""},zv={open(e){return e?C4:null}},Bv={open(e){return e?T4:null}},$c={open(e){return e?E4:A4},anchorHidden(e){return e?R4:null}},Hv={...$c,...oo},Uv="data-trigger-disabled";function Hm(e,t){if(!At(e))return!1;const a=e;if(t.hasElement(a))return!a.hasAttribute(Uv);for(const[,o]of t.entries())if(Qe(o,a))return!o.hasAttribute(Uv);return!1}function Vv(e,t){if(t==null)return!1;if("composedPath"in e)return e.composedPath().includes(t);const a=e;return a.target!=null&&t.contains(a.target)}function O4(e){return e.matches("html,body")}function Um(e){return dn(e)&&e.matches(YC)}function M4(e){return e?.closest(`button,a[href],[role="button"],select,[tabindex]:not([tabindex="-1"]),${YC}`)!=null}function Fv(e){return e?e.getAttribute("role")==="combobox"&&Um(e):!1}function D4(e){if(!e||Pv)return!0;try{return e.matches(":focus-visible")}catch{return!0}}function Vm(e){return e?e.hasAttribute(_v)?e:e.querySelector(`[${_v}]`)||e:null}function io(e,t,a=!0){return e.filter(c=>c.parentId===t).flatMap(c=>[...!a||c.context?.open?[c]:[],...io(e,c.id,a)])}function ZC(e,t){let a=[],o=e.find(c=>c.id===t)?.parentId;for(;o;){const c=e.find(d=>d.id===o);o=c?.parentId,c&&(a=a.concat(c))}return a}function Ns(e){e.preventDefault(),e.stopPropagation()}function I4(e){return"nativeEvent"in e}function Fm(e){return e.pointerType===""&&e.isTrusted?!0:zm&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function $v(e){return Pv?!1:!zm&&e.width===0&&e.height===0||zm&&e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"||e.width<1&&e.height<1&&e.pressure===0&&e.detail===0&&e.pointerType==="touch"}function co(e,t){const a=["mouse","pen"];return t||a.push("",void 0),a.includes(e)}function P4(e){const t=e.type;return t==="click"||t==="mousedown"||t==="keydown"||t==="keyup"}const qc=Math.min,jl=Math.max,$m=Math.round,Ni=Math.floor,wl=e=>({x:e,y:e}),_4={left:"right",right:"left",bottom:"top",top:"bottom"};function WC(e,t,a){return jl(e,qc(t,a))}function uo(e,t){return typeof e=="function"?e(t):e}function ta(e){return e.split("-")[0]}function Sl(e){return e.split("-")[1]}function qv(e){return e==="x"?"y":"x"}function Gv(e){return e==="y"?"height":"width"}function na(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function Kv(e){return qv(na(e))}function L4(e,t,a){a===void 0&&(a=!1);const o=Sl(e),c=Kv(e),d=Gv(c);let f=c==="x"?o===(a?"end":"start")?"right":"left":o==="start"?"bottom":"top";return t.reference[d]>t.floating[d]&&(f=qm(f)),[f,qm(f)]}function z4(e){const t=qm(e);return[Yv(e),t,Yv(t)]}function Yv(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const JC=["left","right"],e1=["right","left"],B4=["top","bottom"],H4=["bottom","top"];function U4(e,t,a){switch(e){case"top":case"bottom":return a?t?e1:JC:t?JC:e1;case"left":case"right":return t?B4:H4;default:return[]}}function V4(e,t,a,o){const c=Sl(e);let d=U4(ta(e),a==="start",o);return c&&(d=d.map(f=>f+"-"+c),t&&(d=d.concat(d.map(Yv)))),d}function qm(e){const t=ta(e);return _4[t]+e.slice(t.length)}function F4(e){var t,a,o,c;return{top:(t=e.top)!=null?t:0,right:(a=e.right)!=null?a:0,bottom:(o=e.bottom)!=null?o:0,left:(c=e.left)!=null?c:0}}function t1(e){return typeof e!="number"?F4(e):{top:e,right:e,bottom:e,left:e}}function Kd(e){const{x:t,y:a,width:o,height:c}=e;return{width:o,height:c,top:a,left:t,right:t+o,bottom:a+c,x:t,y:a}}function Gm(e,t,a){return Math.floor(e/t)!==a}function fo(e,t){return t<0||t>=e.length}function Km(e,t){return Ds(e.current,{disabledIndices:t})}function Xv(e,t){return Ds(e.current,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}function Ds(e,{startingIndex:t=-1,decrement:a=!1,disabledIndices:o,amount:c=1}={}){let d=t;do d+=a?-c:c;while(d>=0&&d<=e.length-1&&po(e,d,o));return d}function $4(e,{event:t,orientation:a,loopFocus:o,onLoop:c,rtl:d,cols:f,disabledIndices:p,minIndex:g,maxIndex:v,prevIndex:y,stopEvent:b=!1}){let j=y,w;if(t.key===Lv?w="up":t.key===Bm&&(w="down"),w){const S=[],N=[];let k=!1,E=0;{let _=null,L=-1;e.forEach((H,B)=>{if(H==null)return;E+=1;const z=H.closest('[role="row"]');z&&(k=!0),(z!==_||L===-1)&&(_=z,L+=1,S[L]=[]),S[L].push(B),N[B]=L})}let D=!1,C=0;if(k)for(const _ of S){const L=_.length;L>C&&(C=L),L!==f&&(D=!0)}const A=D&&E{if(!D||y===-1)return;const L=N[y];if(L==null)return;const H=S[L].indexOf(y),B=_==="up"?-1:1;for(let z=L+B,Q=0;Q=S.length){if(!o||A)return;if(z=z<0?S.length-1:0,c){const X=Math.min(H,S[z].length-1),q=S[z][X]??S[z][0],$=c(t,y,q);z=N[$]??z}}const K=S[z];for(let X=Math.min(H,K.length-1);X>=0;X-=1){const q=K[X];if(!po(e,q,p))return q}}},P=_=>{if(!A||y===-1)return;const L=y%R,H=_==="up"?-R:R,B=v-v%R,z=Ni(v/R)+1;for(let Q=y-L+H,K=0;Kv){if(!o)return;Q=Q<0?B:0}const X=Math.min(Q+R-1,v);for(let q=Math.min(Q+L,X);q>=Q;q-=1)if(!po(e,q,p))return q}};b&&Ns(t);const O=I(w)??P(w);if(O!==void 0)j=O;else if(y===-1)j=w==="up"?v:g;else if(j=Ds(e,{startingIndex:y,amount:R,decrement:w==="up",disabledIndices:p}),o){if(w==="up"&&(y-R_?H:H-R,c&&(j=c(t,y,j))}w==="down"&&y+R>v&&(j=Ds(e,{startingIndex:y%R-R,amount:R,disabledIndices:p}),c&&(j=c(t,y,j)))}fo(e,j)&&(j=y)}if(a==="both"){const S=Ni(y/f);t.key===(d?wi:Si)&&(b&&Ns(t),y%f!==f-1?(j=Ds(e,{startingIndex:y,disabledIndices:p}),o&&Gm(j,f,S)&&(j=Ds(e,{startingIndex:y-y%f-1,disabledIndices:p}),c&&(j=c(t,y,j)))):o&&(j=Ds(e,{startingIndex:y-y%f-1,disabledIndices:p}),c&&(j=c(t,y,j))),Gm(j,f,S)&&(j=y)),t.key===(d?Si:wi)&&(b&&Ns(t),y%f!==0?(j=Ds(e,{startingIndex:y,decrement:!0,disabledIndices:p}),o&&Gm(j,f,S)&&(j=Ds(e,{startingIndex:y+(f-y%f),decrement:!0,disabledIndices:p}),c&&(j=c(t,y,j)))):o&&(j=Ds(e,{startingIndex:y+(f-y%f),decrement:!0,disabledIndices:p}),c&&(j=c(t,y,j))),Gm(j,f,S)&&(j=y));const N=Ni(v/f)===S;fo(e,j)&&(o&&N?(j=t.key===(d?Si:wi)?v:Ds(e,{startingIndex:y-y%f-1,disabledIndices:p}),c&&(j=c(t,y,j))):j=y)}return j}function po(e,t,a){if(typeof a=="function"?a(t):a?.includes(t)??!1)return!0;const c=e[t];return c?!Ym(c)||c.matches(":disabled")?!0:!a&&(c.hasAttribute("disabled")||c.getAttribute("aria-disabled")==="true"):!1}function q4(e){return e.visibility==="hidden"||e.visibility==="collapse"}function Ym(e,t=e?xr(e):null){return!e||!e.isConnected||!t||q4(t)?!1:typeof e.checkVisibility=="function"?e.checkVisibility():t.display!=="none"&&t.display!=="contents"}const G4='a[href],button,input,select,textarea,summary,details,iframe,object,embed,[tabindex],[contenteditable]:not([contenteditable="false"]),audio[controls],video[controls]';function K4(e){const t=e.assignedSlot;if(t)return t;if(e.parentElement)return e.parentElement;const a=e.getRootNode();return Bc(a)?a.host:null}function Qv(e){for(const t of Array.from(e.children))if(Bs(t)==="summary")return t;return null}function Y4(e,t){const a=Qv(t);return!!a&&(e===a||Qe(a,e))}function n1(e){const t=e?Bs(e):"";return e!=null&&e.matches(G4)&&(t!=="summary"||e.parentElement!=null&&Bs(e.parentElement)==="details"&&Qv(e.parentElement)===e)&&(t!=="details"||Qv(e)==null)&&(t!=="input"||e.type!=="hidden")}function s1(e){if(!n1(e)||!e.isConnected||e.matches(":disabled"))return!1;for(let t=e;t;t=K4(t)){const a=t!==e,o=Bs(t)==="slot";if(t.hasAttribute("inert")||a&&Bs(t)==="details"&&!t.open&&!Y4(e,t)||t.hasAttribute("hidden")||!o&&!X4(t,a))return!1}return!0}function X4(e,t){const a=xr(e);return t?a.display!=="none":Ym(e,a)}function r1(e){const t=e.tabIndex;if(t<0){const a=Bs(e);if(a==="details"||a==="audio"||a==="video"||dn(e)&&e.isContentEditable)return 0}return t}function Zv(e){if(Bs(e)!=="input")return null;const t=e;return t.type==="radio"&&t.name!==""?t:null}function Q4(e,t){const a=Zv(e);if(!a)return!0;const o=t.find(c=>{const d=Zv(c);return d?.name===a.name&&d.form===a.form&&d.checked});return o?o===a:t.find(c=>{const d=Zv(c);return d?.name===a.name&&d.form===a.form})===a}function a1(e){if(dn(e)&&Bs(e)==="slot"){const t=e.assignedElements({flatten:!0});if(t.length>0)return t}return dn(e)&&e.shadowRoot?Array.from(e.shadowRoot.children):Array.from(e.children)}function l1(e,t){a1(e).forEach(a=>{n1(a)&&t.push(a),l1(a,t)})}function o1(e,t,a){a1(e).forEach(o=>{dn(o)&&o.matches(t)&&a.push(o),o1(o,t,a)})}function Wv(e){return s1(e)&&r1(e)>=0}function i1(e){const t=[];return l1(e,t),t.filter(s1)}function Yd(e){const t=i1(e);return t.filter(a=>r1(a)>=0&&Q4(a,t))}function c1(e,t){const a=Yd(e),o=a.length;if(o===0)return;const c=or($t(e)),d=a.indexOf(c),f=d===-1?t===1?0:o-1:d+t;return a[f]}function Jv(e){return c1($t(e).body,1)||e}function u1(e){return c1($t(e).body,-1)||e}function d1(e,t){if(!e)return null;const a=Yd($t(e).body),o=a.length;if(o===0)return null;const c=a.indexOf(e);if(c===-1)return null;const d=(c+t+o)%o;return a[d]}function Z4(e){return d1(e,1)}function W4(e){return d1(e,-1)}function Gc(e,t){const a=t||e.currentTarget,o=e.relatedTarget;return!o||!Qe(a,o)}function J4(e){Yd(e).forEach(a=>{a.dataset.tabindex=a.getAttribute("tabindex")||"",a.setAttribute("tabindex","-1")})}function f1(e){const t=[];o1(e,"[data-tabindex]",t),t.forEach(a=>{const o=a.dataset.tabindex;delete a.dataset.tabindex,o?a.setAttribute("tabindex",o):a.removeAttribute("tabindex")})}function ey(e){x.useEffect(e,Rr)}const Xd=0;class sa{constructor(){ln(this,"currentId",Xd);ln(this,"clear",()=>{this.currentId!==Xd&&(clearTimeout(this.currentId),this.currentId=Xd)});ln(this,"disposeEffect",()=>this.clear)}static create(){return new sa}start(t,a){this.clear(),this.currentId=setTimeout(()=>{this.currentId=Xd,a()},t)}isStarted(){return this.currentId!==Xd}}function Qs(){const e=Ms(sa.create).current;return ey(e.disposeEffect),e}function eB(e,t){return e.matches(":disabled")?!1:!t||e.form===t?!0:e.form===null&&!e.hasAttribute("form")}const tB=x.createContext({disabled:!1});function p1(){return x.useContext(tB)}var ty={exports:{}},Hs={};var m1;function nB(){if(m1)return Hs;m1=1;var e=Hd();function t(y){var b="https://react.dev/errors/"+y;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),ty.exports=nB(),ty.exports}var ks=g1();const Xm=null;class sB{constructor(){ln(this,"callbacks",[]);ln(this,"callbacksCount",0);ln(this,"nextId",1);ln(this,"startId",1);ln(this,"isScheduled",!1);ln(this,"tick",t=>{this.isScheduled=!1;const a=this.callbacks,o=this.callbacksCount;if(this.callbacks=[],this.callbacksCount=0,this.startId=this.nextId,o>0)for(let c=0;c=this.callbacks.length||this.callbacks[a]!==null&&(this.callbacks[a]=null,this.callbacksCount-=1)}}let Qm=new sB;class $a{constructor(){ln(this,"currentId",Xm);ln(this,"cancel",()=>{this.currentId!==Xm&&(Qm.cancel(this.currentId),this.currentId=Xm)});ln(this,"disposeEffect",()=>this.cancel)}static create(){return new $a}static request(t){return Qm.request(t)}static cancel(t){return Qm.cancel(t)}request(t){this.cancel(),this.currentId=Qm.request(()=>{this.currentId=Xm,t()})}}function Kc(){const e=Ms($a.create).current;return ey(e.disposeEffect),e}function Nl(e){return e==null?e:"current"in e?e.current:e}let Zm=null;function rB(e){if(!Zm){const t=[];Zm=t,queueMicrotask(()=>{Zm=null,ks.flushSync(()=>{for(const a of t)a()})})}Zm.push(e)}function x1(e,t=!1,a=!1){const o=Kc();return Ie((c,d=null)=>{o.cancel();const f=Nl(e);if(f==null)return;const p=f,g=()=>{if(!a){ks.flushSync(c);return}rB(()=>{d?.aborted||c()})};if(typeof p.getAnimations!="function"||globalThis.BASE_UI_ANIMATIONS_DISABLED){c();return}function v(){Promise.all(p.getAnimations().map(y=>y.finished)).then(()=>{d?.aborted||g()},()=>{if(d?.aborted)return;if(p.getAnimations().some(b=>b.pending||b.playState!=="finished")){v();return}g()})}if(t){const y=XC;if(!p.hasAttribute(y)){o.request(v);return}const b=new MutationObserver(()=>{p.hasAttribute(y)||(b.disconnect(),v())});b.observe(p,{attributes:!0,attributeFilter:[y]}),d?.addEventListener("abort",()=>b.disconnect(),{once:!0});return}o.request(v)})}function ra(e){const{enabled:t=!0,open:a,ref:o,batch:c=!1,onComplete:d}=e,f=Ie(d),p=x1(o,a,c);x.useEffect(()=>{if(!t)return;const g=new AbortController;return p(f,g.signal),()=>{g.abort()}},[t,a,f,p])}function ki(e,t=!1,a=!1,o=!1){const[c,d]=x.useState(e&&t?"idle":void 0),[f,p]=x.useState(e&&!o);return e&&!f&&(p(!0),d("starting")),!e&&f&&c!=="ending"&&!a&&d("ending"),!e&&!f&&c==="ending"&&d(void 0),De(()=>{if(!e&&f&&c!=="ending"&&a){const g=$a.request(()=>{d("ending")});return()=>{$a.cancel(g)}}},[e,f,c,a]),De(()=>{if(!e||t)return;const g=$a.request(()=>{d(void 0)});return()=>{$a.cancel(g)}},[t,e]),De(()=>{if(!e||!t)return;e&&f&&c!=="idle"&&d("starting");const g=$a.request(()=>{d("idle")});return()=>{$a.cancel(g)}},[t,e,f,c]),{mounted:f,setMounted:p,transitionStatus:c}}function qa({controlled:e,default:t,name:a,state:o="value"}){const{current:c}=x.useRef(e!==void 0),[d,f]=x.useState(t),p=c&&e!==void 0?e:d,g=x.useCallback(v=>{c||f(v)},[]);return[p,g]}function Yc(e,t,a,o,c=!0,d){const{registerFieldControl:f}=Sa(),p=Ms(()=>Symbol());De(()=>{const g=p.current;if(!c){f(g,void 0);return}f(g,{controlRef:e,getValue:o,id:t,name:d,value:a})},[e,c,o,t,d,f,p,a]),De(()=>{const g=p.current;return()=>{f(g,void 0)}},[f,p])}function aa(e,t){const a=x.useRef(e),o=Ie(t);De(()=>{a.current!==e&&o(a.current),a.current=e},[e,o])}const Yn="none",mo="trigger-press",Us="trigger-hover",Wm="trigger-focus",Jm="outside-press",Qd="item-press",ny="close-press",Zd="input-change",Ga="input-clear",aB="input-press",ho="focus-out",Xc="escape-key",sy="list-navigation",b1="keyboard",v1="pointer",y1="cancel-open",lB="disabled",ry="imperative-action",oB="window-resize";function Fe(e,t,a,o){let c=!1,d=!1;const f=o??fn;return{reason:e,event:t??new Event("base-ui"),cancel(){c=!0},allowPropagation(){d=!0},get isCanceled(){return c},get isPropagationAllowed(){return d},trigger:a,...f}}function iB(e,t,a){const o=a??fn;return{reason:e,event:t??new Event("base-ui"),...o}}const cB=x.forwardRef(function(t,a){const{render:o,className:c,id:d,name:f,value:p,disabled:g=!1,onValueChange:v,defaultValue:y,autoFocus:b=!1,style:j,...w}=t,{state:S,name:N,disabled:k,setTouched:E,setDirty:D,validityData:C,setFocused:A,setFilled:R,validationMode:I,validation:P}=Sa(),{clearErrors:O,elementRef:_,submitCountRef:L}=Fc(),H=k||g,B=N??f,z={...S,disabled:H},{labelId:Q}=vl(),K=lo({id:d}),[X]=qa({controlled:p,default:y,name:"FieldControl",state:"value"}),q=p!==void 0,$=q?X:void 0,Y=$==null?void 0:String($),F=Ie(()=>P.inputRef.current?.value);Yc(P.inputRef,K,Y,F,!H,f),De(()=>{const M=Y??P.inputRef.current?.value;M!==void 0&&R(M!=="")},[Y,P.inputRef,R]),aa(Y,()=>{Y!==void 0&&(O(B),D(Y!==(C.initialValue??"")),P.change(Y))});const G=x.useRef(null),W=Qs();return De(()=>{b&&G.current===or($t(G.current))&&A(!0)},[b,A]),vt("input",t,{ref:[a,G],state:z,props:[{id:K,disabled:H,name:B,ref:P.inputRef,"aria-labelledby":Q,autoFocus:b,...q?{value:$}:{defaultValue:y},onChange(M){const U=M.currentTarget.value,Z=Fe(Yn,M.nativeEvent);v?.(U,Z),!q&&(D(U!==(C.initialValue??"")),R(U!==""),!M.nativeEvent.defaultPrevented&&!Z.isCanceled&&(O(B),P.change(U)))},onFocus(){A(!0)},onBlur(M){if(E(!0),A(!1),I==="onBlur"){const U=M.currentTarget.value;P.commit(U),q&&queueMicrotask(()=>{const Z=P.inputRef.current?.value;Z!==void 0&&Z!==U&&Z!==(C.initialValue??"")&&P.commit(Z)})}},onKeyDown(M){if(M.currentTarget.tagName==="INPUT"&&M.key==="Enter"){E(!0);const U=M.currentTarget.value,Z=M.currentTarget.form;if(Z&&Z===_.current&&!M.defaultPrevented){const ae=M.currentTarget,ce=L.current;W.start(0,()=>{L.current===ce&&P.commit(ae.value)})}else P.commit(U)}}},w,M=>P.getValidationProps(H,M)],stateAttributesMapping:ji})}),uB=x.forwardRef(function(t,a){return s.jsx(cB,{ref:a,...t})});function $e({className:e,type:t,ref:a,...o}){return s.jsx(uB,{ref:a,type:t,"data-slot":"input",className:Ue("h-[30px] w-full min-w-0 rounded-md border border-control-border bg-control px-2.5","text-[12.5px] text-foreground outline-none","transition-[border-color,box-shadow] duration-150 ease-out","placeholder:text-muted-foreground","hover:border-control-border-hover","focus:border-primary focus:shadow-focus","disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-surface-3 disabled:text-muted-foreground","file:inline-flex file:border-0 file:bg-transparent file:text-foreground",e),...o})}function Qc({className:e,...t}){return s.jsx("textarea",{"data-slot":"textarea",className:Ue("min-h-26 w-full resize-y rounded-md border border-control-border bg-control px-3 py-2.5","font-mono text-[12px] leading-[1.6] text-foreground outline-none","transition-[border-color,box-shadow] duration-150 ease-out","placeholder:text-muted-foreground","hover:border-control-border-hover","focus:border-primary focus:shadow-focus","disabled:cursor-not-allowed disabled:bg-surface-3 disabled:text-muted-foreground",e),...t})}function Ci({className:e,...t}){return s.jsx("div",{"data-slot":"input-group",role:"group",className:Ue("group/input-group relative flex h-[30px] w-full min-w-0 items-center rounded-md border border-control-border bg-control","transition-[border-color,box-shadow] duration-150 ease-out","outline-none","has-[[data-slot=input-group-control]:focus-visible]:border-primary","has-[[data-slot=input-group-control]:focus-visible]:shadow-focus","has-[[data-slot=input-group-control]:hover:not(:focus-visible)]:border-control-border-hover","has-[>textarea]:h-auto","has-[>[data-align=inline-start]]:[&>[data-slot=input-group-control]]:pl-1.5","has-[>[data-align=inline-end]]:[&>[data-slot=input-group-control]]:pr-1.5","has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col","has-[>[data-align=block-start]]:[&>[data-slot=input-group-control]]:pb-1.5","has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col","has-[>[data-align=block-end]]:[&>[data-slot=input-group-control]]:pt-1.5",e),...t})}const dB=Vc(["flex h-auto cursor-text items-center justify-center gap-1.5 select-none","text-[12px] font-medium text-muted-foreground","group-data-[disabled=true]/input-group:opacity-50"],{variants:{align:{"inline-start":"order-first pl-[9px] has-[>button]:-ml-1","inline-end":"order-last pr-[9px] has-[>button]:-mr-1","block-start":"order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-1.5","block-end":"order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-1.5"}},defaultVariants:{align:"inline-start"}});function Ti({className:e,align:t="inline-start",...a}){return s.jsx("div",{role:"group","data-slot":"input-group-addon","data-align":t,className:Ue(dB({align:t}),e),onClick:o=>{o.target.closest("button")||o.currentTarget.parentElement?.querySelector("input")?.focus()},...a})}const fB=Vc("flex items-center shadow-none",{variants:{size:{xs:"h-6 gap-1 rounded-xs px-1.5",sm:"h-8 gap-1.5 rounded-sm px-2.5","icon-xs":"size-6 rounded-xs p-0","icon-sm":"size-8 rounded-sm p-0"}},defaultVariants:{size:"xs"}});function pB({className:e,type:t="button",variant:a="ghost",size:o="xs",...c}){return s.jsx(se,{type:t,"data-size":o,variant:a,className:Ue(fB({size:o}),e),...c})}function Ei({className:e,...t}){return s.jsx($e,{"data-slot":"input-group-control",className:Ue("flex-1 rounded-none border-0 bg-transparent shadow-none focus:border-0 focus:shadow-none",e),...t})}function mB(e){return vt(e.defaultTagName??"div",e,e)}const hB=Vc("inline-flex w-fit shrink-0 items-center justify-center gap-[5px] overflow-hidden whitespace-nowrap border font-semibold",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground",secondary:"border-transparent bg-secondary text-secondary-foreground",destructive:"border-destructive-bd bg-destructive-soft text-destructive",outline:"border-control-border bg-control text-subtle",ghost:"border-transparent bg-transparent text-muted-foreground",link:"border-transparent bg-transparent text-primary underline-offset-4 hover:underline",success:"border-success-bd bg-success-soft text-success",warning:"border-warning-bd bg-warning-soft text-warning",info:"border-info-bd bg-info-soft text-info",brand:"border-primary-bd bg-primary-soft text-primary-fg",cn:"border-cn-bd bg-cn-soft text-cn",intl:"border-intl-bd bg-intl-soft text-intl",sensitive:"border-sensitive-bd bg-sensitive-soft text-sensitive"},shape:{pill:"min-h-[21px] rounded-pill px-[9px] py-px text-[11.5px]",tag:"min-h-[19px] rounded-xs px-2 py-0 text-[11px]"}},defaultVariants:{variant:"default",shape:"pill"}});function ze({className:e,variant:t,shape:a,render:o,...c}){return mB({render:o,defaultTagName:"span",props:Wr({"data-slot":"badge"},c,{className:Ue(hB({variant:t,shape:a}),e)})})}function ay({className:e,...t}){return s.jsx("span",{className:Ue("size-1.5 flex-none rounded-full bg-current",e),...t})}function go(e,t){if(typeof window>"u")return e;const a=window.wbI18n;return a?a.t(e,t)??e:e}function Wd({className:e,...t}){return s.jsx("svg",{"data-slot":"spinner",role:"status","aria-label":go("加载中"),viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",className:Ue("size-4 animate-spin [animation-duration:0.7s]",e),...t,children:s.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})}function Je({className:e,...t}){return s.jsx("label",{"data-slot":"label",className:Ue("flex items-center gap-[6px] text-[11.5px] text-muted-foreground",e),...t})}const j1={clipPath:"inset(50%)",overflow:"hidden",whiteSpace:"nowrap",border:0,padding:0,width:1,height:1,margin:-1},Ai={...j1,position:"fixed",top:0,left:0},Zc={...j1,position:"absolute"},w1=x.createContext(void 0);function gB(){const e=x.useContext(w1);if(e===void 0)throw new Error(on(63));return e}const xB="data-checked",bB="data-unchecked",S1={...ji,checked(e){return e?{[xB]:""}:{[bB]:""}}},vB=x.forwardRef(function(t,a){const{checked:o,className:c,defaultChecked:d,"aria-labelledby":f,form:p,id:g,inputRef:v,name:y,nativeButton:b=!1,onCheckedChange:j,readOnly:w=!1,required:S=!1,disabled:N=!1,render:k,uncheckedValue:E,value:D,style:C,...A}=t,{clearErrors:R}=Fc(),{state:I,setTouched:P,setDirty:O,validityData:_,setFilled:L,setFocused:H,validationMode:B,disabled:z,name:Q,validation:K}=Sa(),{labelId:X}=vl(),q=z||N,$=Q??y,Y=x.useRef(null),F=ea(Y,v,K.inputRef),G=x.useRef(null),W=Na(),le=lo({id:g}),M=b?void 0:le,[U,Z]=qa({controlled:o,default:!!d,name:"Switch",state:"checked"});Yc(G,W,U,void 0,!q,y),De(()=>{L(U)},[U,L]),aa(U,()=>{R($),O(U!==_.initialValue),K.change(U)});const{getButtonProps:ae,buttonRef:ce}=Jr({disabled:q,native:b}),J=Iv(f,X,Y,!b,M),ie={id:b?le:W,role:"switch","aria-checked":U,"aria-readonly":w||void 0,"aria-required":S||void 0,"aria-labelledby":J,onFocus(){q||H(!0)},onBlur(){const te=Y.current;!te||q||(P(!0),H(!1),B==="onBlur"&&K.commit(te.checked))},onClick(te){if(w||q)return;te.preventDefault();const Ce=Y.current;Ce&&Uc(Ce,te)}},ge={...K.getValidationProps(q),checked:U,disabled:q,form:p,id:M,name:$,required:S,style:$?Zc:Ai,tabIndex:-1,type:"checkbox","aria-hidden":!0,ref:F,onChange(te){if(te.nativeEvent.defaultPrevented)return;if(w){te.preventDefault();return}const Ce=te.currentTarget.checked,re=Fe(Yn,te.nativeEvent);j?.(Ce,re),!re.isCanceled&&Z(Ce)},onClick(te){te.stopPropagation()},onFocus(){G.current?.focus()},...D!==void 0?{value:D}:fn},ee=x.useMemo(()=>({...I,checked:U,disabled:q,readOnly:w,required:S}),[I,U,q,w,S]),fe=vt("span",t,{state:ee,ref:[a,G,ce],props:[ie,A,ae,te=>K.getValidationProps(q,te)],stateAttributesMapping:S1});return s.jsxs(w1.Provider,{value:ee,children:[fe,!U&&$&&E!==void 0&&s.jsx("input",{type:"hidden",form:p,name:$,value:E,disabled:q}),s.jsx("input",{...ge,suppressHydrationWarning:!0})]})}),yB=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t,p=gB();return vt("span",t,{state:p,ref:a,stateAttributesMapping:S1,props:f})});function ms({className:e,size:t="default",...a}){const o=t==="sm";return s.jsx(vB,{"data-slot":"switch",className:Ue("relative inline-flex flex-none cursor-pointer items-center rounded-pill border-0 bg-border-strong p-0","transition-colors duration-[180ms] ease-out","data-checked:bg-primary","focus-visible:shadow-focus focus-visible:outline-none","data-disabled:cursor-not-allowed data-disabled:opacity-50",o?"h-[14px] w-6":"h-[21px] w-9",e),...a,children:s.jsx(yB,{"data-slot":"switch-thumb",className:Ue("block rounded-full bg-primary-on shadow-1","transition-transform duration-[180ms] [transition-timing-function:cubic-bezier(.3,1.4,.6,1)]",o?"size-[10px] translate-x-0.5 data-checked:translate-x-[10px]":"size-[17px] translate-x-0.5 data-checked:translate-x-[15px]")})})}function jB(e){if(!e)return null;for(const t of e.elements){const a=t.tagName;if(a==="BUTTON"||a==="INPUT"){const o=t;if(o.type==="submit")return o}}return null}const wB="data-checked",SB="data-unchecked";function N1(e){return{checked(t){return e.indeterminate?{}:t?{[wB]:""}:{[SB]:""}},...ji}}const NB=x.createContext(void 0);function kB(){return x.useContext(NB)}const k1=x.createContext(void 0);function CB(){const e=x.useContext(k1);if(e===void 0)throw new Error(on(14));return e}const TB="data-parent",EB=x.forwardRef(function(t,a){const{checked:o,className:c,defaultChecked:d=!1,"aria-labelledby":f,disabled:p=!1,form:g,id:v,indeterminate:y=!1,inputRef:b,name:j,onCheckedChange:w,parent:S=!1,readOnly:N=!1,render:k,required:E=!1,uncheckedValue:D,value:C,nativeButton:A=!1,style:R,...I}=t,{clearErrors:P}=Fc(),{disabled:O,name:_,setDirty:L,setFilled:H,setFocused:B,setTouched:z,state:Q,validationMode:K,validityData:X,validation:q}=Sa(),$=p1(),{labelId:Y,registerControlId:F,getDescriptionProps:G}=vl(),W=kB(),le=W?.allValues===void 0?void 0:W.parent,M=le!==void 0,U=O||$.disabled||W?.disabled||p,Z=_??j,ae=C??Z,ce=Na(),J=W?.registerControlId!==F,ie=lo({id:v||void 0,enabled:J}),ge=A?ie:ce;let ee={};M&&(S?ee=le.getParentProps():ae!==void 0&&(ee=le.getChildProps(ae)));const{checked:fe=o,indeterminate:te=y,onCheckedChange:Ce,...re}=ee,de=W?.value,ke=x.useRef(null),{getButtonProps:Ee,buttonRef:ve}=Jr({disabled:U,native:A}),he=W?.validation??q,[ye,we]=qa({controlled:ae!==void 0&&de!==void 0&&!S?de.includes(ae):fe,default:d,name:"Checkbox",state:"checked"}),xe=M?!!fe:ye,Te=M&&te||y;Yc(ke,ce,ye,void 0,!W&&!U,j);const Oe=le?.registerChildId,Ne=x.useRef(null),_e=he.registerInput,Ye=W?ae:void 0,kt=x.useCallback(it=>_e(it,{controlRef:ke,value:Ye}),[_e,Ye]),Ct=ea(b,Ne,S?void 0:kt),Rt=Iv(f,Y,Ne,!A,ie);De(()=>{Ne.current&&(Ne.current.indeterminate=Te),W||H(ye)},[ye,Te,W,H]),aa(ye,()=>{W||(P(Z),L(ye!==X.initialValue),he.change(ye))});const ot=Wr({checked:ye,disabled:U,form:g,name:S?void 0:Z,id:A?void 0:ie,required:E,ref:Ct,style:Z?Zc:Ai,tabIndex:-1,type:"checkbox","aria-hidden":!0,onChange(it){if(it.nativeEvent.defaultPrevented)return;if(N){it.preventDefault();return}const Vt=it.currentTarget.checked,Bn=Fe(Yn,it.nativeEvent);if(w?.(Vt,Bn),!Bn.isCanceled&&(Ce?.(Vt,Bn),!Bn.isCanceled&&(we(Vt),ae!==void 0&&W!==void 0&&!S&&!M))){const tn=Vt?[...W.value,ae]:W.value.filter(nt=>nt!==ae);W.setValue(tn,Bn)}},onClick(it){it.stopPropagation()},onFocus(){ke.current?.focus()}},C!==void 0?{value:(W?ye&&C:C)||""}:fn,G,it=>he.getValidationProps(U,it));x.useEffect(()=>{if(!le||ae===void 0)return;const it=le.disabledStatesRef.current;return it.set(ae,U),()=>{it.delete(ae)}},[le,U,ae]);const qn=x.useMemo(()=>({...Q,checked:xe,disabled:U,readOnly:N,required:E,indeterminate:Te}),[Q,xe,U,N,E,Te]),ds=N1(qn),Gn=vt("span",t,{state:qn,ref:[ve,ke,a],props:[{id:ge,role:"checkbox","aria-checked":Te?"mixed":xe,"aria-readonly":N||void 0,"aria-required":E||void 0,"aria-labelledby":Rt,[TB]:S?"":void 0,onFocus(){U||B(!0)},onBlur(){const it=Ne.current;it&&(z(!0),B(!1),K==="onBlur"&&he.commit(W?de:it.checked))},onKeyDown(it){if(it.key!=="Enter"||(it.preventBaseUIHandler(),it.defaultPrevented))return;const Vt=Ne.current?.form??null,Bn=it.currentTarget,tn=it.nativeEvent,nt=it.preventDefault,Ot=tn.preventDefault;let Ft=!1;it.preventDefault=()=>{Ft=!0,nt.call(it)},tn.preventDefault=()=>{Ft=!0,Ot.call(tn)},Ot.call(tn),Sn(Bn).queueMicrotask(()=>{it.preventDefault=nt,tn.preventDefault=Ot,Ft||jB(Vt)?.click()})},onClick(it){if(N||U)return;it.preventDefault();const Vt=Ne.current;Vt&&Uc(Vt,it)}},I,re,Ee,G,it=>he.getValidationProps(U,it)],stateAttributesMapping:ds}),xs=Gn.props.id;return De(()=>{if(!(!Oe||S||ae===void 0||xs===void 0))return Oe(ae,xs)},[Oe,S,ae,xs]),s.jsxs(k1.Provider,{value:qn,children:[Gn,!ye&&!W&&Z&&!S&&D!==void 0&&s.jsx("input",{type:"hidden",form:g,name:Z,value:D,disabled:U}),s.jsx("input",{...ot,suppressHydrationWarning:!0})]})}),AB=x.forwardRef(function(t,a){const{render:o,className:c,style:d,keepMounted:f=!1,...p}=t,g=CB(),v=g.checked||g.indeterminate,{mounted:y,transitionStatus:b,setMounted:j}=ki(v),w=x.useRef(null),S={...g,transitionStatus:b};ra({batch:!0,enabled:!v,open:v,ref:w,onComplete(){v||j(!1)}});const k={...N1(g),...oo},E=f||y,D=vt("span",t,{ref:[a,w],state:S,stateAttributesMapping:k,props:p});return E?D:null});function Or({className:e,...t}){return s.jsx(EB,{"data-slot":"checkbox",className:Ue("group/checkbox relative inline-flex size-3.5 shrink-0 cursor-pointer items-center justify-center rounded-[3px] border border-control-border bg-control","outline-none transition-colors duration-150 ease-out","hover:border-control-border-hover","data-checked:border-primary data-checked:bg-primary","focus-visible:shadow-focus","data-disabled:cursor-not-allowed data-disabled:opacity-45",e),...t,children:s.jsx(AB,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-primary-foreground data-unchecked:hidden",children:s.jsxs("svg",{viewBox:"0 0 12 12",className:"size-2.5","aria-hidden":"true",children:[s.jsx("path",{d:"M2 6h8",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",fill:"none",className:"hidden group-aria-[checked=indeterminate]/checkbox:block"}),s.jsx("path",{d:"M2.5 6.2 4.8 8.5 9.5 3.8",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",fill:"none",className:"group-aria-[checked=indeterminate]/checkbox:hidden"})]})})})}function ly(e){return Array.isArray(e)?e.map(t=>ly(t)).join(","):e==null?"":String(e)}const C1=new Map;function RB(e,t){const a=JSON.stringify({locale:ly(e),options:t}),o=C1.get(a);if(o)return o;const c=new Intl.NumberFormat(e,t);return C1.set(a,c),c}function T1(e,t,a){return e==null?"":RB(t,a).format(e)}function Ri(e,t=Number.MIN_SAFE_INTEGER,a=Number.MAX_SAFE_INTEGER){return Math.max(t,Math.min(e,a))}function OB(e,t,a){return(e-t)*100/(a-t)}const E1=x.createContext(void 0);function A1(){const e=x.useContext(E1);if(e===void 0)throw new Error(on(51));return e}const MB="data-complete",DB="data-indeterminate",IB="data-progressing",oy={status(e){return e==="progressing"?{[IB]:""}:e==="complete"?{[MB]:""}:e==="indeterminate"?{[DB]:""}:null}},PB=x.forwardRef(function(t,a){const{format:o,getAriaValueText:c,locale:d,max:f=100,min:p=0,value:g,render:v,className:y,children:b,style:j,...w}=t,[S,N]=x.useState();let k="indeterminate",E=null,D=null,C="",A="indeterminate progress";if(g!=null&&Number.isFinite(g)){const _=OB(g,p,f);E=Ri(Number.isNaN(_)?0:_,0,100),D=Ri(g,p,f),k=D===f?"complete":"progressing",C=o?T1(D,d,o):T1(E/100,d,{style:"percent"}),A=C}const R=x.useMemo(()=>({status:k}),[k]),I={"aria-labelledby":S,"aria-valuemax":f,"aria-valuemin":p,"aria-valuenow":D??void 0,"aria-valuetext":c?c(C,g):A,role:"progressbar",children:s.jsxs(x.Fragment,{children:[b,s.jsx("span",{role:"presentation",style:Ai,children:"x"})]})},P=x.useMemo(()=>({formattedValue:C,percentageValue:E,setLabelId:N,state:R,value:g}),[C,E,N,R,g]),O=vt("div",t,{state:R,ref:a,props:[I,w],stateAttributesMapping:oy});return s.jsx(E1.Provider,{value:P,children:O})}),_B=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t,{state:p}=A1();return vt("div",t,{state:p,ref:a,props:f,stateAttributesMapping:oy})}),LB=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t,{percentageValue:p,state:g}=A1(),v=p==null?{}:{insetInlineStart:0,height:"inherit",width:`${p}%`};return vt("div",t,{state:g,ref:a,props:[{style:v},f],stateAttributesMapping:oy})});function Jd({className:e,children:t,value:a,...o}){return s.jsxs(PB,{value:a,"data-slot":"progress",className:Ue("flex w-full flex-wrap items-center gap-3",e),...o,children:[t,s.jsx(zB,{children:s.jsx(BB,{})})]})}function zB({className:e,...t}){return s.jsx(_B,{"data-slot":"progress-track",className:Ue("relative flex h-1.5 w-full items-center overflow-x-hidden overflow-y-hidden rounded-pill bg-surface-3",e),...t})}function BB({className:e,...t}){return s.jsx(LB,{"data-slot":"progress-indicator",className:Ue("h-full rounded-[inherit] bg-primary transition-[width] duration-300 ease-out",e),...t})}const iy=[];let cy;function HB(){return cy}function UB(e){iy.push(e)}function eh(e){const t=(a,o)=>{const c=Ms(VB).current;let d;try{cy=c;for(const f of iy)f.before(c);d=e(a,o);for(const f of iy)f.after(c);c.didInitialize=!0}finally{cy=void 0}return d};return t.displayName=e.displayName||e.name,t}function R1(e){return x.forwardRef(eh(e))}function VB(){return{didInitialize:!1}}const O1=x.createContext(void 0);function ef(e){const t=x.useContext(O1);if(t===void 0&&!e)throw new Error(on(72));return t}function FB(e,t){return t!=null&&!co(t)?0:typeof e=="function"?e():e}function Oi(e,t,a){const o=FB(e,a);return typeof o=="number"?o:o?.[t]}function M1(e){return typeof e=="function"?e():e}function D1(e,t){return t||e==="click"||e==="mousedown"}function $B(e){return e?.includes("mouse")&&e!=="mousedown"}const I1=x.createContext({hasProvider:!1,timeoutMs:0,delayRef:{current:0},initialDelayRef:{current:0},timeout:new sa,currentIdRef:{current:null},currentContextRef:{current:null}});function qB(e,t){e.current=t.current}function GB(e){const{children:t,delay:a,timeoutMs:o=0}=e,c=x.useRef(a),d=x.useRef(a),f=x.useRef(null),p=x.useRef(null),g=Qs();return De(()=>{if(d.current=a,!f.current){c.current=a;return}c.current={open:Oi(c.current,"open"),close:Oi(a,"close")}},[a,f,c,d]),s.jsx(I1.Provider,{value:x.useMemo(()=>({hasProvider:!0,delayRef:c,initialDelayRef:d,currentIdRef:f,timeoutMs:o,currentContextRef:p,timeout:g}),[o,g]),children:t})}function KB(e,t={open:!1}){const{open:a}=t,o="rootStore"in e?e.rootStore:e,c=o.useState("floatingId"),d=x.useContext(I1),{currentIdRef:f,delayRef:p,timeoutMs:g,initialDelayRef:v,currentContextRef:y,hasProvider:b,timeout:j}=d,[w,S]=x.useState(!1),N=x.useRef(a);return De(()=>{N.current=a},[a]),De(()=>{function k(){y.current?.setIsInstantPhase(!1),f.current=null,y.current=null,p.current=v.current,j.clear()}if(f.current&&!a&&f.current===c){if(S(!1),g){const E=c;return j.start(g,()=>{o.select("open")||f.current&&f.current!==E||k()}),()=>{(N.current||f.current!==E)&&j.clear()}}k()}},[a,c,f,p,g,v,y,j,o]),De(()=>{if(!a)return;const k=y.current,E=f.current;j.clear(),y.current={onOpenChange:o.setOpen,setIsInstantPhase:S},f.current=c,p.current={open:0,close:Oi(v.current,"close")},E!==null&&E!==c?(S(!0),k?.setIsInstantPhase(!0),k?.onOpenChange(!1,Fe(Yn))):(S(!1),k?.setIsInstantPhase(!1))},[a,c,o,f,p,v,y,j]),De(()=>()=>{if(f.current===c){if(y.current=null,!N.current)return;f.current=null,qB(p,v),j.clear()}},[y,f,p,c,v,j]),x.useMemo(()=>({activeIdRef:f,hasProvider:b,delayRef:p,isInstantPhase:w}),[f,b,p,w])}function St(e,t,a,o){return e.addEventListener(t,a,o),()=>{e.removeEventListener(t,a,o)}}function Ka(...e){return()=>{for(let t=0;t{t.current=t.next}};return t}const Wc=x.forwardRef(function(t,a){const[o,c]=x.useState();De(()=>{b4&&yl&&c("button")},[]);const d={tabIndex:0,role:o};return s.jsx("span",{...t,ref:a,style:Ai,"aria-hidden":o?void 0:!0,...d,"data-base-ui-focus-guard":""})});function tf(e){return`data-base-ui-${e}`}let th=0;function nh(e,t={}){const{preventScroll:a=!1,sync:o=!1,shouldFocus:c}=t;cancelAnimationFrame(th);function d(){c&&!c()||e?.focus({preventScroll:a})}if(o)return d(),qt;const f=requestAnimationFrame(d);return th=f,()=>{th===f&&(cancelAnimationFrame(f),th=0)}}const uy={inert:new WeakMap,"aria-hidden":new WeakMap},P1="data-base-ui-inert",dy={inert:new WeakSet,"aria-hidden":new WeakSet};let nf=new WeakMap,fy=0;function XB(e){return dy[e]}function _1(e){return e?Bc(e)?e.host:_1(e.parentNode):null}const L1=(e,t)=>t.map(a=>{if(e.contains(a))return a;const o=_1(a);return e.contains(o)?o:null}).filter(a=>a!=null),z1=e=>{const t=new Set;return e.forEach(a=>{let o=a;for(;o&&!t.has(o);)t.add(o),o=o.parentNode}),t},B1=(e,t,a)=>{const o=[],c=d=>{!d||a.has(d)||Array.from(d.children).forEach(f=>{Bs(f)!=="script"&&(t.has(f)?c(f):o.push(f))})};return c(e),o};function QB(e,t,a,o,{mark:c=!0}){let d=null;o?d="inert":a&&(d="aria-hidden");let f=null,p=null;const g=L1(t,e),v=c?B1(t,z1(g),new Set(g)):[],y=[],b=[];if(d){const j=uy[d],w=XB(d);p=w,f=j;const S=L1(t,Array.from(t.querySelectorAll("[aria-live]"))),N=g.concat(S);B1(t,z1(N),new Set(N)).forEach(E=>{const D=E.getAttribute(d),C=D!==null&&D!=="false",A=(j.get(E)||0)+1;j.set(E,A),y.push(E),A===1&&C&&w.add(E),C||E.setAttribute(d,d==="inert"?"":"true")})}return c&&v.forEach(j=>{const w=(nf.get(j)||0)+1;nf.set(j,w),b.push(j),w===1&&j.setAttribute(P1,"")}),fy+=1,()=>{f&&y.forEach(j=>{const S=(f.get(j)||0)-1;f.set(j,S),S||(!p?.has(j)&&d&&j.removeAttribute(d),p?.delete(j))}),c&&b.forEach(j=>{const w=(nf.get(j)||0)-1;nf.set(j,w),w||j.removeAttribute(P1)}),fy-=1,fy||(uy.inert=new WeakMap,uy["aria-hidden"]=new WeakMap,dy.inert=new WeakSet,dy["aria-hidden"]=new WeakSet,nf=new WeakMap)}}function H1(e,t={}){const{ariaHidden:a=!1,inert:o=!1,mark:c=!0}=t,d=$t(e[0]).body;return QB(e,d,a,o,{mark:c})}const ZB=500,WB={style:{transition:"none"}},U1="data-base-ui-click-trigger",V1={fallbackAxisSide:"none"},F1={fallbackAxisSide:"end"},JB={clipPath:"inset(50%)",position:"fixed",top:0,left:0},$1=x.createContext(null),q1=()=>x.useContext($1),eH=tf("portal");function G1(e={}){const{ref:t,container:a,componentProps:o=fn,elementProps:c}=e,d=$d(),p=q1()?.portalNode,[g,v]=x.useState(null),[y,b]=x.useState(null),j=Ie(k=>{k!==null&&b(k)}),w=x.useRef(null);De(()=>{if(a===null){w.current&&(w.current=null,b(null),v(null));return}const k=(a&&(bv(a)?a:a.current))??p??document.body;if(k==null){w.current&&(w.current=null,b(null),v(null));return}w.current!==k&&(w.current=k,b(null),v(k))},[a,p]);const S=vt("div",o,{ref:[t,j],props:[{id:d,[eH]:""},c]}),N=g&&S?ks.createPortal(S,g):null;return{node:y,nodeId:x.isValidElement(S)?S.props.id:void 0,subtree:N}}const sh=x.forwardRef(function(t,a){const{render:o,className:c,style:d,children:f,container:p,portalOwnerRole:g,...v}=t,{node:y,nodeId:b,subtree:j}=G1({container:p,ref:a,componentProps:t,elementProps:v}),w=x.useRef(null),S=x.useRef(null),N=x.useRef(null),k=x.useRef(null),[E,D]=x.useState(null),C=x.useRef(!1),A=E?.modal,R=E?.open,I=!!E&&!E.modal&&E.open&&!!y;x.useEffect(()=>{if(!y||A)return;function O(_){y&&_.relatedTarget&&Gc(_)&&(_.type==="focusin"?C.current&&(f1(y),C.current=!1):(J4(y),C.current=!0))}return Ka(St(y,"focusin",O,!0),St(y,"focusout",O,!0))},[y,A]),De(()=>{!y||R!==!0||!C.current||(f1(y),C.current=!1)},[R,y]);const P=x.useMemo(()=>({beforeOutsideRef:w,afterOutsideRef:S,beforeInsideRef:N,afterInsideRef:k,portalNode:y,setFocusManagerState:D}),[y]);return s.jsxs(x.Fragment,{children:[j,s.jsxs($1.Provider,{value:P,children:[I&&y&&s.jsx(Wc,{"data-type":"outside",ref:w,onFocus:O=>{if(Gc(O,y))N.current?.focus();else{const _=E?E.domReference:null;u1(_)?.focus()}}}),I&&y&&s.jsx("span",{role:g,"aria-owns":b,style:JB}),y&&ks.createPortal(f,y),I&&y&&s.jsx(Wc,{"data-type":"outside",ref:S,onFocus:O=>{if(Gc(O,y))k.current?.focus();else{const _=E?E.domReference:null;Jv(_)?.focus(),E?.closeOnFocusOut&&E?.onOpenChange(!1,Fe(ho,O.nativeEvent))}}})]})]})});function K1(){const e=new Map;return{emit(t,a){e.get(t)?.forEach(o=>o(a))},on(t,a){e.has(t)||e.set(t,new Set),e.get(t).add(a)},off(t,a){e.get(t)?.delete(a)}}}class tH{constructor(){ln(this,"nodesRef",{current:[]});ln(this,"events",K1())}addNode(t){this.nodesRef.current.push(t)}removeNode(t){const a=this.nodesRef.current.findIndex(o=>o===t);a!==-1&&this.nodesRef.current.splice(a,1)}}const Y1=x.createContext(null),X1=x.createContext(null),Jc=()=>x.useContext(Y1)?.id||null,Mi=e=>{const t=x.useContext(X1);return e??t};function nH(e){const t=$d(),a=Mi(e),o=Jc();return De(()=>{if(!t)return;const c={id:t,parentId:o};return a?.addNode(c),()=>{a?.removeNode(c)}},[a,t,o]),t}function sH(e){const{children:t,id:a}=e,o=Jc();return s.jsx(Y1.Provider,{value:x.useMemo(()=>({id:a,parentId:o}),[a,o]),children:t})}function rH(e){const{children:t,externalTree:a}=e,o=Ms(()=>a??new tH).current;return s.jsx(X1.Provider,{value:o,children:t})}function aH(e,t){const a=Sn(is(e));return e instanceof a.KeyboardEvent?"keyboard":e instanceof a.FocusEvent?t||"keyboard":"pointerType"in e?e.pointerType||"keyboard":"touches"in e?"touch":e instanceof a.MouseEvent?t||(e.detail===0?"keyboard":"mouse"):""}const Q1=20;let xo=[];function py(){xo=xo.filter(e=>e.deref()?.isConnected)}function Z1(e){py(),e&&Bs(e)!=="body"&&(xo.push(new WeakRef(e)),xo.length>Q1&&(xo=xo.slice(-Q1)))}function W1(){return py(),xo[xo.length-1]?.deref()}function lH(e){return e?Wv(e)?e:Yd(e)[0]||e:null}function J1(e){if(e.hasAttribute("tabindex")&&!e.hasAttribute("data-tabindex")||!e.getAttribute("role")?.includes("dialog"))return;const a=i1(e).filter(c=>{const d=c.getAttribute("data-tabindex")||"";return Wv(c)||c.hasAttribute("data-tabindex")&&!d.startsWith("-")}),o=e.getAttribute("tabindex");a.length===0?o!=="0"&&(e.setAttribute("tabindex","0"),e.setAttribute("data-tabindex","0")):(o!=="-1"||e.hasAttribute("data-tabindex")&&e.getAttribute("data-tabindex")!=="-1")&&(e.setAttribute("tabindex","-1"),e.setAttribute("data-tabindex","-1"))}function rh(e){const{context:t,children:a,disabled:o=!1,initialFocus:c=!0,returnFocus:d=!0,restoreFocus:f=!1,modal:p=!0,closeOnFocusOut:g=!0,openInteractionType:v="",nextFocusableElement:y,previousFocusableElement:b,beforeContentFocusGuardRef:j,externalTree:w,getInsideElements:S}=e,N="rootStore"in t?t.rootStore:t,k=N.useState("open"),E=N.useState("domReferenceElement"),D=N.useState("floatingElement"),{events:C,dataRef:A}=N.context,R=Ie(()=>A.current.floatingContext?.nodeId),I=c===!1,P=Fv(E)&&I,O=Xn(c),_=Xn(d),L=Xn(v),H=Xn(k),B=Mi(w),z=q1(),Q=x.useRef(!1),K=x.useRef(!1),X=x.useRef(!1),q=x.useRef(null),$=x.useRef(""),Y=x.useRef(""),F=x.useRef(null),G=x.useRef(null),W=ea(F,j,z?.beforeInsideRef),le=ea(G,z?.afterInsideRef),M=Qs(),U=Qs(),Z=Kc(),ae=z!=null,ce=Vm(D),J=Ie((ee=ce)=>ee?Yd(ee):[]),ie=Ie(()=>S?.().filter(ee=>ee!=null)??[]);x.useEffect(()=>{if(o||!p)return;function ee(te){te.key==="Tab"&&Qe(ce,or($t(ce)))&&J().length===0&&!P&&Ns(te)}const fe=$t(ce);return St(fe,"keydown",ee)},[o,ce,p,P,J]),x.useEffect(()=>{if(o||!k)return;const ee=$t(ce);function fe(){X.current=!1}function te(re){const de=is(re),ke=ie(),Ee=Qe(D,de)||Qe(E,de)||Qe(z?.portalNode,de)||ke.some(ve=>ve===de||Qe(ve,de));X.current=!Ee,Y.current=re.pointerType||"keyboard",de?.closest(`[${U1}]`)&&(K.current=!0,U.start(0,()=>{K.current=!1}))}function Ce(){Y.current="keyboard"}return Ka(St(ee,"pointerdown",te,!0),St(ee,"pointerup",fe,!0),St(ee,"pointercancel",fe,!0),St(ee,"keydown",Ce,!0),fe)},[o,D,E,ce,k,z,U,ie]),x.useEffect(()=>{if(o||!g)return;const ee=$t(ce);function fe(){K.current=!0,U.start(0,()=>{K.current=!1})}function te(ke){const Ee=is(ke);Wv(Ee)&&(q.current=Ee)}function Ce(ke){const Ee=ke.relatedTarget,ve=ke.currentTarget,he=is(ke);p&&Ee==null&&he!=null&&Qe(D,he)&&Z1(he),queueMicrotask(()=>{const ye=R(),we=N.context.triggerElements,xe=ie(),Te=Ee?.hasAttribute(tf("focus-guard"))&&[F.current,G.current,z?.beforeInsideRef.current,z?.afterInsideRef.current,z?.beforeOutsideRef.current,z?.afterOutsideRef.current,Nl(b),Nl(y)].includes(Ee),Oe=!(Qe(E,Ee)||Qe(D,Ee)||Qe(Ee,D)||Qe(z?.portalNode,Ee)||xe.some(Ne=>Ne===Ee||Qe(Ne,Ee))||we.hasMatchingElement(Ne=>Qe(Ne,Ee))||Te||B&&(io(B.nodesRef.current,ye).find(Ne=>Qe(Ne.context?.elements.floating,Ee)||Qe(Ne.context?.elements.domReference,Ee))||ZC(B.nodesRef.current,ye).find(Ne=>[Ne.context?.elements.floating,Vm(Ne.context?.elements.floating)].includes(Ee)||Ne.context?.elements.domReference===Ee)));if(ve===E&&ce&&J1(ce),f&&ve!==E&&!Ym(he)&&or(ee)===ee.body){if(dn(ce)&&(ce.focus(),f==="popup")){Z.request(()=>{ce.focus()});return}const Ne=J(),_e=q.current,Ye=(_e&&Ne.includes(_e)?_e:null)||Ne[Ne.length-1]||ce;dn(Ye)&&Ye.focus()}if(A.current.insideReactTree){A.current.insideReactTree=!1;return}(P||!p)&&Ee&&Oe&&!K.current&&(P||Ee!==W1())&&(Q.current=!0,N.setOpen(!1,Fe(ho,ke)))})}function re(){X.current||(A.current.insideReactTree=!0,M.start(0,()=>{A.current.insideReactTree=!1}))}const de=dn(E)?E:null;if(!(!D&&!de))return Ka(de&&St(de,"focusout",Ce),de&&St(de,"pointerdown",fe),D&&St(D,"focusin",te),D&&St(D,"focusout",Ce),D&&z&&St(D,"focusout",re,!0))},[o,E,D,ce,p,B,z,N,g,f,J,P,R,A,M,U,Z,y,b,ie]),x.useEffect(()=>{if(o||!D||!k)return;const ee=Array.from(z?.portalNode?.querySelectorAll(`[${tf("portal")}]`)||[]),te=(B?ZC(B.nodesRef.current,R()):[]).find(ve=>Fv(ve.context?.elements.domReference||null))?.context?.elements.domReference,re=[...[D,...ee,F.current,G.current,z?.beforeOutsideRef.current,z?.afterOutsideRef.current,...ie()],te,Nl(b),Nl(y),P?E:null].filter(ve=>ve!=null),de=H1(re,{ariaHidden:p||P,mark:!1}),ke=[D,...ee].filter(ve=>ve!=null),Ee=H1(ke);return()=>{Ee(),de()}},[k,o,E,D,p,z,P,B,R,y,b,ie]),De(()=>{if(!k||o||!dn(ce))return;$.current="",Y.current="";const ee=$t(ce),fe=or(ee);queueMicrotask(()=>{const te=O.current,Ce=typeof te=="function"?te(L.current||""):te;if(Ce===void 0||Ce===!1||Qe(ce,fe))return;let de=null;const ke=()=>(de==null&&(de=J(ce)),de[0]||ce);let Ee;Ce===!0||Ce===null?Ee=ke():Ee=Nl(Ce),Ee=Ee||ke();const ve=Qe(ce,or(ee));nh(Ee,{preventScroll:Ee===ce,shouldFocus(){if(!H.current)return!1;if(ve)return!0;const he=or(ee);return!(he!==Ee&&Qe(ce,he))}})})},[o,k,ce,J,O,L,H]),De(()=>{if(o||!ce)return;const ee=$t(ce),fe=or(ee),te=L.current==null;Z1(fe);function Ce(de){if(de.open||($.current=aH(de.nativeEvent,Y.current)),de.reason===Us&&de.nativeEvent.type==="mouseleave"&&(Q.current=!0),de.reason===Jm)if(de.nested)Q.current=!1;else if(Fm(de.nativeEvent)||$v(de.nativeEvent))Q.current=!1;else{let ke=!1;$t(ce).createElement("div").focus({get preventScroll(){return ke=!0,!1}}),ke?Q.current=!1:Q.current=!0}}C.on("openchange",Ce);function re(de){const ke=_.current;let Ee=typeof ke=="function"?ke(de):ke;if(Ee===void 0||Ee===!1)return null;Ee===null&&(Ee=!0);const ve=E?.isConnected?E:null,he=fe?.isConnected&&Bs(fe)!=="body"?fe:null;let ye=te?he||ve:ve||he;return ye||(ye=W1()||null),typeof Ee=="boolean"?ye:Nl(Ee)||ye||null}return()=>{C.off("openchange",Ce);const de=or(ee),ke=ie(),Ee=Qe(D,de)||ke.some(we=>we===de||Qe(we,de))||B&&io(B.nodesRef.current,R(),!1).some(we=>Qe(we.context?.elements.floating,de)),ve=_.current,he=$.current,ye=re(he);queueMicrotask(()=>{const we=lH(ye),xe=typeof ve!="boolean";if(ve&&!Q.current&&dn(we)&&(!(!xe&&we!==de&&de!==ee.body)||Ee)){const Te={preventScroll:!0};he==="keyboard"&&(Te.focusVisible=!0),we.focus(Te)}Q.current=!1})}},[o,D,ce,_,L,C,B,E,R,ie]),De(()=>{if(!yl||k||!D)return;const ee=or($t(D));!dn(ee)||!Um(ee)||Qe(D,ee)&&ee.blur()},[k,D]),De(()=>{if(!(o||!z))return z.setFocusManagerState({modal:p,closeOnFocusOut:g,open:k,onOpenChange:N.setOpen,domReference:E}),()=>{z.setFocusManagerState(null)}},[o,z,p,k,N,g,E]),De(()=>{if(!(o||!ce))return J1(ce),()=>{queueMicrotask(py)}},[o,ce]);const ge=!o&&(p?!P:!0)&&(ae||p);return s.jsxs(x.Fragment,{children:[ge&&s.jsx(Wc,{"data-type":"inside",ref:W,onFocus:ee=>{if(p){const fe=J();nh(fe[fe.length-1])}else z?.portalNode&&(Q.current=!1,Gc(ee,z.portalNode)?Jv(E)?.focus():Nl(b??z.beforeOutsideRef)?.focus())}}),a,ge&&s.jsx(Wc,{"data-type":"inside",ref:le,onFocus:ee=>{p?nh(J()[0]):z?.portalNode&&(g&&(Q.current=!0),Gc(ee,z.portalNode)?u1(E)?.focus():Nl(y??z.afterOutsideRef)?.focus())}})]})}function ah(e,t={}){const{enabled:a=!0,event:o="click",toggle:c=!0,ignoreMouse:d=!1,stickIfOpen:f=!0,touchOpenDelay:p=0,reason:g=mo}=t,v="rootStore"in e?e.rootStore:e,y=v.context.dataRef,b=x.useRef(void 0),j=Kc(),w=Qs(),S=x.useMemo(()=>{function N(E,D,C,A){const R=Fe(g,D,C);E&&A==="touch"&&p>0?w.start(p,()=>{v.setOpen(!0,R)}):v.setOpen(E,R)}function k(E,D,C){const A=y.current.openEvent,R=v.select("domReferenceElement")!==D;return E&&R||!E||!c?!0:A&&f?!C(A.type):!1}return{onPointerDown(E){b.current=co(E.pointerType,!0)&&$v(E.nativeEvent)?"virtual":E.pointerType},onMouseDown(E){const D=b.current,C=E.nativeEvent,A=v.select("open");if(E.button!==0||o==="click"||co(D,!0)&&d)return;const R=k(A,E.currentTarget,O=>O==="click"||O==="mousedown"),I=is(C);if(Um(I)){N(R,C,I,D);return}const P=E.currentTarget;j.request(()=>{N(R,C,P,D)})},onClick(E){if(o==="mousedown-only")return;const D=b.current;if(o==="mousedown"&&D){b.current=void 0;return}if(co(D,!0)&&d)return;const C=v.select("open"),A=k(C,E.currentTarget,R=>R==="click"||R==="mousedown"||R==="keydown"||R==="keyup");N(A,E.nativeEvent,E.currentTarget,D)},onKeyDown(){b.current=void 0}}},[y,o,d,g,v,f,c,j,w,p]);return x.useMemo(()=>a?{reference:S}:fn,[a,S])}function oH(e,t){let a=null,o=null,c=!1;return{contextElement:e||void 0,getBoundingClientRect(){const d=e?.getBoundingClientRect()||{width:0,height:0,x:0,y:0},f=t.axis==="x"||t.axis==="both",p=t.axis==="y"||t.axis==="both",g=["mouseenter","mousemove"].includes(t.dataRef.current.openEvent?.type||"")&&t.pointerType!=="touch";let v=d.width,y=d.height,b=d.x,j=d.y;return a==null&&t.x&&f&&(a=d.x-t.x),o==null&&t.y&&p&&(o=d.y-t.y),b-=a||0,j-=o||0,v=0,y=0,!c||g?(v=t.axis==="y"?d.width:0,y=t.axis==="x"?d.height:0,b=f&&t.x!=null?t.x:b,j=p&&t.y!=null?t.y:j):c&&!g&&(y=t.axis==="x"?d.height:y,v=t.axis==="y"?d.width:v),c=!0,{width:v,height:y,x:b,y:j,top:j,right:b+v,bottom:j+y,left:b}}}}function eT(e){return e!=null&&e.clientX!=null}function iH(e,t={}){const{enabled:a=!0,axis:o="both"}=t,c="rootStore"in e?e.rootStore:e,d=c.useState("open"),f=c.useState("floatingElement"),p=c.useState("domReferenceElement"),g=c.context.dataRef,v=x.useRef(!1),y=x.useRef(null),[b,j]=x.useState(),[w,S]=x.useState([]),N=Ie(A=>{c.set("positionReference",A)}),k=Ie((A,R,I)=>{v.current||g.current.openEvent&&!eT(g.current.openEvent)||c.set("positionReference",oH(I??p,{x:A,y:R,axis:o,dataRef:g,pointerType:b}))}),E=Ie(A=>{d?y.current||(k(A.clientX,A.clientY,A.currentTarget),S([])):k(A.clientX,A.clientY,A.currentTarget)}),D=co(b)?f:d;x.useEffect(()=>{if(!a){N(p);return}if(!D)return;function A(){y.current?.(),y.current=null}const R=Sn(f);function I(P){const O=is(P);Qe(f,O)?A():k(P.clientX,P.clientY)}return!g.current.openEvent||eT(g.current.openEvent)?y.current=St(R,"mousemove",I):N(p),A},[D,a,f,g,p,c,k,N,w]),x.useEffect(()=>()=>{c.set("positionReference",null)},[c]),x.useEffect(()=>{a&&!f&&(v.current=!1)},[a,f]),x.useEffect(()=>{!a&&d&&(v.current=!0)},[a,d]);const C=x.useMemo(()=>{function A(R){j(R.pointerType)}return{onPointerDown:A,onPointerEnter:A,onMouseMove:E,onMouseEnter:E}},[E]);return x.useMemo(()=>a?{reference:C,trigger:C}:{},[a,C])}function cH(){return!1}function uH(e){return{escapeKey:typeof e=="boolean"?e:e?.escapeKey??!1,outsidePress:typeof e=="boolean"?e:e?.outsidePress??!0}}function sf(e,t={}){const{enabled:a=!0,escapeKey:o=!0,outsidePress:c=!0,outsidePressEvent:d="sloppy",referencePress:f=cH,bubbles:p,externalTree:g}=t,v="rootStore"in e?e.rootStore:e,y=v.useState("open"),b=v.useState("floatingElement"),{dataRef:j,events:w}=v.context,S=Mi(g),N=Ie(typeof c=="function"?c:()=>!1),k=typeof c=="function"?N:c,E=k!==!1,D=Ie(()=>d),{escapeKey:C,outsidePress:A}=uH(p),R=x.useRef(!1),I=x.useRef(!1),P=x.useRef(!1),O=x.useRef(!1),_=x.useRef(!1),L=x.useRef(""),H=x.useRef(null),B=Qs(),z=Qs(),Q=Ie(()=>{z.clear(),j.current.insideReactTree=!1}),K=Ie(M=>{const U=j.current.floatingContext?.nodeId;return(S?io(S.nodesRef.current,U):[]).some(ae=>ae.context?.open&&!ae.context.dataRef.current[M])}),X=Ie(M=>Vv(M,v.select("floatingElement"))||Vv(M,v.select("domReferenceElement"))),q=Ie(M=>{f()&&v.setOpen(!1,Fe(mo,M.nativeEvent))}),$=Ie(M=>{if(!y||!a||!o||M.key!=="Escape"||_.current||!C&&K("__escapeKeyBubbles"))return;const U=I4(M)?M.nativeEvent:M,Z=Fe(Xc,U);v.setOpen(!1,Z),Z.isCanceled||M.preventDefault(),!C&&!Z.isPropagationAllowed&&M.stopPropagation()}),Y=Ie(()=>{j.current.insideReactTree=!0,z.start(0,Q)}),F=Ie(M=>{if(!y||!a||M.button!==0)return;const U=is(M.nativeEvent);Qe(v.select("floatingElement"),U)&&(R.current||(R.current=!0,I.current=!1))}),G=Ie(M=>{!y||!a||(M.defaultPrevented||M.nativeEvent.defaultPrevented)&&R.current&&(I.current=!0)});x.useEffect(()=>{function M(U){U.open||(O.current=!1)}return w.on("openchange",M),()=>{w.off("openchange",M)}},[w]),x.useEffect(()=>{if(!y||!a)return y||(O.current=!1),Q;j.current.__escapeKeyBubbles=C,j.current.__outsidePressBubbles=A;const M=new sa,U=new sa,Z=$t(b);function ae(){M.clear(),_.current=!0}function ce(){M.start(yl?5:0,()=>{_.current=!1})}function J(){P.current=!0,U.start(0,()=>{P.current=!1})}function ie(){R.current=!1,I.current=!1}function ge(){const Oe=L.current,Ne=Oe==="pen"||!Oe?"mouse":Oe,_e=D(),Ye=typeof _e=="function"?_e():_e;return typeof Ye=="string"?Ye:Ye[Ne]}function ee(Oe){const Ne=ge();return Ne==="intentional"&&Oe.type!=="click"||Ne==="sloppy"&&Oe.type==="click"}function fe(Oe){const Ne=j.current.floatingContext?.nodeId,_e=S&&io(S.nodesRef.current,Ne).some(Ye=>Vv(Oe,Ye.context?.elements.floating));return X(Oe)||_e}function te(Oe){if(ee(Oe)){Oe.type!=="click"&&!X(Oe)&&(U.clear(),P.current=!1),Q();return}if(j.current.insideReactTree){Q();return}const Ne=is(Oe),_e=`[${tf("inert")}]`,Ye=At(Ne)?Ne.getRootNode():null,kt=Array.from((Bc(Ye)?Ye:$t(v.select("floatingElement"))).querySelectorAll(_e)),Ct=v.context.triggerElements;if(Ne&&(Ct.hasElement(Ne)||Ct.hasMatchingElement(ot=>Qe(ot,Ne))))return;let Rt=At(Ne)?Ne:null;for(;Rt&&!no(Rt);){const ot=so(Rt);if(no(ot)||!At(ot))break;Rt=ot}if(!(kt.length&&At(Ne)&&!O4(Ne)&&!Qe(Ne,v.select("floatingElement"))&&kt.every(ot=>!Qe(Rt,ot)))){if(dn(Ne)&&!("touches"in Oe)){const ot=no(Ne),qn=xr(Ne),ds=/auto|scroll/,Gn=ot||ds.test(qn.overflowX),xs=ot||ds.test(qn.overflowY),it=Gn&&Ne.clientWidth>0&&Ne.scrollWidth>Ne.clientWidth,Vt=xs&&Ne.clientHeight>0&&Ne.scrollHeight>Ne.clientHeight,Bn=qn.direction==="rtl",tn=Vt&&(Bn?Oe.offsetX<=Ne.offsetWidth-Ne.clientWidth:Oe.offsetX>Ne.clientWidth),nt=it&&Oe.offsetY>Ne.clientHeight;if(tn||nt)return}if(!fe(Oe)){if(ge()==="intentional"){if(Oe.detail!==0&&!Fm(Oe)&&!O.current)return;if(P.current){U.clear(),P.current=!1;return}}typeof k=="function"&&!k(Oe)||K("__outsidePressBubbles")||(v.setOpen(!1,Fe(Jm,Oe)),Q())}}}function Ce(Oe){ge()!=="sloppy"||Oe.pointerType==="touch"||!v.select("open")||!a||X(Oe)||te(Oe)}function re(Oe){if(ge()!=="sloppy"||!v.select("open")||!a||X(Oe))return;const Ne=Oe.touches[0];Ne&&(H.current={startTime:Date.now(),startX:Ne.clientX,startY:Ne.clientY,dismissOnTouchEnd:!1,dismissOnMouseDown:!0},B.start(1e3,()=>{H.current&&(H.current.dismissOnTouchEnd=!1,H.current.dismissOnMouseDown=!1)}))}function de(Oe,Ne){const _e=is(Oe);if(!_e)return;const Ye=St(_e,Oe.type,()=>{Ne(Oe),Ye()})}function ke(Oe){L.current="touch",de(Oe,re)}function Ee(Oe){B.clear(),Oe.type==="pointerdown"&&(Oe.button===0&&(O.current=!0),L.current=Oe.pointerType),!(Oe.type==="mousedown"&&H.current&&!H.current.dismissOnMouseDown)&&de(Oe,Ne=>{Ne.type==="pointerdown"?Ce(Ne):te(Ne)})}function ve(Oe){if(Oe.type==="pointercancel"&&(O.current=!1),!R.current)return;const Ne=I.current;if(ie(),ge()==="intentional"){if(Oe.type==="pointercancel"){Ne&&J();return}if(!fe(Oe)){if(Ne){J();return}typeof k=="function"&&!k(Oe)||(U.clear(),P.current=!0,Q())}}}function he(Oe){if(ge()!=="sloppy"||!H.current||X(Oe))return;const Ne=Oe.touches[0];if(!Ne)return;const _e=Math.abs(Ne.clientX-H.current.startX),Ye=Math.abs(Ne.clientY-H.current.startY),kt=Math.sqrt(_e*_e+Ye*Ye);kt>5&&(H.current.dismissOnTouchEnd=!0),kt>10&&(te(Oe),B.clear(),H.current=null)}function ye(Oe){de(Oe,he)}function we(Oe){ge()!=="sloppy"||!H.current||X(Oe)||(H.current.dismissOnTouchEnd&&te(Oe),B.clear(),H.current=null)}function xe(Oe){de(Oe,we)}const Te=Ka(o&&Ka(St(Z,"keydown",$),St(Z,"compositionstart",ae),St(Z,"compositionend",ce)),E&&Ka(St(Z,"click",Ee,!0),St(Z,"pointerdown",Ee,!0),St(Z,"pointerup",ve,!0),St(Z,"pointercancel",ve,!0),St(Z,"mousedown",Ee,!0),St(Z,"mouseup",ve,!0),St(Z,"touchstart",ke,{capture:!0,passive:!0}),St(Z,"touchmove",ye,{capture:!0,passive:!0}),St(Z,"touchend",xe,{capture:!0,passive:!0})));return()=>{Te(),M.clear(),U.clear(),ie(),P.current=!1,Q()}},[j,b,o,E,k,y,a,C,A,$,Q,D,K,X,S,v,B]);const W=x.useMemo(()=>({onKeyDown:$,onPointerDown:q,onClick:q}),[$,q]),le=x.useMemo(()=>({onKeyDown:$,onPointerDown:G,onMouseDown:G,onClickCapture:Y,onMouseDownCapture(M){Y(),F(M)},onPointerDownCapture(M){Y(),F(M)},onMouseUpCapture:Y,onTouchEndCapture:Y,onTouchMoveCapture:Y}),[$,Y,F,G]);return x.useMemo(()=>a?{reference:W,floating:le,trigger:W}:{},[a,W,le])}function tT(e,t,a){let{reference:o,floating:c}=e;const d=na(t),f=Kv(t),p=Gv(f),g=ta(t),v=d==="y",y=o.x+o.width/2-c.width/2,b=o.y+o.height/2-c.height/2,j=o[p]/2-c[p]/2;let w;switch(g){case"top":w={x:y,y:o.y-c.height};break;case"bottom":w={x:y,y:o.y+o.height};break;case"right":w={x:o.x+o.width,y:b};break;case"left":w={x:o.x-c.width,y:b};break;default:w={x:o.x,y:o.y}}const S=Sl(t);return S&&(w[f]+=j*(S==="end"?1:-1)*(a&&v?-1:1)),w}async function dH(e,t){var a;t===void 0&&(t={});const{x:o,y:c,platform:d,rects:f,elements:p,strategy:g}=e,{boundary:v="clippingAncestors",rootBoundary:y="viewport",elementContext:b="floating",altBoundary:j=!1,padding:w=0}=uo(t,e),S=t1(w),k=p[j?b==="floating"?"reference":"floating":b],E=Kd(await d.getClippingRect({element:(a=await(d.isElement==null?void 0:d.isElement(k)))==null||a?k:k.contextElement||await(d.getDocumentElement==null?void 0:d.getDocumentElement(p.floating)),boundary:v,rootBoundary:y,strategy:g})),D=b==="floating"?{x:o,y:c,width:f.floating.width,height:f.floating.height}:f.reference,C=await(d.getOffsetParent==null?void 0:d.getOffsetParent(p.floating)),A=await(d.isElement==null?void 0:d.isElement(C))&&await(d.getScale==null?void 0:d.getScale(C))||{x:1,y:1},R=Kd(d.convertOffsetParentRelativeRectToViewportRelativeRect?await d.convertOffsetParentRelativeRectToViewportRelativeRect({elements:p,rect:D,offsetParent:C,strategy:g}):D);return{top:(E.top-R.top+S.top)/A.y,bottom:(R.bottom-E.bottom+S.bottom)/A.y,left:(E.left-R.left+S.left)/A.x,right:(R.right-E.right+S.right)/A.x}}const fH=50,pH=async(e,t,a)=>{const{placement:o="bottom",strategy:c="absolute",middleware:d=[],platform:f}=a,p=f.detectOverflow?f:{...f,detectOverflow:dH},g=await(f.isRTL==null?void 0:f.isRTL(t));let v=await f.getElementRects({reference:e,floating:t,strategy:c}),{x:y,y:b}=tT(v,o,g),j=o,w=0;const S={};for(let N=0;NQ<=0)){var H,B;const Q=(((H=d.flip)==null?void 0:H.index)||0)+1,K=P[Q];if(K&&(!(b==="alignment"?D!==na(K):!1)||L.every($=>na($.placement)===D?$.overflows[0]>0:!0)))return{data:{index:Q,overflows:L},reset:{placement:K}};let X=(B=L.filter(q=>q.overflows[0]<=0).sort((q,$)=>q.overflows[1]-$.overflows[1])[0])==null?void 0:B.placement;if(!X)switch(w){case"bestFit":{var z;const q=(z=L.filter($=>{if(I){const Y=na($.placement);return Y===D||Y==="y"}return!0}).map($=>[$.placement,$.overflows.filter(Y=>Y>0).reduce((Y,F)=>Y+F,0)]).sort(($,Y)=>$[1]-Y[1])[0])==null?void 0:z[0];q&&(X=q);break}case"initialPlacement":X=p;break}if(c!==X)return{reset:{placement:X}}}return{}}}},nT=new Set(["left","top"]);async function hH(e,t){const{placement:a,platform:o,elements:c}=e,d=await(o.isRTL==null?void 0:o.isRTL(c.floating)),f=ta(a),p=Sl(a),g=na(a)==="y",v=nT.has(f)?-1:1,y=d&&g?-1:1,b=uo(t,e);let{mainAxis:j,crossAxis:w,alignmentAxis:S}=typeof b=="number"?{mainAxis:b,crossAxis:0,alignmentAxis:null}:{mainAxis:b.mainAxis||0,crossAxis:b.crossAxis||0,alignmentAxis:b.alignmentAxis};return p&&typeof S=="number"&&(w=p==="end"?S*-1:S),g?{x:w*y,y:j*v}:{x:j*v,y:w*y}}const gH=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var a,o;const{x:c,y:d,placement:f,middlewareData:p}=t,g=await hH(t,e);return f===((a=p.offset)==null?void 0:a.placement)&&(o=p.arrow)!=null&&o.alignmentOffset?{}:{x:c+g.x,y:d+g.y,data:{...g,placement:f}}}}},xH=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:a,y:o,placement:c,platform:d}=t,{mainAxis:f=!0,crossAxis:p=!1,limiter:g={fn:D=>{let{x:C,y:A}=D;return{x:C,y:A}}},...v}=uo(e,t),y={x:a,y:o},b=await d.detectOverflow(t,v),j=na(c),w=qv(j);let S=y[w],N=y[j];const k=(D,C)=>WC(C+b[D==="y"?"top":"left"],C,C-b[D==="y"?"bottom":"right"]);f&&(S=k(w,S)),p&&(N=k(j,N));const E=g.fn({...t,[w]:S,[j]:N});return{...E,data:{x:E.x-a,y:E.y-o,enabled:{[w]:f,[j]:p}}}}}},bH=function(e){return e===void 0&&(e={}),{options:e,fn(t){var a,o;const{x:c,y:d,placement:f,rects:p,middlewareData:g}=t,{offset:v=0,mainAxis:y=!0,crossAxis:b=!0}=uo(e,t),j={x:c,y:d},w=na(f),S=qv(w);let N=j[S],k=j[w];const E=uo(v,t),D=typeof E=="number"?{mainAxis:E,crossAxis:0}:{mainAxis:(a=E.mainAxis)!=null?a:0,crossAxis:(o=E.crossAxis)!=null?o:0};if(y){const R=S==="y"?"height":"width",I=p.reference[S]-p.floating[R]+D.mainAxis,P=p.reference[S]+p.reference[R]-D.mainAxis;NP&&(N=P)}if(b){var C,A;const R=S==="y"?"width":"height",I=nT.has(ta(f)),P=p.reference[w]-p.floating[R]+(I&&((C=g.offset)==null?void 0:C[w])||0)+(I?0:D.crossAxis),O=p.reference[w]+p.reference[R]+(I?0:((A=g.offset)==null?void 0:A[w])||0)-(I?D.crossAxis:0);kO&&(k=O)}return{[S]:N,[w]:k}}}},vH=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:a,rects:o,platform:c,elements:d}=t,{apply:f=()=>{},...p}=uo(e,t),g=await c.detectOverflow(t,p),v=ta(a),y=Sl(a),b=na(a)==="y",{width:j,height:w}=o.floating;let S,N;v==="top"||v==="bottom"?(S=v,N=y===(await(c.isRTL==null?void 0:c.isRTL(d.floating))?"start":"end")?"left":"right"):(N=v,S=y==="end"?"top":"bottom");const k=w-g.top-g.bottom,E=j-g.left-g.right,D=qc(w-g[S],k),C=qc(j-g[N],E),A=t.middlewareData.shift,R=!A;let I=D,P=C;A!=null&&A.enabled.x&&(P=E),A!=null&&A.enabled.y&&(I=k),R&&!y&&(b?P=j-2*jl(g.left,g.right):I=w-2*jl(g.top,g.bottom)),await f({...t,availableWidth:P,availableHeight:I});const O=await c.getDimensions(d.floating);return j!==O.width||w!==O.height?{reset:{rects:!0}}:{}}}};function sT(e){const t=xr(e);let a=parseFloat(t.width)||0,o=parseFloat(t.height)||0;const c=dn(e),d=c?e.offsetWidth:a,f=c?e.offsetHeight:o,p=$m(a)!==d||$m(o)!==f;return p&&(a=d,o=f),{width:a,height:o,$:p}}function my(e){return At(e)?e:e.contextElement}function eu(e){const t=my(e);if(!dn(t))return wl(1);const a=t.getBoundingClientRect(),{width:o,height:c,$:d}=sT(t);let f=(d?$m(a.width):a.width)/o,p=(d?$m(a.height):a.height)/c;return(!f||!Number.isFinite(f))&&(f=1),(!p||!Number.isFinite(p))&&(p=1),{x:f,y:p}}const yH=wl(0);function rT(e){const t=Sn(e);return!jv()||!t.visualViewport?yH:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function jH(e,t,a){return t===void 0&&(t=!1),!!a&&t&&a===Sn(e)}function Di(e,t,a,o){t===void 0&&(t=!1),a===void 0&&(a=!1);const c=e.getBoundingClientRect(),d=my(e);let f=wl(1);t&&(o?At(o)&&(f=eu(o)):f=eu(e));const p=jH(d,a,o)?rT(d):wl(0);let g=(c.left+p.x)/f.x,v=(c.top+p.y)/f.y,y=c.width/f.x,b=c.height/f.y;if(d&&o){const j=Sn(d),w=At(o)?Sn(o):o;let S=j,N=wv(S);for(;N&&w!==S;){const k=eu(N),E=N.getBoundingClientRect(),D=xr(N),C=E.left+(N.clientLeft+parseFloat(D.paddingLeft))*k.x,A=E.top+(N.clientTop+parseFloat(D.paddingTop))*k.y;g*=k.x,v*=k.y,y*=k.x,b*=k.y,g+=C,v+=A,S=Sn(N),N=wv(S)}}return Kd({width:y,height:b,x:g,y:v})}function lh(e,t){const a=Om(e).scrollLeft;return t?t.left+a:Di(xl(e)).left+a}function aT(e,t){const a=e.getBoundingClientRect(),o=a.left+t.scrollLeft-lh(e,a),c=a.top+t.scrollTop;return{x:o,y:c}}function wH(e){let{elements:t,rect:a,offsetParent:o,strategy:c}=e;const d=c==="fixed",f=xl(o),p=t?Rm(t.floating):!1;if(o===f||p&&d)return a;let g={scrollLeft:0,scrollTop:0},v=wl(1);const y=wl(0),b=dn(o);if((b||!d)&&((Bs(o)!=="body"||Ud(f))&&(g=Om(o)),b)){const w=Di(o);v=eu(o),y.x=w.x+o.clientLeft,y.y=w.y+o.clientTop}const j=f&&!b&&!d?aT(f,g):wl(0);return{width:a.width*v.x,height:a.height*v.y,x:a.x*v.x-g.scrollLeft*v.x+y.x+j.x,y:a.y*v.y-g.scrollTop*v.y+y.y+j.y}}function SH(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function NH(e){const t=Om(e),a=e.ownerDocument.body,o=jl(e.scrollWidth,e.clientWidth,a.scrollWidth,a.clientWidth),c=jl(e.scrollHeight,e.clientHeight,a.scrollHeight,a.clientHeight);let d=-t.scrollLeft+lh(e);const f=-t.scrollTop;return xr(a).direction==="rtl"&&(d+=jl(e.clientWidth,a.clientWidth)-o),{width:o,height:c,x:d,y:f}}const kH=25;function CH(e,t,a){a===void 0&&(a="viewport");const o=a==="layoutViewport",c=Sn(e),d=xl(e),f=c.visualViewport;let p=d.clientWidth,g=d.clientHeight,v=0,y=0;if(f){const j=!jv()||t==="fixed";o?j||(v=-f.offsetLeft,y=-f.offsetTop):(p=f.width,g=f.height,j&&(v=f.offsetLeft,y=f.offsetTop))}if(lh(d)<=0){const j=d.ownerDocument,w=j.body,S=getComputedStyle(w),N=j.compatMode==="CSS1Compat"&&parseFloat(S.marginLeft)+parseFloat(S.marginRight)||0,k=Math.abs(d.clientWidth-w.clientWidth-N),E=getComputedStyle(d).scrollbarGutter==="stable both-edges"?k/2:k;E<=kH&&(p-=E)}return{width:p,height:g,x:v,y}}function TH(e,t){const a=Di(e,!0,t==="fixed"),o=a.top+e.clientTop,c=a.left+e.clientLeft,d=eu(e),f=e.clientWidth*d.x,p=e.clientHeight*d.y,g=c*d.x,v=o*d.y;return{width:f,height:p,x:g,y:v}}function lT(e,t,a){let o;if(t==="viewport"||t==="layoutViewport")o=CH(e,a,t);else if(t==="document")o=NH(xl(e));else if(At(t))o=TH(t,a);else{const c=rT(e);o={x:t.x-c.x,y:t.y-c.y,width:t.width,height:t.height}}return Kd(o)}function EH(e,t){const a=t.get(e);if(a)return a;let o=Hc(e,[],!1).filter(p=>At(p)&&Bs(p)!=="body"),c=null;const d=xr(e).position==="fixed";let f=d?so(e):e;for(;At(f)&&!no(f);){const p=xr(f),g=yv(f),v=c?c.position:d?"fixed":"";!g&&(v==="fixed"||v==="absolute"&&p.position==="static")?o=o.filter(b=>b!==f):c=p,f=so(f)}return t.set(e,o),o}function AH(e){let{element:t,boundary:a,rootBoundary:o,strategy:c}=e;const f=[...a==="clippingAncestors"?Rm(t)?[]:EH(t,this._c):[].concat(a),o],p=lT(t,f[0],c);let g=p.top,v=p.right,y=p.bottom,b=p.left;for(let j=1;j{p(!1,1e-7)},1e3)}P=!1}try{o=new IntersectionObserver(O,{...I,root:d.ownerDocument})}catch{o=new IntersectionObserver(O,I)}o.observe(e)}const g=Sn(e),v=()=>p(a);return g.addEventListener("resize",v),p(!0),()=>{g.removeEventListener("resize",v),f()}}function dT(e,t,a,o){o===void 0&&(o={});const{ancestorScroll:c=!0,ancestorResize:d=!0,elementResize:f=typeof ResizeObserver=="function",layoutShift:p=typeof IntersectionObserver=="function",animationFrame:g=!1}=o,v=my(e),y=c||d?[...v?Hc(v):[],...t?Hc(t):[]]:[];y.forEach(E=>{c&&E.addEventListener("scroll",a),d&&E.addEventListener("resize",a)});const b=v&&p?IH(v,a,d):null;let j=-1,w=null;f&&(w=new ResizeObserver(E=>{let[D]=E;D&&D.target===v&&w&&t&&(w.unobserve(t),cancelAnimationFrame(j),j=requestAnimationFrame(()=>{var C;(C=w)==null||C.observe(t)})),a()}),v&&!g&&w.observe(v),t&&w.observe(t));let S,N=g?Di(e):null;g&&k();function k(){const E=Di(e);N&&!uT(N,E)&&a(),N=E,S=requestAnimationFrame(k)}return a(),()=>{var E;y.forEach(D=>{c&&D.removeEventListener("scroll",a),d&&D.removeEventListener("resize",a)}),b?.(),(E=w)==null||E.disconnect(),w=null,g&&cancelAnimationFrame(S)}}const PH=gH,_H=xH,LH=mH,zH=vH,BH=bH,HH=(e,t,a)=>{const o=new Map,c=a??{},d={...cT,...c.platform,_c:o};return pH(e,t,{...c,platform:d})};var UH=typeof document<"u",VH=function(){},oh=UH?x.useLayoutEffect:VH;function ih(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 a,o,c;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(a=e.length,a!==t.length)return!1;for(o=a;o--!==0;)if(!ih(e[o],t[o]))return!1;return!0}if(c=Object.keys(e),a=c.length,a!==Object.keys(t).length)return!1;for(o=a;o--!==0;)if(!{}.hasOwnProperty.call(t,c[o]))return!1;for(o=a;o--!==0;){const d=c[o];if(!(d==="_owner"&&e.$$typeof)&&!ih(e[d],t[d]))return!1}return!0}return e!==e&&t!==t}function fT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function pT(e,t){const a=fT(e);return Math.round(t*a)/a}function gy(e){const t=x.useRef(e);return oh(()=>{t.current=e}),t}function FH(e){e===void 0&&(e={});const{placement:t="bottom",strategy:a="absolute",middleware:o=[],platform:c,elements:{reference:d,floating:f}={},transform:p=!0,whileElementsMounted:g,open:v}=e,[y,b]=x.useState({x:0,y:0,strategy:a,placement:t,middlewareData:{},isPositioned:!1}),[j,w]=x.useState(o);ih(j,o)||w(o);const[S,N]=x.useState(null),[k,E]=x.useState(null),D=x.useCallback($=>{$!==I.current&&(I.current=$,N($))},[]),C=x.useCallback($=>{$!==P.current&&(P.current=$,E($))},[]),A=d||S,R=f||k,I=x.useRef(null),P=x.useRef(null),O=x.useRef(y),_=g!=null,L=gy(g),H=gy(c),B=gy(v),z=x.useCallback(()=>{if(!I.current||!P.current)return;const $={placement:t,strategy:a,middleware:j};H.current&&($.platform=H.current),HH(I.current,P.current,$).then(Y=>{const F={...Y,isPositioned:B.current!==!1};Q.current&&!ih(O.current,F)&&(O.current=F,ks.flushSync(()=>{b(F)}))})},[j,t,a,H,B]);oh(()=>{v===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,b($=>({...$,isPositioned:!1})))},[v]);const Q=x.useRef(!1);oh(()=>(Q.current=!0,()=>{Q.current=!1}),[]),oh(()=>{if(A&&(I.current=A),R&&(P.current=R),A&&R){if(L.current)return L.current(A,R,z);z()}},[A,R,z,L,_]);const K=x.useMemo(()=>({reference:I,floating:P,setReference:D,setFloating:C}),[D,C]),X=x.useMemo(()=>({reference:A,floating:R}),[A,R]),q=x.useMemo(()=>{const $={position:a,left:0,top:0};if(!X.floating)return $;const Y=pT(X.floating,y.x),F=pT(X.floating,y.y);return p?{...$,transform:"translate("+Y+"px, "+F+"px)",...fT(X.floating)>=1.5&&{willChange:"transform"}}:{position:a,left:Y,top:F}},[a,p,X.floating,y.x,y.y]);return x.useMemo(()=>({...y,update:z,refs:K,elements:X,floatingStyles:q}),[y,z,K,X,q])}const $H=(e,t)=>{const a=PH(e);return{name:a.name,fn:a.fn,options:[e,t]}},qH=(e,t)=>{const a=_H(e);return{name:a.name,fn:a.fn,options:[e,t]}},GH=(e,t)=>({fn:BH(e).fn,options:[e,t]}),KH=(e,t)=>{const a=LH(e);return{name:a.name,fn:a.fn,options:[e,t]}},YH=(e,t)=>{const a=zH(e);return{name:a.name,fn:a.fn,options:[e,t]}};var xy={exports:{}},by={};var mT;function XH(){if(mT)return by;mT=1;var e=Hd();function t(b,j){return b===j&&(b!==0||1/b===1/j)||b!==b&&j!==j}var a=typeof Object.is=="function"?Object.is:t,o=e.useState,c=e.useEffect,d=e.useLayoutEffect,f=e.useDebugValue;function p(b,j){var w=j(),S=o({inst:{value:w,getSnapshot:j}}),N=S[0].inst,k=S[1];return d(function(){N.value=w,N.getSnapshot=j,g(N)&&k({inst:N})},[b,w,j]),c(function(){return g(N)&&k({inst:N}),b(function(){g(N)&&k({inst:N})})},[b]),f(w),w}function g(b){var j=b.getSnapshot;b=b.value;try{var w=j();return!a(b,w)}catch{return!0}}function v(b,j){return j()}var y=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?v:p;return by.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:y,by}var hT;function gT(){return hT||(hT=1,xy.exports=XH()),xy.exports}var vy=gT(),yy={exports:{}},jy={};var xT;function QH(){if(xT)return jy;xT=1;var e=Hd(),t=gT();function a(v,y){return v===y&&(v!==0||1/v===1/y)||v!==v&&y!==y}var o=typeof Object.is=="function"?Object.is:a,c=t.useSyncExternalStore,d=e.useRef,f=e.useEffect,p=e.useMemo,g=e.useDebugValue;return jy.useSyncExternalStoreWithSelector=function(v,y,b,j,w){var S=d(null);if(S.current===null){var N={hasValue:!1,value:null};S.current=N}else N=S.current;S=p(function(){function E(I){if(!D){if(D=!0,C=I,I=j(I),w!==void 0&&N.hasValue){var P=N.value;if(w(P,I))return A=P}return A=I}if(P=A,o(C,I))return P;var O=j(I);return w!==void 0&&w(P,O)?(C=I,P):(C=I,A=O)}var D=!1,C,A,R=b===void 0?null:b;return[function(){return E(y())},R===null?void 0:function(){return E(R())}]},[y,b,j,w]);var k=c(v,S[0],S[1]);return f(function(){N.hasValue=!0,N.value=k},[k]),g(k),k},jy}var bT;function ZH(){return bT||(bT=1,yy.exports=QH()),yy.exports}var WH=ZH();const JH=Av(19)?tU:nU;function vT(e,t,a,o,c){return JH(e,t,a,o,c)}function eU(e,t,a,o,c){const d=x.useCallback(()=>t(e.getSnapshot(),a,o,c),[e,t,a,o,c]);return vy.useSyncExternalStore(e.subscribe,d,d)}UB({before(e){e.syncIndex=0,e.didInitialize||(e.syncTick=1,e.syncHooks=[],e.didChangeStore=!0,e.getSnapshot=()=>{let t=!1;for(let a=0;a0&&(e.didChangeStore&&(e.didChangeStore=!1,e.subscribe=t=>{const a=new Set;for(const c of e.syncHooks)a.add(c.store);const o=[];for(const c of a)o.push(c.subscribe(t));return()=>{for(const c of o)c()}}),vy.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot))}});function tU(e,t,a,o,c){const d=HB();if(!d)return eU(e,t,a,o,c);const f=d.syncIndex;d.syncIndex+=1;let p;return d.didInitialize?(p=d.syncHooks[f],(p.store!==e||p.selector!==t||!Object.is(p.a1,a)||!Object.is(p.a2,o)||!Object.is(p.a3,c))&&(p.store!==e&&(d.didChangeStore=!0),p.store=e,p.selector=t,p.a1=a,p.a2=o,p.a3=c,p.value=t(e.getSnapshot(),a,o,c))):(p={store:e,selector:t,a1:a,a2:o,a3:c,value:t(e.getSnapshot(),a,o,c)},d.syncHooks.push(p)),p.value}function nU(e,t,a,o,c){return WH.useSyncExternalStoreWithSelector(e.subscribe,e.getSnapshot,e.getSnapshot,d=>t(d,a,o,c))}class sU{constructor(t){ln(this,"subscribe",t=>(this.listeners.add(t),()=>{this.listeners.delete(t)}));ln(this,"getSnapshot",()=>this.state);this.state=t,this.listeners=new Set,this.updateTick=0}static create(t){return new this(t)}setState(t){if(this.state===t)return;this.state=t,this.updateTick+=1;const a=this.updateTick;for(const o of this.listeners){if(a!==this.updateTick)return;o(t)}}update(t){for(const a in t)if(!Object.is(this.state[a],t[a])){this.setState({...this.state,...t});return}}set(t,a){Object.is(this.state[t],a)||this.setState({...this.state,[t]:a})}notifyAll(){const t={...this.state};this.setState(t)}use(t,a,o,c){return vT(this,t,a,o,c)}}class tu extends sU{constructor(t,a={},o){super(t),this.context=a,this.selectors=o}useSyncedValue(t,a){x.useDebugValue(t);const o=this;De(()=>{o.state[t]!==a&&o.set(t,a)},[o,t,a])}useSyncedValueWithCleanup(t,a){const o=this;De(()=>(o.state[t]!==a&&o.set(t,a),()=>{o.set(t,void 0)}),[o,t,a])}useSyncedValues(t){const a=this,o=Object.values(t);De(()=>{a.update(t)},[a,...o])}useControlledProp(t,a){x.useDebugValue(t);const o=this,c=a!==void 0;De(()=>{c&&!Object.is(o.state[t],a)&&o.setState({...o.state,[t]:a})},[o,t,a,c])}select(t,a,o,c){const d=this.selectors[t];return d(this.state,a,o,c)}useState(t,a,o,c){return x.useDebugValue(t),vT(this,this.selectors[t],a,o,c)}useContextCallback(t,a){x.useDebugValue(t);const o=Ie(a??qt);this.context[t]=o}useStateSetter(t){const a=x.useRef(void 0);return a.current===void 0&&(a.current=o=>{this.set(t,o)}),a.current}observe(t,a){let o;typeof t=="function"?o=t:o=this.selectors[t];let c=o(this.state);return a(c,c,this),this.subscribe(d=>{const f=o(d);if(!Object.is(c,f)){const p=c;c=f,a(f,p,this)}})}}const rU={open:e=>e.open,transitionStatus:e=>e.transitionStatus,domReferenceElement:e=>e.domReferenceElement,referenceElement:e=>e.positionReference??e.referenceElement,floatingElement:e=>e.floatingElement,floatingId:e=>e.floatingId};class wy extends tu{constructor(a){const{syncOnly:o,nested:c,onOpenChange:d,triggerElements:f,...p}=a;super({...p,positionReference:p.referenceElement,domReferenceElement:p.referenceElement},{onOpenChange:d,dataRef:{current:{}},events:K1(),nested:c,triggerElements:f},rU);ln(this,"syncOpenEvent",(a,o)=>{(!a||!this.state.open||o!=null&&P4(o))&&(this.context.dataRef.current.openEvent=a?o:void 0)});ln(this,"dispatchOpenChange",(a,o)=>{this.syncOpenEvent(a,o.event);const c={open:a,reason:o.reason,nativeEvent:o.event,nested:this.context.nested,triggerElement:o.trigger};this.context.events.emit("openchange",c)});ln(this,"setOpen",(a,o)=>{if(this.syncOnly){this.context.onOpenChange?.(a,o);return}this.dispatchOpenChange(a,o),this.context.onOpenChange?.(a,o)});this.syncOnly=o}}function aU(e){const{popupStore:t,treatPopupAsFloatingElement:a=!1,floatingRootContext:o,floatingId:c,nested:d,onOpenChange:f}=e,p=t.useState("open"),g=t.useState("activeTriggerElement"),v=t.useState(a?"popupElement":"positionerElement"),y=t.context.triggerElements,b=f,j=x.useRef(null);o===void 0&&j.current===null&&(j.current=new wy({open:p,transitionStatus:void 0,referenceElement:g,floatingElement:v,triggerElements:y,onOpenChange:b,floatingId:c,syncOnly:!0,nested:d}));const w=o??j.current;return t.useSyncedValue("floatingId",c),De(()=>{const S={open:p,floatingId:c,referenceElement:g,floatingElement:v};At(g)&&(S.domReferenceElement=g),w.state.positionReference===w.state.referenceElement&&(S.positionReference=g),w.update(S)},[p,c,g,v,w]),w.context.onOpenChange=b,w.context.nested=d,w}const rf={tabIndex:-1,[_v]:""};function yT(e){return t=>t==="touch"?e.current:!0}function Sy(e,t=!1){const a=$d(),o=Jc()!=null,c=Ms(()=>e(a,o)).current;return aU({popupStore:c,treatPopupAsFloatingElement:t,floatingRootContext:c.state.floatingRootContext,floatingId:a,nested:o,onOpenChange:c.setOpen}),c}function Ny({handle:e,store:t}){return De(()=>e.attachStore(t),[e,t]),null}function jT(e){const t=e.context.triggerElements.size;e.select("open")&&e.state.triggerCount!==t&&e.set("triggerCount",t)}function lU(e,t){const a=x.useRef(null);return Ie(o=>{const c=a.current;if(c!==null){if(c.element===o&&c.store===t&&c.id===e)return;a.current=null;const d=c.store;d.context.triggerElements.getById(c.id)===c.element&&(d.context.triggerElements.delete(c.id),jT(d))}o!==null&&e!==void 0&&(a.current={store:t,id:e,element:o},t.context.triggerElements.add(e,o),jT(t))})}function ky(e,t,a,o=!1){let c=e.preventUnmountingOnClose;t?c=!1:o&&(c=!0);const d=a?.id??null;let f=e.activeTriggerId,p=e.activeTriggerElement;return(d||t)&&(f=d,p=a??null),{open:t,preventUnmountingOnClose:c,activeTriggerId:f,activeTriggerElement:p}}function wT(e){let t=!1;return e.preventUnmountOnClose=()=>{t=!0},()=>t}function oU(e,t,a,o={}){const c=a.reason,d=c===Us,f=t&&c===Wm,p=!t&&(c===mo||c===Xc),g=wT(a);if(e.context.onOpenChange?.(t,a),a.isCanceled)return;o.onBeforeDispatch?.(),e.state.floatingRootContext.dispatchOpenChange(t,a);const v=()=>{const y=ky(e.state,t,a.trigger,g()),b={...o.extraState,...y};f?b.instantType="focus":p?b.instantType="dismiss":d&&(b.instantType=void 0),e.update(b)};d?ks.flushSync(v):v()}function ST(e,t,a,o){const c=a.useState("isMountedByTrigger",e),d=lU(e,a),f=Ie(g=>{const v=a.select("open"),y=a.select("activeTriggerId");if(y===e){const b={activeTriggerElement:g,...v?o:null};a.update(b);return}if(y==null&&v){const b={activeTriggerId:e??null,activeTriggerElement:g,...o};a.update(b)}}),p=Ie(g=>{d(g),g&&f(g)});return De(()=>(p(t.current),()=>p(null)),[p,t,a,e]),De(()=>{if(c){const g={activeTriggerElement:t.current,...o};a.update(g)}},[c,a,t,...Object.values(o)]),{registerTrigger:p,isMountedByThisTrigger:c}}function Cy(e,t={}){const{closeOnActiveTriggerUnmount:a=!1}=t,o=x.useRef(null),c=e.useState("open"),d=e.useState("triggerCount"),f=e.useState("activeTriggerId"),p=e.useState("activeTriggerElement");De(()=>{if(!c){o.current=null,e.state.triggerCount!==0&&e.set("triggerCount",0);return}const g=e.context.triggerElements.size,v={};e.state.triggerCount!==g&&(v.triggerCount=g);const y=e.select("activeTriggerId");let b=null;if(y){const j=e.context.triggerElements.getById(y);if(j)o.current=y,j!==e.state.activeTriggerElement&&(v.activeTriggerElement=j);else{for(const[w,S]of e.context.triggerElements.entries())if(S===e.state.activeTriggerElement){v.activeTriggerId=w,v.activeTriggerElement=S,o.current=w;break}v.activeTriggerId===void 0&&(o.current===y?b=y:o.current=null)}}else o.current=null;if(!b&&!y&&g===1){const j=e.context.triggerElements.entries().next();if(!j.done){const[w,S]=j.value;v.activeTriggerId=w,v.activeTriggerElement=S,o.current=w}}(v.triggerCount!==void 0||v.activeTriggerId!==void 0||v.activeTriggerElement!==void 0)&&e.update(v),b&&a&&queueMicrotask(()=>{if(e.select("open")&&e.select("activeTriggerId")===b&&!e.context.triggerElements.getById(b)){const j=Fe(Yn);e.setOpen(!1,j),j.isCanceled||e.update({activeTriggerId:null,activeTriggerElement:null})}})},[c,e,d,f,p,a])}function Ty(e,t,a,o){const{mounted:c,setMounted:d,transitionStatus:f}=ki(e,!1,!1,o),p=t.useState("preventUnmountingOnClose"),g=e?!1:p;t.useSyncedValues({mounted:c,transitionStatus:f,preventUnmountingOnClose:g});const v=Ie(()=>{d(!1),t.update({activeTriggerId:null,activeTriggerElement:null,mounted:!1,preventUnmountingOnClose:!1}),a?.(),t.context.onOpenChangeComplete?.(!1)});return ra({enabled:c&&!e&&!g,open:e,ref:t.context.popupRef,onComplete(){e||v()}}),{forceUnmount:v,transitionStatus:f}}function Ey(e,t){e.useSyncedValues(t),De(()=>()=>{e.update({activeTriggerProps:fn,inactiveTriggerProps:fn,popupProps:fn})},[e])}function NT(e,t){De(()=>{!t&&e.state.openMethod!==null&&e.set("openMethod",null)},[t,e]),De(()=>()=>{e.state.openMethod!==null&&e.set("openMethod",null)},[e])}class ch{constructor(){this.idMap=new Map}add(t,a){this.idMap.set(t,a)}delete(t){this.idMap.delete(t)}hasElement(t){for(const a of this.idMap.values())if(a===t)return!0;return!1}hasMatchingElement(t){for(const a of this.idMap.values())if(t(a))return!0;return!1}getById(t){return this.idMap.get(t)}entries(){return this.idMap.entries()}elements(){return this.idMap.values()}get size(){return this.idMap.size}}function Ay(e,t,a=!1){return{open:!1,openProp:void 0,mounted:!1,transitionStatus:void 0,floatingRootContext:new wy({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:e,floatingId:t,syncOnly:!0,nested:a,onOpenChange:void 0}),floatingId:t,triggerCount:0,preventUnmountingOnClose:!1,payload:void 0,activeTriggerId:null,activeTriggerElement:null,triggerIdProp:void 0,popupElement:null,positionerElement:null,activeTriggerProps:fn,inactiveTriggerProps:fn,popupProps:fn}}const af=e=>e.triggerIdProp??e.activeTriggerId,Ry=e=>e.openProp??e.open,kT=e=>(e.popupElement?.id??e.floatingId)||void 0;function CT(e,t){return t!==void 0&&Ry(e)&&af(e)===t}function iU(e,t){return CT(e,t)?!0:t!==void 0&&Ry(e)&&af(e)==null&&e.triggerCount===1}const Oy={open:Ry,mounted:e=>e.mounted,transitionStatus:e=>e.transitionStatus,floatingRootContext:e=>e.floatingRootContext,triggerCount:e=>e.triggerCount,preventUnmountingOnClose:e=>e.preventUnmountingOnClose,payload:e=>e.payload,activeTriggerId:af,activeTriggerElement:e=>e.mounted?e.activeTriggerElement:null,popupId:kT,isTriggerActive:(e,t)=>t!==void 0&&af(e)===t,isOpenedByTrigger:(e,t)=>CT(e,t),isMountedByTrigger:(e,t)=>t!==void 0&&af(e)===t&&e.mounted,triggerProps:(e,t)=>t?e.activeTriggerProps:e.inactiveTriggerProps,triggerPopupId:(e,t)=>iU(e,t)?kT(e):void 0,popupProps:e=>e.popupProps,popupElement:e=>e.popupElement,positionerElement:e=>e.positionerElement};function TT(e){const t=x.useCallback(o=>e===void 0?qt:e.subscribeStore(o),[e]),a=x.useCallback(()=>e===void 0?void 0:e.store,[e]);return vy.useSyncExternalStore(t,a,()=>e?.serverStore)}function ET(e){const{open:t=!1,onOpenChange:a,elements:o={}}=e,c=$d(),d=Jc()!=null,f=Ms(()=>new wy({open:t,transitionStatus:void 0,onOpenChange:a,referenceElement:o.reference??null,floatingElement:o.floating??null,triggerElements:new ch,floatingId:c,syncOnly:!1,nested:d})).current;return De(()=>{const p={open:t,floatingId:c};o.reference!==void 0&&(p.referenceElement=o.reference,p.domReferenceElement=At(o.reference)?o.reference:null),o.floating!==void 0&&(p.floatingElement=o.floating),f.update(p)},[t,c,o.reference,o.floating,f]),f.context.onOpenChange=a,f.context.nested=d,f}function cU(e){return uU(e,e.rootContext)}function uU(e,t){const{nodeId:a,externalTree:o}=e,c=t.useState("referenceElement"),d=t.useState("floatingElement"),f=t.useState("domReferenceElement"),p=t.useState("open"),g=t.useState("floatingId"),[v,y]=x.useState(null),[b,j]=x.useState(void 0),[w,S]=x.useState(void 0),N=x.useRef(null),k=Mi(o),E=x.useMemo(()=>({reference:c,floating:d,domReference:f}),[c,d,f]),D=FH({...e,elements:{...E,...v&&{reference:v}}}),C=At(b)?b:null,A=w===void 0?t.state.floatingElement:w;t.useSyncedValue("referenceElement",b??null),t.useSyncedValue("domReferenceElement",b===void 0?f:C),t.useSyncedValue("floatingElement",A);const R=x.useCallback(H=>{const B=At(H)?{getBoundingClientRect:()=>H.getBoundingClientRect(),getClientRects:()=>H.getClientRects(),contextElement:H}:H;y(B),D.refs.setReference(B)},[D.refs]),I=x.useCallback(H=>{(At(H)||H===null)&&(N.current=H,j(H)),(At(D.refs.reference.current)||D.refs.reference.current===null||H!==null&&!At(H))&&D.refs.setReference(H)},[D.refs,j]),P=x.useCallback(H=>{S(H),D.refs.setFloating(H)},[D.refs]),O=x.useMemo(()=>({...D.refs,setReference:I,setFloating:P,setPositionReference:R,domReference:N}),[D.refs,I,P,R]),_=x.useMemo(()=>({...D.elements,domReference:f}),[D.elements,f]),L=x.useMemo(()=>({...D,dataRef:t.context.dataRef,open:p,onOpenChange:t.setOpen,events:t.context.events,floatingId:g,refs:O,elements:_,nodeId:a,rootStore:t}),[D,O,_,a,t,p,g]);return De(()=>{f&&(N.current=f)},[f]),De(()=>{t.context.dataRef.current.floatingContext=L;const H=k?.nodesRef.current.find(B=>B.id===a);H&&(H.context=L)}),x.useMemo(()=>({...D,context:L,refs:O,elements:_,rootStore:t}),[D,O,_,L,t])}const My=GC&&yl;function dU(e,t={}){const{enabled:a=!0,delay:o}=t,c="rootStore"in e?e.rootStore:e,{events:d,dataRef:f}=c.context,p=x.useRef(!1),g=x.useRef(null),v=x.useRef(!0),y=Qs();x.useEffect(()=>{const j=c.select("domReferenceElement");if(!a)return;const w=Sn(j);function S(){const E=c.select("domReferenceElement");!c.select("open")&&dn(E)&&E===or($t(E))&&(p.current=!0,g.current=E)}function N(){v.current=!0}function k(){v.current=!1}return Ka(St(w,"blur",S),My&&St(w,"keydown",N,!0),My&&St(w,"pointerdown",k,!0))},[c,a]),x.useEffect(()=>{if(!a)return;function j(w){if(w.reason===mo||w.reason===Xc){const S=c.select("domReferenceElement");At(S)&&(g.current=S,p.current=!0)}}return d.on("openchange",j),()=>{d.off("openchange",j)}},[d,a,c]);const b=x.useMemo(()=>{function j(){p.current=!1,g.current=null}return{onMouseLeave(){j()},onFocus(w){const S=w.currentTarget;if(p.current){if(g.current===S)return;j()}const N=is(w.nativeEvent);if(At(N)){if(My&&!w.relatedTarget){if(!v.current&&!Um(N))return}else if(!D4(N))return}const k=Hm(w.relatedTarget,c.context.triggerElements),{nativeEvent:E,currentTarget:D}=w,C=typeof o=="function"?o():o;if(c.select("open")&&k||C===0||C===void 0){c.setOpen(!0,Fe(Wm,E,D));return}y.start(C,()=>{p.current||c.setOpen(!0,Fe(Wm,E,D))})},onBlur(w){j();const S=w.relatedTarget,N=w.nativeEvent,k=At(S)&&S.hasAttribute(tf("focus-guard"))&&S.getAttribute("data-type")==="outside";y.start(0,()=>{const E=c.select("domReferenceElement"),D=or($t(E));!S&&D===E||Qe(f.current.floatingContext?.refs.floating.current,D)||Qe(E,D)||k||Hm(S??D,c.context.triggerElements)||c.setOpen(!1,Fe(Wm,N))})}}},[f,o,c,y]);return x.useMemo(()=>a?{reference:b,trigger:b}:{},[a,b])}class Dy{constructor(){ln(this,"dispose",()=>{this.openChangeTimeout.clear(),this.restTimeout.clear()});ln(this,"disposeEffect",()=>this.dispose);this.pointerType=void 0,this.interactedInside=!1,this.handler=void 0,this.blockMouseMove=!0,this.performedPointerEventsMutation=!1,this.pointerEventsScopeElement=null,this.pointerEventsReferenceElement=null,this.pointerEventsFloatingElement=null,this.restTimeoutPending=!1,this.openChangeTimeout=new sa,this.restTimeout=new sa,this.handleCloseOptions=void 0}static create(){return new Dy}}const uh=new WeakMap;function dh(e){if(!e.performedPointerEventsMutation)return;const t=e.pointerEventsScopeElement;t&&uh.get(t)===e&&(e.pointerEventsScopeElement?.style.removeProperty("pointer-events"),e.pointerEventsReferenceElement?.style.removeProperty("pointer-events"),e.pointerEventsFloatingElement?.style.removeProperty("pointer-events"),uh.delete(t)),e.performedPointerEventsMutation=!1,e.pointerEventsScopeElement=null,e.pointerEventsReferenceElement=null,e.pointerEventsFloatingElement=null}function AT(e,t){const{scopeElement:a,referenceElement:o,floatingElement:c}=t,d=uh.get(a);d&&d!==e&&dh(d),dh(e),e.performedPointerEventsMutation=!0,e.pointerEventsScopeElement=a,e.pointerEventsReferenceElement=o,e.pointerEventsFloatingElement=c,uh.set(a,e),a.style.pointerEvents="none",o.style.pointerEvents="auto",c.style.pointerEvents="auto"}function Iy(e){const t=e.context.dataRef.current,a=Ms(()=>t.hoverInteractionState??Dy.create()).current;return t.hoverInteractionState||(t.hoverInteractionState=a),ey(t.hoverInteractionState.disposeEffect),t.hoverInteractionState}function RT(e,t={}){const{enabled:a=!0,closeDelay:o=0,nodeId:c}=t,d="rootStore"in e?e.rootStore:e,f=d.useState("open"),p=d.useState("floatingElement"),g=d.useState("domReferenceElement"),{dataRef:v}=d.context,y=Mi(),b=Jc(),j=Iy(d),w=Qs(),S=Ie(()=>D1(v.current.openEvent?.type,j.interactedInside)),N=Ie(()=>$B(v.current.openEvent?.type)),k=Ie(()=>{dh(j)});De(()=>{f||(j.pointerType=void 0,j.restTimeoutPending=!1,j.interactedInside=!1,k())},[f,j,k]),x.useEffect(()=>k,[k]),De(()=>{if(a&&f&&j.handleCloseOptions?.blockPointerEvents&&N()&&At(g)&&p){const E=g,D=p,C=$t(p),A=y?.nodesRef.current.find(O=>O.id===b)?.context?.elements.floating;A&&(A.style.pointerEvents="");const R=j.pointerEventsScopeElement!==D?j.pointerEventsScopeElement:null,I=A!==D?A:null,P=j.handleCloseOptions?.getScope?.()??R??I??E.closest("[data-rootownerid]")??C.body;return AT(j,{scopeElement:P,referenceElement:E,floatingElement:D}),()=>{k()}}},[a,f,g,p,j,N,y,b,k]),x.useEffect(()=>{if(!a)return;function E(){return!!(y&&b&&io(y.nodesRef.current,b).length>0)}function D(O){const _=Oi(o,"close",j.pointerType),L=()=>{d.setOpen(!1,Fe(Us,O)),y?.events.emit("floating.closed",O)};_?j.openChangeTimeout.start(_,L):(j.openChangeTimeout.clear(),L())}function C(O){const _=is(O);if(!M4(_)){j.interactedInside=!1;return}j.interactedInside=_?.closest("[aria-haspopup]")!=null}function A(){j.openChangeTimeout.clear(),w.clear(),y?.events.off("floating.closed",I),k()}function R(O){if(E()&&y){y.events.on("floating.closed",I);return}if(Hm(O.relatedTarget,d.context.triggerElements))return;const _=v.current.floatingContext?.nodeId??c,L=O.relatedTarget;if(!(y&&_&&At(L)&&io(y.nodesRef.current,_,!1).some(B=>Qe(B.context?.elements.floating,L)))){if(j.handler){j.handler(O);return}k(),N()&&!S()&&D(O)}}function I(O){!y||!b||E()||w.start(0,()=>{y.events.off("floating.closed",I),d.setOpen(!1,Fe(Us,O)),y.events.emit("floating.closed",O)})}const P=p;return Ka(P&&St(P,"mouseenter",A),P&&St(P,"mouseleave",R),P&&St(P,"pointerdown",C,!0),()=>{y?.events.off("floating.closed",I)})},[a,p,d,v,o,c,N,S,k,j,y,b,w])}const fU={current:null};function OT(e,t={}){const{enabled:a=!0,delay:o=0,handleClose:c=null,mouseOnly:d=!1,restMs:f=0,move:p=!0,triggerElementRef:g=fU,externalTree:v,isActiveTrigger:y=!0,getHandleCloseContext:b,isClosing:j,shouldOpen:w,guardStaleOpen:S=!1}=t,N="rootStore"in e?e.rootStore:e,{dataRef:k,events:E}=N.context,D=Mi(v),C=Iy(N),A=x.useRef(!1),R=Xn(c),I=Xn(o),P=Xn(f),O=Xn(a),_=Xn(w),L=Xn(j),H=Ie(()=>D1(k.current.openEvent?.type,C.interactedInside)),B=Ie(()=>_.current?.()!==!1),z=Ie((X,q,$)=>{const Y=N.context.triggerElements;if(Y.hasElement(q))return!X||!Qe(X,q);if(!At($))return!1;const F=$;return Y.hasMatchingElement(G=>Qe(G,F))&&(!X||!Qe(X,F))}),Q=Ie(()=>{if(!C.handler)return;$t(N.select("domReferenceElement")).removeEventListener("mousemove",C.handler),C.handler=void 0}),K=Ie(()=>{dh(C)});return y&&(C.handleCloseOptions=c?.__options),x.useEffect(()=>Q,[Q]),x.useEffect(()=>{if(!a)return;function X(q){q.open?A.current=!1:(A.current=q.reason===Us,Q(),C.openChangeTimeout.clear(),C.restTimeout.clear(),C.blockMouseMove=!0,C.restTimeoutPending=!1)}return E.on("openchange",X),()=>{E.off("openchange",X)}},[a,E,C,Q]),x.useEffect(()=>{if(!a)return;function X(W,le=!0){const M=Oi(I.current,"close",C.pointerType);M?C.openChangeTimeout.start(M,()=>{N.setOpen(!1,Fe(Us,W)),D?.events.emit("floating.closed",W)}):le&&(C.openChangeTimeout.clear(),N.setOpen(!1,Fe(Us,W)),D?.events.emit("floating.closed",W))}const q=g.current??(y?N.select("domReferenceElement"):null);if(!At(q))return;function $(W){if(C.openChangeTimeout.clear(),C.blockMouseMove=!1,d&&!co(C.pointerType))return;const le=M1(P.current),M=Oi(I.current,"open",C.pointerType),U=is(W),Z=W.currentTarget??null,ae=N.select("domReferenceElement");let ce=Z;if(At(U)&&!N.context.triggerElements.hasElement(U)){for(const de of N.context.triggerElements.elements())if(Qe(de,U)){ce=de;break}}At(Z)&&At(ae)&&!N.context.triggerElements.hasElement(Z)&&Qe(Z,ae)&&(ce=ae);const J=ce==null?!1:z(ae,ce,U),ie=N.select("open"),ge=L.current?.()??N.select("transitionStatus")==="ending",ee=!ie&&ge&&A.current,fe=!J&&At(ce)&&At(ae)&&Qe(ae,ce)&&ee,te=le>0&&!M,Ce=J&&(ie||ee)||fe,re=!ie||J;if(Ce){B()&&N.setOpen(!0,Fe(Us,W,ce));return}te||(M?C.openChangeTimeout.start(M,()=>{re&&B()&&N.setOpen(!0,Fe(Us,W,ce))}):re&&B()&&N.setOpen(!0,Fe(Us,W,ce)))}function Y(W){if(H()){K();return}Q();const le=N.select("domReferenceElement"),M=$t(le);C.restTimeout.clear(),C.restTimeoutPending=!1;const U=k.current.floatingContext??b?.();if(Hm(W.relatedTarget,N.context.triggerElements))return;if(R.current&&U){N.select("open")||C.openChangeTimeout.clear();const ae=g.current;C.handler=R.current({...U,tree:D,x:W.clientX,y:W.clientY,onClose(){K(),Q(),O.current&&!H()&&ae===N.select("domReferenceElement")&&X(W,!0)}}),M.addEventListener("mousemove",C.handler),C.handler(W);return}(C.pointerType!=="touch"||!Qe(N.select("floatingElement"),W.relatedTarget))&&X(W)}function F(W){Qe(q,W.relatedTarget)||(C.openChangeTimeout.clear(),C.restTimeout.clear(),C.restTimeoutPending=!1)}const G=S?St(q,"mouseout",F):void 0;return p?Ka(St(q,"mousemove",$,{once:!0}),St(q,"mouseenter",$),St(q,"mouseleave",Y),G):Ka(St(q,"mouseenter",$),St(q,"mouseleave",Y),G)},[Q,K,k,I,N,a,R,C,y,z,H,d,p,P,g,D,O,b,L,B,S]),x.useMemo(()=>{if(!a)return;function X(q){C.pointerType=q.pointerType}return{onPointerDown:X,onPointerEnter:X,onMouseMove(q){const{nativeEvent:$}=q,Y=q.currentTarget,F=N.select("domReferenceElement"),G=N.select("open"),W=z(F,Y,q.target);if(d&&!co(C.pointerType))return;if(G&&W&&C.handleCloseOptions?.blockPointerEvents){const U=N.select("floatingElement");if(U){const Z=C.handleCloseOptions?.getScope?.()??Y.ownerDocument.body;AT(C,{scopeElement:Z,referenceElement:Y,floatingElement:U})}}const le=M1(P.current);if(G&&!W||le===0||!W&&C.restTimeoutPending&&q.movementX**2+q.movementY**2<2)return;C.restTimeout.clear();function M(){if(C.restTimeoutPending=!1,H())return;const U=N.select("open");!C.blockMouseMove&&(!U||W)&&B()&&N.setOpen(!0,Fe(Us,$,Y))}C.pointerType==="touch"?ks.flushSync(()=>{M()}):W&&G?M():(C.restTimeoutPending=!0,C.restTimeout.start(le,M))}}},[a,C,H,z,d,N,P,B])}const pU="Escape";function MT(e){return yl&&e.movementX===0&&e.movementY===0}function fh(e,t,a){switch(e){case"vertical":return t;case"horizontal":return a;default:return t||a}}function ph(e,t){return fh(t,e===Lv||e===Bm,e===wi||e===Si)}function Py(e,t,a){return fh(t,e===Bm,a?e===wi:e===Si)||e==="Enter"||e===" "||e===""}function mU(e,t,a){return fh(t,a?e===wi:e===Si,e===Bm)}function hU(e,t,a,o){const c=a?e===Si:e===wi,d=e===Lv;return t==="both"||t==="horizontal"&&o?e===pU:fh(t,c,d)}function DT(e,t){const{listRef:a,activeIndex:o,onNavigate:c=()=>{},enabled:d=!0,selectedIndex:f=null,allowEscape:p=!1,loopFocus:g=!1,nested:v=!1,rtl:y=!1,virtual:b=!1,focusItemOnOpen:j="auto",focusItemOnHover:w=!0,openOnArrowKeyDown:S=!0,disabledIndices:N=void 0,orientation:k="vertical",parentOrientation:E,id:D,resetOnPointerLeave:C=!0,externalTree:A,grid:R}=t,I=R!=null,P="rootStore"in e?e.rootStore:e,O=P.useState("open"),_=P.useState("floatingElement"),L=P.useState("domReferenceElement"),H=P.context.dataRef,B=Vm(_),z=Fv(L),Q=Xn(B),K=Jc(),X=Mi(A),q=x.useRef(j),$=x.useRef(f??-1),Y=x.useRef(null),F=x.useRef(!0),G=Ie(xe=>{c($.current===-1?null:$.current,xe)}),W=x.useRef(!!_),le=x.useRef(O),M=x.useRef(!1),U=x.useRef(!1),Z=x.useRef(null),ae=Xn(N),ce=Xn(O),J=Xn(f),ie=Xn(C),ge=Kc(),ee=Kc(),fe=Ie(()=>{function xe(_e){b?X?.events.emit("virtualfocus",_e):Z.current=nh(_e,{sync:M.current,preventScroll:!0})}const Te=a.current[$.current],Oe=U.current;Te&&xe(Te),(M.current?_e=>_e():_e=>ge.request(_e))(()=>{const _e=a.current[$.current]||Te;if(!_e)return;Te||xe(_e),Ee&&(Oe||!F.current)&&_e.scrollIntoView?.({block:"nearest",inline:"nearest"})})});De(()=>{H.current.orientation=k},[H,k]),De(()=>{d&&(O&&_?($.current=f??-1,q.current&&f!=null&&(U.current=!0,G())):W.current&&($.current=-1,G()))},[d,O,_,f,G]),De(()=>{if(d){if(!O){M.current=!1;return}if(_)if(o==null){if(M.current=!1,J.current!=null)return;if(W.current&&($.current=-1,fe()),(!le.current||!W.current)&&q.current&&(Y.current!=null||q.current===!0&&Y.current==null)){let xe=0;const Te=()=>{a.current[0]==null?(xe<2&&(xe?Ne=>ee.request(Ne):queueMicrotask)(Te),xe+=1):($.current=Y.current==null||Py(Y.current,k,y)||v?Km(a):Xv(a),Y.current=null,G())};Te()}}else fo(a.current,o)||($.current=o,fe(),U.current=!1)}},[d,O,_,o,J,v,a,k,y,G,fe,ee]),De(()=>{if(!d||_||!X||b||!W.current)return;const xe=X.nodesRef.current,Te=xe.find(_e=>_e.id===K)?.context?.elements.floating,Oe=or($t(L??Te??null)),Ne=xe.some(_e=>_e.context&&Qe(_e.context.elements.floating,Oe));Te&&!Ne&&F.current&&Te.focus({preventScroll:!0})},[d,_,L,X,K,b]),De(()=>{le.current=O,W.current=!!_}),De(()=>{O||(Y.current=null,q.current=j)},[O,j]);const te=o!=null,Ce=Ie(xe=>{if(!ce.current)return;const Te=a.current.indexOf(xe.currentTarget);Te!==-1&&($.current!==Te||o!==Te)&&($.current=Te,G(xe))}),re=Ie(()=>E??X?.nodesRef.current.find(xe=>xe.id===K)?.context?.dataRef?.current.orientation),de=Ie(()=>Km(a,ae.current)),ke=Ie(xe=>{if(F.current=!1,M.current=!0,xe.which===229||!ce.current&&xe.currentTarget===Q.current)return;if(v&&hU(xe.key,k,y,I)){ph(xe.key,re())||Ns(xe),P.setOpen(!1,Fe(sy,xe.nativeEvent)),dn(L)&&(b?X?.events.emit("virtualfocus",L):L.focus());return}const Te=$.current,Oe=Km(a,N),Ne=Xv(a,N);if(z||(xe.key==="Home"&&(Ns(xe),$.current=Oe,G(xe)),xe.key==="End"&&(Ns(xe),$.current=Ne,G(xe))),R!=null){const _e=R(xe,$.current,a,k,g,y,N,Oe,Ne);if(_e!=null&&($.current=_e,G(xe)),k==="both")return}if(ph(xe.key,k)){if(Ns(xe),O&&!b&&or(xe.currentTarget.ownerDocument)===xe.currentTarget){$.current=Py(xe.key,k,y)?Oe:Ne,G(xe);return}Py(xe.key,k,y)?g?Te>=Ne?p&&Te!==a.current.length?$.current=-1:(M.current=!1,$.current=Oe):$.current=Ds(a.current,{startingIndex:Te,disabledIndices:N}):$.current=Math.min(Ne,Ds(a.current,{startingIndex:Te,disabledIndices:N})):g?Te<=Oe?p&&Te!==-1?$.current=a.current.length:(M.current=!1,$.current=Ne):$.current=Ds(a.current,{startingIndex:Te,decrement:!0,disabledIndices:N}):$.current=Math.max(Oe,Ds(a.current,{startingIndex:Te,decrement:!0,disabledIndices:N})),fo(a.current,$.current)&&($.current=-1),G(xe)}}),Ee=x.useMemo(()=>({onFocus(Te){M.current=!0,Ce(Te)},onClick:({currentTarget:Te})=>Te.focus({preventScroll:!0}),onMouseMove(Te){MT(Te)||(M.current=!0,U.current=!1,w&&Ce(Te))},onPointerLeave(Te){if(!ce.current||!F.current||Te.pointerType==="touch")return;M.current=!0;const Oe=Te.relatedTarget;if(!(!w||a.current.includes(Oe))&&ie.current&&(Z.current?.(),Z.current=null,$.current=-1,G(Te),!b)){const Ne=Q.current,_e=or($t(Ne));Ne&&Qe(Ne,_e)&&Ne.focus({preventScroll:!0})}}}),[Ce,ce,Q,w,a,G,ie,b]),ve=x.useMemo(()=>b&&O&&te&&{"aria-activedescendant":`${D}-${o}`},[b,O,te,D,o]),he=x.useMemo(()=>({...z?{}:ve,onKeyDown(xe){if(xe.key==="Tab"&&xe.shiftKey&&O&&!b){const Te=is(xe.nativeEvent);if(Te&&!Qe(Q.current,Te))return;Ns(xe),P.setOpen(!1,Fe(ho,xe.nativeEvent)),dn(L)&&L.focus();return}ke(xe)},onPointerMove(xe){MT(xe)||(F.current=!0)}}),[ve,ke,Q,z,P,O,b,L]),ye=x.useMemo(()=>{function xe(Ne){P.setOpen(!0,Fe(sy,Ne.nativeEvent,Ne.currentTarget))}function Te(Ne){j==="auto"&&Fm(Ne.nativeEvent)&&(q.current=!b)}function Oe(Ne){q.current=j,j==="auto"&&$v(Ne.nativeEvent)&&(q.current=!0)}return{onKeyDown(Ne){const _e=P.select("open");F.current=!1;const Ye=Ne.key.startsWith("Arrow"),kt=mU(Ne.key,re(),y),Ct=ph(Ne.key,k),Rt=(v?kt:Ct)||Ne.key==="Enter"||Ne.key.trim()==="";if(b&&_e)return ke(Ne);if(!(!_e&&!S&&Ye)){if(Rt){const ot=ph(Ne.key,re());Y.current=v&&ot?null:Ne.key}if(v){kt&&(Ns(Ne),_e?($.current=de(),G(Ne)):xe(Ne));return}Ct&&(J.current!=null&&($.current=J.current),Ns(Ne),!_e&&S?xe(Ne):ke(Ne),_e&&G(Ne))}},onFocus(Ne){P.select("open")&&!b&&($.current=-1,G(Ne))},onPointerDown:Oe,onPointerEnter:Oe,onMouseDown:Te,onClick:Te}},[ke,j,de,v,G,P,S,k,re,y,J,b]),we=x.useMemo(()=>({...ve,...ye}),[ve,ye]);return x.useMemo(()=>d?{reference:we,floating:he,item:Ee,trigger:ye}:{},[d,we,he,ye,Ee])}function IT(e,t){const{listRef:a,elementsRef:o,activeIndex:c,onMatch:d,disabledIndices:f,onTyping:p,enabled:g=!0,resetMs:v=750,selectedIndex:y=null}=t,b="rootStore"in e?e.rootStore:e,j=b.useState("open"),w=Qs(),S=x.useRef(""),N=x.useRef(y??c??-1),k=x.useRef(null),E=Ie(A=>{function R(Q){return o?.current[Q]}function I(Q){const K=R(Q);return K&&!Ym(K)||K?.matches(":disabled")?!1:f==null||!po(Rr,Q,f)}function P(Q,K,X=0){if(Q.length===0)return-1;const q=(X%Q.length+Q.length)%Q.length,$=K.toLowerCase();for(let Y=0;Y0&&A.key===" "&&(Ns(A),p?.(!0)),S.current.length>0&&S.current[0]!==" "&&P(O,S.current)===-1&&A.key!==" "&&p?.(!1),O==null||A.key.length!==1||A.ctrlKey||A.metaKey||A.altKey)return;j&&A.key!==" "&&(Ns(A),p?.(!0));const _=S.current==="";_&&(N.current=y??c??-1),O.every((Q,K)=>Q&&I(K)?Q[0]?.toLowerCase()!==Q[1]?.toLowerCase():!0)&&S.current===A.key&&(S.current="",N.current=k.current),S.current+=A.key,w.start(v,()=>{S.current="",N.current=k.current,p?.(!1)});const B=((_?y??c??-1:N.current)??0)+1,z=P(O,S.current,B);z!==-1?(d?.(z),k.current=z):A.key!==" "&&(S.current="",p?.(!1))}),D=Ie(A=>{const R=A.relatedTarget,I=b.select("domReferenceElement"),P=b.select("floatingElement");Qe(I,R)||Qe(P,R)||(w.clear(),S.current="",N.current=k.current,p?.(!1))});De(()=>{!j&&y!==null||(w.clear(),k.current=null,S.current!==""&&(S.current=""))},[j,y,w]);const C=x.useMemo(()=>({onKeyDown:E,onBlur:D}),[E,D]);return x.useMemo(()=>g?{reference:C,floating:C}:{},[g,C])}const PT=.1,gU=PT*PT,bn=.5;function mh(e,t,a,o,c,d){return o>=t!=d>=t&&e<=(c-a)*(t-o)/(d-o)+a}function hh(e,t,a,o,c,d,f,p,g,v){let y=!1;return mh(e,t,a,o,c,d)&&(y=!y),mh(e,t,c,d,f,p)&&(y=!y),mh(e,t,f,p,g,v)&&(y=!y),mh(e,t,g,v,a,o)&&(y=!y),y}function xU(e,t,a){return e>=a.x&&e<=a.x+a.width&&t>=a.y&&t<=a.y+a.height}function gh(e,t,a,o,c,d){const f=Math.min(a,c),p=Math.max(a,c),g=Math.min(o,d),v=Math.max(o,d);return e>=f&&e<=p&&t>=g&&t<=v}function _T(e={}){const{blockPointerEvents:t=!1}=e,a=new sa,o=({x:c,y:d,placement:f,elements:p,onClose:g,nodeId:v,tree:y})=>{const b=f?.split("-")[0];let j=!1,w=null,S=null,N=typeof performance<"u"?performance.now():0;function k(D,C){const A=performance.now(),R=A-N;if(w===null||S===null||R===0)return w=D,S=C,N=A,!1;const I=D-w,P=C-S,O=I*I+P*P,_=R*R*gU;return w=D,S=C,N=A,O<_}function E(){a.clear(),g()}return function(C){a.clear();const A=p.domReference,R=p.floating;if(!A||!R||b==null||c==null||d==null)return;const{clientX:I,clientY:P}=C,O=is(C),_=C.type==="mouseleave",L=Qe(R,O),H=Qe(A,O);if(L&&(j=!0,!_))return;if(H&&(j=!1,!_)){j=!0;return}if(_&&At(C.relatedTarget)&&Qe(R,C.relatedTarget))return;function B(){return!!(y&&io(y.nodesRef.current,v).length>0)}function z(){B()||E()}if(B())return;const Q=A.getBoundingClientRect(),K=R.getBoundingClientRect(),X=c>K.right-K.width/2,q=d>K.bottom-K.height/2,$=K.width>Q.width,Y=K.height>Q.height,F=($?Q:K).left,G=($?Q:K).right,W=(Y?Q:K).top,le=(Y?Q:K).bottom;if(b==="top"&&d>=Q.bottom-1||b==="bottom"&&d<=Q.top+1||b==="left"&&c>=Q.right-1||b==="right"&&c<=Q.left+1){z();return}let M=!1;switch(b){case"top":M=gh(I,P,F,Q.top+1,G,K.bottom-1);break;case"bottom":M=gh(I,P,F,K.top+1,G,Q.bottom-1);break;case"left":M=gh(I,P,K.right-1,le,Q.left+1,W);break;case"right":M=gh(I,P,Q.right-1,le,K.left+1,W);break}if(M)return;if(j&&!xU(I,P,Q)){z();return}if(!_&&k(I,P)){z();return}let U=!1;switch(b){case"top":{const Z=$?bn/2:bn*4,ae=$||X?c+Z:c-Z,ce=$?c-Z:X?c+Z:c-Z,J=d+bn+1,ie=X||$?K.bottom-bn:K.top,ge=X?$?K.bottom-bn:K.top:K.bottom-bn;U=hh(I,P,ae,J,ce,J,K.left,ie,K.right,ge);break}case"bottom":{const Z=$?bn/2:bn*4,ae=$||X?c+Z:c-Z,ce=$?c-Z:X?c+Z:c-Z,J=d-bn,ie=X||$?K.top+bn:K.bottom,ge=X?$?K.top+bn:K.bottom:K.top+bn;U=hh(I,P,ae,J,ce,J,K.left,ie,K.right,ge);break}case"left":{const Z=Y?bn/2:bn*4,ae=Y||q?d+Z:d-Z,ce=Y?d-Z:q?d+Z:d-Z,J=c+bn+1,ie=q||Y?K.right-bn:K.left,ge=q?Y?K.right-bn:K.left:K.right-bn;U=hh(I,P,ie,K.top,ge,K.bottom,J,ae,J,ce);break}case"right":{const Z=Y?bn/2:bn*4,ae=Y||q?d+Z:d-Z,ce=Y?d-Z:q?d+Z:d-Z,J=c-bn,ie=q||Y?K.left+bn:K.right,ge=q?Y?K.left+bn:K.right:K.left+bn;U=hh(I,P,J,ae,J,ce,ie,K.top,ge,K.bottom);break}}U?j||a.start(40,z):z()}};return o.__options={...e,blockPointerEvents:t},o}const bU={...Oy,disabled:e=>e.disabled,instantType:e=>e.instantType,isInstantPhase:e=>e.isInstantPhase,trackCursorAxis:e=>e.trackCursorAxis,disableHoverablePopup:e=>e.disableHoverablePopup,lastOpenChangeReason:e=>e.openChangeReason,closeOnClick:e=>e.closeOnClick,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin};class vU extends tu{constructor(a,o,c){const d=new ch;super(yU(a,d,o,c),jU(d),bU);ln(this,"setOpen",(a,o)=>{oU(this,a,o,{extraState:{openChangeReason:o.reason}})})}cancelPendingOpen(a){this.state.floatingRootContext.dispatchOpenChange(!1,Fe(mo,a))}}function yU(e,t,a,o=!1){return{...Ay(t,a,o),disabled:!1,instantType:void 0,isInstantPhase:!1,trackCursorAxis:"none",disableHoverablePopup:!1,openChangeReason:null,closeOnClick:!0,closeDelay:0,adaptiveOrigin:void 0,...e}}function jU(e){return{popupRef:x.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerElements:e}}const wU=eh(function(t){const{disabled:a=!1,defaultOpen:o=!1,open:c,disableHoverablePopup:d=!1,trackCursorAxis:f="none",actionsRef:p,onOpenChange:g,onOpenChangeComplete:v,handle:y,triggerId:b,defaultTriggerId:j=null,children:w}=t,S=Sy((H,B)=>new vU({open:o,openProp:c,activeTriggerId:j,triggerIdProp:b},H,B));S.useControlledProp("openProp",c),S.useControlledProp("triggerIdProp",b),S.useContextCallback("onOpenChange",g),S.useContextCallback("onOpenChangeComplete",v);const N=S.useState("open"),k=!a&&N,E=S.useState("activeTriggerId"),D=S.useState("mounted"),C=S.useState("payload");S.useSyncedValues({trackCursorAxis:f,disableHoverablePopup:d,disabled:a}),Cy(S,{closeOnActiveTriggerUnmount:!0});const{forceUnmount:A,transitionStatus:R}=Ty(k,S),I=S.useState("isInstantPhase"),P=S.useState("instantType"),O=S.useState("lastOpenChangeReason"),_=x.useRef(null);De(()=>{N&&a&&S.setOpen(!1,Fe(lB))},[N,a,S]),De(()=>{R==="ending"&&O===Yn||R!=="ending"&&I?(P!=="delay"&&(_.current=P),S.set("instantType","delay")):_.current!==null&&(S.set("instantType",_.current),_.current=null)},[R,I,O,P,S]),De(()=>{k&&E==null&&S.set("payload",void 0)},[S,E,k]),x.useImperativeHandle(p,()=>({unmount:A,close:()=>S.setOpen(!1,Fe(ry))}),[A,S]);const L=k||D||!a&&f!=="none";return s.jsxs(O1.Provider,{value:S,children:[y&&s.jsx(Ny,{handle:y,store:S}),L&&s.jsx(SU,{store:S,disabled:a,trackCursorAxis:f}),typeof w=="function"?w({payload:C}):w]})});function SU({store:e,disabled:t,trackCursorAxis:a}){const o=e.useState("floatingRootContext"),c=sf(o,{enabled:!t,referencePress:()=>e.select("closeOnClick")}),d=iH(o,{enabled:!t&&a!=="none",axis:a==="none"?void 0:a}),f=x.useMemo(()=>Wr(d.reference,c.reference),[d.reference,c.reference]);return Ey(e,{activeTriggerProps:f,inactiveTriggerProps:f,popupProps:c.floating??fn}),null}const LT=x.createContext(void 0);function NU(){return x.useContext(LT)}const kU=600,zT="data-base-ui-tooltip-trigger";function BT(e){if("composedPath"in e){const a=e.composedPath();for(let o=0;ok.select("transitionStatus")==="ending",shouldOpen(){return!F.current}}),ae=dU(A,{enabled:!X}).reference,ce=fe=>{const te=F.current,Ce=BT(fe),re=U(Ce),de=R.current,ke=de&&Ce&&Qe(de,Ce);if(re&&k.select("open")&&k.select("lastOpenChangeReason")===Us){k.setOpen(!1,Fe(Us,fe));return}if(te&&!re&&ke&&!q.current&&!k.select("open")&&de&&co(W.current)){const Ee=()=>{!F.current&&!q.current&&!k.select("open")&&k.setOpen(!0,Fe(Us,fe,de))},ve=le();ve===0?(G.clear(),Ee()):G.start(ve,Ee)}},J=k.useState("triggerProps",O);return vt("button",t,{state:{open:C},ref:[a,P,R],props:[Z,ae,O||$!=="none"?J:void 0,{onMouseOver(fe){ce(fe.nativeEvent)},onFocus(fe){M(BT(fe.nativeEvent))&&fe.preventBaseUIHandler()},onMouseLeave(){F.current=!1,G.clear(),W.current=void 0},onPointerEnter(fe){W.current=fe.pointerType},onPointerDown(fe){W.current=fe.pointerType,k.set("closeOnClick",y),y&&!k.select("open")&&k.cancelPendingOpen(fe.nativeEvent)},onClick(fe){y&&!k.select("open")&&k.cancelPendingOpen(fe.nativeEvent)},id:E,[Uv]:X?"":void 0,[zT]:X?void 0:""},w],stateAttributesMapping:zv})}),HT=x.createContext(void 0);function EU(){const e=x.useContext(HT);if(e===void 0)throw new Error(on(70));return e}const AU=x.forwardRef(function(t,a){const{children:o,container:c,className:d,render:f,style:p,...g}=t,{node:v,subtree:y}=G1({container:c,ref:a,componentProps:t,elementProps:g});return!y&&!v?null:s.jsxs(x.Fragment,{children:[y,v&&ks.createPortal(o,v)]})}),RU=x.forwardRef(function(t,a){const{keepMounted:o=!1,...c}=t;return ef().useState("mounted")||o?s.jsx(HT.Provider,{value:o,children:s.jsx(AU,{ref:a,...c})}):null}),UT=x.createContext(void 0);function VT(){const e=x.useContext(UT);if(e===void 0)throw new Error(on(71));return e}const OU=x.createContext(void 0);function lf(){return x.useContext(OU)?.direction??"ltr"}const MU=e=>({name:"arrow",options:e,async fn(t){const{x:a,y:o,placement:c,rects:d,platform:f,elements:p,middlewareData:g}=t,{element:v,padding:y=0,offsetParent:b="real"}=uo(e,t)||{};if(v==null)return{};const j=t1(y),w={x:a,y:o},S=Kv(c),N=Gv(S),k=await f.getDimensions(v),E=S==="y",D=E?"top":"left",C=E?"bottom":"right",A=E?"clientHeight":"clientWidth",R=d.reference[N]+d.reference[S]-w[S]-d.floating[N],I=w[S]-d.reference[S],P=b==="real"?await f.getOffsetParent?.(v):p.floating;let O=p.floating[A]||d.floating[N];(!O||!await f.isElement?.(P))&&(O=p.floating[A]||d.floating[N]);const _=R/2-I/2,L=O/2-k[N]/2-1,H=Math.min(j[D],L),B=Math.min(j[C],L),z=H,Q=O-k[N]-B,K=O/2-k[N]/2+_,X=WC(z,K,Q),q=!g.arrow&&Sl(c)!=null&&K!==X&&d.reference[N]/2-(K{const{name:a,fn:o}=MU(e);return{name:a,fn:o,options:[e,t]}},IU={name:"hide",async fn(e){const{width:t,height:a,x:o,y:c}=e.rects.reference,d=t===0&&a===0&&o===0&&c===0,f=await e.platform.detectOverflow(e,{elementContext:"reference"});return{data:{referenceHidden:f.top-a>=0||f.right-t>=0||f.bottom-a>=0||f.left-t>=0||d}}}},PU={sideX:"left",sideY:"top"},_U="--available-width",LU="--available-height",zU="--anchor-width",BU="--anchor-height",HU="--transform-origin",FT=_U,$T=LU;function qT(e,t,a){const o=e==="inline-start"||e==="inline-end";return{top:"top",right:o?a?"inline-start":"inline-end":"right",bottom:"bottom",left:o?a?"inline-end":"inline-start":"left"}[t]}function GT(e,t,a){const{rects:o,placement:c}=e;return{side:qT(t,ta(c),a),align:Sl(c)||"center",anchor:{width:o.reference.width,height:o.reference.height},positioner:{width:o.floating.width,height:o.floating.height}}}function xh(e){return UU(e,cU)}function UU(e,t){const{anchor:a,positionMethod:o="absolute",side:c="bottom",sideOffset:d=0,align:f="center",alignOffset:p=0,collisionBoundary:g,collisionPadding:v=5,sticky:y=!1,arrowPadding:b=5,disableAnchorTracking:j=!1,inline:w,keepMounted:S=!1,floatingRootContext:N,mounted:k,collisionAvoidance:E,shift:D,nodeId:C,adaptiveOrigin:A,lazyFlip:R=!1,externalTree:I}=e,[P,O]=x.useState(null);!k&&P!==null&&O(null);const _=E.side||"flip",L=E.align||"flip",H=E.fallbackAxisSide||"end",B=D?.crossAxis??!1,z=D?.rootBoundary,Q=typeof a=="function"?a:void 0,K=Ie(Q),X=Q?K:a,q=Xn(a),$=Xn(k),F=lf()==="rtl",G=P||{top:"top",right:"right",bottom:"bottom",left:"left","inline-end":F?"left":"right","inline-start":F?"right":"left"}[c],W=f==="center"?G:`${G}-${f}`;let le=v;typeof le=="number"?le={top:le,right:le,bottom:le,left:le}:le&&(le={top:le.top||0,right:le.right||0,bottom:le.bottom||0,left:le.left||0});const M=1,U=c==="bottom"?M:0,Z=c==="top"?M:0,ae=c==="right"?M:0,ce=c==="left"?M:0,J={boundary:g==="clipping-ancestors"?"clippingAncestors":g,padding:le},ie=x.useRef(null),ge=Xn(d),ee=Xn(p),fe=typeof d!="function"?d:0,te=typeof p!="function"?p:0,Ce=[];w&&Ce.push(w),Ce.push($H(nt=>{const Ot=GT(nt,c,F),Ft=typeof ge.current=="function"?ge.current(Ot):ge.current,Zn=typeof ee.current=="function"?ee.current(Ot):ee.current;return{mainAxis:Ft,crossAxis:Zn,alignmentAxis:Zn}},[fe,te,F,c]));const re=L==="none"&&_!=="shift",de=!re&&(y||B||_==="shift"),ke=_==="none"?null:KH({...J,padding:{top:le.top+M+U,right:le.right+M+ce,bottom:le.bottom+M+Z,left:le.left+M+ae},mainAxis:!B&&_==="flip",crossAxis:L==="flip"?"alignment":!1,fallbackAxisSideDirection:H}),Ee=re?null:qH({...J,rootBoundary:z,mainAxis:L!=="none",crossAxis:de,limiter:y||B?void 0:GH(nt=>{if(!ie.current)return{};const{width:Ot,height:Ft}=ie.current.getBoundingClientRect(),Zn=na(ta(nt.placement)),Hn=Zn==="y"?Ot:Ft,Un=Zn==="y"?le.left+le.right:le.top+le.bottom;return{offset:Hn/2+Un/2}})},[J,y,B,z,le,L]);_==="shift"||L==="shift"||f==="center"?Ce.push(Ee,ke):Ce.push(ke,Ee),Ce.push(YH({...J,apply({elements:{floating:nt},availableWidth:Ot,availableHeight:Ft,rects:Zn}){if(!$.current)return;const Hn=nt.style;Hn.setProperty(FT,`${Ot}px`),Hn.setProperty($T,`${Ft}px`);const Un=Sn(nt).devicePixelRatio||1,{x:Rn,y:Jt,width:as,height:Tt}=Zn.reference,gt=(Math.round((Rn+as)*Un)-Math.round(Rn*Un))/Un,jt=(Math.round((Jt+Tt)*Un)-Math.round(Jt*Un))/Un;Hn.setProperty(zU,`${gt}px`),Hn.setProperty(BU,`${jt}px`)}}),DU(nt=>({element:ie.current||$t(nt.elements.floating).createElement("div"),padding:ie.current?b:0,offsetParent:"floating"}),[b]),{name:"transformOrigin",fn(nt){const{elements:{floating:Ot},middlewareData:Ft,placement:Zn,platform:Hn,rects:Un,y:Rn}=nt,Jt=ta(Zn),as=Sl(Zn),Tt=na(Jt)==="y",gt=ie.current,jt=typeof d=="function"?d(GT(nt,c,F)):d;let wt;if(!gt&&as&&Math.abs(Tt?Ft.shift?.x||0:Ft.shift?.y||0)<=1)wt=as==="start"===(Tt&&Hn.isRTL?.(Ot)===!0)?"100%":"0%";else{const rr=Tt?Ft.arrow?.x||0:Ft.arrow?.y||0,Hr=Tt?gt?.clientWidth||0:gt?.clientHeight||0;wt=`${rr+Hr/2}px`}let Sr=Jt==="top"||Jt==="left"?`calc(100% + ${jt}px)`:`${-jt}px`;return de&&Tt&&Math.abs(Ft.shift?.y||0)>jt&&(Sr=`${Un.reference.y+Un.reference.height/2-Rn}px`),Ot.style.setProperty(HU,Tt?`${wt} ${Sr}`:`${Sr} ${wt}`),{}}},IU,A),De(()=>{!k&&N&&N.update({referenceElement:null,floatingElement:null,domReferenceElement:null,positionReference:null})},[k,N]);const ve=x.useMemo(()=>({ancestorScroll:!j,elementResize:!j&&typeof ResizeObserver<"u",layoutShift:!j&&typeof IntersectionObserver<"u"}),[j]),{refs:he,elements:ye,x:we,y:xe,middlewareData:Te,update:Oe,placement:Ne,context:_e,isPositioned:Ye,floatingStyles:kt}=t({rootContext:N,open:S?k:void 0,placement:W,middleware:Ce,strategy:o,whileElementsMounted:S?void 0:(...nt)=>dT(...nt,ve),nodeId:C,externalTree:I}),{sideX:Ct,sideY:Rt}=Te.adaptiveOrigin||PU,ot=Ye?o:"fixed",qn=x.useMemo(()=>{let nt;return Ye?A?nt={position:ot,[Ct]:we,[Rt]:xe}:nt={...kt,position:ot}:nt={position:ot,top:0,left:0},nt[FT]="100vw",nt[$T]="100vh",Ye||(nt.opacity=0),nt},[A,ot,Ct,we,Rt,xe,kt,Ye]),ds=x.useRef(null);De(()=>{if(!k)return;const nt=q.current,Ot=typeof nt=="function"?nt():nt,Zn=(KT(Ot)?Ot.current:Ot)||null||null;Zn!==ds.current&&(he.setPositionReference(Zn),ds.current=Zn)},[k,he,X,q]),x.useEffect(()=>{if(!k)return;const nt=q.current;typeof nt!="function"&&KT(nt)&&nt.current!==ds.current&&(he.setPositionReference(nt.current),ds.current=nt.current)},[k,he,X,q]),x.useEffect(()=>{if(S&&k&&ye.reference&&ye.floating)return dT(ye.reference,ye.floating,Oe,ve)},[S,k,ye,Oe,ve]);const Gn=ta(Ne),xs=qT(c,Gn,F),it=Sl(Ne)||"center",Vt=!!Te.hide?.referenceHidden;De(()=>{R&&k&&Ye&&Gn!==G&&O(Gn)},[R,k,Ye,Gn,G]);const Bn=x.useMemo(()=>({position:"absolute",top:Te.arrow?.y,left:Te.arrow?.x}),[Te.arrow]),tn=Te.arrow?.centerOffset!==0;return x.useMemo(()=>({positionerStyles:qn,arrowStyles:Bn,arrowRef:ie,arrowUncentered:tn,side:xs,align:it,physicalSide:Gn,anchorHidden:Vt,refs:he,context:_e,isPositioned:Ye,update:Oe}),[qn,Bn,ie,tn,xs,it,Gn,Vt,he,_e,Ye,Oe])}function KT(e){return e!=null&&"current"in e}function of(e){return e==="starting"?WB:fn}function bh(e,t,{styles:a,transitionStatus:o,props:c,refs:d,hidden:f,inert:p=!1}){const g={...a};return p&&(g.pointerEvents="none"),vt("div",e,{state:t,ref:d,props:[{role:"presentation",hidden:f,style:g},of(o),c],stateAttributesMapping:$c})}const VU=x.forwardRef(function(t,a){const{render:o,className:c,anchor:d,positionMethod:f="absolute",side:p="top",align:g="center",sideOffset:v=0,alignOffset:y=0,collisionBoundary:b="clipping-ancestors",collisionPadding:j=5,arrowPadding:w=5,sticky:S=!1,disableAnchorTracking:N=!1,collisionAvoidance:k=F1,style:E,...D}=t,C=ef(),A=EU(),R=C.useState("open"),I=C.useState("mounted"),P=C.useState("trackCursorAxis"),O=C.useState("disableHoverablePopup"),_=C.useState("floatingRootContext"),L=C.useState("instantType"),H=C.useState("transitionStatus"),B=C.useState("adaptiveOrigin"),z=xh({anchor:d,positionMethod:f,floatingRootContext:_,mounted:I,side:p,sideOffset:v,align:g,alignOffset:y,collisionBoundary:b,collisionPadding:j,sticky:S,arrowPadding:w,disableAnchorTracking:N,keepMounted:A,collisionAvoidance:k,adaptiveOrigin:B}),Q=x.useMemo(()=>({open:R,side:z.side,align:z.align,anchorHidden:z.anchorHidden,instant:P!=="none"?"tracking-cursor":L}),[R,z.side,z.align,z.anchorHidden,P,L]),K=bh(t,Q,{styles:z.positionerStyles,transitionStatus:H,props:D,refs:[a,C.useStateSetter("positionerElement")],hidden:!I,inert:!R||P==="both"||O});return s.jsx(UT.Provider,{value:z,children:K})}),FU=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t,p=ef(),{side:g,align:v}=VT(),y=p.useState("open"),b=p.useState("instantType"),j=p.useState("transitionStatus"),w=p.useState("popupProps"),S=p.useState("floatingRootContext"),N=p.useState("disabled"),k=p.useState("closeDelay");ra({open:y,ref:p.context.popupRef,onComplete(){y&&p.context.onOpenChangeComplete?.(!0)}}),RT(S,{enabled:!N,closeDelay:k});const E=p.useStateSetter("popupElement");return vt("div",t,{state:{open:y,side:g,align:v,instant:b,transitionStatus:j},ref:[a,p.context.popupRef,E],props:[rf,w,of(j),f],stateAttributesMapping:Hv})}),$U=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t,p=ef(),{arrowRef:g,side:v,align:y,arrowUncentered:b,arrowStyles:j}=VT(),w=p.useState("open"),S=p.useState("instantType");return vt("div",t,{state:{open:w,side:v,align:y,uncentered:b,instant:S},ref:[a,g],props:[{style:j,"aria-hidden":!0},f],stateAttributesMapping:$c})}),qU=function(t){const{delay:a,closeDelay:o,timeout:c=400}=t,d=x.useMemo(()=>({open:a,close:o}),[a,o]);return s.jsx(LT.Provider,{value:a,children:s.jsx(GB,{delay:d,timeoutMs:c,children:t.children})})};function vh(e){return Av(19)?e:e?"true":void 0}function GU(e){const[t,a]=x.useState({current:e,previous:null});return Object.is(e,t.current)||a({current:e,previous:t.current}),t.previous}function KU(e){return s.jsx(qU,{"data-slot":"tooltip-provider",...e})}function Ii(e){return s.jsx(wU,{"data-slot":"tooltip",...e})}function Pi(e){return s.jsx(TU,{"data-slot":"tooltip-trigger",...e})}function _i({className:e,sideOffset:t=8,side:a="top",children:o,...c}){return s.jsx(RU,{children:s.jsx(VU,{sideOffset:t,side:a,className:"z-[35]",children:s.jsx(FU,{"data-slot":"tooltip-content",className:Ue("max-w-[288px] rounded-md bg-primary px-2.5 py-2 text-[11.5px] leading-[1.55] text-primary-on shadow-3","break-words outline-none","transition-[opacity,transform] duration-150 ease-out","data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95","data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...c,children:o})})})}function YU({className:e,...t}){return s.jsx($U,{className:Ue("size-2 rotate-45 rounded-[1px] bg-primary","data-[side=top]:-bottom-1 data-[side=bottom]:-top-1",e),...t})}const YT=x.createContext(void 0);function nu(e){const t=x.useContext(YT);if(!e&&t===void 0)throw new Error(on(27));return t}const XT=x.forwardRef(function(t,a){const{render:o,className:c,style:d,forceRender:f=!1,...p}=t,g=nu(),v=g.useState("open"),y=g.useState("nested"),b=g.useState("mounted"),j=g.useState("transitionStatus");return vt("div",t,{state:{open:v,transitionStatus:j},ref:[g.context.backdropRef,a],stateAttributesMapping:Hv,props:[{role:"presentation",hidden:!b,style:{userSelect:"none",WebkitUserSelect:"none"}},p],enabled:f||!y})}),QT=x.forwardRef(function(t,a){const{render:o,className:c,style:d,disabled:f=!1,nativeButton:p=!0,...g}=t,v=nu(),y=v.useState("open"),{getButtonProps:b,buttonRef:j}=Jr({disabled:f,native:p}),w={disabled:f};function S(N){y&&v.setOpen(!1,Fe(ny,N.nativeEvent))}return vt("button",t,{state:w,ref:[a,j],props:[{onClick:S},g,b]})}),ZT=x.createContext(void 0);function XU(){const e=x.useContext(ZT);if(e===void 0)throw new Error(on(26));return e}const _y="ArrowUp",Ly="ArrowDown",zy="ArrowLeft",By="ArrowRight",Hy="Home",Uy="End",yh=new Set([_y,Ly,zy,By,Hy,Uy]),WT="Shift",QU=[WT,"Control","Alt","Meta"];function ZU(e){return dn(e)&&e.tagName==="INPUT"}function JT(e){return!!(ZU(e)&&e.selectionStart!=null||dn(e)&&e.tagName==="TEXTAREA")}function eE(e,t,a,o){if(!e||!t||!t.scrollTo)return;let c=e.scrollLeft,d=e.scrollTop;const f=e.clientWidthe.scrollLeft+e.clientWidth-v.scrollPaddingRight?c=g+t.offsetWidth+y.scrollMarginRight-e.clientWidth+v.scrollPaddingRight:g-y.scrollMarginLefte.scrollLeft+e.clientWidth-v.scrollPaddingRight&&(c=g+t.offsetWidth+y.scrollMarginRight-e.clientWidth+v.scrollPaddingRight))}if(p&&o!=="horizontal"){const g=tE(e,t,"top"),v=jh(e),y=jh(t);g-y.scrollMarginTope.scrollTop+e.clientHeight-v.scrollPaddingBottom&&(d=g+t.offsetHeight+y.scrollMarginBottom-e.clientHeight+v.scrollPaddingBottom)}e.scrollTo({left:c,top:d,behavior:"auto"})}function tE(e,t,a){const o=a==="left"?"offsetLeft":"offsetTop";let c=0;for(;t.offsetParent&&(c+=t[o],t.offsetParent!==e);)t=t.offsetParent;return c}function jh(e){const t=getComputedStyle(e);return{scrollMarginTop:parseFloat(t.scrollMarginTop)||0,scrollMarginRight:parseFloat(t.scrollMarginRight)||0,scrollMarginBottom:parseFloat(t.scrollMarginBottom)||0,scrollMarginLeft:parseFloat(t.scrollMarginLeft)||0,scrollPaddingTop:parseFloat(t.scrollPaddingTop)||0,scrollPaddingRight:parseFloat(t.scrollPaddingRight)||0,scrollPaddingBottom:parseFloat(t.scrollPaddingBottom)||0,scrollPaddingLeft:parseFloat(t.scrollPaddingLeft)||0}}const WU="--nested-dialogs",JU="data-nested-dialog-open",eV={...$c,...oo,nestedDialogOpen(e){return e?{[JU]:""}:null}},nE=x.forwardRef(function(t,a){const{render:o,className:c,style:d,finalFocus:f,initialFocus:p,...g}=t,v=nu(),y=v.useState("descriptionElementId"),b=v.useState("disablePointerDismissal"),j=v.useState("floatingRootContext"),w=v.useState("popupProps"),S=v.useState("modal"),N=v.useState("mounted"),k=v.useState("nested"),E=v.useState("nestedOpenDialogCount"),D=v.useState("open"),C=v.useState("openMethod"),A=v.useState("titleElementId"),R=v.useState("transitionStatus"),I=v.useState("role"),P=j.useState("floatingId");XU(),ra({open:D,ref:v.context.popupRef,onComplete(){D&&v.context.onOpenChangeComplete?.(!0)}});const O=p===void 0?yT(v.context.popupRef):p,_=E>0,L=v.useStateSetter("popupElement"),B=vt("div",t,{state:{open:D,nested:k,transitionStatus:R,nestedDialogOpen:_},props:[w,{id:P,"aria-labelledby":A,"aria-describedby":y,role:I,...rf,hidden:!N,onKeyDown(z){yh.has(z.key)&&z.stopPropagation()},style:{[WU]:E}},g],ref:[a,v.context.popupRef,L],stateAttributesMapping:eV});return s.jsx(rh,{context:j,openInteractionType:C,disabled:!N,closeOnFocusOut:!b,initialFocus:O,returnFocus:f,modal:S!==!1,restoreFocus:"popup",children:B})}),wh=x.forwardRef(function(t,a){const{cutout:o,...c}=t;let d;if(o){const f=o.getBoundingClientRect();d=`polygon(0% 0%,100% 0%,100% 100%,0% 100%,0% 0%,${f.left}px ${f.top}px,${f.left}px ${f.bottom}px,${f.right}px ${f.bottom}px,${f.right}px ${f.top}px,${f.left}px ${f.top}px)`}return s.jsx("div",{ref:a,role:"presentation","data-base-ui-inert":"",...c,style:{position:"fixed",inset:0,userSelect:"none",WebkitUserSelect:"none",clipPath:d}})}),sE=x.forwardRef(function(t,a){const{keepMounted:o=!1,...c}=t,d=nu(),f=d.useState("mounted"),p=d.useState("modal"),g=d.useState("open");return f||o?s.jsx(ZT.Provider,{value:o,children:s.jsxs(sh,{ref:a,...c,children:[f&&p===!0&&s.jsx(wh,{ref:d.context.internalBackdropRef,inert:vh(!g)}),t.children]})}):null});let rE={},aE={},lE="";function Sh(e,t){return Ud(e)?e:t}function oE(e,t,a){return/hidden|clip/.test(e.getComputedStyle(Sh(t,a)).overflowY)}function tV(e){if(typeof document>"u")return!1;const t=$t(e);return Sn(t).innerWidth-t.documentElement.clientWidth>0}function nV(e){if(!(typeof CSS<"u"&&CSS.supports&&CSS.supports("scrollbar-gutter","stable"))||typeof document>"u")return!1;const a=$t(e),o=a.documentElement,c=a.body,d=Sh(o,c),f=d.style.overflowY,p=o.style.scrollbarGutter;o.style.scrollbarGutter="stable",d.style.overflowY="scroll";const g=d.offsetWidth;d.style.overflowY="hidden";const v=d.offsetWidth;return d.style.overflowY=f,o.style.scrollbarGutter=p,g===v}function sV(e){const t=$t(e),a=t.documentElement,o=t.body,c=Sh(a,o),d={overflowY:c.style.overflowY,overflowX:c.style.overflowX};return Object.assign(c.style,{overflowY:"hidden",overflowX:"hidden"}),()=>{Object.assign(c.style,d)}}function rV(e){const t=$t(e),a=t.documentElement,o=t.body,c=Sn(a);let d=0,f=0,p=!1;const g=$a.create();if(yl&&(c.visualViewport?.scale??1)!==1)return()=>{};function v(){const w=c.getComputedStyle(a),S=c.getComputedStyle(o),E=(w.scrollbarGutter||"").includes("both-edges")?"stable both-edges":"stable";d=a.scrollTop,f=a.scrollLeft,rE={scrollbarGutter:a.style.scrollbarGutter,overflowY:a.style.overflowY,overflowX:a.style.overflowX},lE=a.style.scrollBehavior,aE={position:o.style.position,height:o.style.height,width:o.style.width,boxSizing:o.style.boxSizing,overflowY:o.style.overflowY,overflowX:o.style.overflowX,scrollBehavior:o.style.scrollBehavior};const D=a.scrollHeight>a.clientHeight,C=a.scrollWidth>a.clientWidth,A=w.overflowY==="scroll"||S.overflowY==="scroll",R=w.overflowX==="scroll"||S.overflowX==="scroll",I=Math.max(0,c.innerWidth-o.clientWidth),P=Math.max(0,c.innerHeight-o.clientHeight),O=parseFloat(S.marginTop)+parseFloat(S.marginBottom),_=parseFloat(S.marginLeft)+parseFloat(S.marginRight),L=Sh(a,o);if(p=nV(e),p){a.style.scrollbarGutter=E,L.style.overflowY="hidden",L.style.overflowX="hidden";return}Object.assign(a.style,{scrollbarGutter:E,overflowY:"hidden",overflowX:"hidden"}),(D||A)&&(a.style.overflowY="scroll"),(C||R)&&(a.style.overflowX="scroll"),Object.assign(o.style,{position:"relative",height:O||P?`calc(100dvh - ${O+P}px)`:"100dvh",width:_||I?`calc(100vw - ${_+I}px)`:"100vw",boxSizing:"border-box",overflowY:"hidden",overflowX:"hidden",scrollBehavior:"unset"}),o.scrollTop=d,o.scrollLeft=f,a.setAttribute("data-base-ui-scroll-locked",""),a.style.scrollBehavior="unset"}function y(){Object.assign(a.style,rE),Object.assign(o.style,aE),p||(a.scrollTop=d,a.scrollLeft=f,a.removeAttribute("data-base-ui-scroll-locked"),a.style.scrollBehavior=lE)}function b(){y(),g.request(v)}v();const j=St(c,"resize",b);return()=>{g.cancel(),y(),typeof c.removeEventListener=="function"&&j()}}class aV{constructor(){ln(this,"lockCount",0);ln(this,"restore",null);ln(this,"timeoutLock",sa.create());ln(this,"timeoutUnlock",sa.create());ln(this,"release",()=>{this.lockCount-=1,this.lockCount===0&&this.restore&&this.timeoutUnlock.start(0,this.unlock)});ln(this,"unlock",()=>{this.lockCount===0&&this.restore&&(this.restore?.(),this.restore=null)})}acquire(t){return this.lockCount+=1,this.lockCount===1&&this.restore===null&&this.timeoutLock.start(0,()=>this.lock(t)),this.release}lock(t){if(this.lockCount===0||this.restore!==null)return;const a=$t(t),o=a.documentElement,c=a.body,d=Sn(o);if(oE(d,o,c)){const p=new d.MutationObserver(()=>{oE(d,o,c)||(p.disconnect(),this.restore=null,this.lock(t))}),g={attributes:!0};p.observe(o,g),p.observe(c,g),this.restore=()=>p.disconnect();return}const f=Gd||!tV(t);this.restore=f?sV(t):rV(t)}}const lV=new aV;function iE(e=!0,t=null){De(()=>{if(e)return lV.acquire(t)},[e,t])}function oV({store:e,parentContext:t,isDrawer:a}){const o=e.useState("open"),c=e.useState("disablePointerDismissal"),d=e.useState("modal"),f=e.useState("popupElement"),p=e.useState("floatingRootContext"),[g,v]=x.useState(0),[y,b]=x.useState(0),j=g===0,w=sf(p,{outsidePressEvent(){return e.context.internalBackdropRef.current||e.context.backdropRef.current?"intentional":{mouse:d==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}},outsidePress(S){if(!e.context.outsidePressEnabledRef.current||"button"in S&&S.button!==0)return!1;if("touches"in S){if(S.type==="touchend"){if(S.changedTouches.length!==1||S.touches.length!==0)return!1}else if(S.touches.length!==1)return!1}const N=is(S);if(j&&!c){if(d){const k=e.context.internalBackdropRef.current,E=e.context.backdropRef.current;return k||E?k===N||E===N||Qe(N,f)&&!N?.hasAttribute("data-base-ui-portal"):!0}return!0}return!1},escapeKey:j});return iE(o&&d===!0,f),e.useContextCallback("onNestedDialogOpen",(S,N)=>{v(S),b(N)}),De(()=>(t?.onNestedDialogOpen&&(o?t.onNestedDialogOpen(g+1,y+(a?1:0)):t.onNestedDialogOpen(0,0)),()=>{t?.onNestedDialogOpen&&o&&t.onNestedDialogOpen(0,0)}),[a,o,g,y,t]),Ey(e,{activeTriggerProps:w.reference,inactiveTriggerProps:w.trigger,popupProps:w.floating,nestedOpenDialogCount:g,nestedOpenDrawerCount:y}),null}const iV={...Oy,modal:e=>e.modal,nested:e=>e.nested,nestedOpenDialogCount:e=>e.nestedOpenDialogCount,nestedOpenDrawerCount:e=>e.nestedOpenDrawerCount,disablePointerDismissal:e=>e.disablePointerDismissal,openMethod:e=>e.openMethod,descriptionElementId:e=>e.descriptionElementId,titleElementId:e=>e.titleElementId,viewportElement:e=>e.viewportElement,role:e=>e.role};class cV extends tu{constructor(a,o,c){const d=new ch,f=uV(a,d,o,c);super(f,dV(d),iV);ln(this,"setOpen",(a,o)=>{o.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},!a&&o.trigger==null&&this.state.activeTriggerId!=null&&(o.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(a,o),!o.isCanceled&&(this.state.floatingRootContext.dispatchOpenChange(a,o),this.update(ky(this.state,a,o.trigger)))})}}function uV(e,t,a,o=!1){return{...Ay(t,a,o),modal:!0,disablePointerDismissal:!1,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:"dialog",...e}}function dV(e){return{popupRef:x.createRef(),backdropRef:x.createRef(),internalBackdropRef:x.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:e,onOpenChange:void 0,onOpenChangeComplete:void 0}}function cE(e,t){const{children:a,open:o,defaultOpen:c=!1,onOpenChange:d,onOpenChangeComplete:f,disablePointerDismissal:p=!1,modal:g=!0,actionsRef:v,handle:y,triggerId:b,defaultTriggerId:j=null}=t,w=e==="drawer",S=e==="alert-dialog",N=S?!0:g,k=S||p,E=S?"alertdialog":"dialog",D=nu(!0),C=D!=null,A={modal:N,disablePointerDismissal:k,nested:C,role:E},R=Sy((H,B)=>new cV({open:c,openProp:o,activeTriggerId:j,triggerIdProp:b,...A},H,B),!0);R.useControlledProp("openProp",o),R.useControlledProp("triggerIdProp",b),R.useSyncedValues(A),R.useContextCallback("onOpenChange",d),R.useContextCallback("onOpenChangeComplete",f);const I=R.useState("open"),P=R.useState("mounted"),O=R.useState("payload");NT(R,I),Cy(R);const{forceUnmount:_}=Ty(I,R);x.useImperativeHandle(v,()=>({unmount:_,close:()=>R.setOpen(!1,Fe(ry))}),[_,R]);const L=I||P;return s.jsxs(YT.Provider,{value:R,children:[y&&s.jsx(Ny,{handle:y,store:R}),L&&s.jsx(oV,{store:R,parentContext:D?.context,isDrawer:w}),typeof a=="function"?a({payload:O}):a]})}const fV=eh(function(t){return cE("dialog",t)}),uE=x.forwardRef(function(t,a){const{render:o,className:c,style:d,id:f,...p}=t,g=nu(),v=Na(f);return g.useSyncedValueWithCleanup("titleElementId",v),vt("h2",t,{ref:a,props:[{id:v},p]})});function pV(e){const t=x.useRef(""),a=x.useCallback(c=>{c.defaultPrevented||(t.current=c.pointerType,e(c,c.pointerType))},[e]);return{onClick:x.useCallback(c=>{if(c.detail===0){e(c,"keyboard");return}"pointerType"in c?e(c,c.pointerType):e(c,t.current),t.current=""},[e]),onPointerDown:a}}function dE(e,t){const a=Ie((d,f)=>{(typeof e=="function"?e():e)||t(f||(Gd?"touch":""))}),{onClick:o,onPointerDown:c}=pV(a);return x.useMemo(()=>({onClick:o,onPointerDown:c}),[o,c])}function fE(e){const[t,a]=x.useState(null),o=dE(e,a);return aa(e,c=>{c&&!e&&a(null)}),x.useMemo(()=>({openMethod:t,triggerProps:o}),[t,o])}function Qt(e){return s.jsx(fV,{"data-slot":"dialog",...e})}function mV(e){return s.jsx(sE,{"data-slot":"dialog-portal",...e})}const Gt=e=>s.jsx(uE,{"data-slot":"dialog-title",...e});function hV({className:e,...t}){return s.jsx(XT,{"data-slot":"dialog-overlay",className:Ue("fixed inset-0 isolate z-30 bg-mask backdrop-blur-[3px]","transition-opacity duration-150","data-open:animate-in data-open:fade-in-0","data-closed:animate-out data-closed:fade-out-0 data-closed:fill-mode-forwards",e),...t})}function Zt({className:e,children:t,showCloseButton:a=!0,keepMounted:o=!1,overlayForceRender:c=!1,...d}){return s.jsxs(mV,{keepMounted:o,children:[s.jsx(hV,{forceRender:c}),s.jsxs(nE,{"data-slot":"dialog-content",className:Ue("fixed top-1/2 left-1/2 z-30 flex max-h-[calc(100vh-48px)] w-[min(620px,calc(100vw-48px))] -translate-x-1/2 -translate-y-1/2 flex-col","overflow-hidden rounded-lg border border-border bg-surface shadow-3 outline-none","transition-[opacity,transform] duration-200 [transition-timing-function:cubic-bezier(.2,.9,.3,1)]","data-open:animate-in data-open:fade-in-0 data-open:zoom-in-[.985] data-open:slide-in-from-bottom-2.5","data-closed:animate-out data-closed:fade-out-0 data-closed:fill-mode-forwards",e),...d,children:[t,a&&s.jsxs(QT,{"data-slot":"dialog-close",render:s.jsx(se,{variant:"ghost",size:"icon-sm",className:"absolute top-3 right-3"}),children:[s.jsx("svg",{viewBox:"0 0 12 12",className:"size-3","aria-hidden":"true",children:s.jsx("path",{d:"M2.5 2.5l7 7M9.5 2.5l-7 7",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",fill:"none"})}),s.jsx("span",{className:"sr-only",children:go("关闭")})]})]})]})}function Kt({className:e,...t}){return s.jsx("div",{"data-slot":"dialog-header",className:Ue("flex items-center gap-2.5 border-b border-hairline px-5 py-[15px] pr-10","[&_h2]:flex-1 [&_h2]:text-[14.5px] [&_h2]:font-semibold",e),...t})}function Bt({className:e,...t}){return s.jsx("div",{"data-slot":"dialog-body",className:Ue("flex flex-col gap-4 overflow-y-auto px-5 py-[18px]",e),...t})}function nn({className:e,...t}){return s.jsx("div",{"data-slot":"dialog-footer",className:Ue("flex items-center gap-2 border-t border-hairline bg-surface-2 px-5 py-[13px]",e),...t})}function Vn({className:e,...t}){return s.jsx("div",{"data-slot":"dialog-section",className:Ue("flex flex-col gap-2.5 rounded-md border border-border bg-surface-inset p-3.5","[&_h3]:text-[12.5px] [&_h3]:font-semibold","[&_p]:text-xs [&_p]:leading-[1.65] [&_p]:text-subtle",e),...t})}function gV(e){return cE("alert-dialog",e)}const xV=gV,bV=sE,vV=e=>s.jsx(uE,{"data-slot":"alert-dialog-title",...e});function yV({className:e,...t}){return s.jsx(XT,{"data-slot":"alert-dialog-overlay",className:Ue("fixed inset-0 isolate z-[38] bg-mask backdrop-blur-[3px]","transition-opacity duration-150","data-open:animate-in data-open:fade-in-0","data-closed:animate-out data-closed:fade-out-0 data-closed:fill-mode-forwards",e),...t})}function jV({className:e,children:t,showCloseButton:a=!1,...o}){return s.jsxs(bV,{children:[s.jsx(yV,{}),s.jsxs(nE,{"data-slot":"alert-dialog-content",className:Ue("fixed top-1/2 left-1/2 z-[38] flex max-h-[calc(100vh-48px)] w-[min(440px,calc(100vw-48px))] -translate-x-1/2 -translate-y-1/2 flex-col","overflow-hidden rounded-lg border border-border bg-surface shadow-3 outline-none","transition-[opacity,transform] duration-200 [transition-timing-function:cubic-bezier(.2,.9,.3,1)]","data-open:animate-in data-open:fade-in-0 data-open:zoom-in-[.985] data-open:slide-in-from-bottom-2.5","data-closed:animate-out data-closed:fade-out-0 data-closed:fill-mode-forwards",e),...o,children:[t,a&&s.jsxs(QT,{"data-slot":"alert-dialog-close",render:s.jsx(se,{variant:"ghost",size:"icon-sm",className:"absolute top-3 right-3"}),children:[s.jsx("svg",{viewBox:"0 0 12 12",className:"size-3","aria-hidden":"true",children:s.jsx("path",{d:"M2.5 2.5l7 7M9.5 2.5l-7 7",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",fill:"none"})}),s.jsx("span",{className:"sr-only",children:go("关闭")})]})]})]})}function wV({className:e,...t}){return s.jsx("div",{"data-slot":"alert-dialog-header",className:Ue("flex items-center gap-2.5 border-b border-hairline px-5 py-[15px]","[&_h2]:flex-1 [&_h2]:text-[14.5px] [&_h2]:font-semibold",e),...t})}function SV({className:e,...t}){return s.jsx("div",{"data-slot":"alert-dialog-body",className:Ue("flex flex-col gap-4 overflow-y-auto px-5 py-[18px]",e),...t})}function NV({className:e,...t}){return s.jsx("div",{"data-slot":"alert-dialog-footer",className:Ue("flex items-center gap-2 border-t border-hairline bg-surface-2 px-5 py-[13px]",e),...t})}function kV({className:e,tone:t="danger",...a}){return s.jsx("div",{"data-slot":"alert-dialog-banner","data-tone":t,className:Ue("rounded-md border px-3.5 py-3 text-xs leading-[1.65] text-subtle","[&_strong]:font-semibold",t==="danger"?"border-destructive-bd bg-destructive-soft [&_strong]:text-destructive":"border-border bg-surface-inset [&_strong]:text-foreground",e),...a})}function Vy({className:e,containerClassName:t,...a}){return s.jsx("div",{"data-slot":"table-container",className:Ue("relative w-full overflow-auto",t),children:s.jsx("table",{"data-slot":"table",className:Ue("w-full caption-bottom border-collapse text-[12.5px]",e),...a})})}function pE({className:e,...t}){return s.jsx("thead",{"data-slot":"table-header",className:Ue(e),...t})}function Fy({className:e,...t}){return s.jsx("tbody",{"data-slot":"table-body",className:Ue(e),...t})}function kl({className:e,...t}){return s.jsx("tr",{"data-slot":"table-row",className:Ue("transition-colors duration-100 hover:[&>td]:bg-control-hover",e),...t})}function mE({className:e,...t}){return s.jsx("th",{"data-slot":"table-head",className:Ue("sticky top-0 z-[2] whitespace-nowrap border-b border-border bg-surface-2 px-3.5 py-2","text-left text-[10.5px] font-semibold tracking-[.05em] text-muted-foreground",e),...t})}function Nn({className:e,...t}){return s.jsx("td",{"data-slot":"table-cell",className:Ue("border-b border-hairline px-3.5 py-2 align-middle",e),...t})}const CV="data-checked",TV="data-unchecked",$y={checked(e){return e?{[CV]:""}:{[TV]:""}},...oo,...ji},qy="data-composite-item-active",hE=x.createContext({register:()=>{},unregister:()=>{},subscribeMapChange:()=>()=>{},nextIndexRef:{current:0}});function EV(){return x.useContext(hE)}function Gy(e={}){const{guess:t,label:a,metadata:o,textRef:c,index:d}=e,{register:f,unregister:p,subscribeMapChange:g,nextIndexRef:v}=EV(),y=x.useRef(-1),[b,j]=x.useState(d==null&&t?()=>{if(y.current===-1){const k=v.current;v.current+=1,y.current=k}return y.current}:-1),w=d??b,S=x.useRef(null),N=x.useCallback(k=>{const E=S.current;E&&p(E),S.current=k,k&&f(k,{metadata:o??null,index:d??null,label:a,textRef:c})},[d,f,p,o,a,c]);return De(()=>{if(d==null)return g(k=>{const E=S.current?k.get(S.current)?.index:null;E!=null&&j(E)})},[d,g]),{ref:N,index:w}}function AV(e={}){const{highlightItemOnHover:t,highlightedIndex:a,onHighlightedIndexChange:o}=fC(),{ref:c,index:d}=Gy(e),f=a===d,p=x.useRef(null),g=ea(c,p);return{compositeProps:{tabIndex:f?0:-1,onFocus(){o(d)},onMouseMove(){const y=p.current;if(!t||!y)return;const b=y.hasAttribute("disabled")||y.ariaDisabled==="true";!f&&!b&&y.focus()}},compositeRef:g,index:d}}function gE(e){const{render:t,className:a,style:o,state:c=fn,props:d=Rr,refs:f=Rr,metadata:p,stateAttributesMapping:g,tag:v="div",...y}=e,{compositeProps:b,compositeRef:j}=AV({metadata:p});return vt(v,e,{state:c,ref:[j,...f],props:[b,...d,y],stateAttributesMapping:g})}const xE=x.createContext(void 0);function RV(){return x.useContext(xE)}function Nh(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}const bE=x.createContext(void 0);function OV(){const e=x.useContext(bE);if(e===void 0)throw new Error(on(52));return e}const vE=x.forwardRef(function(t,a){const{render:o,className:c,disabled:d=!1,readOnly:f=!1,required:p=!1,"aria-labelledby":g,value:v,inputRef:y,nativeButton:b=!1,id:j,style:w,...S}=t,N=RV(),{disabled:k,readOnly:E,required:D,form:C,checkedValue:A,touched:R=!1,validation:I,name:P,setCheckedValue:O=qt,setTouched:_=qt,registerInputRef:L=qt}=N??{},{setTouched:H,setFilled:B,state:z,disabled:Q}=Sa(),K=p1(),{labelId:X,getDescriptionProps:q}=vl(),$=Q||K.disabled||k||d,Y=E||f,F=D||p,G=C,W=N?A===v:v==="",le=x.useRef(null),M=x.useRef(null),U=I?.registerInput,Z=x.useCallback(ye=>U?.(ye,{controlRef:le,value:void 0}),[U]),ae=ea(y,M,L,Z);De(()=>{M.current?.checked&&B(!0)},[B]),De(()=>{if(M.current){if($&&W){L(null);return}L(M.current)}},[W,$,L]);const ce=Na(),J=lo({id:j}),ie=b?void 0:J,ge=Iv(g,X,M,!b,ie),ee={role:"radio","aria-checked":W,"aria-labelledby":ge,[qy]:W?"":void 0,id:b?J:ce,onKeyDown(ye){ye.key==="Enter"&&ye.preventDefault()},onClick(ye){if(ye.defaultPrevented||$||Y)return;ye.preventDefault();const we=M.current;we&&Uc(we,ye)},onFocus(ye){ye.defaultPrevented||$||Y||!R||(M.current?.click(),_(!1))}},{getButtonProps:fe,buttonRef:te}=Jr({disabled:$,native:b,composite:!1}),Ce={type:"radio",ref:ae,form:G,id:ie,name:P,tabIndex:-1,style:P?Zc:Ai,"aria-hidden":!0,...v!==void 0?{value:Nh(v)}:fn,disabled:$,checked:W,required:F,readOnly:Y,onChange(ye){if(ye.nativeEvent.defaultPrevented||$||Y||v===void 0)return;const we=Fe(Yn,ye.nativeEvent);O(v,we),!we.isCanceled&&H(!0)},onClick(ye){ye.stopPropagation()},onFocus(){le.current?.focus()}},re=x.useMemo(()=>({...z,required:F,disabled:$,readOnly:Y,checked:W}),[z,$,Y,W,F]),de=re,ke=N!==void 0,Ee=[a,le,te],ve=[ee,S,fe,q,I?ye=>I.getValidationProps($,ye):fn],he=vt("span",t,{enabled:!ke,state:re,ref:Ee,props:ve,stateAttributesMapping:$y});return s.jsxs(bE.Provider,{value:de,children:[ke?s.jsx(gE,{tag:"span",render:o,className:c,style:w,state:re,refs:Ee,props:ve,stateAttributesMapping:$y}):he,s.jsx("input",{...Ce,suppressHydrationWarning:!0})]})}),MV=x.forwardRef(function(t,a){const{render:o,className:c,style:d,keepMounted:f=!1,...p}=t,g=OV(),v=g.checked,{mounted:y,transitionStatus:b,setMounted:j}=ki(v),w={...g,transitionStatus:b},S=x.useRef(null),N=f||y,k=vt("span",t,{ref:[a,S],state:w,props:p,stateAttributesMapping:$y});return ra({batch:!0,enabled:!v,open:v,ref:S,onComplete(){v||j(!1)}}),N?k:null});function Ky(e){const{children:t,elementsRef:a,labelsRef:o,onMapChange:c}=e,d=Ie(c),[,f]=x.useState(!1),p=Ms(IV).current,g=Ms(DV).current,v=x.useRef(0),y=x.useRef(!0),b=x.useRef(null),j=x.useRef(null),w=Ie(()=>{y.current||(y.current=!0,f(R=>!R))}),S=Ie((R,I)=>{g.set(R,I),w()}),N=Ie(R=>{g.delete(R),w()}),k=Ie(R=>{const I=new Map;return a.current.length=0,o&&(o.current.length=0),R.forEach(P=>{I.set(P.element,{...P.registration.metadata??{},index:P.index}),a.current[P.index]=P.element,o&&(o.current[P.index]=P.registration.label!==void 0?P.registration.label:P.registration.textRef?.current?.textContent??P.element.textContent)}),v.current=a.current.length,I});function E(R){if(j.current?.disconnect(),j.current=null,typeof MutationObserver!="function"||R.length<2)return;const I=new MutationObserver(O=>{if(!LV(O))return;let _=null;for(const L of R)if(L.isConnected){if(_&&yE(_,L)>0){I.disconnect(),w();return}_=L}});j.current=I;const P=new Set;for(let O=1;OI.observe(O,{childList:!0}))}const D=Ie(()=>{const[R,I]=PV(g),P=k(R),O=b.current,_=!O||O.length!==R.length||R.some((L,H)=>{const B=O[H];return L.index!==B.index||L.element!==B.element||L.registration.index!==B.registration.index||L.registration.metadata!==B.registration.metadata});E(I),b.current=R,y.current=!1,_&&(p.forEach(L=>L(P)),d(P))});De(()=>(!y.current&&b.current&&k(b.current),()=>{a.current=[],o&&(o.current=[])}),[a,o,k]),De(()=>{y.current&&D()}),De(()=>()=>{j.current?.disconnect(),y.current=!0},[]);const C=Ie(R=>(p.add(R),()=>{p.delete(R)})),A=x.useMemo(()=>({register:S,unregister:N,subscribeMapChange:C,nextIndexRef:v}),[S,N,C,v]);return s.jsx(hE.Provider,{value:A,children:t})}function DV(){return new Map}function IV(){return new Set}function PV(e){const t=new Set,a=[],o=[];e.forEach((d,f)=>{if(!f.isConnected)return;const p=d.index,g={index:p??-1,element:f,registration:d};p===null?o.push(g):p>=0&&(t.add(p),a.push(g))});let c=0;return o.sort((d,f)=>yE(d.element,f.element)),o.forEach(d=>{for(;t.has(c);)c+=1;d.index=c,a.push(d),c+=1}),t.size>0&&a.sort((d,f)=>d.index-f.index),[a,o.map(d=>d.element)]}function _V(e,t){let a=e.parentElement;for(;a&&!a.contains(t);)a=a.parentElement;return a}function LV(e){for(const t of e)for(let a=0;a{if(A.current=D.current[H]??null,(p??S)(H),B){const z=D.current[H];eE(k.current,z,d,a)}}),P=Ie(H=>{if(H.size===0)return;if(C.current){const K=D.current,X=K.indexOf(A.current);if(X===-1){const q=K[R];!q||po(K,R,b)?I(BV(K,b)):A.current=q}else X!==R&&I(X);return}C.current=!0;const B=Array.from(H.keys()),z=B.find(K=>K?.hasAttribute(qy))??null,Q=z?H.get(z)?.index??-1:-1;if(Q!==-1)I(Q);else if(po(B,R,b)){const K=Ds(B,{disabledIndices:b});fo(B,K)||I(K)}eE(k.current,z,d,a)});De(()=>{if(b==null||f!=null||!C.current)return;const H=D.current;if(po(H,R,b)){const B=Ds(H,{disabledIndices:b});fo(H,B)||I(B)}},[b,f,R,D,I]);const O=Ie((H,B,z)=>c?c(H,B,z,D):z),_=Ie(H=>{const B=H.key===Hy||H.key===Uy;if(!yh.has(H.key)||!v&&B||HV(H,j)||!k.current)return;const Q=d==="rtl",K=Q?zy:By,X=Q?By:zy,q=a==="vertical"?Ly:K,$=a==="vertical"?_y:X,Y=is(H.nativeEvent);if(Y!=null&&JT(Y)&&!jE(Y)){const U=Y.selectionStart,Z=Y.selectionEnd,ae=Y.value;if(U==null||H.shiftKey||U!==Z||H.key!==$&&U0)return}let F=R;const G=Km(D,b),W=Xv(D,b);o!=null&&(F=o({disabledIndices:b,elementsRef:D,event:H,highlightedIndex:R,loopFocus:t,maxIndex:W,minIndex:G,onLoop:O,orientation:a,rtl:Q}));const le=a!=="vertical"&&H.key===K||a!=="horizontal"&&H.key===Ly,M=a!=="vertical"&&H.key===X||a!=="horizontal"&&H.key===_y;v&&(H.key===Hy?F=G:H.key===Uy&&(F=W)),F===R&&(le||M)&&(t&&F===W&&le?(F=G,c&&(F=c(H,R,F,D))):t&&F===G&&M?(F=W,c&&(F=c(H,R,F,D))):F=Ds(D.current,{startingIndex:F,decrement:M,disabledIndices:b})),F!==R&&!fo(D.current,F)&&(y&&H.stopPropagation(),(N||B||le||M)&&H.preventDefault(),I(F,!0),queueMicrotask(()=>{D.current[F]?.focus()}))});return{props:{ref:E,onFocus(H){const B=k.current,z=is(H.nativeEvent);!B||z==null||!JT(z)||z.setSelectionRange(0,z.value.length)},onKeyDown:_},highlightedIndex:R,onHighlightedIndexChange:I,elementsRef:D,onMapChange:P,relayKeyboardEvent:_}}function BV(e,t){let a=-1;for(let o=0;o({highlightedIndex:_,onHighlightedIndexChange:L,highlightItemOnHover:A,relayKeyboardEvent:z}),[_,L,A,z]);return s.jsx(dC.Provider,{value:K,children:s.jsx(Ky,{elementsRef:H,onMapChange:X=>{N?.(X),B(X)},children:Q})})}const VV=[WT],wE=x.forwardRef(function(t,a){const{render:o,className:c,disabled:d,readOnly:f,required:p,onValueChange:g,value:v,defaultValue:y,form:b,name:j,inputRef:w,id:S,style:N,...k}=t,{setTouched:E,setFocused:D,validationMode:C,name:A,disabled:R,state:I,validation:P,setDirty:O,setFilled:_,validityData:L}=Sa(),{labelId:H}=vl(),{clearErrors:B,elementRef:z}=Fc(),Q=o4(!0),K=R||d,X=A??j,q=Na(S),[$,Y]=qa({controlled:v,default:y,name:"RadioGroup",state:"value"}),[F,G]=x.useState(!1),W=Ie((te,Ce)=>{g?.(te,Ce),!Ce.isCanceled&&Y(te)}),le=P.getInputControl,M=x.useMemo(()=>({get current(){return le()}}),[le]),U=x.useRef(null),Z=x.useRef(null);function ae(te){let Ce;return w&&(typeof w=="function"?Ce=w(te):w.current=te),U.current=te,Ce}const ce=Ie(te=>{if(!te||te.disabled)return;Z.current||(Z.current=te);const Ce=U.current,re=te.checked||Ce==null||Ce.disabled?ae(te):void 0;return()=>{Z.current===te&&(Z.current=null),U.current===te?re?(re(),U.current=null):ae(null):re?.()}}),J=Ie(()=>{const te=z.current;if(!te)return $??null;for(const Ce of P.registeredInputs.keys())if(Ce.checked&&eB(Ce,te))return $??null;return null});Yc(M,q,$??null,J,!K,j),aa($,()=>{B(X),O($!==L.initialValue),_($!=null),P.change($);const te=Z.current;$==null&&te&&!te.disabled&&ae(te)});const ie=H??Q?.legendId,ge={...I,disabled:K??!1,required:p??!1,readOnly:f??!1},ee=x.useMemo(()=>({checkedValue:$,disabled:K,form:b,validation:P,name:X,readOnly:f,registerInputRef:ce,required:p,setCheckedValue:W,setTouched:G,touched:F}),[$,K,b,P,X,f,ce,p,W,G,F]),fe={id:S,role:"radiogroup","aria-required":p||void 0,"aria-disabled":K||void 0,"aria-readonly":f||void 0,"aria-labelledby":ie,onFocus(){D(!0)},onBlur(te){Qe(te.currentTarget,te.relatedTarget)||(E(!0),D(!1),C==="onBlur"&&P.commit($))},onKeyDownCapture(te){te.key.startsWith("Arrow")&&(G(!0),D(!0))}};return s.jsx(xE.Provider,{value:ee,children:s.jsx(UV,{render:o,className:c,style:N,state:ge,props:[fe,k,te=>P.getValidationProps(K??!1,te)],refs:[a],stateAttributesMapping:ji,enableHomeAndEndKeys:!1,modifierKeys:VV})})});function kh({className:e,...t}){return s.jsx(wE,{"data-slot":"radio-group",className:Ue("flex flex-col gap-2",e),...t})}function bo({className:e,...t}){return s.jsx(vE,{"data-slot":"radio-group-item",className:Ue("relative inline-flex size-3.5 flex-none cursor-pointer items-center justify-center rounded-full border border-control-border bg-control","outline-none transition-colors duration-150 ease-out","hover:border-control-border-hover","data-checked:border-primary data-checked:bg-primary","focus-visible:shadow-focus","data-disabled:cursor-not-allowed data-disabled:opacity-45",e),...t,children:s.jsx(MV,{"data-slot":"radio-group-indicator",className:"grid place-content-center data-unchecked:hidden",children:s.jsx("span",{className:"block size-[5px] rounded-full bg-primary-foreground"})})})}function SE(e){const t=x.useRef(!0);t.current&&(t.current=!1,e())}const NE=x.createContext(void 0),kE=x.createContext(void 0),CE=x.createContext(void 0);function vo(){const e=x.useContext(NE);if(e===void 0)throw new Error(on(60));return e}function Yy(){const e=x.useContext(kE);if(e===void 0)throw new Error(on(101));return e}function TE(){const e=x.useContext(CE);if(e===void 0)throw new Error(on(61));return e}function FV(e,t,a=Object.is){const{length:o}=e;if(o!==t.length)return!1;for(let c=0;cObject.is(e,t);function la(e,t,a){return e==null||t==null?Object.is(e,t):a(e,t)}function EE(e,t,a){return Array.isArray(e)&&Array.isArray(t)?!FV(e,t,(o,c)=>la(o,c,a)):e!==t}function Th(e,t,a){return e?e.some(o=>o===void 0?!1:la(t,o,a)):!1}function su(e,t,a){return e?e.findIndex(o=>o===void 0?!1:la(o,t,a)):-1}function $V(e,t){if(t!==Ch)return o=>Th(e,o,t);const a=new Set(e);return a.delete(void 0),o=>a.has(o)&&(o!==0||e.some(c=>Object.is(o,c)))}function cf(e,t,a,o){const c=o&&Array.isArray(t)?e.findIndex($V(t,a)):su(e,t,a);return c===-1?null:c}function AE(e,t,a,o,c,d){return Th(o,t,c)?d!=null&&e>d&&Th(o,a[d],c)?d:e:e===d?cf(a,o,c,!0):d}function RE(e,t,a){return e.filter(o=>!la(t,o,a))}function qV(e){return typeof e=="object"&&e!=null&&Array.isArray(e.items)}function Xy(e){return qV(e?.[0])}function Eh(e){return Xy(e)?e.flatMap(t=>t.items):e}function OE(e){if(!Array.isArray(e))return e!=null&&"null"in e;const t=e;if(Xy(t)){for(const a of t)for(const o of a.items)if(o&&o.value==null&&o.label!=null)return!0;return!1}for(const a of t)if(a&&a.value==null&&a.label!=null)return!0;return!1}function yo(e,t){if(t&&e!=null)return t(e)??"";if(e&&typeof e=="object"){if("label"in e&&e.label!=null)return String(e.label);if("value"in e)return String(e.value)}return Nh(e)}function ka(e,t){return t&&e!=null?t(e)??"":e&&typeof e=="object"&&"value"in e&&"label"in e?Nh(e.value):Nh(e)}function ME(e,t,a){function o(){return yo(e,a)}if(a&&e!=null)return a(e);if(e&&typeof e=="object"&&"label"in e&&e.label!=null)return e.label;if(t&&!Array.isArray(t))return(Object.hasOwn(t,e)?t[e]:void 0)??o();if(Array.isArray(t)){const d=Eh(t);if(e==null||typeof e!="object"){const f=d.find(p=>p.value===e);return f&&f.label!=null?f.label:o()}if("value"in e){const f=d.find(p=>p&&p.value===e.value);if(f&&f.label!=null)return f.label}}return o()}function GV(e,t,a){return e.reduce((o,c,d)=>(d>0&&o.push(", "),o.push(s.jsx(x.Fragment,{children:ME(c,t,a)},d)),o),[])}const KV={id:e=>e.id,labelId:e=>e.labelId,modal:e=>e.modal,items:e=>e.items,itemToStringLabel:e=>e.itemToStringLabel,isItemEqualToValue:e=>e.isItemEqualToValue,value:e=>e.value,hasSelectedValue:e=>{const{value:t,multiple:a,itemToStringValue:o}=e;return t==null?!1:a&&Array.isArray(t)?t.length>0:ka(t,o)!==""},hasNullItemLabel:(e,t)=>t?OE(e.items):!1,open:e=>e.open,mounted:e=>e.mounted,forceMount:e=>e.forceMount,transitionStatus:e=>e.transitionStatus,openMethod:e=>e.openMethod,activeIndex:e=>e.activeIndex,selectedIndex:e=>e.selectedIndex,isActive:(e,t)=>e.activeIndex===t,isSelected:(e,t)=>{const a=e.isItemEqualToValue,o=e.value;return e.multiple?Array.isArray(o)&&o.some(c=>la(t,c,a)):la(t,o,a)},isSelectedByFocus:(e,t)=>e.selectedIndex===t,popupProps:e=>e.popupProps,triggerProps:e=>e.triggerProps,triggerElement:e=>e.triggerElement,positionerElement:e=>e.positionerElement,listElement:e=>e.listElement,popupSide:e=>e.popupSide,scrollUpArrowVisible:e=>e.scrollUpArrowVisible,scrollDownArrowVisible:e=>e.scrollDownArrowVisible,hasScrollArrows:e=>e.hasScrollArrows},Cl=1;function DE(e,t){return Math.max(0,e-t)}function YV(e,t){if(t<=0)return 0;const a=Ri(e,0,t),o=a,c=t-a,d=o<=Cl,f=c<=Cl;return d&&f?o<=c?0:t:d?0:f?t:a}function XV(e){const{id:t,value:a,defaultValue:o=null,onValueChange:c,open:d,defaultOpen:f=!1,onOpenChange:p,name:g,form:v,autoComplete:y,disabled:b=!1,readOnly:j=!1,required:w=!1,modal:S=!0,actionsRef:N,inputRef:k,onOpenChangeComplete:E,items:D,multiple:C=!1,itemToStringLabel:A,itemToStringValue:R,isItemEqualToValue:I=Ch,highlightItemOnHover:P=!0,children:O}=e,{clearErrors:_}=Fc(),{setDirty:L,setTouched:H,setFocused:B,validityData:z,setFilled:Q,name:K,disabled:X,validation:q,validationMode:$}=Sa(),Y=lo({id:t}),F=X||b,G=K??g,[W,le]=qa({controlled:a,default:C?o??Rr:o,name:"Select",state:"value"}),[M,U]=qa({controlled:d,default:f,name:"Select",state:"open"}),Z=x.useRef([]),ae=x.useRef([]),ce=x.useRef(null),J=x.useRef(null),ie=x.useRef(0),ge=x.useRef(null),ee=x.useRef([]),fe=x.useRef(!1),te=x.useRef(null),Ce=x.useRef(null),re=x.useRef({allowSelectedMouseUp:!1,allowUnselectedMouseUp:!1,dragY:0}),de=x.useRef(!1),ke=x.useRef(W),{mounted:Ee,setMounted:ve,transitionStatus:he}=ki(M),{openMethod:ye,triggerProps:we}=fE(M),xe=Ms(()=>new tu({id:Y,labelId:void 0,modal:S,multiple:C,itemToStringLabel:A,itemToStringValue:R,isItemEqualToValue:I,value:W,open:M,mounted:Ee,transitionStatus:he,items:D,forceMount:!1,openMethod:null,activeIndex:null,selectedIndex:null,popupProps:fn,triggerProps:fn,triggerElement:null,positionerElement:null,listElement:null,popupSide:null,scrollUpArrowVisible:!1,scrollDownArrowVisible:!1,hasScrollArrows:!1},{setValue:qt,setOpen:qt,handleScrollArrowVisibility:qt,onOpenChangeComplete:qt,listRef:Z,popupRef:ce,scrollHandlerRef:J,scrollArrowsMountedCountRef:ie,valueRef:ge,valuesRef:ee,labelsRef:ae,typingRef:fe,selectionRef:re,firstItemTextRef:te,selectedItemTextRef:Ce,alignItemWithTriggerActiveRef:de,initialValueRef:ke},KV)).current,Te=xe.useState("activeIndex"),Oe=xe.useState("selectedIndex"),Ne=xe.useState("triggerElement"),_e=xe.useState("positionerElement"),Ye=GU(ye),kt=ye??Ye,Ct=x.useMemo(()=>C?"":ka(W,R),[C,W,R]),Rt=x.useMemo(()=>C&&Array.isArray(W)?W.map(gt=>ka(gt,R)):ka(W,R),[C,W,R]),ot=Xn(Ne),qn=Ie(()=>Rt);Yc(ot,Y,W,qn,!F,g);const ds=C?Array.isArray(W)&&W.length>0:W!=null&&Ct!=="";De(()=>{Q(ds)},[ds,Q]),De(function(){const jt=cf(ee.current,W,I,C);jt===null&&(Ce.current=null),!M&&xe.set("selectedIndex",jt)},[C,M,W,I,xe]),aa(W,()=>{_(G),L(EE(W,z.initialValue,I)),q.change(W)});const Gn=Ie((gt,jt)=>{p?.(gt,jt),!jt.isCanceled&&(U(gt),!gt&&(jt.reason===ho||jt.reason===Jm)&&(H(!0),B(!1),$==="onBlur"&&q.commit(W)))}),xs=Ie(()=>{ve(!1),xe.update({activeIndex:null,openMethod:null,scrollUpArrowVisible:!1,scrollDownArrowVisible:!1}),E?.(!1)});ra({enabled:!N,open:M,ref:ce,onComplete(){M||xs()}}),x.useImperativeHandle(N,()=>({unmount:xs}),[xs]);const it=Ie((gt,jt)=>{c?.(gt,jt),!jt.isCanceled&&le(gt)}),Vt=Ie(gt=>{const jt=DE(gt.scrollHeight,gt.clientHeight),wt=YV(gt.scrollTop,jt),Sr=wt>0,rr=wtjE(Z.current[gt]),onMatch(gt){M?xe.set("activeIndex",gt):it(ee.current[gt],Fe(Yn))},onTyping(gt){fe.current=gt}}),Zn=x.useMemo(()=>Wr(Ft.reference,Ot.reference,nt.reference,tn.reference,we),[tn.reference,Ft.reference,Ot.reference,nt.reference,we]),Hn=x.useMemo(()=>Wr(rf,Ft.floating,Ot.floating,nt.floating),[Ft.floating,Ot.floating,nt.floating]),Un=Ot.item??fn;xe.useContextCallback("setValue",it),xe.useContextCallback("setOpen",Gn),xe.useContextCallback("handleScrollArrowVisibility",Vt),xe.useContextCallback("onOpenChangeComplete",E),SE(()=>{xe.update({popupProps:Hn,triggerProps:Zn})}),xe.useSyncedValues({id:Y,modal:S,multiple:C,value:W,open:M,mounted:Ee,transitionStatus:he,popupProps:Hn,triggerProps:Zn,items:D,itemToStringLabel:A,itemToStringValue:R,isItemEqualToValue:I,openMethod:kt});const Rn=x.useMemo(()=>({disabled:F,readOnly:j,required:w,multiple:C,highlightItemOnHover:P,itemProps:Un}),[F,j,w,C,P,Un]),Jt=ea(k,q.inputRef),as=C?void 0:G,Tt=x.useMemo(()=>!C||!Array.isArray(W)||!G?null:W.map(gt=>{const jt=ka(gt,R);return s.jsx("input",{type:"hidden",form:v,name:G,value:jt,disabled:F},jt)}),[C,W,v,G,R,F]);return s.jsxs(NE.Provider,{value:xe,children:[s.jsx(kE.Provider,{value:Rn,children:s.jsx(CE.Provider,{value:Bn,children:O})}),s.jsx("input",{...q.getValidationProps(F,{onFocus(){xe.state.triggerElement?.focus({focusVisible:!0})},onChange(gt){if(gt.nativeEvent.defaultPrevented||F||j)return;const jt=gt.currentTarget.value,wt=Fe(Yn,gt.nativeEvent);function Sr(){if(C)return;const rr=jt.toLowerCase();let Hr=ee.current.findIndex(rl=>ka(rl,R).toLowerCase()===rr||yo(rl,A).toLowerCase()===rr);Hr===-1&&(Hr=ee.current.findIndex((rl,rn)=>{const ic=ae.current[rn];return ic!=null&&ic.toLowerCase()===rr}));const jn=ee.current[Hr];jn!=null&&it(jn,wt)}xe.set("forceMount",!0),queueMicrotask(Sr)}}),id:Y&&as==null?`${Y}-hidden-input`:void 0,form:v,name:as,autoComplete:y,value:Ct,disabled:F,required:w&&!(C&&ds),readOnly:j,ref:Jt,style:G?Zc:Ai,tabIndex:-1,"aria-hidden":!0,suppressHydrationWarning:!0}),Tt]})}function IE(e,t){return e??t}const Ah=5;function PE(e,t){const a=QV(t);return e.clientX>=a.left-Ah&&e.clientX<=a.right+Ah&&e.clientY>=a.top-Ah&&e.clientY<=a.bottom+Ah}function QV(e){const t=e.getBoundingClientRect(),a=Sn(e);if(Pv)return t;const o=a.getComputedStyle(e,"::before"),c=a.getComputedStyle(e,"::after");if(!(o.content!=="none"||c.content!=="none"))return t;const f=parseFloat(o.width)||0,p=parseFloat(o.height)||0,g=parseFloat(c.width)||0,v=parseFloat(c.height)||0,y=Math.max(t.width,f,g),b=Math.max(t.height,p,v),j=y-t.width,w=b-t.height;return{left:t.left-j/2,right:t.right+j/2,top:t.top-w/2,bottom:t.bottom+w/2}}const ZV="data-popup-side",WV=400,JV={...Bv,...ji,popupSide:e=>e?{[ZV]:e}:null,value:()=>null},e6=x.forwardRef(function(t,a){const{render:o,className:c,id:d,disabled:f=!1,nativeButton:p=!0,style:g,...v}=t,{setTouched:y,setFocused:b,validationMode:j,validation:w,state:S,disabled:N}=Sa(),{labelId:k}=vl(),E=vo(),{readOnly:D,required:C,disabled:A}=Yy(),R=N||A||f,I=E.useState("open"),P=E.useState("mounted"),O=E.useState("value"),_=E.useState("triggerProps"),L=E.useState("positionerElement"),H=E.useState("listElement"),B=E.useState("popupSide"),z=E.useState("id"),Q=E.useState("labelId"),K=E.useState("hasSelectedValue"),X=P&&L?B:null,q=d??z,$=IE(k,Q);lo({id:d});const Y=Xn(L),F=x.useRef(null),{getButtonProps:G,buttonRef:W}=Jr({disabled:R,native:p}),le=E.useStateSetter("triggerElement"),M=Qs(),U=Qs(),Z=Qs();x.useEffect(()=>{if(I)return Z.start(WV,()=>{E.context.selectionRef.current.allowUnselectedMouseUp=!0,E.context.selectionRef.current.allowSelectedMouseUp=!0}),()=>{Z.clear()};E.context.selectionRef.current={allowSelectedMouseUp:!1,allowUnselectedMouseUp:!1,dragY:0},U.clear()},[I,E,U,Z]);const ae=Wr(_,{id:q,role:"combobox","aria-expanded":I,"aria-haspopup":"listbox","aria-controls":I?H?.id??Vm(L)?.id:void 0,"aria-labelledby":$,"aria-readonly":D||void 0,"aria-required":C||void 0,tabIndex:R?-1:0,onFocus(ie){b(!0),I&&E.context.alignItemWithTriggerActiveRef.current&&E.context.setOpen(!1,Fe(Yn,ie.nativeEvent)),M.start(0,()=>{E.set("forceMount",!0)})},onBlur(ie){Qe(L,ie.relatedTarget)||(y(!0),b(!1),j==="onBlur"&&w.commit(O))},onMouseDown(ie){if(I)return;const ge=$t(ie.currentTarget);function ee(fe){if(!F.current)return;const te=fe.target;Qe(F.current,te)||Qe(Y.current,te)||PE(fe,F.current)||E.context.setOpen(!1,Fe(y1,fe))}U.start(0,()=>{ge.addEventListener("mouseup",ee,{once:!0})})}},v,G),ce=w.getValidationProps(R,ae);ce.role="combobox";const J={...S,open:I,disabled:R,value:O,readOnly:D,popupSide:X,placeholder:!K};return vt("button",t,{ref:[a,F,W,le],state:J,stateAttributesMapping:JV,props:ce})}),t6={value:()=>null},n6=x.forwardRef(function(t,a){const{className:o,render:c,children:d,placeholder:f,style:p,...g}=t,v=vo(),y=v.useState("value"),b=v.useState("items"),j=v.useState("itemToStringLabel"),w=v.useState("hasSelectedValue"),S=!w&&f!=null&&d==null,N=v.useState("hasNullItemLabel",S),k={value:y,placeholder:!w};let E=null;return typeof d=="function"?E=d(y):d!=null?E=d:S&&!N?E=f:Array.isArray(y)?E=GV(y,b,j):E=ME(y,b,j),vt("span",t,{state:k,ref:[a,v.context.valueRef],props:[{children:E},g],stateAttributesMapping:t6})}),s6=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t,v={open:vo().useState("open")};return vt("span",t,{state:v,ref:a,props:[{"aria-hidden":!0,children:"▼"},f],stateAttributesMapping:zv})}),r6=x.forwardRef(function(t,a){const o=vo(),c=o.useState("mounted"),d=o.useState("forceMount");return c||d?s.jsx(sh,{ref:a,...t}):null}),_E=x.createContext(void 0);function a6(){const e=x.useContext(_E);if(!e)throw new Error(on(59));return e}function Rh(e,t){e&&Object.assign(e.style,t)}const l6={position:"relative",maxHeight:"100%",overflowX:"hidden",overflowY:"auto"},o6=20;function Qy(e,t,a,o){const[c,d]=x.useState(!1);De(()=>{if(!e||!t||a==null){d(!1);return}const f=$t(a).documentElement.clientWidth,p=a.offsetWidth;d(f>0&&p>0&&p>=f-o6)},[e,t,a]),iE(e&&(!t||c),o)}const i6={position:"fixed"},c6=x.forwardRef(function(t,a){const{anchor:o,className:c,render:d,positionMethod:f,side:p,align:g,sideOffset:v,alignOffset:y,collisionBoundary:b="clipping-ancestors",collisionPadding:j,arrowPadding:w,sticky:S,disableAnchorTracking:N,alignItemWithTrigger:k=!0,collisionAvoidance:E=V1,style:D,...C}=t,A=vo(),R=TE(),I=A.useState("open"),P=A.useState("mounted"),O=A.useState("modal"),_=A.useState("value"),L=A.useState("openMethod"),H=A.useState("positionerElement"),B=A.useState("triggerElement"),z=A.useState("isItemEqualToValue"),Q=A.useState("transitionStatus"),K=x.useRef(null),X=x.useRef(null),[q,$]=x.useState(k),Y=P&&q&&L!=="touch";!P&&q!==k&&$(k),x.useImperativeHandle(A.context.alignItemWithTriggerActiveRef,()=>Y),Qy((Y||O)&&I,L==="touch",H,B);const F=xh({anchor:o,floatingRootContext:R,positionMethod:f,mounted:P,side:p,sideOffset:v,align:g,alignOffset:y,arrowPadding:w,collisionBoundary:b,collisionPadding:j,sticky:S,disableAnchorTracking:N??Y,collisionAvoidance:E,keepMounted:!0}),G=Y?"none":F.side,W=Y?i6:F.positionerStyles,le={open:I,side:G,align:F.align,anchorHidden:F.anchorHidden};De(()=>{A.set("popupSide",F.side)},[A,F.side]);const M=A.useStateSetter("positionerElement"),U=bh(t,le,{styles:W,transitionStatus:Q,props:C,refs:[a,M],hidden:!P,inert:!I}),Z=x.useRef(0),ae=Ie(J=>{if(A.context.valuesRef.current.length===0)return;const ie=Z.current;Z.current=J.size;const ge=Fe(Yn);if(ie!==0&&!A.state.multiple&&_!==null&&su(A.context.valuesRef.current,_,z)===-1){const fe=A.context.initialValueRef.current,Ce=fe!=null&&su(A.context.valuesRef.current,fe,z)!==-1?fe:null;A.context.setValue(Ce,ge),Ce===null&&(A.set("selectedIndex",null),A.context.selectedItemTextRef.current=null)}if(ie!==0&&A.state.multiple&&Array.isArray(_)){const ee=_.filter(fe=>su(A.context.valuesRef.current,fe,z)!==-1);ee.length!==_.length&&(A.context.setValue(ee,ge),ee.length===0&&(A.set("selectedIndex",null),A.context.selectedItemTextRef.current=null))}if(I&&Y){A.update({scrollUpArrowVisible:!1,scrollDownArrowVisible:!1});const ee={height:""};Rh(H,ee),Rh(A.context.popupRef.current,ee)}}),ce=x.useMemo(()=>({...F,side:G,alignItemWithTriggerActive:Y,setControlledAlignItemWithTrigger:$,scrollUpArrowRef:K,scrollDownArrowRef:X}),[F,G,Y,$]);return s.jsx(Ky,{elementsRef:A.context.listRef,labelsRef:A.context.labelsRef,onMapChange:ae,children:s.jsxs(_E.Provider,{value:ce,children:[P&&O&&s.jsx(wh,{inert:vh(!I),cutout:B}),U]})})}),Oh="base-ui-disable-scrollbar",LE={className:Oh,getElement(e){return s.jsx("style",{nonce:e,href:Oh,precedence:"base-ui:low",children:`.${Oh}{scrollbar-width:none}.${Oh}::-webkit-scrollbar{display:none}`})}},u6=x.createContext(void 0);function zE(e){return x.useContext(u6)}const d6=x.createContext(void 0),f6={disableStyleElements:!1};function p6(){return x.useContext(d6)??f6}const BE="--transform-origin",m6={...$c,...oo},h6=x.forwardRef(function(t,a){const{render:o,className:c,style:d,finalFocus:f,...p}=t,g=vo(),{multiple:v,readOnly:y,highlightItemOnHover:b}=Yy(),j=TE(),{side:w,align:S,alignItemWithTriggerActive:N,isPositioned:k,setControlledAlignItemWithTrigger:E}=a6(),D=zE()!=null,C=lf(),{nonce:A,disableStyleElements:R}=p6(),I=g.useState("id"),P=g.useState("open"),O=g.useState("openMethod"),_=g.useState("mounted"),L=g.useState("popupProps"),H=g.useState("transitionStatus"),B=g.useState("triggerElement"),z=g.useState("positionerElement"),Q=g.useState("listElement"),K=x.useRef(!1),X=x.useRef(!1),q=x.useRef({}),$=Kc(),Y=Ie(le=>{if(!z||!g.context.popupRef.current||!X.current)return;const M=z.style.top==="0px",U=z.style.bottom==="0px";if(K.current||!N||!M&&!U){g.context.handleScrollArrowVisibility(le);return}const Z=UE(z),ae=uf(z.getBoundingClientRect().height,"y",Z),ce=$t(z),J=Sn(z),ie=J.getComputedStyle(z),ge=parseFloat(ie.marginTop),ee=parseFloat(ie.marginBottom),fe=HE(J.getComputedStyle(g.context.popupRef.current)),te=Math.min(ce.documentElement.clientHeight-ge-ee,fe),Ce=le.scrollTop,re=Mh(le);let de=null;const ke=ye=>{z.style.height=`${ye}px`},Ee=M?re-Ce:Ce,ve=Math.min(ae+Ee,te);if(Ee<=Cl){const ye=Ri(Ee,0,te-ae);ye>0&&ke(ae+ye),le.scrollTop=M?re:0,te-(ae+ye)<=Cl&&(K.current=!0),g.context.handleScrollArrowVisibility(le);return}if(te-ve>Cl)de=M?1/0:0;else if(U&&CeCl&&(le.scrollTop=ye)}he>=te-Cl&&(K.current=!0),g.context.handleScrollArrowVisibility(le)});x.useImperativeHandle(g.context.scrollHandlerRef,()=>Y,[Y]),ra({open:P,ref:g.context.popupRef,onComplete(){P&&g.context.onOpenChangeComplete(!0)}});const F={open:P,transitionStatus:H,side:w,align:S};De(()=>{!z||!g.context.popupRef.current||Object.keys(q.current).length||(q.current={top:z.style.top||"0",left:z.style.left||"0",right:z.style.right,height:z.style.height,bottom:z.style.bottom,minHeight:z.style.minHeight,maxHeight:z.style.maxHeight,marginTop:z.style.marginTop,marginBottom:z.style.marginBottom})},[g,z]),De(()=>{P||N||(X.current=!1,K.current=!1,Rh(z,q.current))},[P,N,z]),De(()=>{const le=g.context.popupRef.current;if(!P||!B||!z||!le||N&&!k||g.state.transitionStatus==="ending")return;if(X.current=!0,le.style.removeProperty(BE),!N){$.request(()=>g.context.handleScrollArrowVisibility(Q||le));return}const M=g6(le);try{let U=g.context.selectedItemTextRef.current;U?.isConnected||(U=!g.select("hasSelectedValue")&&g.context.firstItemTextRef.current?.isConnected?g.context.firstItemTextRef.current:null);const Z=g.context.valueRef.current,ae=Sn(z),ce=ae.getComputedStyle(z),J=ae.getComputedStyle(le),ie=$t(B),ge=UE(B),ee=Dh(B.getBoundingClientRect(),ge),fe=Dh(z.getBoundingClientRect(),ge),te=ee.height,Ce=Q||le,re=Ce.scrollHeight,de=parseFloat(J.borderBottomWidth),ke=parseFloat(ce.marginTop)||10,Ee=parseFloat(ce.marginBottom)||10,ve=parseFloat(ce.minHeight)||100,he=HE(J),ye=5,we=5,xe=20,Te=ie.documentElement.clientHeight-ke-Ee,Oe=ie.documentElement.clientWidth,Ne=Te-ee.bottom+te;let _e,Ye=C==="rtl"?ee.right-fe.width:ee.left,kt=0;if(U&&Z){const tn=Dh(Z.getBoundingClientRect(),ge);_e=Dh(U.getBoundingClientRect(),ge),Ye=fe.left+(C==="rtl"?tn.right-_e.right:tn.left-_e.left);const nt=tn.top-ee.top+tn.height/2;kt=_e.top-fe.top+_e.height/2-nt}const Ct=Ne+kt+Ee+de;let Rt=Math.min(Te,Ct);const ot=Te-ke-Ee,qn=Ct-Rt,ds=Oe-we;z.style.left=`${Ri(Ye,ye,ds-fe.width)}px`,z.style.height=`${Rt}px`,z.style.maxHeight="none",z.style.marginTop=`${ke}px`,z.style.marginBottom=`${Ee}px`,le.style.height="100%";const Gn=Mh(Ce),xs=qn>=Gn-Cl;xs&&(Rt=Math.min(Te,fe.height)-(qn-Gn));const it=ee.topTe-xe||Math.ceil(Rt)+Cl=ot?"0":`${tn}px`,z.style.height=`${Rt}px`,Ce.scrollTop=Mh(Ce)}else z.style.bottom="0",Ce.scrollTop=qn;if(_e){const tn=fe.top,nt=fe.height,Ot=_e.top+_e.height/2,Ft=Ri(nt>0?(Ot-tn)/nt*100:50,0,100);le.style.setProperty(BE,`50% ${Ft}%`)}(Bn===Te||Rt>=he)&&(K.current=!0),g.context.handleScrollArrowVisibility(Ce),b&&g.state.selectedIndex===null&&g.state.activeIndex===null&&g.context.listRef.current[0]!=null&&g.set("activeIndex",0)}finally{M()}},[g,P,z,B,N,E,$,Q,b,C,k]),x.useEffect(()=>{if(!N||!z||!P)return;const le=Sn(z);function M(U){g.context.setOpen(!1,Fe(oB,U))}return St(le,"resize",M)},[g,N,z,P]);const G={...Q?{role:"presentation"}:{role:"listbox","aria-multiselectable":v||void 0,"aria-readonly":y||void 0,id:`${I}-list`},onKeyDown(le){D&&yh.has(le.key)&&le.stopPropagation()},onScroll(le){Q||Y(le.currentTarget)},...N&&{style:Q?{height:"100%"}:l6},className:!Q&&N?LE.className:void 0},W=vt("div",t,{ref:[a,g.context.popupRef],state:F,stateAttributesMapping:m6,props:[L,G,of(H),p]});return s.jsxs(x.Fragment,{children:[!R&&LE.getElement(A),s.jsx(rh,{context:j,modal:!1,disabled:!_,openInteractionType:O,returnFocus:f,restoreFocus:!0,children:W})]})});function HE(e){const t=e.maxHeight;return t.endsWith("px")&&parseFloat(t)||1/0}function Mh(e){return DE(e.scrollHeight,e.clientHeight)}function UE(e){return cT.getScale(e)}function uf(e,t,a){return e/a[t]}function Dh(e,t){return Kd({x:uf(e.x,"x",t),y:uf(e.y,"y",t),width:uf(e.width,"x",t),height:uf(e.height,"y",t)})}const VE=[["transform","none"],["scale","1"],["translate","0 0"]];function g6(e){const{style:t}=e,a={};for(const[o,c]of VE)a[o]=t.getPropertyValue(o),t.setProperty(o,c,"important");return()=>{for(const[o]of VE){const c=a[o];c?t.setProperty(o,c):t.removeProperty(o)}}}const FE=x.createContext(void 0);function Zy(){const e=x.useContext(FE);if(!e)throw new Error(on(57));return e}const x6=x.memo(x.forwardRef(function(t,a){const{render:o,className:c,style:d,value:f=null,label:p,disabled:g=!1,nativeButton:v=!1,...y}=t,b=x.useRef(null),j=Gy({guess:!0,label:p,textRef:b}),w=vo(),{itemProps:S,multiple:N,disabled:k,readOnly:E}=Yy(),D=k||g,C=w.useState("isActive",j.index),A=w.useState("open"),R=w.useState("isSelected",f),I=w.useState("isSelectedByFocus",j.index),P=w.useState("isItemEqualToValue"),O=j.index,_=x.useRef(null);De(()=>{const F=w.context.valuesRef.current;return F[O]=f,()=>{delete F[O]}},[O,f,w]),De(()=>{const F=w.state.value,G=w.state.selectedIndex;let W=G,le;N&&Array.isArray(F)?(W=AE(O,f,w.context.valuesRef.current,F,P,G),le=W===O,O===G&&!le&&(w.context.selectedItemTextRef.current=null)):(le=F!==void 0&&la(f,F,P),le&&(W=O)),w.set("selectedIndex",W),le&&b.current&&(w.context.selectedItemTextRef.current=b.current)},[O,N,P,w,f]);const L=x.useRef("mouse"),H=x.useRef(!1),{getButtonProps:B,buttonRef:z}=Jr({disabled:D,focusableWhenDisabled:!0,native:v,composite:!0}),Q={disabled:D,selected:R,highlighted:C};function K(F){if(k||E)return;const G=w.state.value;if(N){const W=Array.isArray(G)?G:[],le=R?RE(W,f,P):[...W,f];w.context.setValue(le,Fe(Qd,F))}else w.context.setValue(f,Fe(Qd,F)),w.context.setOpen(!1,Fe(Qd,F))}function X(){w.context.selectionRef.current.dragY=0}const q={role:"option","aria-selected":R,tabIndex:A&&C?0:-1,onKeyDown(F){w.set("activeIndex",O),F.key===" "&&w.context.typingRef.current&&F.preventDefault()},onClick(F){const G=L.current!=="touch",W=F.nativeEvent.pointerType,le=G&&Fm(F.nativeEvent)&&(W!==void 0||C),M=G&&!le&&!H.current;H.current=!1,!(D||M)&&K(F.nativeEvent)},onPointerEnter(F){L.current=F.pointerType},onPointerMove(F){if(F.pointerType==="mouse"&&F.buttons===1){const G=w.context.selectionRef.current;G.dragY+=F.movementY,G.dragY**2>=64&&(G.allowUnselectedMouseUp=!0)}},onPointerDown(F){L.current=F.pointerType,H.current=!0,X()},onMouseUp(){if(X(),D||L.current==="touch"||H.current)return;const F=!w.context.selectionRef.current.allowSelectedMouseUp&&R,G=!w.context.selectionRef.current.allowUnselectedMouseUp&&!R;F||G||(H.current=!0,_.current?.click(),H.current=!1)}},$=vt("div",t,{ref:[z,a,j.ref,_],state:Q,props:[S,q,y,B]}),Y=x.useMemo(()=>({selected:R,index:O,textRef:b,selectedByFocus:I}),[R,O,b,I]);return s.jsx(FE.Provider,{value:Y,children:$})})),b6=x.forwardRef(function(t,a){const{selected:o}=Zy();return t.keepMounted||o?s.jsx(v6,{...t,ref:a}):null}),v6=x.memo(x.forwardRef((e,t)=>{const{render:a,className:o,style:c,keepMounted:d,...f}=e,{selected:p}=Zy(),g=x.useRef(null),{transitionStatus:v,setMounted:y}=ki(p),j=vt("span",e,{ref:[t,g],state:{selected:p,transitionStatus:v},props:[{"aria-hidden":!0,children:"✔️"},f],stateAttributesMapping:oo});return ra({batch:!0,enabled:!p,open:p,ref:g,onComplete(){p||y(!1)}}),j})),y6=x.memo(x.forwardRef(function(t,a){const{index:o,textRef:c,selectedByFocus:d}=Zy(),f=vo(),{render:p,className:g,style:v,...y}=t,b=x.useCallback(w=>{w&&(o===0&&(f.context.firstItemTextRef.current=w),d&&(f.context.selectedItemTextRef.current=w))},[f,o,d]);return vt("div",t,{ref:[b,a,c],props:y})})),ft=XV,pt=n6;function mt({className:e,children:t,...a}){return s.jsxs(e6,{"data-slot":"select-trigger",className:Ue("inline-flex h-[30px] min-w-0 cursor-pointer items-center justify-between gap-1.5 rounded-md border border-control-border bg-control px-2.5","[&>span]:min-w-0 [&>span]:truncate","text-[12.5px] font-normal text-foreground","transition-colors duration-150 ease-out","hover:border-control-border-hover hover:bg-control-hover","focus-visible:border-primary focus-visible:shadow-focus focus-visible:outline-none","data-disabled:cursor-not-allowed data-disabled:bg-control data-disabled:text-muted-foreground data-disabled:opacity-60",e),...a,children:[t,s.jsx(s6,{className:"flex flex-none text-muted-foreground transition-transform duration-[180ms] data-popup-open:rotate-180",children:s.jsx("svg",{viewBox:"0 0 10 6",className:"size-2.5","aria-hidden":"true",children:s.jsx("path",{d:"M1 1l4 4 4-4",stroke:"currentColor",strokeWidth:"1.4",fill:"none",strokeLinecap:"round",strokeLinejoin:"round"})})})]})}function ht({className:e,sideOffset:t=4,children:a,...o}){return s.jsx(r6,{children:s.jsx(c6,{sideOffset:t,alignItemWithTrigger:!1,className:"z-[35]",children:s.jsx(h6,{"data-slot":"select-content",className:Ue("max-h-[260px] min-w-[var(--anchor-width)] overflow-y-auto overscroll-contain rounded-lg border border-border-strong bg-raised p-[5px] shadow-3","outline-none","data-open:animate-in data-open:fade-in-0","data-closed:animate-out data-closed:fade-out-0",e),...o,children:a})})})}function qe({className:e,children:t,...a}){return s.jsxs(x6,{"data-slot":"select-item",className:Ue("flex min-h-7 cursor-pointer items-center gap-2 rounded-sm px-[9px] text-[12.5px] leading-[1.4] text-foreground select-none","transition-colors duration-[120ms] ease-out","data-[highlighted]:bg-nav-hover","data-[selected]:bg-primary-soft data-[selected]:font-semibold data-[selected]:text-primary-fg","data-[highlighted]:data-[selected]:bg-primary-tint","data-disabled:pointer-events-none data-disabled:font-normal data-disabled:text-muted-foreground",e),...a,children:[s.jsx(y6,{className:"min-w-0 flex-1 truncate",children:t}),s.jsx(b6,{className:"flex flex-none text-primary",children:s.jsx("svg",{viewBox:"0 0 12 12",className:"size-3","aria-hidden":"true",children:s.jsx("path",{d:"M2.5 6.2 4.8 8.5 9.5 3.8",stroke:"currentColor",strokeWidth:"1.8",fill:"none",strokeLinecap:"round",strokeLinejoin:"round"})})})]})}function In({options:e,value:t,onValueChange:a,disabled:o=!1,className:c,...d}){const f=x.useRef(null),p=x.useRef(new Map),[g,v]=x.useState({left:0,width:0,ready:!1}),[y,b]=x.useState(!1),j=x.useCallback(()=>{const w=f.current,S=p.current.get(t);if(!w||!S){v(C=>C.ready?{...C,ready:!1}:C);return}const N=w.getBoundingClientRect(),k=S.getBoundingClientRect(),E=k.left-N.left-w.clientLeft,D=k.width;v(C=>C.ready&&C.left===E&&C.width===D?C:{left:E,width:D,ready:!0})},[t]);return x.useLayoutEffect(()=>{j();const w=f.current;if(!w||typeof ResizeObserver>"u")return;const S=new ResizeObserver(()=>j());S.observe(w);for(const N of p.current.values())S.observe(N);return()=>S.disconnect()},[j,e]),x.useEffect(()=>{if(!g.ready||y)return;const w=requestAnimationFrame(()=>b(!0));return()=>cancelAnimationFrame(w)},[g.ready,y]),s.jsxs(wE,{ref:f,"data-slot":"segmented-control",className:Ue("relative inline-flex gap-0.5 rounded-md border border-control-border bg-control p-0.5",c),value:t,disabled:o,onValueChange:w=>a(w),...d,children:[s.jsx("span",{"aria-hidden":"true","data-slot":"segmented-thumb","data-ready":g.ready?"true":"false","data-animate":y?"true":"false",className:Ue("pointer-events-none absolute top-0.5 bottom-0.5 left-0 rounded-sm bg-primary-soft","data-[ready=false]:opacity-0","data-[animate=true]:transition-[transform,width] data-[animate=true]:duration-200 data-[animate=true]:ease-in-out"),style:{transform:`translateX(${g.left}px)`,width:g.width}}),e.map(w=>s.jsxs(vE,{value:w.value,"data-slot":"segmented-item",disabled:w.disabled,"data-zero":w.count===0?"true":void 0,className:Ue("group/seg relative z-[1] inline-flex h-6 items-center gap-[5px] rounded-sm border-0 bg-transparent px-2.5","text-xs font-medium whitespace-nowrap text-subtle select-none","transition-[background-color,color] duration-150 ease-out","hover:bg-nav-hover hover:text-foreground","data-checked:bg-transparent data-checked:text-primary-fg data-checked:hover:bg-transparent","data-disabled:cursor-not-allowed data-disabled:opacity-40","data-[zero=true]:data-unchecked:opacity-45"),ref:S=>{S?p.current.set(w.value,S):p.current.delete(w.value)},children:[w.label,w.count!==void 0&&s.jsx("span",{className:Ue("min-w-4 rounded-pill bg-surface-3 px-[5px] text-center text-[10.5px] font-semibold tabular-nums text-muted-foreground","group-data-checked/seg:bg-primary-tint group-data-checked/seg:text-primary-fg"),children:w.count})]},w.value))]})}const j6=x.createContext(void 0);function w6(){return x.useContext(j6)}const S6=x.forwardRef(function(t,a){const{className:o,defaultPressed:c=!1,disabled:d=!1,form:f,onPressedChange:p,pressed:g,render:v,type:y,value:b,nativeButton:j=!0,style:w,...S}=t,N=Na(b||void 0),k=w6(),E=k?.value??[],D=(d||k?.disabled)??!1,[C,A]=qa({controlled:k?N!==void 0&&E.indexOf(N)>-1:g,default:c,name:"Toggle",state:"pressed"}),{getButtonProps:R,buttonRef:I}=Jr({disabled:D,native:j}),P={disabled:D,pressed:C},O=[I,a],_=[{"aria-pressed":C,onClick(B){const z=!C,Q=Fe(Yn,B.nativeEvent);p?.(z,Q),!Q.isCanceled&&(N&&k?.setGroupValue?.(N,z,Q),!Q.isCanceled&&A(z))}},S,R],L=vt("button",t,{enabled:!k,state:P,ref:O,props:_}),H=x.useMemo(()=>({disabled:D,focusableWhenDisabled:!1}),[D]);return k?s.jsx(gE,{tag:"button",render:v,className:o,style:w,metadata:H,state:P,refs:O,props:_}):L}),N6=Vc(["inline-flex shrink-0 cursor-pointer items-center justify-center gap-1.5 whitespace-nowrap border","font-medium transition-[background-color,border-color,color] duration-150 ease-out","outline-none select-none disabled:pointer-events-none disabled:opacity-45","[&_svg]:pointer-events-none [&_svg]:shrink-0","data-pressed:border-primary-bd data-pressed:bg-primary-soft data-pressed:font-semibold data-pressed:text-primary-fg","data-pressed:hover:bg-primary-tint"],{variants:{variant:{default:"border-transparent bg-transparent text-subtle hover:bg-nav-hover hover:text-foreground",outline:"border-control-border bg-control text-foreground shadow-1 hover:border-control-border-hover hover:bg-control-hover"},size:{default:"h-[30px] rounded-md px-3 text-[12.5px]",xs:"h-6 rounded-sm px-2 text-[11.5px]",sm:"h-[26px] rounded-sm px-2.5 text-[12px]",lg:"h-9 rounded-md px-4 text-[13px]"}},defaultVariants:{variant:"default",size:"default"}});function k6({className:e,variant:t,size:a,...o}){return s.jsx(S6,{"data-slot":"toggle",className:Ue(N6({variant:t,size:a}),e),...o})}function C6(e,t,a,o,c,d,f,p,g,v=2){const y=$4(a.current,{event:e,orientation:o,loopFocus:c,rtl:d,cols:v,disabledIndices:f,minIndex:p,maxIndex:g,prevIndex:t>g?p:t,stopEvent:!0});return fo(a.current,y)?void 0:y}const $E=x.createContext(void 0),qE=x.createContext(void 0),GE=x.createContext(void 0),KE=x.createContext(!1),YE=x.createContext("");function Ca(){const e=x.useContext($E);if(!e)throw new Error(on(22));return e}function Ih(){const e=x.useContext(qE);if(!e)throw new Error(on(23));return e}function df(){const e=x.useContext(GE);if(!e)throw new Error(on(24));return e}function XE(){return x.useContext(YE)}function T6(){return x.useContext(KE)}const E6={id:e=>e.id,labelId:e=>e.labelId,items:e=>e.items,selectedValue:e=>e.selectedValue,hasSelectionChips:e=>{const t=e.selectedValue;return Array.isArray(t)&&t.length>0},hasSelectedValue:e=>{const{selectedValue:t,selectionMode:a}=e;return t==null?!1:a==="multiple"&&Array.isArray(t)?t.length>0:!0},hasNullItemLabel:(e,t)=>t?OE(e.items):!1,open:e=>e.open,mounted:e=>e.mounted,forceMounted:e=>e.forceMounted,inline:e=>e.inline,activeIndex:e=>e.activeIndex,selectedIndex:e=>e.selectedIndex,isActive:(e,t)=>e.activeIndex===t,isSelected:(e,t)=>{const a=e.isItemEqualToValue,o=e.selectedValue;return Array.isArray(o)?o.some(c=>la(t,c,a)):la(t,o,a)},transitionStatus:e=>e.transitionStatus,popupProps:e=>e.popupProps,listProps:e=>e.listProps,inputProps:e=>e.inputProps,triggerProps:e=>e.triggerProps,itemProps:e=>e.itemProps,positionerElement:e=>e.positionerElement,listElement:e=>e.listElement,popupId:e=>e.popupId,triggerElement:e=>e.triggerElement,inputElement:e=>e.inputElement,inputGroupElement:e=>e.inputGroupElement,popupSide:e=>e.popupSide,openMethod:e=>e.openMethod,inputInsidePopup:e=>e.inputInsidePopup,inputOwnsFormValue:e=>e.inputOwnsFormValue,selectionMode:e=>e.selectionMode,name:e=>e.name,form:e=>e.form,disabled:e=>e.disabled,readOnly:e=>e.readOnly,required:e=>e.required,grid:e=>e.grid,virtualized:e=>e.virtualized,itemToStringLabel:e=>e.itemToStringLabel,isItemEqualToValue:e=>e.isItemEqualToValue,modal:e=>e.modal,autoHighlight:e=>e.autoHighlight};function QE(e){return e==null?void 0:`${e}-popup`}function A6(e,t){return(a,o)=>a==null?!1:e.contains(a,o,t)}const ZE=new Map;function R6(e={}){const t={usage:"search",sensitivity:"base",ignorePunctuation:!0,...e},a=`${ly(e.locale)}|${JSON.stringify(t)}`,o=ZE.get(a);if(o)return o;const c=new Intl.Collator(e.locale,t),d={contains(f,p,g){if(!p)return!0;const v=yo(f,g);for(let y=0;y<=v.length-p.length;y+=1)if(c.compare(v.slice(y,y+p.length),p)===0)return!0;return!1},startsWith(f,p,g){if(!p)return!0;const v=yo(f,g);return c.compare(v.slice(0,p.length),p)===0},endsWith(f,p,g){if(!p)return!0;const v=yo(f,g),y=p.length;return v.length>=y&&c.compare(v.slice(v.length-y),p)===0}};return ZE.set(a,d),d}const O6=R6;function M6(e,t=!1){const{overflowY:a}=xr(e);return a!=="auto"&&a!=="scroll"?!1:t?e.clientHeight>0:e.scrollHeight>e.clientHeight}const WE=Symbol("none"),Wy={value:WE,index:-1};function D6(e,t,a){const o=e.get(t);if(o!==void 0||a===Ch)return o;for(const[c,d]of e)if(la(c,t,a))return d}function I6(e){const{id:t,onOpenChangeComplete:a,defaultSelectedValue:o=null,selectedValue:c,onSelectedValueChange:d,defaultInputValue:f,inputValue:p,open:g,defaultOpen:v=!1,selectionMode:y,onItemHighlighted:b,name:j,form:w,disabled:S=!1,readOnly:N=!1,required:k=!1,inputRef:E,grid:D=!1,items:C,filteredItems:A,filter:R,filterQuery:I,openOnInputClick:P=!0,autoHighlight:O=!1,keepHighlight:_=!1,highlightItemOnHover:L=!0,loopFocus:H=!0,itemToStringLabel:B,itemToStringValue:z,isItemEqualToValue:Q=Ch,virtualized:K=!1,inline:X=!1,fillInputOnItemPress:q=!0,modal:$=!1,limit:Y=-1,autoComplete:F="list",formAutoComplete:G,locale:W,submitOnItemClick:le=!1}=e,{clearErrors:M}=Fc(),{setDirty:U,validityData:Z,setFilled:ae,name:ce,disabled:J,setTouched:ie,setFocused:ge,validationMode:ee,validation:fe}=Sa(),te=lf(),Ce=lo({id:t}),re=O6({locale:W}),de=Array.isArray(C)?null:C;if(de&&typeof de.label!="function")throw new Error(on(100));const ke=de?de.data:C,Ee=de?.value,ve=Ee?void 0:ke,he=x.useMemo(()=>{if(!A||!Ee)return;const Me=Eh(A),Be=Me.map(Ee);let lt;return{values:Be,findItem(Yt,On){if(!lt){lt=new Map;for(let mn=0;mnde?Me=>de.label(Me,Q,Be=>{const lt=he?.findItem(Be,Q);return lt!=null?de.itemLabel(lt):yo(Be,B)}):B,[de,B,he,Q]),we=x.useMemo(()=>de?Object.assign(Me=>de.itemLabel(Me),{selected:Me=>yo(Me,ye)}):B,[de,ye,B]);function xe(Me){return yo(Me,ye)}const[Te,Oe]=x.useState(!1),[Ne,_e]=x.useState(null),Ye=x.useRef(Ne),kt=x.useRef([]),Ct=x.useRef([]),Rt=x.useRef(null),ot=x.useRef(null),qn=x.useRef(null),ds=x.useRef(null),Gn=x.useRef(null),xs=x.useRef(!0),it=x.useRef(!1),Vt=x.useRef(null),Bn=x.useRef(null),tn=x.useRef(null),nt=x.useRef(Wy),Ot=x.useRef(null),Ft=x.useRef([]),Zn=x.useRef(null),Hn=J||S,Un=ce??j,Rn=y==="multiple",Jt=y==="single",as=p!==void 0||f!==void 0,Tt=ke!==void 0,gt=A!==void 0;let jt;O==="always"?jt="always":jt=O?"input-change":!1;const[wt,Sr]=qa({controlled:c,default:Rn?o??Rr:o,name:"Combobox",state:"selectedValue"}),rr=x.useMemo(()=>R===null?()=>!0:R!==void 0?R:A6(re,we),[R,re,we]),Hr=Ms(()=>as?f??"":Jt?xe(wt):"").current,[jn,rl]=qa({controlled:p,default:Hr,name:"Combobox",state:"inputValue"}),[rn,ic]=qa({controlled:g,default:v,name:"Combobox",state:"open"}),Yx=Xy(ke),dr=!rn&&Ne!==null?Ne:String(jn).trim(),Da=Jt?xe(wt):"",Ho=Jt&&!Te&&dr!==""&&Da.length===dr.length&&re.contains(Da,dr),Uo=Ho?"":I??dr,Dp=Tt&>&&Ho&&(!de||de.hasValue(wt,Q)),cc=x.useMemo(()=>ke?Eh(ke):Rr,[ke]),Vo=x.useMemo(()=>{if(A&&!Dp)return A;if(!ke)return Rr;if(Yx){const Be=ke,lt=[];let Yt=0;for(const On of Be){if(Y>-1&&Yt>=Y)break;const mn=Y>-1?Y-Yt:1/0,Mn=Uo===""?On.items.slice(0,mn):[];if(Uo!=="")for(const fs of On.items){if(Mn.length>=mn)break;rr(fs,Uo,we)&&Mn.push(fs)}if(Mn.length>0){const fs={...On,items:Mn};lt.push(fs),Yt+=Mn.length}}return lt}if(Uo==="")return Y>-1?cc.slice(0,Y):cc;const Me=[];for(const Be of cc){if(Y>-1&&Me.length>=Y)break;rr(Be,Uo,we)&&Me.push(Be)}return Me},[A,Dp,ke,Yx,Uo,Y,rr,we,cc]),Es=x.useMemo(()=>{if(he&&Vo===A)return he.values;const Me=Eh(Vo);return Ee?Me.map(Be=>Ee(Be)):Me},[Vo,A,he,Ee]),et=Ms(()=>{let Me=null;return X&&rn&&Tt&&y!=="none"&&(Me=cf(Es,wt,Q,Rn)),new tu({id:Ce,labelId:void 0,selectedValue:wt,open:rn,items:ve,selectionMode:y,name:Un,form:w,disabled:Hn,readOnly:N,required:k,grid:D,virtualized:K,openOnInputClick:P,itemToStringLabel:ye,isItemEqualToValue:Q,modal:$,autoHighlight:jt,submitOnItemClick:le,hasInputValue:as,mounted:!1,forceMounted:!1,transitionStatus:"idle",inline:X,activeIndex:null,selectedIndex:Me,popupProps:{},listProps:{},inputProps:{},triggerProps:{},itemProps:fn,positionerElement:null,listElement:null,popupId:void 0,triggerElement:null,inputElement:null,inputGroupElement:null,popupSide:null,openMethod:null,inputInsidePopup:!0,inputOwnsFormValue:y==="none"},{onOpenChangeComplete:qt,setOpen:qt,setInputValue:qt,setSelectedValue:qt,setIndices:qt,handleSelection:qt,forceMount:qt,requestSubmit:qt,listRef:kt,labelsRef:Ct,popupRef:Rt,emptyRef:Gn,inputRef:ot,startDismissRef:qn,endDismissRef:ds,keyboardActiveRef:xs,chipsContainerRef:Vt,clearRef:Bn,valuesRef:Ft,pointerDownItemRef:Zn,selectionEventRef:tn},E6)}).current,_l=y==="none"?jn:wt,Xx=x.useMemo(()=>y==="none"?_l:Array.isArray(wt)?wt.map(Me=>ka(Me,z)):ka(wt,z),[_l,z,y,wt]),Ia=Ie(b),As=Ie(a),$s=et.useState("activeIndex"),Fo=et.useState("selectedIndex"),uc=et.useState("positionerElement"),Qx=et.useState("listElement"),dc=et.useState("triggerElement"),fc=et.useState("inputElement"),pc=et.useState("inputGroupElement"),Rs=et.useState("inline"),ar=et.useState("inputInsidePopup"),Ll=et.useState("inputOwnsFormValue"),zl=Jt&&!ar&&jn===Da,mc=Xn(dc),{mounted:$o,setMounted:bs,transitionStatus:Ip}=ki(rn),{openMethod:Zx,triggerProps:Pp}=fE(rn),Bl=Ie(()=>Xx);Yc(ar?mc:ot,Ce,_l,Bl,!Hn,j);const Hl=Ie(()=>{ke?Ct.current=Es.map(xe):et.set("forceMounted",!0)}),qo=Ie((Me,Be,lt)=>{if(Be===-1){if(nt.current===Wy)return;nt.current=Wy}else nt.current={value:Me,index:Be};Ia(Me,iB(lt,void 0,{index:Be}))}),Ur=Ie(Me=>{const Be={};Me.activeIndex!==void 0&&(Be.activeIndex=Me.activeIndex),Me.selectedIndex!==void 0&&(Be.selectedIndex=Me.selectedIndex),et.update(Be);const lt=Me.activeIndex;if(lt===void 0)return;const Yt=Me.type||Yn;lt===null?qo(void 0,-1,Yt):qo(Ft.current[lt],lt,Yt)}),Vr=Ie((Me,Be)=>{if(e.onInputValueChange?.(Me,Be),!Be.isCanceled){if(it.current=Be.reason===Ga,Be.reason===Zd){rn&&Ne!==null&&_e(null);const lt=Be.event,Yt=lt.inputType;if(lt.type==="compositionend"||Yt!=null&&Yt!==""&&Yt!=="insertReplacementText"){const mn=Me.trim()!=="";mn&&Oe(!0),Ot.current={hasQuery:mn};const Mn=et.state.listElement;if(!et.state.virtualized&&Mn){const fs=Rt.current;for(const Nr of Hc(Mn.firstElementChild??Mn)){if(!dn(Nr)||(fs?!Qe(fs,Nr):Nr.getAttribute("role")==="dialog"))break;if(M6(Nr)){Nr.scrollTop=0;break}}}mn&&jt&&et.state.activeIndex==null&&(rn||Rs)&&et.set("activeIndex",0)}}else Be.reason===Ga&&Me===""&&et.state.inputInsidePopup&&(Ot.current={hasQuery:!1,selection:!0});rl(Me)}}),Wx=Ie(Me=>{const Be=!Me&&ar&&!Rs&&jn!==""&&(String(jn).trim()===Ne||jn===Da);!Me&&(Be||jn===""||zl)&&Oe(!1),_e(null),Be&&Vr("",Fe(Ga))}),Mt=Ie((Me,Be)=>{if(rn!==Me&&(Be.reason===Xc&&Tt&&Es.length===0&&!Gn.current&&Be.allowPropagation(),e.onOpenChange?.(Me,Be),!Be.isCanceled&&(Me&&Ne!==null&&Wx(Be.reason===Zd),!Me&&Te&&(Jt?(Rs||_e(dr),dr===""&&Oe(!1)):Rn&&(Rs||_e(dr),ar&&Ur({activeIndex:null}),(!ar||Rs)&&Vr("",Fe(Ga,Be.event,void 0,{isItemPress:Be.reason===Qd})))),ic(Me),!Me&&ar&&(Be.reason===ho||Be.reason===Jm)&&(ie(!0),ge(!1),ee==="onBlur")))){const lt=y==="none"?jn:wt;fe.commit(lt)}}),hc=Ie((Me,Be)=>{if(d?.(Me,Be),Be.isCanceled)return;Sr(Me),(y==="none"&&Rt.current&&q||Jt&&!et.state.inputInsidePopup)&&Vr(xe(Me),Fe(Be.reason,Be.event))}),Wu=Ie((Me,Be)=>{const lt=is(Me),Yt=tn.current??Me;tn.current=null;const On=Fe(Qd,Yt),mn=lt?.closest("a")?.getAttribute("href");if(mn){mn.startsWith("#")&&Mt(!1,On);return}if(Rn){const Mn=Array.isArray(wt)?wt:[],fs=Th(Mn,Be,Q),Nr=fs?RE(Mn,Be,Q):[...Mn,Be];if(hc(Nr,On),On.isCanceled||!(ot.current?ot.current.value.trim()!=="":!1))return;if(et.state.inputInsidePopup){Vr("",Fe(Ga,On.event,void 0,{isItemPress:!0}));const $r=Ot.current;$r&&!fs&&($r.toggledValue=Be)}else Mt(!1,On)}else{if(hc(Be,On),On.isCanceled)return;Mt(!1,On)}}),Ju=Ie(()=>{const Me=fe.inputRef.current?.form??et.state.inputElement?.form;Me&&typeof Me.requestSubmit=="function"&&Me.requestSubmit()}),Fr=Ie(()=>{if(bs(!1),As?.(!1),Oe(!1),_e(null),Ur(y==="none"?{activeIndex:null,selectedIndex:null}:{activeIndex:null}),Rn&&ot.current&&ot.current.value!==""&&!it.current&&Vr("",Fe(Ga)),Jt)if(et.state.inputInsidePopup)ot.current&&ot.current.value!==""&&Vr("",Fe(Ga));else{const Me=xe(wt);ot.current&&ot.current.value!==Me&&Vr(Me,Fe(Me===""?Ga:Yn))}}),fr=x.useMemo(()=>Rs&&uc?{current:uc.closest('[role="dialog"]')}:Rt,[Rs,uc]);ra({enabled:!e.actionsRef,open:rn,ref:fr,onComplete(){rn||Fr()}}),x.useImperativeHandle(e.actionsRef,()=>({unmount:Fr}),[Fr]),De(function(){const Be=Ye.current!==null&&Ne===null;if(Ye.current=Ne,rn&&(!Be||!Tt)||(rn||(Zn.current=null),y==="none"))return;const lt=Tt?Es:Ft.current;Ur({selectedIndex:cf(lt,wt,Q,Rn)})},[rn,Ne,wt,y,Rn,Tt,Es,Q,Ur]),De(()=>{ke&&(Ft.current=Es,kt.current.length=Es.length)},[ke,Es]),De(()=>{const Me=Ot.current;if(Me){const fs=rn||Rs||et.state.positionerElement?.hidden===!1;if(Me.hasQuery)jt&&fs&&et.set("activeIndex",0),Ot.current=null;else if(String(jn).trim()===""&&(Ot.current=null,fs)){const Nr=Me.selection;jt==="always"&&!Nr&&et.state.selectionMode==="none"&&et.set("activeIndex",0),queueMicrotask(()=>{if(!et.state.open&&!et.state.inline||ot.current&&ot.current.value.trim()!=="")return;const ma=et.state.selectedValue,$r=et.state.selectionMode==="multiple";if($r&&Array.isArray(ma)?ma.length>0:et.state.selectionMode!=="none"&&ma!=null){const Ps=Tt||gt?Es:Ft.current,_a=su(Ps,Me.toggledValue,et.state.isItemEqualToValue);et.set("activeIndex",_a!==-1?_a:cf(Ps,ma,et.state.isItemEqualToValue,$r))}else Nr?et.set("activeIndex",null):jt==="always"&&et.set("activeIndex",0)})}}if(!rn&&!Rs)return;const lt=Tt||gt?Es:Ft.current,Yt=et.state.activeIndex;if(Yt==null){if(jt==="always"&<.length>0){et.set("activeIndex",0);return}qo(void 0,-1,Yn);return}if(Yt>=lt.length){qo(void 0,-1,Yn),et.set("activeIndex",null);return}const On=lt[Yt],mn=nt.current.value,Mn=mn!==WE&&la(On,mn,et.state.isItemEqualToValue);(nt.current.index!==Yt||!Mn)&&qo(On,Yt,Yn)},[$s,jt,qo,gt,Tt,Es,Rs,rn,et,jn]),De(()=>{if(y==="none"){ae(String(jn)!=="");return}ae(Rn?Array.isArray(wt)&&wt.length>0:wt!=null)},[ae,y,jn,wt,Rn]),x.useEffect(()=>{Tt&&jt&&Es.length===0&&Ur({activeIndex:null})},[Tt,jt,Es.length,Ur]);function Jx(){rn&&dr!==""&&dr!==String(Hr)&&!zl&&Oe(!0)}function _S(){rn&&Ne!==null&&Wx(!1)}let ed=!1;function _p(){!ed&&jn!==Da&&(ed=!0,Vr(Da,Fe(Yn)))}function LS(){y!=="none"&&(M(Un),U(EE(wt,Z.initialValue,Q)),fe.change(wt),Jt&&!as&&!ar&&_p())}function pr(){Jt&&!as&&!ar&&!Te&&_p()}function Lp(){y==="none"&&(M(Un),U(jn!==Z.initialValue),fe.change(jn))}aa(dr,Jx),aa(rn,_S),aa(wt,LS),aa(Da,pr),aa(ke,pr),aa(jn,Lp);const gc=ET({open:Rs?!0:rn,onOpenChange:Mt,elements:{reference:ar?dc:fc,floating:uc}}),td=D?"grid":"listbox",Pa=rn||Rs,zp=Pa?"true":"false",xc=x.useMemo(()=>{const Me=fc?.tagName==="INPUT",Be=fc==null||Me,lt=Be||Pa,Yt=Be?{autoComplete:"off",spellCheck:"false",autoCorrect:"off",autoCapitalize:"none"}:{};return lt&&(Yt.role="combobox",Yt["aria-expanded"]=zp,Yt["aria-haspopup"]=td,Yt["aria-controls"]=Pa?Qx?.id:void 0,Yt["aria-autocomplete"]=N?"none":F),{reference:Yt,floating:{role:"presentation"}}},[fc,Pa,zp,td,Qx?.id,F,N]),Ul=ah(gc,{enabled:!Hn&&P,event:"mousedown-only",toggle:!1,touchOpenDelay:ar?0:100,reason:aB}),nd=sf(gc,{enabled:!Hn&&!Rs,outsidePressEvent:{mouse:"sloppy",touch:"intentional"},bubbles:Rs?!0:void 0,outsidePress(Me){const Be=is(Me);return!Qe(dc,Be)&&!Qe(Bn.current,Be)&&!Qe(Vt.current,Be)&&!Qe(pc,Be)}}),Vl=DT(gc,{enabled:!Hn,id:Ce,listRef:kt,activeIndex:$s,selectedIndex:Fo,virtual:!0,loopFocus:H,allowEscape:H&&!jt,focusItemOnOpen:Te||y==="none"&&!jt?!1:"auto",focusItemOnHover:L,resetOnPointerLeave:!_,orientation:D?"horizontal":void 0,rtl:te==="rtl",disabledIndices:Rr,grid:D?C6:void 0,onNavigate(Me,Be){!Be&&!rn||Ip==="ending"||Ur(Be?{activeIndex:Me,type:xs.current?b1:v1}:{activeIndex:Me})}}),Bp=x.useMemo(()=>Wr(Vl.reference,{onKeyDown(Me){D&&et.state.activeIndex==null&&(Me.key==="ArrowLeft"||Me.key==="ArrowRight")&&Me.preventBaseUIHandler()}},nd.reference,Ul.reference,xc.reference),[Vl.reference,nd.reference,Ul.reference,xc.reference,D,et]),sd=x.useMemo(()=>Wr(rf,nd.floating),[nd.floating]),eb=x.useMemo(()=>Wr(Vl.floating,xc.floating),[Vl.floating,xc.floating]),tb=x.useMemo(()=>{const Me=Vl.item;return Me?{...Me,onFocus:void 0}:fn},[Vl.item]);et.useContextCallback("setOpen",Mt),et.useContextCallback("setInputValue",Vr),et.useContextCallback("setSelectedValue",hc),et.useContextCallback("setIndices",Ur),et.useContextCallback("handleSelection",Wu),et.useContextCallback("forceMount",Hl),et.useContextCallback("requestSubmit",Ju),et.useContextCallback("onOpenChangeComplete",a),SE(()=>{et.update({inline:X,popupProps:sd,listProps:eb,inputProps:Bp,triggerProps:Pp,itemProps:tb})});const bc={id:Ce,selectedValue:wt,open:rn,mounted:$o,transitionStatus:Ip,items:ve,inline:X,popupProps:sd,listProps:eb,inputProps:Bp,triggerProps:Pp,itemProps:tb,openMethod:Zx,selectionMode:y,name:Un,form:w,disabled:Hn,readOnly:N,required:k,grid:D,virtualized:K,openOnInputClick:P,itemToStringLabel:ye,modal:$,autoHighlight:jt,isItemEqualToValue:Q,submitOnItemClick:le,hasInputValue:as};De(()=>{et.update({...bc,inputOwnsFormValue:y==="none"&&(X||!et.state.inputInsidePopup)})},[et,...Object.values(bc)]);const pa=ea(E,fe.inputRef),Hp=x.useMemo(()=>({query:dr,hasItems:Tt,filteredItems:Vo,flatFilteredValues:Es}),[dr,Tt,Vo,Es]),Up=x.useMemo(()=>Array.isArray(_l)?"":ka(_l,z),[_l,z]),Go=Rn&&Array.isArray(wt)&&wt.length>0,al=Rn||y==="none"&&Ll?void 0:Un,nb=x.useMemo(()=>!Rn||!Array.isArray(wt)||!Un?null:wt.map(Me=>{const Be=ka(Me,z);return s.jsx("input",{type:"hidden",form:w,name:Un,value:Be,disabled:Hn},Be)}),[Rn,wt,w,Un,z,Hn]),Vp=s.jsxs(x.Fragment,{children:[e.children,s.jsx("input",{...fe.getValidationProps(Hn,{onFocus(){if(ar){dc?.focus();return}(ot.current||dc)?.focus()},onChange(Me){if(Me.nativeEvent.defaultPrevented||Hn||N)return;const Be=Me.currentTarget.value,lt=Be.toLowerCase(),Yt=Fe(Yn,Me.nativeEvent),On=()=>Ft.current.findIndex(Mn=>ka(Mn,z).toLowerCase()===lt||xe(Mn).toLowerCase()===lt);function mn(){if(Rn)return;if(y==="none"){Vr(Be,Yt);return}let Mn=On();Mn===-1&&(Mn=Ft.current.findIndex((Nr,ma)=>{const $r=Ct.current[ma];return $r!=null&&$r.toLowerCase()===lt}));const fs=Mn===-1?void 0:Ft.current[Mn];fs!=null&&hc?.(fs,Yt)}Jt&&(Hl(),ke&&On()===-1&&et.set("forceMounted",!0)),queueMicrotask(mn)}}),id:Ce&&al==null?`${Ce}-hidden-input`:void 0,form:w,name:al,autoComplete:G,disabled:Hn,required:k&&!Go,readOnly:N,value:Up,ref:pa,style:al?Zc:Ai,tabIndex:-1,"aria-hidden":!0,suppressHydrationWarning:!0}),nb]});return s.jsx($E.Provider,{value:et,children:s.jsx(qE.Provider,{value:gc,children:s.jsx(KE.Provider,{value:Tt,children:s.jsx(GE.Provider,{value:Hp,children:s.jsx(YE.Provider,{value:jn,children:Vp})})})})})}function P6(e){const{multiple:t=!1,defaultValue:a,value:o,onValueChange:c,autoComplete:d,...f}=e;return s.jsx(I6,{...f,selectionMode:t?"multiple":"single",selectedValue:o,defaultSelectedValue:a,onSelectedValueChange:c,formAutoComplete:d})}const _6="data-popup-side",L6="data-list-empty",JE={...Bv,...ji,popupSide:e=>e?{[_6]:e}:null,listEmpty:e=>e?{[L6]:""}:null},z6=x.createContext(void 0);function B6(){return x.useContext(z6)}const eA=x.createContext(void 0);function Jy(e){const t=x.useContext(eA);if(t===void 0&&!e)throw new Error(on(21));return t}const tA=x.forwardRef(function(t,a){const o=Ca(),{buttonRef:c,getButtonProps:d}=Jr({native:!1}),f=ea(a,c);function p(v){o.context.setOpen(!1,Fe(ny,v.nativeEvent,v.currentTarget))}const g=d({onClick:p});return s.jsx("span",{ref:f,...g,"aria-label":"Dismiss",tabIndex:void 0,style:Zc})});function nA(e){const t=e.useState("mounted"),a=e.useState("popupSide"),o=e.useState("positionerElement");return t&&o?a:null}function Ph(){return df().filteredItems.length===0}function H6(e){return e==="rtl"?["ArrowRight","ArrowLeft"]:["ArrowLeft","ArrowRight"]}function U6(e,t){const a=e>=t-1?t-2:e;return a>=0?a:void 0}function sA(e,t,a){const o=e.context.listRef.current[t];o&&(e.context.selectionEventRef.current=a,o.click(),e.context.selectionEventRef.current=null)}const V6=x.forwardRef(function(t,a){const{render:o,className:c,disabled:d=!1,id:f,style:p,...g}=t,{state:v,disabled:y,setTouched:b,setFocused:j,validationMode:w,validation:S}=Sa(),{labelId:N}=vl(),k=B6(),D=!!Jy(!0),C=Ca(),A=XE(),R=lf(),I=C.useState("required"),P=C.useState("disabled"),O=C.useState("readOnly"),_=C.useState("name"),L=C.useState("form"),H=C.useState("selectionMode"),B=C.useState("autoHighlight"),z=C.useState("inputProps"),Q=C.useState("triggerProps"),K=C.useState("open"),X=C.useState("mounted"),q=C.useState("selectedValue"),$=C.useState("id"),Y=C.useState("inline"),F=C.useState("modal"),G=!!B,W=nA(C),le=y||P||d,M=Ph(),U=D||Y,Z=!U||F,ae=Na(f??(U?void 0:$)),ce=D?HC:v,[J,ie]=x.useState(null),ge=x.useRef(!1),ee=x.useRef(null),fe=x.useRef(!1),te=H==="none"&&!D,Ce=Ie(we=>{const xe=D||C.state.inline;xe&&!C.state.hasInputValue&&C.context.setInputValue("",Fe(Yn)),C.update({inputElement:we,inputInsidePopup:xe,inputOwnsFormValue:te})}),re=D?g:S.getValidationProps(le,g);function de(){C.context.setIndices({activeIndex:null,selectedIndex:null,type:C.context.keyboardActiveRef.current?b1:v1})}function ke(){C.context.keyboardActiveRef.current=!1}const Ee={...ce,open:K,disabled:le,readOnly:O,popupSide:W,listEmpty:M};function ve(we){if(!k)return;let xe;const{highlightedChipIndex:Te}=k,Oe=k.chipsRef.current.length,[Ne,_e]=H6(R);return Te!==void 0?(we.key===Ne?(we.preventDefault(),Te>0?xe=Te-1:xe=void 0):we.key===_e?(we.preventDefault(),Te0&&(we.preventDefault(),xe=Oe>0?Oe-1:void 0),xe)}const he=vt("input",t,{state:Ee,ref:[a,C.context.inputRef,Ce],props:[z,Q,{value:J??A,"aria-readonly":O||void 0,"aria-required":I||void 0,"aria-labelledby":N,disabled:le,readOnly:O,required:H==="none"?I:void 0,form:L,...te&&_&&{name:_},id:ae,onFocus(){if(j(!0),!Y||!fe.current)return;fe.current=!1;const we=ee.current;we==null||!Object.hasOwn(C.context.valuesRef.current,we)||C.context.setIndices({activeIndex:we})},onBlur(){b(!0),j(!1);const we=C.state.activeIndex;if(Y&&we!==null&&B!=="always"&&(ee.current=we,fe.current=!0,C.context.setIndices({activeIndex:null})),w==="onBlur"){const xe=H==="none"?A:q;S.commit(xe)}},onCompositionStart(we){zm||(ge.current=!0,ie(we.currentTarget.value))},onCompositionEnd(we){ge.current=!1;const xe=we.currentTarget.value;ie(null),C.context.setInputValue(xe,Fe(Zd,we.nativeEvent))},onChange(we){const xe=we.nativeEvent,Te=xe.inputType,Oe=!Te||Te==="insertReplacementText",Ne=ge.current||!Oe;function _e(Rt){O||le||!Rt||!Ne||(C.context.setOpen(!0,Fe(Zd,xe)),G||de())}if(ge.current){const Rt=we.currentTarget.value;ie(Rt),Rt===""&&!C.state.openOnInputClick&&!C.state.inputInsidePopup&&C.context.setOpen(!1,Fe(Ga,xe));const ot=Rt.trim(),qn=G&&ot!=="";_e(ot),K&&C.state.activeIndex!==null&&!qn&&de();return}const Ye=Fe(Zd,xe);if(C.context.setInputValue(we.currentTarget.value,Ye),Ye.isCanceled)return;const kt=we.currentTarget.value==="",Ct=Fe(Ga,xe);kt&&!C.state.inputInsidePopup&&(H==="single"&&C.context.setSelectedValue(null,Ct),C.state.openOnInputClick||C.context.setOpen(!1,Ct)),_e(we.currentTarget.value.trim()),K&&C.state.activeIndex!==null&&!G&&de()},onKeyDown(we){if(we.ctrlKey||we.shiftKey||we.altKey||we.metaKey)return;if(C.context.keyboardActiveRef.current=!0,le||O){O&&we.key==="Enter"&&K&&C.state.activeIndex!==null&&Ns(we);return}const xe=we.currentTarget,Te=xe.scrollWidth-xe.clientWidth,Oe=R==="rtl";if(we.key==="Home"){Ns(we);const Ye=KC&&Oe?xe.value.length:0;xe.setSelectionRange(Ye,Ye),xe.scrollLeft=0;return}if(we.key==="End"){Ns(we);const Ye=KC&&Oe?0:xe.value.length;xe.setSelectionRange(Ye,Ye),xe.scrollLeft=Oe?-Te:Te;return}if(!X&&we.key==="Escape"){const Ye=H==="multiple"&&Array.isArray(q)?q.length===0:q===null,kt=Fe(Xc,we.nativeEvent),Ct=H==="multiple"?[]:null;C.context.setInputValue("",kt),C.context.setSelectedValue(Ct,kt),!Ye&&!C.state.inline&&!kt.isPropagationAllowed&&we.stopPropagation();return}if(k&&we.key==="Backspace"&&xe.value===""&&k.highlightedChipIndex===void 0&&Array.isArray(q)&&q.length>0){const Ye=k.chipsRef.current.length,kt=Ye>0?Ye-1:q.length-1,Ct=q.filter((Rt,ot)=>ot!==kt);de(),C.context.setSelectedValue(Ct,Fe(Yn,we.nativeEvent));return}const Ne=k?.highlightedChipIndex!==void 0,_e=ve(we);if(k?.setHighlightedChipIndex(_e),_e!==void 0?k?.chipsRef.current[_e]?.focus():Ne&&C.context.inputRef.current?.focus(),we.which!==229&&we.key==="Enter"&&K){const Ye=C.state.activeIndex,kt=we.nativeEvent;if(Ye===null){if(Y)return;C.context.setOpen(!1,Fe(Yn,kt));return}Ns(we),sA(C,Ye,kt)}},onPointerMove:ke,onPointerDown:ke},re],stateAttributesMapping:JE}),ye=D?s.jsx(VC.Provider,{value:UC,children:he}):he;return s.jsxs(x.Fragment,{children:[K&&Z&&s.jsx(tA,{ref:C.context.startDismissRef}),ye]})}),F6=x.forwardRef(function(t,a){const{render:o,className:c,nativeButton:d=!0,disabled:f=!1,id:p,style:g,...v}=t,{state:y,disabled:b,setTouched:j,setFocused:w,validationMode:S,validation:N}=Sa(),{labelId:k}=vl(),E=Ca(),D=E.useState("selectionMode"),C=E.useState("disabled"),A=E.useState("readOnly"),R=E.useState("required"),I=E.useState("positionerElement"),P=E.useState("listElement"),O=E.useState("popupId"),_=E.useState("triggerProps"),L=E.useState("inputInsidePopup"),H=E.useState("id"),B=E.useState("labelId"),z=E.useState("open"),Q=E.useState("selectedValue"),K=E.useState("activeIndex"),X=E.useState("selectedIndex"),q=E.useState("hasSelectedValue"),$=Ih(),Y=XE(),F=Qs(),G=b||C||f,W=Ph(),le=nA(E);lo({id:L?p:void 0});const M=L?p??H:p,U=IE(k,B);let Z;z&&L?Z=O??QE(H):z&&(Z=P?.id);const ae=x.useRef("");function ce(re){ae.current=re.pointerType}const{reference:J}=IT($,{enabled:!z&&!A&&!C&&D==="single",listRef:E.context.labelsRef,activeIndex:K,selectedIndex:X,onMatch(re){const de=E.context.valuesRef.current[re];de!==void 0&&E.context.setSelectedValue(de,Fe(Yn))}}),{reference:ie}=ah($,{enabled:!C,event:"mousedown"}),{buttonRef:ge,getButtonProps:ee}=Jr({native:d,disabled:G}),fe={...y,readOnly:A,open:z,disabled:G,popupSide:le,listEmpty:W,placeholder:D==="none"?!1:!q},te=Ie(re=>{E.set("triggerElement",re)});return vt("button",t,{ref:[a,ge,te],state:fe,props:[_,ie,J,{id:M,tabIndex:L?0:-1,role:L?"combobox":void 0,"aria-expanded":z,"aria-haspopup":L?"dialog":"listbox","aria-controls":Z,"aria-required":L&&R||void 0,"aria-readonly":L&&A||void 0,"aria-labelledby":U,onPointerDown:ce,onPointerEnter:ce,onFocus(){w(!0),!G&&F.start(0,E.context.forceMount)},onBlur(re){if(!Qe(I,re.relatedTarget)&&(j(!0),w(!1),S==="onBlur")){const de=D==="none"?Y:Q;N.commit(de)}},onMouseDown(re){if(G||(L||$.set("domReferenceElement",re.currentTarget),E.context.forceMount(),ae.current!=="touch"&&(E.context.inputRef.current?.focus(),L||re.preventDefault()),z))return;const de=$t(re.currentTarget);function ke(Ee){const ve=E.state.triggerElement;if(!ve)return;const he=is(Ee),ye=E.state.positionerElement,we=E.state.listElement;Qe(ve,he)||Qe(ye,he)||Qe(we,he)||PE(Ee,ve)||E.context.setOpen(!1,Fe(y1,Ee))}L&&de.addEventListener("mouseup",ke,{once:!0})},onKeyDown(re){(re.key==="ArrowDown"||re.key==="ArrowUp")&&(Ns(re),E.context.setOpen(!0,Fe(sy,re.nativeEvent)),E.context.inputRef.current?.focus())}},N.getValidationProps(G,v),ee],stateAttributesMapping:JE})}),$6=x.createContext(null);function q6(){return x.useContext($6)}function G6(e){const{children:t}=e,{filteredItems:a}=df(),o=q6(),c=o?o.items:a;return s.jsx(x.Fragment,{children:c.map(t)})}const K6=x.forwardRef(function(t,a){var o;const{render:c,className:d,style:f,children:p,...g}=t,v=Ca(),y=Ih(),b=!!Jy(!0),{filteredItems:j,hasItems:w}=df(),S=v.useState("selectionMode"),N=v.useState("grid"),k=v.useState("readOnly"),E=v.useState("listProps"),D=v.useState("virtualized"),C=v.useState("forceMounted"),A=S==="multiple",R=j.length===0,I=Ie(z=>{v.set("positionerElement",z)}),P=Ie(z=>{v.set("listElement",z)}),O=x.useMemo(()=>typeof p=="function"?o||(o=s.jsx(G6,{children:p})):p,[p]),_={empty:R},L=y.useState("floatingId"),H=vt("div",t,{state:_,ref:[a,P,b?null:I],props:[E,{children:O,tabIndex:-1,id:L,role:N?"grid":"listbox","aria-multiselectable":A?"true":void 0,"aria-readonly":!N&&k?!0:void 0,onKeyDown(z){if(!(v.state.disabled||v.state.readOnly)&&z.key==="Enter"){const Q=v.state.activeIndex;if(Q==null)return;Ns(z),sA(v,Q,z.nativeEvent)}},onKeyDownCapture(){v.context.keyboardActiveRef.current=!0},onPointerMoveCapture(){v.context.keyboardActiveRef.current=!1}},g]});if(D)return H;const B=w&&!C?void 0:v.context.labelsRef;return s.jsx(Ky,{elementsRef:v.context.listRef,labelsRef:B,children:H})}),Y6="⁠",X6=200;function Q6(e){const t=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT);let a=null;for(;t.nextNode();){const o=t.currentNode;o.nodeValue!==""&&(a=o)}return a}function Z6(){const e=Qs(),t=x.useRef(null);return x.useEffect(()=>{if(Gd)return;const a=t.current;if(a==null)return;const o=Q6(a);if(o==null)return;const c=o.data,d=`${c}${Y6}`;return o.nodeValue=d,e.start(X6,()=>{o.nodeValue===d&&(o.nodeValue=c)}),()=>{e.clear(),o.nodeValue===d&&(o.nodeValue=c)}},[t,e]),t}const rA=x.createContext(void 0);function W6(){const e=x.useContext(rA);if(e===void 0)throw new Error(on(20));return e}const J6=x.forwardRef(function(t,a){const{keepMounted:o=!1,...c}=t,d=Ca(),f=d.useState("mounted"),p=d.useState("forceMounted");return f||o||p?s.jsx(rA.Provider,{value:o,children:s.jsx(sh,{ref:a,...c})}):null}),eF=x.forwardRef(function(t,a){const{render:o,className:c,anchor:d,positionMethod:f,side:p,align:g,sideOffset:v,alignOffset:y,collisionBoundary:b="clipping-ancestors",collisionPadding:j,arrowPadding:w,sticky:S,disableAnchorTracking:N=!1,collisionAvoidance:k=V1,style:E,...D}=t,C=Ca(),A=Ih(),R=W6(),I=C.useState("modal"),P=C.useState("open"),O=C.useState("mounted"),_=C.useState("openMethod"),L=C.useState("positionerElement"),H=C.useState("triggerElement"),B=C.useState("inputElement"),z=C.useState("inputGroupElement"),Q=C.useState("inputInsidePopup"),K=C.useState("transitionStatus"),X=Ph(),$=xh({anchor:d??(Q?H:z??B),floatingRootContext:A,positionMethod:f,mounted:O,side:p,sideOffset:v,align:g,alignOffset:y,arrowPadding:w,collisionBoundary:b,collisionPadding:j,sticky:S,disableAnchorTracking:N,keepMounted:R,collisionAvoidance:k,lazyFlip:!0});Qy(P&&I,_==="touch",L,H);const Y={open:P,side:$.side,align:$.align,anchorHidden:$.anchorHidden,empty:X};De(()=>{C.set("popupSide",$.side)},[C,$.side]);const F=Ie(W=>{C.set("positionerElement",W)}),G=bh(t,Y,{styles:$.positionerStyles,transitionStatus:K,props:D,refs:[a,F],hidden:!O,inert:!P});return s.jsxs(eA.Provider,{value:$,children:[O&&I&&s.jsx(wh,{inert:vh(!P),cutout:z??B??H}),G]})}),tF={...$c,...oo},nF=x.forwardRef(function(t,a){const{render:o,className:c,style:d,initialFocus:f,finalFocus:p,...g}=t,v=Ca(),y=Jy(),b=Ih(),j=v.useState("mounted"),w=v.useState("open"),S=v.useState("openMethod"),N=v.useState("popupProps"),k=v.useState("transitionStatus"),E=v.useState("inputInsidePopup"),D=v.useState("inputElement"),C=v.useState("modal"),A=v.useState("id"),R=Ph(),I=g.id??(E?QE(A):void 0);De(()=>(v.set("popupId",v.context.popupRef.current?.id||I),()=>{v.set("popupId",void 0)}),[v,I]),ra({open:w,ref:v.context.popupRef,onComplete(){w&&v.context.onOpenChangeComplete(!0)}});const P={open:w,side:y.side,align:y.align,anchorHidden:y.anchorHidden,transitionStatus:k,empty:R},O=vt("div",t,{state:P,ref:[a,v.context.popupRef],props:[N,{id:I,role:E?"dialog":"presentation",onFocus(z){const Q=is(z.nativeEvent);S!=="touch"&&(Qe(v.state.listElement,Q)||Q===z.currentTarget)&&v.context.inputRef.current?.focus()}},of(k),g],stateAttributesMapping:tF}),L=f===void 0?E?z=>z==="touch"?v.context.popupRef.current:D:!1:f;let H;p!=null?H=p:H=E?void 0:!1;const B=!E||C;return s.jsx(rh,{context:b,disabled:!j,modal:B,openInteractionType:S,initialFocus:L,returnFocus:H,getInsideElements:()=>[v.context.startDismissRef.current,v.context.endDismissRef.current],children:s.jsxs(x.Fragment,{children:[O,B&&s.jsx(tA,{ref:v.context.endDismissRef})]})})}),sF=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t;return vt("span",t,{ref:a,props:[{"aria-hidden":!0,children:"▼"},f]})}),aA=x.createContext(void 0);function lA(){const e=x.useContext(aA);if(!e)throw new Error(on(19));return e}const rF=x.createContext(!1);function aF(){return x.useContext(rF)}function oA(e){const{componentProps:t,forwardedRef:a,virtualized:o,indexFromFilter:c}=e,{render:d,className:f,style:p,value:g=null,index:v,disabled:y=!1,nativeButton:b=!1,...j}=t,w=x.useRef(null),S=Gy({guess:!0,index:v,textRef:w}),N=Ca(),k=aF(),E=T6(),D=N.useState("selectionMode"),C=N.useState("disabled"),A=N.useState("readOnly"),R=N.useState("isItemEqualToValue"),I=C||y,P=D!=="none",O=v??c??S.index,_=O!==-1,L=N.useState("id"),H=N.useState("isActive",O),B=N.useState("isSelected",g),z=N.useState("itemProps"),Q=x.useRef(null),K=L!=null&&_?`${L}-${O}`:void 0,X=B&&P;De(()=>{if(!(_&&(o||v!=null)))return;const U=N.context.listRef.current;return U[O]=Q.current,()=>{delete U[O]}},[_,o,O,v,N]),De(()=>{if(!_||E)return;const M=N.context.valuesRef.current;return M[O]=g,()=>{delete M[O]}},[_,E,O,g,N]),De(()=>{if(!_||E)return;const M=N.state.selectedValue;let U=N.state.selectedIndex;N.state.selectionMode==="multiple"&&Array.isArray(M)?U=AE(O,g,N.context.valuesRef.current,M,R,U):la(g,M,R)&&(U=O),N.set("selectedIndex",U)},[_,E,N,O,g,R]);const{getButtonProps:q,buttonRef:$}=Jr({disabled:I,focusableWhenDisabled:!0,native:b,composite:!0}),Y={disabled:I,selected:X,highlighted:H};function F(M){function U(){N.context.handleSelection(M,g)}N.state.submitOnItemClick?(ks.flushSync(U),N.context.requestSubmit()):U()}const G={id:K,role:k?"gridcell":"option","aria-selected":P?X:void 0,tabIndex:void 0,onPointerDownCapture(M){M.isPrimary&&(N.context.pointerDownItemRef.current=M.currentTarget),M.preventDefault()},onMouseDown(M){M.preventDefault()},onClick(M){I||A||F(M.nativeEvent)},onMouseUp(M){const U=N.context.pointerDownItemRef.current===M.currentTarget;N.context.pointerDownItemRef.current=null,!(I||A||M.button!==0||U||!H)&&F(M.nativeEvent)}},W=vt("div",t,{ref:[$,a,S.ref,Q],state:Y,props:[z,G,j,q]}),le=x.useMemo(()=>({selected:X,textRef:w}),[X,w]);return s.jsx(aA.Provider,{value:le,children:W})}function lF(e){const{componentProps:t,forwardedRef:a}=e,c=Ca().useState("isItemEqualToValue"),{flatFilteredValues:d}=df(),f=t.value??null,p=su(d,f,c);return s.jsx(oA,{componentProps:t,forwardedRef:a,virtualized:!0,indexFromFilter:p})}const oF=x.memo(x.forwardRef(function(t,a){const c=Ca().useState("virtualized");return c&&t.index==null?s.jsx(lF,{componentProps:t,forwardedRef:a}):s.jsx(oA,{componentProps:t,forwardedRef:a,virtualized:c,indexFromFilter:void 0})})),iF=x.forwardRef(function(t,a){const{selected:o}=lA();return t.keepMounted||o?s.jsx(cF,{...t,ref:a}):null}),cF=x.memo(x.forwardRef((e,t)=>{const{render:a,className:o,style:c,keepMounted:d,...f}=e,{selected:p}=lA(),g=x.useRef(null),{transitionStatus:v,setMounted:y}=ki(p),j=vt("span",e,{ref:[t,g],state:{selected:p,transitionStatus:v},props:[{"aria-hidden":!0,children:"✔️"},f],stateAttributesMapping:oo});return ra({batch:!0,enabled:!p,open:p,ref:g,onComplete(){p||y(!1)}}),j})),uF=x.forwardRef(function(t,a){const{render:o,className:c,style:d,children:f,...p}=t,{filteredItems:g}=df(),v=Ca(),y=Z6(),b=g.length===0?f:null;return vt("div",t,{ref:[a,v.context.emptyRef,y],props:[{children:b,role:"status","aria-live":"polite","aria-atomic":!0},p]})}),dF="、";function _h({value:e,onValueChange:t,options:a,placeholder:o="",emptyHint:c=go("没有匹配的选项"),searchPlaceholder:d=go("搜索…"),disabled:f=!1,className:p,id:g,title:v,...y}){const b=x.useMemo(()=>a.filter(w=>e.includes(w.value)),[a,e]),j=b.length?b.map(w=>w.label).join(dF):o;return s.jsxs(P6,{items:a,multiple:!0,value:b,onValueChange:w=>t(w.map(S=>S.value)),isItemEqualToValue:(w,S)=>w?.value===S?.value,disabled:f,children:[s.jsxs(F6,{"data-slot":"multi-select-trigger",id:g,title:v,"aria-label":y["aria-label"],className:Ue("inline-flex h-[30px] min-w-0 cursor-pointer items-center justify-between gap-1.5 rounded-md border border-control-border bg-control px-2.5","text-[12.5px] font-normal text-foreground","transition-colors duration-150 ease-out","hover:border-control-border-hover hover:bg-control-hover","focus-visible:border-primary focus-visible:shadow-focus focus-visible:outline-none","data-disabled:cursor-not-allowed data-disabled:bg-control data-disabled:text-muted-foreground data-disabled:opacity-60",p),children:[s.jsx("span",{"data-slot":"multi-select-value",className:"min-w-0 flex-1 truncate text-left data-[placeholder]:text-muted-foreground","data-placeholder":b.length?void 0:"",title:j,children:j}),s.jsx(sF,{className:"flex flex-none text-muted-foreground transition-transform duration-[180ms] data-popup-open:rotate-180",children:s.jsx("svg",{viewBox:"0 0 10 6",className:"size-2.5","aria-hidden":"true",children:s.jsx("path",{d:"M1 1l4 4 4-4",stroke:"currentColor",strokeWidth:"1.4",fill:"none",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),s.jsx(J6,{children:s.jsx(eF,{sideOffset:4,className:"z-[35]",children:s.jsxs(nF,{"data-slot":"multi-select-content",className:Ue("flex max-h-[280px] w-[max(var(--anchor-width),220px)] flex-col overflow-hidden","rounded-lg border border-border-strong bg-raised shadow-3 outline-none","data-open:animate-in data-open:fade-in-0","data-closed:animate-out data-closed:fade-out-0"),children:[s.jsxs("div",{className:"flex flex-none items-center gap-1.5 border-b border-hairline px-2.5 py-1.5",children:[s.jsxs("svg",{viewBox:"0 0 12 12",className:"size-3 flex-none text-muted-foreground","aria-hidden":"true",children:[s.jsx("circle",{cx:"5",cy:"5",r:"3.4",stroke:"currentColor",strokeWidth:"1.3",fill:"none"}),s.jsx("path",{d:"M7.6 7.6 10.5 10.5",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"})]}),s.jsx(V6,{placeholder:d,className:"min-w-0 flex-1 border-0 bg-transparent p-0 text-[12.5px] text-foreground outline-none placeholder:text-muted-foreground"})]}),s.jsx(uF,{children:s.jsx("div",{className:"px-2.5 py-3 text-[11.5px] leading-[1.5] text-muted-foreground",children:c})}),s.jsx(K6,{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain p-[5px]",children:w=>s.jsxs(oF,{value:w,className:Ue("grid cursor-pointer grid-cols-[14px_minmax(0,1fr)] items-center gap-2 rounded-sm px-[9px] py-[5px]","text-[12.5px] leading-[1.4] text-foreground select-none outline-none","transition-colors duration-[120ms] ease-out","data-[highlighted]:bg-nav-hover","data-[selected]:bg-primary-soft data-[selected]:font-semibold data-[selected]:text-primary-fg","data-[highlighted]:data-[selected]:bg-primary-tint","data-disabled:pointer-events-none data-disabled:text-muted-foreground"),children:[s.jsx(iF,{className:"col-start-1 flex text-primary",children:s.jsx("svg",{viewBox:"0 0 12 12",className:"size-3","aria-hidden":"true",children:s.jsx("path",{d:"M2.5 6.2 4.8 8.5 9.5 3.8",stroke:"currentColor",strokeWidth:"1.8",fill:"none",strokeLinecap:"round",strokeLinejoin:"round"})})}),s.jsx("span",{className:"col-start-2 min-w-0 truncate",children:w.label})]},w.value)})]})})})]})}const iA=x.createContext(void 0);function ff(e){const t=x.useContext(iA);if(t===void 0&&!e)throw new Error(on(47));return t}const fF={...Oy,disabled:e=>e.disabled,instantType:e=>e.instantType,openMethod:e=>e.openMethod,openChangeReason:e=>e.openChangeReason,modal:e=>e.modal,focusManagerModal:e=>e.focusManagerModal,stickIfOpen:e=>e.stickIfOpen,titleElementId:e=>e.titleElementId,descriptionElementId:e=>e.descriptionElementId,openOnHover:e=>e.openOnHover,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin};class pF extends tu{constructor(a,o,c){const d=new ch;super(mF(a,d,o,c),hF(d),fF);ln(this,"setOpen",(a,o)=>{const c=o.reason===Us,d=o.reason===mo&&o.event.detail===0,f=!a&&(o.reason===Xc||o.reason==null),p=wT(o),g=this.select("activeTriggerId");if(!a&&o.reason===ny&&o.trigger==null&&g!=null&&(o.trigger=this.context.triggerElements.getById(g)??this.select("activeTriggerElement")??void 0),this.context.onOpenChange?.(a,o),o.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(a,o);const v=()=>{const b=ky(this.state,a,o.trigger,p());b.openChangeReason=o.reason,this.update(b)};c?(this.set("stickIfOpen",!0),this.context.stickIfOpenTimeout.start(ZB,()=>{this.set("stickIfOpen",!1)}),ks.flushSync(v)):v();let y;d?y="click":f?y="dismiss":o.reason===ho&&(y="focus"),this.set("instantType",y)})}}function mF(e,t,a,o=!1){const c={...Ay(t,a,o),disabled:!1,modal:!1,focusManagerModal:!1,instantType:void 0,openMethod:null,openChangeReason:null,titleElementId:void 0,descriptionElementId:void 0,stickIfOpen:!0,openOnHover:!1,closeDelay:0,adaptiveOrigin:void 0,...e};return c.open&&e?.mounted===void 0&&(c.mounted=!0),c}function hF(e){return{popupRef:x.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:x.createRef(),beforeContentFocusGuardRef:x.createRef(),stickIfOpenTimeout:new sa,triggerElements:e}}const cA=eh(function({props:t}){const{children:a,open:o,defaultOpen:c=!1,onOpenChange:d,onOpenChangeComplete:f,modal:p=!1,handle:g,triggerId:v,defaultTriggerId:y=null}=t,b=xF(g,{modal:p,open:c,openProp:o,activeTriggerId:y,triggerIdProp:v});b.useControlledProp("openProp",o),b.useControlledProp("triggerIdProp",v);const j=b.useState("open"),w=b.useState("mounted"),S=b.useState("payload");b.useContextCallback("onOpenChange",d),b.useContextCallback("onOpenChangeComplete",f),NT(b,j),Cy(b);const{forceUnmount:N}=Ty(j,b,()=>{b.update({stickIfOpen:!0,openChangeReason:null})});b.useSyncedValues({modal:p}),x.useEffect(()=>{j||b.context.stickIfOpenTimeout.clear()},[b,j]),x.useImperativeHandle(t.actionsRef,()=>({unmount:N,close:()=>b.setOpen(!1,Fe(ry))}),[N,b]);const k=j||w;return s.jsxs(iA.Provider,{value:b,children:[g&&s.jsx(Ny,{handle:g,store:b}),k&&s.jsx(bF,{store:b,modal:p}),typeof a=="function"?a({payload:S}):a]})});function gF(e){return ff(!0)?s.jsx(cA,{props:e}):s.jsx(rH,{children:s.jsx(cA,{props:e})})}function xF(e,t){const a=Sy((o,c)=>new pF(t,o,c));return x.useEffect(()=>a.context.stickIfOpenTimeout.disposeEffect(),[a]),a}function bF({store:e,modal:t}){const a=e.useState("floatingRootContext"),o=sf(a,{outsidePressEvent:{mouse:t==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}}),c=o.reference,d=o.floating;return Ey(e,{activeTriggerProps:c,inactiveTriggerProps:c,popupProps:d}),null}const vF=300;function yF(e,t){const a=x.useRef(null);function o(d){ks.flushSync(()=>{e.setOpen(!1,Fe(ho,d.nativeEvent,d.currentTarget))}),W4(a.current)?.focus()}function c(d){const f=e.select("positionerElement");if(f&&Gc(d,f))e.context.beforeContentFocusGuardRef.current?.focus();else{ks.flushSync(()=>{e.setOpen(!1,Fe(ho,d.nativeEvent,d.currentTarget))});let p=Z4(e.context.triggerFocusTargetRef.current||t.current);for(;p!==null&&Qe(f,p);){const g=p;if(p=Jv(p),p===g)break}p?.focus()}}return{preFocusGuardRef:a,handlePreFocusGuardFocus:o,handleFocusTargetFocus:c}}const jF=R1(function(t,a){const{render:o,className:c,style:d,disabled:f=!1,nativeButton:p=!0,handle:g,payload:v,openOnHover:y=!1,delay:b=vF,closeDelay:j=0,id:w,...S}=t,N=ff(!0),E=TT(g)??N;if(!E)throw new Error(on(74));const D=Na(w),C=E.useState("isTriggerActive",D),A=E.useState("floatingRootContext"),R=E.useState("isOpenedByTrigger",D),I=E.useState("triggerPopupId",D),P=x.useRef(null),{registerTrigger:O,isMountedByThisTrigger:_}=ST(D,P,E,{payload:v,disabled:f,openOnHover:y,closeDelay:j}),L=E.useState("openChangeReason"),H=E.useState("stickIfOpen"),B=E.useState("openMethod"),z=E.useState("focusManagerModal"),Q=OT(A,{enabled:!f&&y&&(B!=="touch"||L!==mo),mouseOnly:!0,move:!1,handleClose:_T(),restMs:b,delay:{close:j},triggerElementRef:P,isActiveTrigger:C,isClosing:()=>E.select("transitionStatus")==="ending"}),K=ah(A,{stickIfOpen:H}),X=dE(()=>E.select("open"),ae=>{E.set("openMethod",ae)}),q=E.useState("triggerProps",_),{getButtonProps:$,buttonRef:Y}=Jr({disabled:f,native:p}),F={open(ae){return ae&&L===mo?Bv.open(ae):zv.open(ae)}},{preFocusGuardRef:G,handlePreFocusGuardFocus:W,handleFocusTargetFocus:le}=yF(E,P),U=vt("button",t,{state:{disabled:f,open:R},ref:[Y,a,O,P],props:[K.reference,Q,q,X,{[U1]:"",id:D,"aria-haspopup":"dialog","aria-expanded":R,"aria-controls":I},S,$],stateAttributesMapping:F}),Z=s.jsx(x.Fragment,{children:U},D);return _&&!z?s.jsxs(x.Fragment,{children:[s.jsx(Wc,{ref:G,onFocus:W}),Z,s.jsx(Wc,{ref:E.context.triggerFocusTargetRef,onFocus:le})]}):Z}),uA=x.createContext(void 0);function wF(){const e=x.useContext(uA);if(e===void 0)throw new Error(on(45));return e}const SF=x.forwardRef(function(t,a){const{keepMounted:o=!1,...c}=t;return ff().useState("mounted")||o?s.jsx(uA.Provider,{value:o,children:s.jsx(sh,{ref:a,...c})}):null}),dA=x.createContext(void 0);function NF(){const e=x.useContext(dA);if(!e)throw new Error(on(46));return e}const kF=x.forwardRef(function(t,a){const{render:o,className:c,style:d,anchor:f,positionMethod:p,side:g,align:v,sideOffset:y,alignOffset:b,collisionBoundary:j="clipping-ancestors",collisionPadding:w,arrowPadding:S,sticky:N,disableAnchorTracking:k=!1,collisionAvoidance:E=F1,...D}=t,C=ff(),A=wF(),R=nH(),I=C.useState("floatingRootContext"),P=C.useState("mounted"),O=C.useState("open"),_=C.useState("openChangeReason"),L=C.useState("activeTriggerElement"),H=C.useState("modal"),B=C.useState("openMethod"),z=C.useState("positionerElement"),Q=C.useState("instantType"),K=C.useState("transitionStatus"),X=C.useState("adaptiveOrigin"),q=x.useRef(null),$=x1(z),Y=xh({anchor:f,floatingRootContext:I,positionMethod:p,mounted:P,side:g,sideOffset:y,align:v,alignOffset:b,arrowPadding:S,collisionBoundary:j,collisionPadding:w,sticky:N,disableAnchorTracking:k,keepMounted:A,nodeId:R,collisionAvoidance:E,adaptiveOrigin:X}),F=I.useState("domReferenceElement");De(()=>{const U=F,Z=q.current;if(U&&(q.current=U),Z&&U&&U!==Z){C.set("instantType",void 0);const ae=new AbortController;return $(()=>{C.set("instantType","trigger-change")},ae.signal),()=>{ae.abort()}}},[F,$,C]);const G=H===!0&&_!==Us;Qy(O&&G,B==="touch",z,L);const W=C.useStateSetter("positionerElement"),le={open:O,side:Y.side,align:Y.align,anchorHidden:Y.anchorHidden,instant:Q},M=bh(t,le,{styles:Y.positionerStyles,transitionStatus:K,props:D,refs:[a,W],hidden:!P,inert:!O});return s.jsxs(dA.Provider,{value:Y,children:[P&&G&&s.jsx(wh,{inert:vh(!O),cutout:L}),s.jsx(sH,{id:R,children:M})]})}),CF=x.createContext(void 0);function TF(){const[e,t]=x.useState(0),a=Ie(()=>(t(c=>c+1),()=>{t(c=>Math.max(0,c-1))}));return{context:x.useMemo(()=>({register:a}),[a]),hasClosePart:e>0}}const EF=x.forwardRef(function(t,a){const{render:o,className:c,style:d,initialFocus:f,finalFocus:p,...g}=t,v=ff(),y=NF(),b=zE()!=null,{context:j,hasClosePart:w}=TF(),S=v.useState("open"),N=v.useState("openMethod"),k=v.useState("instantType"),E=v.useState("transitionStatus"),D=v.useState("popupProps"),C=v.useState("titleElementId"),A=v.useState("descriptionElementId"),R=v.useState("modal"),I=v.useState("mounted"),P=v.useState("openChangeReason"),O=v.useState("activeTriggerElement"),_=v.useState("floatingRootContext"),L=_.useState("floatingId"),H=v.useState("disabled"),B=v.useState("openOnHover"),z=v.useState("closeDelay");ra({open:S,ref:v.context.popupRef,onComplete(){S&&v.context.onOpenChangeComplete?.(!0)}}),RT(_,{enabled:B&&!H,closeDelay:z});const Q=f===void 0?yT(v.context.popupRef):f,K=R!==!1&&w;v.useSyncedValue("focusManagerModal",K);const X=v.useStateSetter("popupElement"),q={open:S,side:y.side,align:y.align,instant:k,transitionStatus:E},$=vt("div",t,{state:q,ref:[a,v.context.popupRef,X],props:[D,{id:L,role:"dialog",...rf,"aria-labelledby":C,"aria-describedby":A,onKeyDown(Y){b&&yh.has(Y.key)&&Y.stopPropagation()}},of(E),g],stateAttributesMapping:Hv});return s.jsx(rh,{context:_,openInteractionType:N,modal:K,disabled:!I||P===Us,initialFocus:Q,returnFocus:p,restoreFocus:"popup",previousFocusableElement:dn(O)?O:void 0,nextFocusableElement:v.context.triggerFocusTargetRef,beforeContentFocusGuardRef:v.context.beforeContentFocusGuardRef,children:s.jsx(CF.Provider,{value:j,children:$})})});function pf(e){return s.jsx(gF,{"data-slot":"popover",...e})}function Lh(e){return s.jsx(jF,{"data-slot":"popover-trigger",...e})}function mf({className:e,sideOffset:t=6,align:a="start",side:o,alignOffset:c,collisionPadding:d=8,anchor:f,children:p,...g}){return s.jsx(SF,{children:s.jsx(kF,{className:"z-[35] outline-none",sideOffset:t,align:a,side:o,alignOffset:c,collisionPadding:d,anchor:f,children:s.jsx(EF,{"data-slot":"popover-content",className:Ue("flex max-h-[min(70vh,560px)] flex-col overflow-hidden rounded-lg border border-border-strong bg-raised text-foreground shadow-3","outline-none","data-open:animate-in data-open:fade-in-0 data-open:slide-in-from-top-1","data-closed:animate-out data-closed:fade-out-0",e),...g,children:p})})})}function AF({page:e,pageCount:t,onPageChange:a,disabled:o=!1,className:c,infoFirst:d=!1}){const f=Math.max(1,Number(t)||1),p=Math.min(Math.max(1,Number(e)||1),f),g=s.jsx("span",{"data-slot":"pager-info",className:"text-[11.5px] text-subtle [font-variant-numeric:tabular-nums]",children:go("第 {current} / {total} 页",{current:p,total:f})});return s.jsxs("div",{"data-slot":"pager",className:Ue("flex items-center gap-2",c),children:[d&&g,s.jsx(se,{type:"button",variant:"outline",size:"sm",disabled:o||p<=1,onClick:()=>a(p-1),children:go("上一页")}),s.jsx(se,{type:"button",variant:"outline",size:"sm",disabled:o||p>=f,onClick:()=>a(p+1),children:go("下一页")}),!d&&g]})}const RF=Vc(["relative flex w-full items-center gap-2.5 text-left","border border-transparent rounded-sm","shadow-none","transition-[background-color,border-color,color] duration-150 ease-out","outline-none focus-visible:shadow-focus","disabled:pointer-events-none disabled:opacity-45","[&_svg]:pointer-events-none [&_svg]:shrink-0"],{variants:{variant:{default:["cursor-pointer px-2.5 py-2","text-[12.5px] font-medium text-sidebar-fg","hover:bg-nav-hover hover:text-foreground","data-[active]:border-nav-selected-border data-[active]:bg-nav-selected-bg data-[active]:font-semibold data-[active]:text-nav-selected-fg"],add:["cursor-pointer justify-center px-2 py-1.5","border-dashed border-border-strong bg-transparent","text-[11.5px] text-muted-foreground","hover:border-primary hover:text-primary-fg"]}},defaultVariants:{variant:"default"}});function ru({className:e,variant:t,active:a=!1,count:o,icon:c,trailing:d,children:f,...p}){return s.jsxs("button",{type:"button","data-slot":"nav-item","data-active":a?"":void 0,"aria-current":a?"true":void 0,className:Ue(RF({variant:t}),e),...p,children:[c,s.jsx("span",{"data-slot":"nav-item-label",className:"min-w-0 flex-1 truncate",children:f}),d,o!=null&&s.jsx("span",{"data-slot":"nav-item-count",className:Ue("flex-none text-[10.5px] text-sidebar-muted [font-variant-numeric:tabular-nums]",a&&"text-inherit"),children:o})]})}function r(e,t){const a=typeof window<"u"?window.wbI18n:void 0;return a&&typeof a.t=="function"?a.t(e,t):e}function zh(e){if(e.source==="subscription"&&(e.port===null||e.port===void 0))return r("未分配端口");const t=e.resolved;return t?.protocol&&t.host&&t.port?`${String(t.protocol).toUpperCase()} ${t.host}:${t.port}`:t?.label||""}function au(e){const t=e.name||e.id,o=[e.resolveError?r("解析失败"):zh(e),e.enabled===!1?r("已禁用"):""].filter(Boolean);return o.length?r("{name}({parts})",{name:t,parts:o.join(" · ")}):t}const Ya="pool:";function Pe(){return window}function Le(e,t){Pe().wbApp?.toast?.(e,t)}function Xa(e){const t=Pe().wbApp?.esc;return t?t(e):String(e??"").replace(/[&<>"']/g,a=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[a]||a)}function Vs(e){const t=Pe().wbApp?.formatTime;if(t)return t(e);const a=Number(e);return!Number.isFinite(a)||a<=0?"":new Date(a).toLocaleString("zh-CN")}function ut(e){return e instanceof Error?e.message:String(e)}function lu(e){if(e==null||e==="")return null;const t=Number(e);return Number.isFinite(t)?t:null}function ej(e){const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const a=o=>String(o).padStart(2,"0");return`${a(t.getMonth()+1)}-${a(t.getDate())} ${a(t.getHours())}:${a(t.getMinutes())}`}function OF(e){return e==="积分"?r("积分"):e==="额度"?r("额度"):e}function MF(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=e,a=Array.isArray(t.credits)?t.credits:[],o=Date.now();return a.map(c=>{const d=String(c?.name||"").trim()||r("积分包"),f=String(c?.unit||"").trim(),p=lu(c?.total),g=lu(c?.used),v=lu(c?.remain),y=c?.unlimited===!0,b=lu(c?.grantAt),j=lu(c?.startAt),w=lu(c?.expireAt),S=c?.daily===!0,N=String(c?.grantReason||"").trim(),k=w!==null&&w>0&&w<=o,E=p!==null&&p>0,D=y?r("不限"):v!==null?E?r("剩 {remaining} / {total}",{remaining:v,total:p}):r("剩 {remaining}",{remaining:v}):g!==null?r("已用 {used}",{used:g}):"—",C=!y&&f&&D!=="—"?`${D} ${OF(f)}`:D,A=E&&v!==null?Math.max(0,Math.min(100,v/p*100)):null,R=v!==null&&v<=0||v===null&&g!==null&&E&&g>=p,I=!y&&!S&&(R||k),P=[];b!==null&&b>0?P.push(r("{time} 领取",{time:ej(b)})):j!==null&&j>0&&P.push(r("{time} 生效",{time:ej(j)})),S?P.push(r("每日重置")):w!==null&&w>0&&P.push(k?r("已过期"):r("{time} 到期",{time:ej(w)})),N&&P.push(N);const O=k||v===0?"muted":A!==null&&A<20?"warn":v===null&&g===null&&!y?"muted":"ok",_=[d,C,b!==null&&b>0?r("领取 {time}",{time:Vs(b)}):j!==null&&j>0?r("生效 {time}",{time:Vs(j)}):"",w!==null&&w>0?k?r("已过期({time})",{time:Vs(w)}):r("到期 {time}",{time:Vs(w)}):"",S?r("每日重置(额度按周期回满,不是作废)"):"",N,A===null&&v!==null?r("上游未给总量,画不出剩余比例"):"",g!==null&&p!==null?r("已用 {used} / 共 {total}",{used:g,total:p}):""].filter(Boolean).join(" · ");return{name:d,view:C,tone:O,percent:A,window:P.length?P.join(" · "):null,title:_,spent:I}})}function fA({row:e}){return s.jsxs("div",{className:"usage-pop-row",title:e.title,children:[s.jsxs("div",{className:"usage-pop-line",children:[s.jsx("span",{className:"usage-pop-name",children:e.name}),s.jsx("span",{className:`usage-pop-view ${e.tone}`,children:e.view})]}),e.window?s.jsx("div",{className:"usage-pop-window",children:e.window}):null,e.percent!==null?s.jsx("span",{className:"usage-pop-track",children:s.jsx("i",{style:{width:`${e.percent}%`},"aria-label":r("剩余 {percent}%",{percent:Math.round(e.percent)})})}):null]})}function pA({rows:e,subscriptionLine:t,variant:a,kind:o,title:c,children:d}){const[f,p]=x.useState(!1),[g,v]=x.useState(!1),y=e.filter(k=>!k.spent),b=e.filter(k=>k.spent),j=a==="pool"?`usage-toggle usage-pool-line ${o}`:`usage-toggle ${o}`,w=x.useRef(null),S=x.useCallback(k=>{w.current=k,k&&(k.scrollTop=0)},[]),N=x.useCallback(()=>w.current??null,[]);return x.useLayoutEffect(()=>{if(!g)return;const k=w.current?.querySelector(".usage-pop-spent .usage-pop-row");k instanceof HTMLElement&&k.scrollIntoView({block:"nearest"})},[g]),s.jsxs(pf,{open:f,onOpenChange:p,children:[s.jsxs(Lh,{render:s.jsx("button",{type:"button",className:j,title:c,"aria-label":r("积分明细")}),children:[a==="pool"?d:s.jsx("span",{className:"val",children:d}),s.jsx("span",{className:"caret","aria-hidden":!0,children:"▾"})]}),s.jsx(mf,{align:"end",sideOffset:6,className:"w-[320px]",initialFocus:N,children:s.jsxs("div",{className:"usage-pop-credit",ref:S,tabIndex:-1,children:[t?s.jsx("div",{className:"usage-pop-sub",children:t}):null,s.jsx("div",{className:"usage-pop-group",children:r("积分明细")}),y.map((k,E)=>s.jsx(fA,{row:k},`${k.name}-${E}`)),b.length>0?s.jsxs("div",{className:"usage-pop-spent",children:[s.jsxs("button",{type:"button",className:"usage-pop-spent-head","aria-expanded":g,title:r("展开或收起(默认收起)"),onClick:()=>v(k=>!k),children:[s.jsx("span",{className:"caret","aria-hidden":!0,children:"▾"}),s.jsx("span",{children:r("已用完 / 已过期")}),s.jsx("span",{className:"n",children:r("{count} 份",{count:b.length})})]}),g?b.map((k,E)=>s.jsx(fA,{row:k},`spent-${k.name}-${E}`)):null]}):null]})})]})}const ou="workbuddy",DF="raccoon",IF={workbuddy:{usage:!0,creditDetail:!0,edition:!0,identifier:"uid",expiry:"expiresAt"},"workbuddy-intl":{usage:!0,creditDetail:!0,edition:!1,identifier:"uid",expiry:"expiresAt"},raccoon:{usage:!0,creditDetail:!0,edition:!1,identifier:"userId",expiry:"tokenExpiresAt"},catpaw:{usage:!0,edition:!1,identifier:"uid",expiry:"tokenExpiresAt"},autoclaw:{usage:!0,creditDetail:!0,edition:!1,identifier:"userId",expiry:"tokenExpiresAt"},"autoclaw-intl":{usage:!0,creditDetail:!0,edition:!1,identifier:"userId",expiry:"tokenExpiresAt",emailAsName:!0},qoder:{usage:!0,creditDetail:!0,edition:!0,identifier:"userId",expiry:"expiresAt",emailAsName:!0},"qoder-intl":{usage:!0,creditDetail:!0,edition:!0,identifier:"userId",expiry:"expiresAt",emailAsName:!0},"cline-free":{usage:!0,edition:!1,identifier:"account",expiry:"expiresAt"},"cline-pass":{usage:!0,edition:!1,identifier:"account",expiry:"expiresAt"},accio:{usage:!0,edition:!0,identifier:"userId",expiry:"expiresAt",emailAsName:!0},"accio-cn":{usage:!0,edition:!0,identifier:"userId",expiry:"expiresAt",emailAsName:!0},zcode:{usage:!0,creditDetail:!0,claim:!0,planChannel:!0,edition:!0,identifier:"userId",expiry:"expiresAt"},"zcode-intl":{usage:!0,creditDetail:!0,claim:!0,planChannel:!0,edition:!0,identifier:"userId",expiry:"expiresAt"},codearts:{usage:!0,usageDetail:!0,edition:!1,identifier:"userId",expiry:"expiresAt",concurrencyDefault:3},trae:{usage:!0,creditDetail:!0,edition:!1,identifier:"uid",expiry:"expiresAt"},loomy:{usage:!0,creditDetail:!0,edition:!1,identifier:"userId",expiry:"expiresAt"},kuku:{usage:!0,edition:!1,identifier:"uid",expiry:""},officeace:{usage:!0,creditDetail:!0,edition:!1,identifier:"id",expiry:"expiresAt"},antigravity:{usage:!0,edition:!1,identifier:"userId",expiry:""}},PF={usage:!1,edition:!1,identifier:"userId",expiry:"tokenExpiresAt",emailAsName:!1};function kn(e){const t=e?.provider;return typeof t=="string"&&t?t:ou}function ir(e){return e&&IF[e]||PF}const _F="opencode",LF="https://opencode.ai/zen/go/v1";function mA(e,t){if(!e||e.clientEmulation!==_F)return!1;const o=((typeof t=="string"?t.trim():"")||String(e.baseUrl||"")).trim().replace(/\/+$/,"").toLowerCase();return o?o!==LF:!1}function zF(e){const t=e?kn(e):"";return t.startsWith("custom-")&&(Pe().wbProviders?.customList?.()||[]).find(o=>o?.id===t)||null}function BF(e){return e?mA(zF(e),e.baseUrl):!1}function hA(e){const t=Array.isArray(e?.providers)?e.providers:[],a=Array.isArray(e?.accounts)?e.accounts:[],o=new Map;a.forEach(d=>{const f=kn(d);o.set(f,(o.get(f)||0)+1)});const c=new Map;return t.forEach(d=>{d?.id&&c.set(String(d.id),{id:String(d.id),label:String(d.label||d.id),count:Number(d.count)||0})}),o.forEach((d,f)=>{c.has(f)||c.set(f,{id:f,label:Pe().wbProviders?.labelOf?.(f)||f,count:d})}),c.size||c.set(ou,{id:ou,label:Pe().wbProviders?.labelOf?.(ou)||"WorkBuddy 国内版",count:0}),[...c.values()]}function Bh(e){const t=ir(kn(e)).identifier;return String(e?.[t]||"")}function gA(e){const t=Number(e)||0;return t<=0?0:t<1e11?t*1e3:t}function HF(e){const t=ir(kn(e)).expiry;return gA(e?.[t])}function Ta(e){const t=kn(e);return t.startsWith("custom-")?!!e?.balanceQuery?.scheme:ir(t).usage}const tj=30,xA=86400,bA=60,vA=1800,yA=86400,jA=1,UF=95e5;function VF(e){return e==="codearts"?[{type:"token",action:"skip",threshold:UF,reset:"daily",enabled:!0}]:e==="cline-free"?[]:[{type:"balance",action:"skip",threshold:jA,enabled:!0}]}function wA(e){const t=e?.usageQuery;if(!t||typeof t!="object")return{enabled:!0,interval:bA};const a=t.enabled===void 0?!0:t.enabled===!0,o=Number(t.interval)||0,c=o>=tj&&o<=xA;return{enabled:a,interval:a&&!c?bA:o}}function FF(e){if(!e||typeof e!="object")return!1;const t=e;if(t.type!=="balance"&&t.type!=="token"||t.action!=="skip"&&t.action!=="disable")return!1;const a=Number(t.threshold);if(!Number.isFinite(a)||a<=0)return!1;if(t.type==="token"&&t.reset!=="daily"){const o=Number(t.period);if(!Number.isInteger(o)||oyA)return!1}return!0}function $F(e){const t=e?.lowBalance;if(!t||typeof t!="object"||!t.mode)return VF(kn(e));const a=Number(t.threshold),o=Number.isFinite(a)&&a>0?a:jA;return t.mode!=="skip"&&t.mode!=="disable"?[]:[{type:"balance",action:t.mode,threshold:o,enabled:!0}]}function iu(e){const t=e?.limiters;return Array.isArray(t)?t.filter(FF):$F(e)}function qF(e){return iu(e).filter(t=>t.type==="token")}function GF(e,t){const a=t*1e3;return e-e%a}function SA(e){return e.reset==="daily"?0:e.period??0}function nj(e,t=Date.now()){if(e===0){const a=new Date(t);return a.setHours(0,0,0,0),a.getTime()}return GF(t,e)}function hf(e,t,a=Date.now()){if(e.type!=="token")return null;const o=SA(e),c=(t||[]).find(d=>Number(d.kind)===o);return c&&Number(c.windowStart)===nj(o,a)?c:null}function Hh(e,t){const a=iu(e).filter(f=>f.type==="balance"&&f.action==="skip"&&f.enabled!==!1&&f.threshold>0);if(!a.length||!t||typeof t!="object")return!1;const o=t;if(o.unlimited)return!1;const c=o.totalLeft??o.available;if(c==null||c==="")return!1;const d=Number(c);return Number.isFinite(d)&&a.some(f=>dc.type==="token"&&c.action==="skip"&&c.enabled!==!1);if(!a.length||!t?.length)return!1;const o=Date.now();return a.some(c=>{const d=hf(c,t,o);return d!==null&&Number(d.used)>=c.threshold})}function KF(e,t){return iu(e).some(a=>{if(a.type!=="token"||a.action!=="disable"||a.enabled===!1)return!1;const o=hf(a,t);return o!==null&&Number(o.used)>=a.threshold})}function rj(e,t=Date.now()){const a=SA(e),o=nj(a,t),c=a===0?Math.max(0,nj(0,o+864e5+36e5)-t):Math.max(0,o+a*1e3-t);return{kind:a,startMs:o,remainingMs:c,daily:a===0}}function Uh(e,t){if(e<=0)return"";const a=Math.ceil(e/6e4);if(t){const o=Math.ceil(e/36e5);return o>=1?r("今日剩 {n} 小时",{n:o}):r("今日剩 {n} 分钟",{n:a})}return a>=1?r("剩 {n} 分钟",{n:a}):r("剩不到 1 分钟")}function Tl(e){const t=Number(e);if(!Number.isFinite(t))return"—";const a=window.wbUnits;return a?.formatTokens?a.formatTokens(t):String(Math.round(t))}function NA(e){return e>0&&e%3600===0?r("{n} 小时",{n:e/3600}):e>0&&e%60===0?r("{n} 分钟",{n:e/60}):r("{n} 秒",{n:e})}function gf(e){return e?.desktop===!0}function kA(e){return e?.chatSupported!==!1}function YF(e){return typeof e=="string"&&e.startsWith("custom-")}function XF(e){return r(e==="enterprise"?"企业":e==="ultimate"?"旗舰":"个人")}function Vh(e,t){const a=Number(e?.priority??100)-Number(t?.priority??100);return a!==0?a:(Number(e?.addedAt)||0)-(Number(t?.addedAt)||0)}function cr(e){return e?.enabled!==!1}function xf(e,t=""){const a=e?.rateLimits||{},o=Date.now();return t?Number(a[t]?.resetAt)>o:Object.values(a).some(c=>Number(c?.resetAt)>o)}function CA(e){return e?.edition==="intl"?"intl":"cn"}function TA(e){return ir(kn(e)).claim?e?.canClaim!==!1:!1}const EA="coding-plan",jo="start-plan";function Fh(e){return!!ir(kn(e)).planChannel}function aj(e){return Fh(e)?String(e?.zcodePlan||"").trim()===jo?jo:EA:""}function QF(e){return r(e===jo?"活动套餐(Start Plan)":"编码套餐(Coding Plan)")}function AA(e){switch(String(e??"").trim()){case"pending":return r("待生效");case"active":return r("生效中");case"expired":return r("已过期");case"unknown":return r("状态未知");default:return String(e??"")}}function $h(e){const t=e?.claimPlans;if(!t||typeof t!="object"||Array.isArray(t))return[];const a=lj();return Object.entries(t).filter(([,o])=>Number(o)>0&&lj(Number(o))===a).map(([o])=>o)}function ZF(e){return $h(e).length>0}function WF(e){const t=$h(e),a=t.length?r("({plans})",{plans:t.join(r("、"))}):"";return r("今天(北京时间 {day})已领取 {n} 份{names};还有其他可领套餐时,点这里可以继续领;活动按自然日发新套餐,明天可再领",{day:lj(),n:t.length,names:a})}function JF(e){return!!ir(kn(e)).usageDetail}function RA(e){return!!ir(kn(e)).creditDetail}function OA(e){return/^free$/i.test(String(e??"").trim())}function e$(e){const t=String(e??"").trim();return/^trial$/i.test(t)?r("试用版"):OA(t)?r("免费版"):t}function lj(e=Date.now()){return new Date(e+8*3600*1e3).toISOString().slice(0,10)}function bf(e,t,a){return xf(e)||Hh(e,t)||sj(e,a)}function MA(e,t){const a=String(t.q||"").trim().toLowerCase();return a?[cu(e),e?.name,e?.nickname,e?.email,Bh(e),e?.id].some(c=>String(c||"").toLowerCase().includes(a)):!0}function DA(e,t){return t.provider==="all"||kn(e)===t.provider}function oj(e,t){return t.enabled==="all"?!0:t.enabled==="enabled"?cr(e):!cr(e)}function IA(e,t,a,o){if(t.limit==="all")return!0;if(!cr(e))return!1;const c=bf(e,a?.(e),o?.(e));return t.limit==="limited"?c:!c}function PA(e,t,a,o){return DA(e,t)&&oj(e,t)&&IA(e,t,a,o)&&MA(e,t)}function t$(e,t,a,o){return(e||[]).filter(c=>PA(c,t,a,o))}function _A(e,t,a,o){const c=e||[],d=g=>c.filter(v=>DA(v,t)&&(g==="enabled"||oj(v,t))&&MA(v,t)),f=d("enabled"),p=d("limit");return{enabledAll:f.length,enabled:f.filter(cr).length,disabled:f.filter(g=>!cr(g)).length,limitAll:p.length,normal:p.filter(g=>cr(g)&&!bf(g,a?.(g),o?.(g))).length,limited:p.filter(g=>cr(g)&&bf(g,a?.(g),o?.(g))).length}}function ij(e){const t=e?.rateLimits;if(!t||typeof t!="object")return[];const a=Date.now();return Object.entries(t).map(([o,c])=>({model:o,...c&&typeof c=="object"?c:{}})).filter(o=>Number(o.resetAt)>a).sort((o,c)=>Number(o.resetAt)-Number(c.resetAt))}function cj(e){const t=(e||[]).slice().sort(Vh),a=new Map;return t.forEach((o,c)=>a.set(o.id,{position:c+1,total:t.length})),a}function n$(e,t,a,o){const c=(e||[]).slice().sort(Vh),d=[],f=new Map;for(const p of c){const g=kn(p);f.has(g)||(f.set(g,[]),d.push(g)),f.get(g).push(p)}return d.map((p,g)=>{const v=f.get(p)||[];return{provider:p,label:Pe().wbProviders?.labelOf?.(p)||p,rank:g+1,members:v,accounts:t?v.filter(t):v,enabled:v.filter(cr).length,disabled:v.filter(y=>!cr(y)).length,limited:v.filter(y=>cr(y)&&bf(y,a?.(y),o?.(y))).length}})}function cu(e){if(!e)return"";const t=String(e.name||"").trim();if(e.nameCustom===!0&&t)return t;const a=String(e.email||"").trim();return ir(kn(e)).emailAsName&&a?a:e?.nickname||t||Bh(e)||e?.id||""}const uj="已限流",LA=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime();function dj(e){const t=Number(e);if(!Number.isFinite(t)||t<=0||t<=Date.now())return uj;const a=new Date(t),o=a.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",hour12:!1}),c=Math.round((LA(a)-LA(new Date))/864e5);return c===0?r("今天 {clock}",{clock:o}):c===1?r("明天 {clock}",{clock:o}):r("{month}月{day}日 {clock}",{month:a.getMonth()+1,day:a.getDate(),clock:o})}function s$(e){const t=kn(e);if(!ir(t).edition)return"";const a=CA(e),o=e?.editionLabel,c=o||(a==="intl"?"国际版":"国内版");return(Pe().wbProviders?.labelOf?.(t)||"").includes(c)?"":o||r(a==="intl"?"国际版":"国内版")}function r$(e){return[kA(e)?null:{text:r("仅账号管理"),kind:"plain",title:r("该提供商的推理转发尚未接入,账号不参与转发")},YF(kn(e))&&e.hasCredentials===!1?{text:r("未配置凭证"),kind:"bad",title:r("这条自定义账号既没有 API Key,也没有勾选「无需鉴权」:转发时会被跳过,该提供商下的模型也不会出现在模型列表里。去账号「设置」里补上 Key,或勾选「该上游无需鉴权」")}:null,e.proxy?.error?{text:r("代理异常"),kind:"bad",title:r("{error}(转发时会回退直连)",{error:e.proxy.error})}:null,aj(e)===jo?{text:r("活动套餐"),kind:"plain",title:r("转发走活动套餐通道(zcode.z.ai 的 Anthropic 端点,用账号里领到的额度);在账号设置里可切回编码套餐")}:null].filter(t=>t!==null)}const zA="workbuddy-desktop-accounts-filters",BA="workbuddy-desktop-accounts-collapsed",HA="workbuddy-desktop-accounts-names-hidden";function a$(){const e={provider:"all",enabled:"all",limit:"all",q:""},t=Pe().wbFilterMemory?.load(zA,e)||e;return{provider:String(t.provider||"all"),enabled:String(t.enabled||"all"),limit:String(t.limit||"all"),q:""}}function l$(){try{const e=JSON.parse(localStorage.getItem(BA)||"[]");return new Set(Array.isArray(e)?e.map(t=>String(t)).filter(Boolean):[])}catch{return new Set}}function o$(){try{return localStorage.getItem(HA)==="1"}catch{return!1}}let pn={version:0,filter:a$(),collapsed:l$(),selected:new Set,panels:new Map,connections:new Map,clash:null,dialog:null,namesHidden:o$(),usageBusy:!1,usageInflight:new Set};const fj=new Set;function UA(e){return fj.add(e),()=>{fj.delete(e)}}function Zs(){return pn}function Cn(e){pn={...pn,...e,version:pn.version+1},fj.forEach(t=>t())}function br(){Cn({})}function pj(){return Pe().wbApp?.getState?.()?.accounts}function El(){const e=pj()?.accounts;return Array.isArray(e)?e:[]}function Ea(e){return El().find(t=>t.id===e)||null}function i$(e,t){const a=n$(El(),c=>PA(c,pn.filter,e,t),e,t);return{groups:a.filter(c=>c.accounts.length>0),allGroups:a}}function VA(){return hA(pj())}function c$(e,t){return _A(El(),pn.filter,e,t)}function u$(){return cj(El())}function qh(){Pe().wbFilterMemory?.save(zA,{provider:pn.filter.provider,enabled:pn.filter.enabled,limit:pn.filter.limit})}function d$(e){pn.filter.q!==e&&Cn({filter:{...pn.filter,q:e}})}function f$(e){const t=e||"all";pn.filter.provider!==t&&(Cn({filter:{...pn.filter,provider:t}}),qh())}function FA(e,t){const a={...pn.filter,[e]:t};a.enabled==="disabled"&&a.limit!=="all"&&(a.limit="all"),Cn({filter:a}),qh()}function Gh(){return pn.filter.provider!=="all"||pn.filter.enabled!=="all"||pn.filter.limit!=="all"||pn.filter.q.trim()!==""}function $A(){Cn({filter:{provider:"all",enabled:"all",limit:"all",q:""}}),qh()}function p$(){const e=pn.filter.provider;e!=="all"&&(VA().some(t=>t.id===e)||(Cn({filter:{...pn.filter,provider:"all"}}),qh()))}function qA(e){try{localStorage.setItem(BA,JSON.stringify([...e]))}catch{}}function GA(e){const t=new Set(pn.collapsed);t.has(e)?t.delete(e):t.add(e),qA(t),Cn({collapsed:t})}function m$(e,t){const a=new Set(pn.collapsed);for(const o of e)t?a.add(o):a.delete(o);qA(a),Cn({collapsed:a})}function h$(e){return pn.selected.has(e)}function g$(e,t){const a=new Set(pn.selected);t?a.add(e):a.delete(e),Cn({selected:a})}function KA(e,t){const a=new Set(pn.selected);for(const o of e)t?a.add(o):a.delete(o);Cn({selected:a})}function x$(){Cn({selected:new Set})}function YA(e,t){return pn.panels.get(e)?.has(t)===!0}function XA(e,t,a){if(!e)return;const o=new Map(pn.panels),c=new Set(o.get(e)||[]);a?c.add(t):c.delete(t),c.size?o.set(e,c):o.delete(e),Cn({panels:o})}function b$(e,t){const a=new Map(pn.panels);for(const o of e){const c=new Set(a.get(o)||[]);c.add(t),a.set(o,c)}Cn({panels:a})}function v$(){const e=!pn.namesHidden;try{localStorage.setItem(HA,e?"1":"0")}catch{}Cn({namesHidden:e})}function y$(e){return"*".repeat(Math.min(Math.max(e.length,4),12))}const QA="usage_not_configured",wo=new Map,vf=new Map;function oa(e,t,a){wo.set(e,t),t!=null&&uu(t)?vf.set(e,a):vf.delete(e)}function Qa(e){const t=wo.get(e.id);if(t===void 0)return;if(!uu(t))return t;const a=Math.max(Number(e.addedAt)||0,Number(e.updatedAt)||0);return(vf.get(e.id)||0)>=a?t:void 0}const yf=new Map;let ZA=0;function Al(e){return e?yf.get(e.id)||[]:[]}function j$(e){const t=Number(e?.tokenAt)||0;if(!t||t===ZA)return!1;const a=e?.tokenUsage;if(!a||typeof a!="object")return!1;ZA=t;const o=new Map;for(const[d,f]of Object.entries(a)){if(!Array.isArray(f))continue;const p=[];for(const g of f){if(!g||typeof g!="object")continue;const v=Number(g.kind),y=Number(g.windowStart),b=Number(g.used);!Number.isFinite(v)||v<0||!Number.isFinite(y)||y<=0||!Number.isFinite(b)||b<0||p.push({kind:v,windowStart:y,used:b})}o.set(d,p)}const c=o.size!==yf.size||[...o].some(([d,f])=>{const p=yf.get(d);return!p||p.length!==f.length||f.some((g,v)=>g.used!==p[v]?.used||g.windowStart!==p[v]?.windowStart)});yf.clear();for(const[d,f]of o)yf.set(d,f);return c}let Kh=null;async function WA(e={}){const t=Zs().clash;if(!e.force&&t)return t;Kh||(Kh=(async()=>{try{const o=await Pe().workbuddyDesktop?.getProxies?.();if(!o||typeof o!="object"||!o.clash)throw new Error(r("代理列表响应异常({type})",{type:typeof o}));return o.clash}finally{Kh=null}})());const a=await Kh;return Cn({clash:a}),a}function w$(){Cn({clash:null})}let jf=null,Yh=null;function S$(){return jf}async function JA(e={}){if(!e.force&&jf)return jf;Yh||(Yh=(async()=>{try{const a=await Pe().workbuddyDesktop?.getProxyPool?.();if(!a||typeof a!="object"||!Array.isArray(a.items))throw new Error(r("代理池响应异常({type})",{type:typeof a}));return a.items}finally{Yh=null}})());const t=await Yh;return jf=t,t}let mj=null;function N$(){return mj}let Xh=0,eR=!1;function k$(){if(!(jf||Date.now(){Xh=0,mj=null,br()}).catch(e=>{mj=ut(e),br()})}}function Qh(e){if(!Ea(e)){Le(r("账号不存在,请刷新后重试"),"err");return}Cn({dialog:{kind:"settings",id:e}})}function Zh(){Cn({dialog:null})}function hj(e,t="enable"){const a=(Array.isArray(e)?e:[]).filter(o=>Ea(o));if(!a.length){Le(r("请先勾选要操作的账号"),"err");return}Cn({dialog:{kind:"batch",ids:a,action:t}})}function C$(e){let t=!1;for(const f of[...wo.keys()])e.has(f)||(wo.delete(f),t=!0);for(const f of[...vf.keys()])e.has(f)||vf.delete(f);const a=new Map(Zs().panels);for(const f of[...a.keys()])e.has(f)||(a.delete(f),t=!0);const o=new Map(Zs().connections);for(const f of[...o.keys()])e.has(f)||(o.delete(f),t=!0);const c=new Set(Zs().usageInflight);for(const f of[...c])e.has(f)||(c.delete(f),t=!0);const d=new Set(Zs().selected);for(const f of[...d])e.has(f)||(d.delete(f),t=!0);t&&Cn({panels:a,connections:o,usageInflight:c,selected:d})}const T$=2e3;function tR(e){return Zs().connections.get(e)||0}async function nR(){try{const e=await Pe().workbuddyDesktop?.getAccountConnections?.(),t=e?.counts&&typeof e.counts=="object"?e.counts:{},a=new Map;for(const[o,c]of Object.entries(t)){const d=Number(c)||0;d>0&&a.set(o,d)}return Cn({connections:a}),!0}catch{return!1}}let sR=null;function E$(){sR||(sR=setInterval(()=>{document.hidden||Pe().wbApp?.currentPage!=="accounts"||nR()},T$))}function gj(){return El().filter(e=>Ta(e)&&e.available!==!1)}function uu(e){if(e==null)return null;if(typeof e=="string")return{message:e,notConfigured:!1};if(typeof e!="object")return null;const t=e.error;return t?{message:String(t),notConfigured:e.code===QA}:null}function rR(e){return e.usage?e.usage:{error:e.error?String(e.error):r("余额响应为空"),code:e.code}}function aR(e){const t=Array.isArray(e?.results)?e.results:[],a=Number(e?.at)||Date.now();let o=0;for(const c of t)c?.id&&(oa(String(c.id),rR(c),Number(c.at)||a),o++);return o&&(br(),Pe().wbApp?.renderTopbarStatus?.()),o}let lR=!1;function A$(e){if(!RA(e))return!1;const t=Qa(e);return!t||typeof t!="object"||Array.isArray(t)||uu(t)?!1:!Array.isArray(t.credits)}async function R$(){if(!lR){lR=!0;for(const e of El().filter(A$)){const t=wo.get(e.id);try{await wf(e.id)}catch{}const a=wo.get(e.id);t!==void 0&&(!a||uu(a))&&oa(e.id,t,Date.now()),br()}}}let oR=0;async function O$(){try{const e=await Pe().workbuddyDesktop?.getBalancesSnapshot?.(),t=j$(e);t&&(br(),Pe().wbApp?.renderTopbarStatus?.());const a=Number(e?.at)||0;return!a||a===oR||(oR=a,!aR(e))?t:(R$(),!0)}catch{return!1}}async function wf(e){const t=await Pe().workbuddyDesktop?.getAllBalances?.(e||void 0),a=Array.isArray(t?.results)?t.results:[],o=Date.now(),c=new Set;for(const d of a){if(!d?.id)continue;const f=String(d.id);e&&f!==e||(c.add(f),oa(f,rR(d),o))}if(e)return c.has(e)||oa(e,r("未返回余额数据"),o),br(),t;for(const d of gj())c.has(d.id)||oa(d.id,r("未返回余额数据"),o);return br(),t}async function iR(){if(Zs().usageBusy)return;const e=gj();if(!e.length){Le(r("暂无可查询余额的账号"),"err");return}Cn({usageBusy:!0}),e.forEach(t=>oa(t.id,null,Date.now())),br();try{const t=(await wf(null))?.results||[],a=t.filter(f=>f.usage).length,o=t.filter(f=>f.code===QA).length,c=o?r("({n} 个未配置查询凭证)",{n:o}):"",d=t.length-a-o;Le(a+o===t.length?r("✅ 已更新 {n} 个账号的余额{suffix}",{n:a,suffix:c}):r("已更新 {ok}/{total} 个账号,{failed} 个失败",{ok:a,total:t.length,failed:d}),d?"err":"ok")}catch(t){const a=ut(t);e.forEach(o=>oa(o.id,r("查询失败:{message}",{message:a}),Date.now())),br(),Le(r("余额查询失败:{message}",{message:a}),"err")}finally{Cn({usageBusy:!1})}}async function cR(e){if(Zs().usageInflight.has(e))return;const t=new Set(Zs().usageInflight);t.add(e),oa(e,null,Date.now()),Cn({usageInflight:t});try{await wf(e)}finally{const a=new Set(Zs().usageInflight);a.delete(e),Cn({usageInflight:a})}}async function M$(e){if(!Zs().usageInflight.has(e))try{await cR(e);const t=uu(wo.get(e));t?.notConfigured?Le(t.message,"ok"):t?Le(r("余额查询失败:{message}",{message:t.message}),"err"):Le(r("✅ 已更新余额"))}catch(t){oa(e,r("查询失败:{message}",{message:ut(t)}),Date.now()),br(),Le(r("余额查询失败:{message}",{message:ut(t)}),"err")}}async function Wh(e){if(e){const a=Ea(e);if(!a||!Ta(a))return;try{await cR(e)}catch(o){oa(e,r("查询失败:{message}",{message:ut(o)}),Date.now()),br()}return}if(Zs().usageBusy)return;const t=gj();if(t.length){Cn({usageBusy:!0}),t.forEach(a=>oa(a.id,null,Date.now())),br();try{await wf(null)}catch(a){const o=ut(a);t.forEach(c=>oa(c.id,r("查询失败:{message}",{message:o}),Date.now())),br()}finally{Cn({usageBusy:!1})}}}async function uR(e,t){try{await Pe().workbuddyDesktop?.updateAccount?.(e,{enabled:t}),await Pe().wbApp?.refresh?.(),Le(r(t?"✅ 已启用":"✅ 已禁用"))}catch(a){Le(r("操作失败:{message}",{message:ut(a)}),"err"),Pe().wbApp?.refresh?.()}}async function dR(e,t){if(!e.length)return!1;try{return await Pe().workbuddyDesktop?.reorderAccounts?.(e),Le(t?r("✅ 已保存:{note}",{note:t}):r("✅ 顺序已保存")),await Pe().wbApp?.refresh?.(),!0}catch(a){return Le(r("顺序未保存:{message}",{message:ut(a)}),"err"),Pe().wbApp?.refresh?.(),!1}}async function fR(e,t){if(e.length)try{await Pe().workbuddyDesktop?.batchAccounts?.({action:t?"enable":"disable",ids:e}),Le(t?r("✅ 已启用 {n} 个账号",{n:e.length}):r("✅ 已禁用 {n} 个账号",{n:e.length})),await Pe().wbApp?.refresh?.()}catch(a){Le(r("操作失败:{message}",{message:ut(a)}),"err"),Pe().wbApp?.refresh?.()}}async function D$(e,t){try{await Pe().workbuddyDesktop?.clearRateLimits?.(e,t||null),Le(t?r("✅ 已清除 {model} 的限流标记",{model:t}):r("✅ 已清除该账号全部限流标记")),await Pe().wbApp?.refresh?.()}catch(a){Le(r("清除失败:{message}",{message:ut(a)}),"err")}}async function I$(e,t,a){if(t===pR){Qh(e);return}if(t!==Jh&&t!==a)try{const o=t===""?null:{source:"pool",proxyId:t.slice(Ya.length)},d=(await Pe().workbuddyDesktop?.updateAccount?.(e,{proxy:o}))?.changes,f=Array.isArray(d)&&d.length?d[0]:r("代理已更新");Le(`✅ ${f}`)}catch(o){Le(r("保存失败:{message}",{message:ut(o)}),"err")}finally{await Pe().wbApp?.refresh?.()}}const Jh="__proxy_custom__",pR="__proxy_custom_edit__";function mR(e,t){const a=Ea(e);if(!a){Le(r("账号不存在,请刷新后重试"),"err");return}const o=Pe().wbZcodePlans;if(!o?.open){Le(r("套餐明细弹窗未加载,请重启应用后重试"),"err");return}o.open({id:e,name:t||a.name})}function P$(e,t,a=1){return{seat:t.get(e.id)||{position:1,total:1},rank:a,picked:h$(e.id),usageEntry:wo.get(e.id),limitsOpen:YA(e.id,"limits"),connections:tR(e.id)}}const _$={DEFAULT_PROVIDER_ID:ou,RACCOON_PROVIDER_ID:DF,providerOf:kn,providerFeatures:ir,providerSummaries:hA,identifierOf:Bh,tokenExpiryOf:HF,supportsUsage:Ta,isDesktopAccount:gf,supportsChat:kA,byPriorityOrder:Vh,typeLabel:XF,isEnabled:cr,isRateLimited:xf,isLimited:e=>bf(e,e?Qa(e):void 0,Al(e)),accountEdition:CA,supportsClaim:TA,matchEnabled:oj,matchLimit:IA,visibleAccounts:t$,filterCounts:_A,positionMap:cj,activeLimits:ij,editionSuffix:s$,formatResetText:dj};function L$(){window.wbAccountsView={render:()=>br(),refreshCaches:C$,openPanels:b$,syncConnections:nR,applyBalances:aR,syncBalancesSnapshot:O$,queryUsageFor:wf,queryAllUsage:iR,refreshUsageAfterCheckin:Wh,supportsUsage:Ta,isDesktopAccount:gf,isEnabled:cr,isRateLimited:xf},window.wbAccountsModel=_$,window.wbAccountPanel={open:Qh,close:Zh,openBatch:hj,closeBatch:Zh,syncAddProvider:()=>Pe().wbAccountAddForms?.syncAddProvider?.(),invalidate:w$}}function z$(e){return e.type==="balance"?r("余额 < {threshold}",{threshold:e.threshold}):e.reset==="daily"?r("每日消耗 ≥ {count} Token(每天 0 点重置)",{count:Tl(e.threshold)}):r("每 {period}消耗 ≥ {count} Token",{period:NA(e.period??0),count:Tl(e.threshold)})}function B$(e){return e.action==="disable"?r("禁用该账号(需手动重新启用)"):r("跳过该账号(自动恢复)")}function H$(e){return`${Math.round(e.threshold).toLocaleString("en-US")} Token`}function U$(e,t){if(t.enabled===!1)return{text:r("已停用"),kind:"off"};if(t.type==="balance"){const v=Qa(e),y=Hh(e,v),b=v&&typeof v=="object"?v:null,j=b?b.totalLeft??b.available:void 0,w=j==null||j===""||b?.unlimited?"":r(" · 当前 {n}",{n:Number(j)});return y?{text:r("已跳过{current}",{current:w}),kind:"warn",title:r("余额低于阈值,转发时会跳过该账号(余额回升自动恢复)")}:{text:r("未触发{current}",{current:w}),kind:"ok"}}const a=Al(e),o=hf(t,a),c=o?o.used:0,d=Tl(t.threshold),f=t.reset==="daily"?r(" · 今日 {used} / {quota}",{used:Tl(c),quota:d}):r(" · 本周期 {used} / {quota}",{used:Tl(c),quota:d}),p=o?` · ${Uh(rj(t).remainingMs,t.reset==="daily")}`:"";return o!==null&&c>=t.threshold?t.action==="disable"?e.enabled===!1?{text:r("已触发 · 账号已禁用"),kind:"danger",title:r("重置也不恢复,需手动启用")}:{text:r("已达上限{usage}",{usage:f}),kind:"warn",title:r("稍后由后台判定自动禁用")}:{text:r("已跳过{usage}{countdown}",{usage:f,countdown:p}),kind:"warn",title:r("窗口内已用 {used} / {limit} Token,转发时会跳过该账号(重置后自动恢复)",{used:Math.round(c).toLocaleString("en-US"),limit:Math.round(t.threshold).toLocaleString("en-US")})}:{text:r("未触发{usage}{countdown}",{usage:f,countdown:p}),kind:"ok",title:H$(t)}}function V$(e){return e>0&&e%3600===0?{value:String(e/3600),unit:"hours"}:e>0&&e%60===0?{value:String(e/60),unit:"minutes"}:{value:"1",unit:"hours"}}function hR(e){const t={type:"balance",action:"skip",thresholdInput:"",tokenUnit:"wan",reset:"fixed",periodInput:"1",periodUnit:"hours"};if(!e)return t;if(e.type==="balance")return{...t,type:"balance",action:e.action,thresholdInput:String(e.threshold)};if(e.reset==="daily")return{...t,type:"token",action:e.action,reset:"daily",thresholdInput:String(e.threshold%1e4===0?e.threshold/1e4:e.threshold),tokenUnit:e.threshold%1e4===0?"wan":"unit"};const a=V$(e.period??0);return{...t,type:"token",action:e.action,reset:"fixed",thresholdInput:String(e.threshold%1e4===0?e.threshold/1e4:e.threshold),tokenUnit:e.threshold%1e4===0?"wan":"unit",periodInput:a.value,periodUnit:a.unit}}function gR(e){const t=Number(e.thresholdInput);if(!Number.isFinite(t)||t<=0)return{error:r("限制阈值必须是大于 0 的数字")};if(e.type==="balance")return{rule:{type:"balance",action:e.action,threshold:t,enabled:!0}};const a=Math.round(e.tokenUnit==="wan"?t*1e4:t);if(e.reset==="daily")return{rule:{type:"token",action:e.action,threshold:a,reset:"daily",enabled:!0}};const o=Number(e.periodInput)*(e.periodUnit==="hours"?3600:60);if(!Number.isFinite(o)||o<=0)return{error:r("请填写重置周期")};const c=Math.round(o);return cyA?{error:r("重置周期必须是 30 分钟 ~ 24 小时")}:{rule:{type:"token",action:e.action,threshold:a,period:c,reset:"fixed",enabled:!0}}}function F$({account:e,target:t,onClose:a,onSave:o}){const[c,d]=x.useState(""),[f,p]=x.useState(t?.draft??null);if(x.useEffect(()=>{p(t?.draft??null),d("")},[t]),!t||!f)return null;const g=b=>{d(""),p({...f,...b})},v=()=>{const b=gR(f);if("error"in b){d(b.error);return}o(b.rule,t.index)},y=()=>{if(f.type==="balance"){const D=Qa(e);if(D&&typeof D=="object"){const C=D;if(C.unlimited)return r("当前可用 ∞(不参与余额不足判定)");const A=C.totalLeft??C.available;if(A!=null&&A!=="")return r("当前余额 {n};与余额列同一数字口径,严格小于才触发(等于阈值仍可用)",{n:Number(A)})}return r("读数来自自动余额查询;与余额列同一数字口径,严格小于才触发(等于阈值仍可用)")}const b=gR(f);if(!("rule"in b))return"";const j=b.rule,w=hf(j,Al(e));if(!w)return j.reset==="daily"?r("窗口 = 今天 0 点起(本地时区),0 点重置即清零恢复;按账号在 requests 表聚合"):r("窗口对齐自然时间(整点 / 整 N 分钟一轮回),重置即清零恢复;按账号在 requests 表聚合");const S=rj(j),N=Tl(w.used),k=Tl(j.threshold),E=j.reset==="daily"?r("今日已用"):r("本周期已用");return r("{scope} {used} / {quota} Token,{countdown}重置",{scope:E,used:N,quota:k,countdown:Uh(S.remainingMs,S.daily)})};return s.jsx(Qt,{open:!0,onOpenChange:b=>{b||a()},children:s.jsxs(Zt,{className:"w-[min(580px,calc(100vw-48px))]",showCloseButton:!0,children:[s.jsx(Kt,{children:s.jsx(Gt,{children:t.index>=0?r("编辑限制"):r("添加限制")})}),s.jsxs(Bt,{children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("限制类型")}),s.jsxs(ft,{value:f.type,onValueChange:b=>g({type:b,thresholdInput:""}),children:[s.jsx(mt,{className:"w-[150px]","aria-label":r("限制类型"),children:s.jsx(pt,{children:f.type==="balance"?r("余额"):r("Token 消耗")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"balance",children:r("余额")}),s.jsx(qe,{value:"token",children:r("Token 消耗")})]})]}),s.jsx("span",{className:"detail",children:r("余额沿用现有口径;Token 按重置方式内的累计消耗判定(切换类型会清空阈值)")})]}),f.type==="balance"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("触发条件")}),s.jsx("span",{className:"detail",style:{fontSize:13},children:r("余额低于")}),s.jsx($e,{type:"number",min:0,step:1,className:"max-w-[120px]",placeholder:r("阈值"),value:f.thresholdInput,onChange:b=>g({thresholdInput:b.currentTarget.value})}),s.jsx("span",{className:"detail",style:{fontSize:13},children:r("时")})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("触发后")}),s.jsxs(ft,{value:f.action,onValueChange:b=>g({action:b}),children:[s.jsx(mt,{className:"min-w-[280px]","aria-label":r("触发动作"),children:s.jsx(pt,{children:f.action==="disable"?r("禁用该账号(需手动重新启用)"):r("跳过该账号(余额回升自动恢复)")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"skip",children:r("跳过该账号(余额回升自动恢复)")}),s.jsx(qe,{value:"disable",children:r("禁用该账号(需手动重新启用)")})]})]})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("重置方式")}),s.jsxs(ft,{value:f.reset,onValueChange:b=>g({reset:b}),children:[s.jsx(mt,{className:"w-[190px]","aria-label":r("重置方式"),children:s.jsx(pt,{children:f.reset==="daily"?r("自然日(每天 0 点)"):r("固定周期")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"fixed",children:r("固定周期")}),s.jsx(qe,{value:"daily",children:r("自然日(每天 0 点)")})]})]}),s.jsx("span",{className:"detail",children:r("有的账号过了 0 点额度就回来 —— 选「自然日」")})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("触发条件")}),f.reset==="daily"?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"detail",style:{fontSize:13},children:r("每日消耗 ≥")}),s.jsx($e,{type:"number",min:0,step:1,className:"max-w-[110px]",placeholder:r("阈值"),value:f.thresholdInput,onChange:b=>g({thresholdInput:b.currentTarget.value})}),s.jsxs(ft,{value:f.tokenUnit,onValueChange:b=>g({tokenUnit:b}),children:[s.jsx(mt,{className:"w-[92px]","aria-label":r("Token 单位"),children:s.jsx(pt,{children:f.tokenUnit==="wan"?r("万"):r("个")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"wan",children:r("万")}),s.jsx(qe,{value:"unit",children:r("个")})]})]}),s.jsx("span",{className:"detail",style:{fontSize:13},children:r("Token 时")})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"detail",style:{fontSize:13},children:r("每")}),s.jsx($e,{type:"number",min:1,step:1,className:"max-w-[90px]",placeholder:r("周期"),value:f.periodInput,onChange:b=>g({periodInput:b.currentTarget.value})}),s.jsxs(ft,{value:f.periodUnit,onValueChange:b=>g({periodUnit:b}),children:[s.jsx(mt,{className:"w-[92px]","aria-label":r("周期单位"),children:s.jsx(pt,{children:f.periodUnit==="hours"?r("小时"):r("分钟")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"minutes",children:r("分钟")}),s.jsx(qe,{value:"hours",children:r("小时")})]})]}),s.jsx("span",{className:"detail",style:{fontSize:13},children:r("内消耗 ≥")}),s.jsx($e,{type:"number",min:0,step:1,className:"max-w-[110px]",placeholder:r("阈值"),value:f.thresholdInput,onChange:b=>g({thresholdInput:b.currentTarget.value})}),s.jsxs(ft,{value:f.tokenUnit,onValueChange:b=>g({tokenUnit:b}),children:[s.jsx(mt,{className:"w-[92px]","aria-label":r("Token 单位"),children:s.jsx(pt,{children:f.tokenUnit==="wan"?r("万"):r("个")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"wan",children:r("万")}),s.jsx(qe,{value:"unit",children:r("个")})]})]}),s.jsx("span",{className:"detail",style:{fontSize:13},children:r("Token 时")})]})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("触发后")}),s.jsxs(ft,{value:f.action,onValueChange:b=>g({action:b}),children:[s.jsx(mt,{className:"min-w-[280px]","aria-label":r("触发动作"),children:s.jsx(pt,{children:f.action==="disable"?r("禁用该账号(需手动重新启用)"):r("跳过该账号(重置后自动恢复)")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"skip",children:r("跳过该账号(重置后自动恢复)")}),s.jsx(qe,{value:"disable",children:r("禁用该账号(需手动重新启用)")})]})]})]})]}),s.jsx("p",{className:"detail limiter-hint",children:y()}),c?s.jsx("p",{className:"detail text-destructive",children:c}):null]}),s.jsxs(nn,{children:[s.jsx(se,{variant:"outline",onClick:a,children:r("取消")}),s.jsx(se,{variant:"default",onClick:v,children:t.index>=0?r("保存规则"):r("添加规则")})]})]})})}function $$({account:e,draft:t,onChange:a}){const[o,c]=x.useState(null),d=()=>c({index:-1,draft:hR(null)}),f=y=>c({index:y,draft:hR(t[y])}),p=(y,b)=>{const j=[...t];b>=0?j[b]=y:j.push(y),a(j),c(null)},g=y=>{a(t.filter((b,j)=>j!==y)),o&&c(null)},v=(y,b)=>{const j=[...t];j[y]={...j[y],enabled:b},a(j)};return s.jsxs(s.Fragment,{children:[t.length?s.jsx("div",{className:"limiter-rules mt-2.5",children:t.map((y,b)=>{const j=U$(e,y);return s.jsxs("div",{className:"limiter-rule","data-off":y.enabled===!1||void 0,children:[s.jsx(ms,{checked:y.enabled!==!1,"aria-label":r("启用该规则"),onCheckedChange:w=>v(b,w===!0)}),s.jsx("div",{className:"limiter-rule-main",children:s.jsxs("span",{className:"limiter-rule-cond",children:[s.jsx(ze,{variant:"secondary",shape:"tag",children:y.type==="balance"?r("余额"):"Token"})," ",r("{cond} 时 → {action}",{cond:z$(y),action:B$(y)})]})}),s.jsx(ze,{variant:j.kind==="ok"?"success":j.kind==="warn"?"warning":j.kind==="danger"?"destructive":"secondary",shape:"tag",title:j.title,children:j.text}),s.jsxs("div",{className:"limiter-rule-ops",children:[s.jsx(se,{variant:"ghost",onClick:()=>f(b),children:r("编辑")}),s.jsx(se,{variant:"ghost",onClick:()=>g(b),children:r("删除")})]})]},b)})}):s.jsx("p",{className:"detail mt-2.5",children:r("还没有限制规则:账号照常参与转发,余额与 Token 消耗都不设上限。")}),s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx(se,{variant:"outline",onClick:d,children:r("+ 添加限制")}),s.jsx("span",{className:"detail",children:r("可添加多条;同类规则也允许并存(例如一条按余额、两条不同重置方式的 Token)")})]}),s.jsx(F$,{account:e,target:o,onClose:()=>c(null),onSave:p})]})}function q$(e,t){const a=iu(e);return JSON.stringify(t)===JSON.stringify(a)?null:{patch:{limiters:t}}}function G$(e){return iu(e).map(t=>({...t}))}const K$={seconds:1,minutes:60,hours:3600};function Y$(e){return e>0&&e%3600===0?{value:String(e/3600),unit:"hours"}:e>0&&e%60===0?{value:String(e/60),unit:"minutes"}:e>0?{value:String(e),unit:"seconds"}:{value:"5",unit:"minutes"}}function X$(e){const{enabled:t,interval:a}=wA(e),o=Y$(t?a:0);return{enabled:t,intervalInput:o.value,unit:o.unit}}function Q$(e,t){const a=Math.round(Number(t.intervalInput)*K$[t.unit]);if(t.enabled){if(!Number.isFinite(Number(t.intervalInput))||Number(t.intervalInput)<=0)return{error:r("请填写查询间隔")};if(axA)return{error:r("查询间隔必须是 {min} 秒 ~ 24 小时",{min:tj})}}const o={},c=wA(e);return(t.enabled!==c.enabled||t.enabled&&a!==c.interval)&&(o.usageQuery={enabled:t.enabled,interval:t.enabled?a:c.interval}),o.usageQuery?{patch:o}:null}function Z$({account:e,draft:t,onChange:a}){const o=c=>a({...t,...c});return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"field-row mt-2.5",children:s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2.5 font-normal",children:[s.jsx(ms,{checked:t.enabled,onCheckedChange:c=>o({enabled:c===!0}),"aria-label":r("自动查询余额")}),s.jsx("span",{className:"text-xs text-subtle",children:r("自动查询余额(按下面的间隔自动刷新余额列的读数)")})]})}),t.enabled?s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:"account-usage-interval",children:r("查询间隔")}),s.jsx($e,{id:"account-usage-interval",type:"number",min:1,step:1,className:"max-w-[110px]",value:t.intervalInput,onChange:c=>o({intervalInput:c.currentTarget.value})}),s.jsxs(ft,{value:t.unit,onValueChange:c=>o({unit:c}),children:[s.jsx(mt,{className:"w-[92px]","aria-label":r("间隔单位"),children:s.jsx(pt,{children:t.unit==="hours"?r("小时"):t.unit==="minutes"?r("分钟"):r("秒")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"seconds",children:r("秒")}),s.jsx(qe,{value:"minutes",children:r("分钟")}),s.jsx(qe,{value:"hours",children:r("小时")})]})]}),s.jsx("span",{className:"detail",children:r("30 秒 ~ 24 小时;手动查询会顺延下一轮")})]}):null]})}const W$={sub2api:{label:"Sub2API",endpoint:"{base}/v1/usage",note:r("用这条账号的 API Key 查询,不需要额外配置。"),fields:[]},new_api:{label:"NewAPI",endpoint:"{base}/api/user/self + /api/status",note:r("用 NewAPI 站点的个人访问令牌查询账户余额(不是这条账号的上游 API Key)。令牌在站点的「个人设置」里生成,只有旧版 / 定制站点才需要额外填用户 ID。"),fields:[{key:"accessToken",label:r("NewAPI 个人访问令牌"),secret:!0,placeholder:r("在 NewAPI 站点「个人设置」里生成的访问令牌"),hint:r("必填;留空 = 不修改,清除用右边的按钮")},{key:"userId",label:r("NewAPI 用户 ID"),placeholder:r("旧版 / 定制站点才需要,新版可留空"),hint:r("可留空:新版请求头只认令牌;旧版会把用户 ID 放进 New-Api-User 头")}]},deepseek:{label:"DeepSeek",endpoint:"{base}/user/balance",note:r("用这条账号的 API Key 查询,不需要额外配置。"),fields:[]},opencode:{label:"OpenCode Go",endpoint:"{base}/v1/usage",note:r("用这条账号的 API Key 查询订阅用量,不需要额外配置;读数展开成 5 小时 / 每周 / 每月三个窗口。"),fields:[]},sensenova:{label:"商汤日日新",endpoint:"platform.sensenova.cn 控制台",note:r("用商汤日日新控制台的账号密码查询(与推理用的 API Key 不是同一套)。网关会自动换取登录票并缓存,过期后自动重登,不需要手动维护。"),fields:[{key:"username",label:r("账号"),placeholder:r("商汤日日新控制台的登录账号"),hint:r("必填")},{key:"password",label:r("密码"),secret:!0,placeholder:r("商汤日日新控制台的登录密码"),hint:r("留空 = 不修改,清除用右边的按钮")}]},zhipu:{label:"智谱",endpoint:"bigmodel.cn 控制台",note:r("用 bigmodel.cn 控制台的访问令牌查询账户余额(人民币元)。令牌是登录后浏览器 Cookie `bigmodel_token_production` 的值:开发者工具 → 应用(Application)→ Cookie 里复制。"),fields:[{key:"token",label:r("访问令牌"),secret:!0,placeholder:r("bigmodel_token_production 的值"),hint:r("必填;留空 = 不修改,清除用右边的按钮")}]},zhipu_zai:{label:"智谱(z.ai 国际)",endpoint:"api.z.ai 控制台",note:r("用这条账号的 API Key 生成签名后查询账户余额(美元),不需要额外配置。要求 API Key 是 z.ai 的「id.secret」形态(控制台生成的 Key 就是)。"),fields:[]}};function Sf(e){return e?W$[e]??null:null}function J$(e,t){return t.secret?t.key==="accessToken"?e?.hasAccessToken===!0:t.key==="password"?e?.hasPassword===!0:t.key==="token"?e?.hasToken===!0:!1:!1}function e8(e){const t=String(e?.scheme||"");return t==="new_api"?e?.hasAccessToken===!0:t==="sensenova"?String(e?.username||"").trim()!==""&&e?.hasPassword===!0:t==="zhipu"?e?.hasToken===!0:!0}function t8(e){return{userId:String(e?.userId||""),username:String(e?.username||""),accessToken:"",password:"",token:""}}function n8(e,t){const a=Sf(e);if(!a||!a.fields.length)return null;const o={};for(const c of a.fields){const d=String(t[c.key]??"").trim();if(c.secret){d&&(o[c.key]=d);continue}o[c.key]=d}return Object.keys(o).length?o:null}function s8({field:e,value:t,configured:a,onValue:o,onClear:c,clearBusy:d,idPrefix:f}){const p=`${f}-${e.key}`;return s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:p,children:e.label}),s.jsx($e,{id:p,className:"min-w-[220px]",type:e.secret?"password":"text",autoComplete:e.secret?"new-password":"off",placeholder:a?r("已配置,留空则不修改"):e.placeholder,title:e.hint,value:t,onChange:g=>o(g.currentTarget.value)}),a&&c?s.jsx(se,{variant:"outline",size:"sm",disabled:d===!0,onClick:c,title:r("清除已配置的 {label}",{label:e.label}),children:r("清除")}):null]})}function r8({spec:e,values:t,configured:a,onValue:o,onClear:c,clearBusy:d,idPrefix:f}){return s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"detail mt-2.5",children:[r("余额查询方案:{label}",{label:e.label}),s.jsx("span",{className:"ml-1 text-subtle",children:e.endpoint})," — ",e.note]}),e.fields.map(p=>s.jsx(s8,{field:p,idPrefix:f,value:t[p.key]||"",configured:a[p.key]===!0,onValue:g=>o(p.key,g),onClear:c?()=>c(p.key):void 0,clearBusy:d},p.key))]})}const xR=64;function a8(e,t){const a=kn(e);return t.filter(o=>o.id!==e.id&&kn(o)===a)}const Rl=999,bR=8;function eg(e){return cu(e)||e?.id||""}function vR(e){const t=e?.config?.source||e?.source,a=e?.config||null,o=t==="rotate";return{mode:t==="pool"?"pool":o?"rotate":t==="clash"?"clash":t==="custom"?"custom":"none",proxyId:t==="pool"?String(a?.proxyId||""):"",rotateAll:o?a?.all!==!1:!0,rotateIds:o&&Array.isArray(a?.proxyIds)?a.proxyIds.map(String):[],listenerUid:a?.source==="clash"||t==="clash"?String(a?.listenerUid||""):"",protocol:a?.protocol==="socks5"?"socks5":"http",host:a?.host||"",port:a?.port===void 0||a?.port===null?"":String(a.port),username:a?.username||"",password:a?.password||""}}function xj(e){if(e.mode==="none")return null;if(e.mode==="pool"){if(!e.proxyId)throw new Error(r("请先选择已保存的代理"));return{source:"pool",proxyId:e.proxyId}}if(e.mode==="rotate"){if(e.rotateAll)return{source:"rotate",all:!0};if(!e.rotateIds.length)throw new Error(r("轮询至少要选择一条代理(或改选「全部」)"));return{source:"rotate",all:!1,proxyIds:[...e.rotateIds]}}if(e.mode==="clash"){if(!e.listenerUid)throw new Error(r("请先选择 Clash Verge 出口"));return{source:"clash",listenerUid:e.listenerUid}}const t=e.host.trim(),a=Number(e.port);if(!t)throw new Error(r("请填写代理主机地址"));if(!Number.isInteger(a)||a<1||a>65535)throw new Error(r("代理端口必须是 1-65535 的整数"));return{source:"custom",protocol:e.protocol==="socks5"?"socks5":"http",host:t,port:a,username:e.username.trim(),password:e.password}}function yR(e){const t=e.profileActive===!1?r("(其他订阅,可能未生效)"):"",a=e.enabled===!1?r("(已在 Clash 中禁用)"):"";return`${e.name} :${e.port}${t}${a}`}function jR({draft:e,onChange:t,idPrefix:a,allowRotate:o=!1}){const d=Zs().clash,f=Array.isArray(d?.options)?d.options:[],p=e.mode==="clash",[g,v]=x.useState(!1),[y,b]=x.useState(null),[j,w]=x.useState(null),[S,N]=x.useState(""),k=A=>t({...e,...A});x.useEffect(()=>{p&&WA().catch(()=>{})},[p]);const E=x.useCallback((A=!1)=>{N(""),JA({force:A}).then(R=>w(R)).catch(R=>{w([]),N(ut(R))})},[]);x.useEffect(()=>{(e.mode==="pool"||e.mode==="rotate")&&j===null&&E()},[e.mode,j,E]);function D(){return e.rotateAll?(j??[]).filter(A=>A.enabled!==!1).map(A=>A.id):[...e.rotateIds]}async function C(){if(g)return;if(e.mode==="rotate"){const R=D();if(!R.length){Le(r("轮询至少要选择一条代理(或改选「全部」)"),"err");return}const I=R.slice(0,bR);v(!0),b(r("正在连接上游…"));let P=0;const O=[];for(const H of I){const B=j?.find(z=>z.id===H)?.name||H;try{const z=await Pe().workbuddyDesktop?.testProxyPoolItem?.(H);z?.success?P+=1:O.push(`${B}(${z?.error||r("连接失败")})`)}catch(z){O.push(`${B}(${ut(z)})`)}}const _=R.length-I.length,L=r("✅ {ok}/{total} 个出口可用",{ok:P,total:I.length})+(_>0?r("(只测了前 {limit} 个,还有 {rest} 个未测)",{limit:bR,rest:_}):"");b(s.jsxs("span",{className:O.length?"text-destructive":"text-success",children:[L,O.length?` ${Xa(O.join(r(";")))}`:""]})),v(!1);return}if(e.mode==="pool"){if(!e.proxyId){Le(r("请先选择已保存的代理"),"err");return}v(!0),b(r("正在连接上游…"));try{const R=await Pe().workbuddyDesktop?.testProxyPoolItem?.(e.proxyId);b(R?.success?s.jsxs("span",{className:"text-success",children:[r("✅ 出口可用"),R.ip?r(" 出口 IP {ip}",{ip:Xa(R.ip)}):"",R.durationMs!==void 0&&R.durationMs!==""?` ${Xa(String(R.durationMs))}ms`:""]}):s.jsxs("span",{className:"text-destructive",children:["❌ ",Xa(R?.error||r("连接失败"))]}))}catch(R){b(s.jsxs("span",{className:"text-destructive",children:["❌ ",Xa(ut(R))]}))}finally{v(!1)}return}let A;try{A=xj(e)}catch(R){Le(ut(R),"err");return}v(!0),b(r("正在连接上游…"));try{const R=await Pe().workbuddyDesktop?.testProxy?.({proxy:A});R?.success?b(s.jsxs("span",{className:"text-success",children:[r("✅ 出口可用"),R.status!==void 0&&R.status!==""?` HTTP ${Xa(String(R.status))}`:"",R.ip?r(" 出口 IP {ip}",{ip:Xa(R.ip)}):"",R.durationMs!==void 0&&R.durationMs!==""?` ${Xa(String(R.durationMs))}ms`:""]})):b(s.jsxs("span",{className:"text-destructive",children:["❌ ",Xa(R?.error||r("连接失败"))]}))}catch(R){b(s.jsxs("span",{className:"text-destructive",children:["❌ ",Xa(ut(R))]}))}finally{v(!1)}}return s.jsxs("div",{className:"flex flex-col",children:[s.jsxs(kh,{value:e.mode,onValueChange:A=>k({mode:A}),className:"flex-row flex-wrap items-center gap-5","aria-label":r("代理方式"),children:[s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(bo,{value:"none"}),r("无代理(直连)")]}),s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(bo,{value:"pool"}),r("已保存的代理")]}),o?s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",title:r("逐请求轮换出口(换 IP):OpenCode Zen 免费档按 IP 限流,单个 IP 的额度用完会对它一律 429"),children:[s.jsx(bo,{value:"rotate"}),r("轮询(换 IP)")]}):null,p?s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(bo,{value:"clash"}),"Clash Verge"]}):null,s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(bo,{value:"custom"}),r("自定义")]})]}),e.mode==="pool"?s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:`${a}-pool-exit`,children:r("代理")}),s.jsxs(ft,{value:e.proxyId,disabled:!j?.length,onValueChange:A=>k({proxyId:String(A)}),children:[s.jsx(mt,{id:`${a}-pool-exit`,className:"min-w-[220px]",children:s.jsx(pt,{children:j?.find(A=>A.id===e.proxyId)?au(j.find(A=>A.id===e.proxyId)):j===null?r("正在读取…"):j.length?r("请选择代理"):r("还没有保存的代理")})}),s.jsx(ht,{children:(j??[]).map(A=>s.jsx(qe,{value:A.id,children:au(A)},A.id))})]}),s.jsx(se,{variant:"outline",size:"sm",onClick:()=>E(!0),children:r("重新读取")})]}),s.jsx("div",{className:"detail mt-1.5",children:S?r("读取失败:{error}",{error:S}):j===null?r("正在读取代理列表…"):j.length?r("地址与端口由「网络代理」页管理:那边改一次、测一次,所有引用它的账号一起生效"):r("「网络代理」页还没有出口 —— 去那里新增,或点「同步 Clash Verge」把 Clash 的出口导进来")})]}):null,e.mode==="rotate"?s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-x-2.5 gap-y-1",children:[s.jsx(Or,{id:`${a}-rotate-all`,checked:e.rotateAll,"aria-label":r("轮询全部代理节点"),onCheckedChange:A=>k({rotateAll:A===!0})}),s.jsx("label",{htmlFor:`${a}-rotate-all`,className:"cursor-pointer text-xs text-subtle",children:r("全部代理节点(推荐)")}),s.jsx("span",{className:"detail",children:r("「网络代理」页里每个启用的出口轮流使用;之后新加的出口自动加入")})]}),e.rotateAll?null:s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:`${a}-rotate-exits`,children:r("轮询的代理")}),s.jsx(_h,{id:`${a}-rotate-exits`,value:e.rotateIds,onValueChange:A=>k({rotateIds:A.map(String)}),options:(j??[]).map(A=>({value:A.id,label:au(A)})),placeholder:r("选择要轮询的代理(可多选)"),"aria-label":r("轮询的代理")}),s.jsx(se,{variant:"outline",size:"sm",onClick:()=>E(!0),children:r("重新读取")})]}),s.jsx("div",{className:"detail mt-1.5",children:S?r("读取失败:{error}",{error:S}):j===null?r("正在读取代理列表…"):j.length?r("每条请求换一个出口(按顺序轮流),上游看到的 IP 因此是变化的;出口的地址与端口由「网络代理」页管理"):r("「网络代理」页还没有出口 —— 去那里新增,或点「同步 Clash Verge」把 Clash 的出口导进来")})]}):null,e.mode==="clash"?s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:`${a}-clash-exit`,children:r("出口")}),s.jsxs(ft,{value:e.listenerUid,disabled:!f.length,onValueChange:A=>k({listenerUid:String(A)}),children:[s.jsx(mt,{id:`${a}-clash-exit`,className:"min-w-[220px]",children:s.jsx(pt,{children:f.find(A=>String(A.uid)===e.listenerUid)?yR(f.find(A=>String(A.uid)===e.listenerUid)):d?.available===!1?r("未检测到 Clash Verge"):f.length?r("请选择出口"):r("没有可用出口")})}),s.jsx(ht,{children:f.map(A=>s.jsx(qe,{value:String(A.uid),children:yR(A)},String(A.uid)))})]}),s.jsx(se,{variant:"outline",size:"sm",onClick:()=>{WA({force:!0}).then(()=>Le(r("✅ 已重新读取 Clash Verge 配置"))).catch(A=>Le(r("读取失败:{error}",{error:ut(A)}),"err"))},children:r("重新读取")})]}),s.jsx("div",{className:"detail mt-1.5",children:d===null?r("正在读取 Clash Verge 配置…"):d.available===!1?d.error?r("不可用:{error}",{error:d.error}):r("未检测到 Clash Verge 配置"):f.length?r("读取自 {dir};端口由 Clash Verge 管理,这里实时同步",{dir:d.dir||"Clash Verge"}):r("Clash Verge 里还没有配置混合监听器或节点端口")}),s.jsxs("p",{className:"detail mt-1.5",children:[r("这是既有配置(直接引用 Clash 出口,不经过代理池)。推荐改用上面的"),s.jsx("b",{children:r("「已保存的代理」")}),r(":到「网络代理」页点「同步 Clash Verge」把出口导进池后即可选 —— 那样能集中测试、也能被多个账号共用。")]})]}):null,e.mode==="custom"?s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:`${a}-protocol`,children:r("协议")}),s.jsxs(ft,{value:e.protocol,onValueChange:A=>k({protocol:A}),children:[s.jsx(mt,{id:`${a}-protocol`,className:"min-w-[110px]",children:s.jsx(pt,{children:e.protocol==="socks5"?"SOCKS5":"HTTP"})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"http",children:"HTTP"}),s.jsx(qe,{value:"socks5",children:"SOCKS5"})]})]}),s.jsx("label",{htmlFor:`${a}-host`,className:"ml-2",children:r("主机")}),s.jsx($e,{id:`${a}-host`,className:"min-w-[140px]",placeholder:"127.0.0.1",value:e.host,onChange:A=>k({host:A.currentTarget.value})}),s.jsx("label",{htmlFor:`${a}-port`,children:r("端口")}),s.jsx($e,{id:`${a}-port`,type:"number",min:1,max:65535,className:"max-w-[110px]",placeholder:"7890",value:e.port,onChange:A=>k({port:A.currentTarget.value})})]}),s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:`${a}-user`,children:r("用户名")}),s.jsx($e,{id:`${a}-user`,placeholder:r("可选"),autoComplete:"off",value:e.username,onChange:A=>k({username:A.currentTarget.value})}),s.jsx("label",{htmlFor:`${a}-pass`,children:r("密码")}),s.jsx($e,{id:`${a}-pass`,type:"password",placeholder:r("可选"),autoComplete:"new-password",value:e.password,onChange:A=>k({password:A.currentTarget.value})})]})]}):null,s.jsxs("div",{className:"field-row mt-3",children:[s.jsx(se,{variant:"outline",size:"sm",disabled:g,onClick:()=>{C()},children:r(g?"测试中…":"测试出口")}),s.jsx("span",{className:"detail",children:y})]})]})}function l8({plan:e,hasJwt:t,onChange:a}){const o=QF(e),[c,d]=x.useState(null);return x.useEffect(()=>{if(e!==jo)return()=>{};let f=!0;const p=()=>{Promise.resolve(Pe().workbuddyDesktop?.zcodeCaptchaStats?.()).then(v=>{f&&v&&d({ready:Number(v.ready)||0,target:Number(v.target)||0})}).catch(()=>{})};p();const g=window.setInterval(p,5e3);return()=>{f=!1,window.clearInterval(g)}},[e]),s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:"account-plan-channel",children:r("使用套餐")}),s.jsxs(ft,{value:e,onValueChange:f=>a(String(f)),children:[s.jsx(mt,{id:"account-plan-channel",className:"min-w-[220px]",children:s.jsx(pt,{children:o})}),s.jsxs(ht,{children:[s.jsx(qe,{value:EA,children:r("编码套餐(Coding Plan)— 走开放平台端点,用自己订阅的额度")}),s.jsx(qe,{value:jo,children:r("活动套餐(Start Plan)— 走官方活动端点,用活动里领到的额度")})]})]}),e===jo&&!t?s.jsx("span",{className:"detail text-destructive",children:r("该账号没有套餐登录态(jwt),活动套餐会失败:请重新登录该账号")}):null,e===jo?s.jsxs("span",{className:"detail",title:r("活动套餐的推理端点要求每条请求带一个阿里云验证码令牌;令牌由本应用在后台静默铸造,界面关闭时无法铸造"),children:[r("验证码令牌:{counts}",{counts:c?`${c.ready} / ${c.target||3}`:r("读取中…")}),c&&c.ready===0?r("(库存为空,正在补;补不上时转发会失败)"):""]}):null]})}function o8({configured:e,value:t,onChange:a,onClear:o,clearBusy:c}){return s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:"account-balance-token-input",children:r("余额查询凭证")}),s.jsx($e,{id:"account-balance-token-input",className:"min-w-[220px]",placeholder:r(e?"已配置,留空则不修改":"一般不用填"),title:r("积分查询已复用转发用的登录凭证,这里通常留空即可。只有旧版本填过、或从旧代理导入过凭证时才有值"),value:t,onChange:d=>a(d.currentTarget.value)}),e?s.jsx(se,{variant:"outline",size:"sm",disabled:c,onClick:o,title:r("清除已配置的余额查询凭证"),children:r("清除")}):null]})}function i8({hasApiKey:e,noAuth:t,value:a,onValue:o,onToggleNoAuth:c,onClear:d,clearBusy:f}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:"account-api-key-input",children:r("API Key")}),s.jsx($e,{id:"account-api-key-input",type:"password",autoComplete:"new-password",className:"min-w-[220px]",disabled:t,placeholder:e?r("已配置,留空则不修改"):"sk-…",title:r("上游的 API Key。留空 = 不修改(改凭证不会换账号 id);要清掉已配的凭证用右边的「清除」"),value:a,onChange:p=>o(p.currentTarget.value)}),e&&!t?s.jsx(se,{variant:"outline",size:"sm",disabled:f,onClick:d,title:r("清除已配置的 API Key(转发时会因缺少凭证被跳过)"),children:r("清除")}):null]}),s.jsx("div",{className:"field-row mt-2.5",children:s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2.5 font-normal",children:[s.jsx(Or,{checked:t,"aria-label":r("该上游无需鉴权"),onCheckedChange:p=>c(p===!0)}),s.jsx("span",{className:"text-xs text-subtle",children:r("该上游无需鉴权(转发与拉取模型都不发送鉴权头)")})]})}),s.jsxs("p",{className:"detail",children:[r("上游本来不要凭证时(本地 Ollama、OpenCode Zen 的免费档)勾上这一项:账号会被正常选路;只把 Key 留空"),s.jsx("strong",{children:r("又不勾")}),r("会被当成「未配置凭证」而跳过。")]})]})}function c8({provider:e,name:t,protocol:a,baseUrl:o,count:c,emulation:d,onName:f,onProtocol:p,onBaseUrl:g,onEmulation:v,onRemove:y}){const b=Pe().wbProviders?.PROTOCOL_OPTIONS||[{value:"openai",label:r("OpenAI 兼容")},{value:"anthropic",label:"Anthropic"}],j=b.find(w=>w.value===a)?.label||a;return s.jsxs(Vn,{children:[s.jsx("h3",{children:r("提供商")}),s.jsxs("p",{children:[r("这一栏改的是"),s.jsx("strong",{children:r("「{name}」本身",{name:e.name||e.id})}),r("(名下 {count} 个账号共用)",{count:c}),r("改协议 / Base URL 会改变它们的转发方式,正在进行的请求可能失败;模型清单与映射在「模型管理」页。")]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:"account-provider-name",children:r("名称")}),s.jsx($e,{id:"account-provider-name",maxLength:xR,className:"min-w-[220px]",placeholder:r("提供商显示名,1~{max} 个字符",{max:xR}),value:t,onChange:w=>f(w.currentTarget.value)})]}),s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:"account-provider-protocol",children:r("协议")}),s.jsxs(ft,{value:a,onValueChange:w=>p(String(w)),children:[s.jsx(mt,{id:"account-provider-protocol",className:"min-w-[180px]",children:s.jsx(pt,{children:j})}),s.jsx(ht,{children:b.map(w=>s.jsx(qe,{value:w.value,children:w.label},w.value))})]})]}),s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:"account-provider-baseurl",children:r("Base URL")}),s.jsx($e,{id:"account-provider-baseurl",className:"min-w-[260px]",placeholder:r("OpenAI 兼容填到 /v1;Anthropic 填根地址"),value:o,onChange:w=>g(w.currentTarget.value)})]}),s.jsx("div",{className:"field-row mt-2.5",children:s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2.5 font-normal",children:[s.jsx(Or,{checked:d==="opencode","aria-label":r("伪装 OpenCode 官方客户端"),onCheckedChange:w=>v(w===!0?"opencode":"")}),s.jsx("span",{className:"text-xs text-subtle",children:r("伪装 OpenCode 官方客户端(OpenCode Zen 免费档要它才放行)")})]})}),s.jsxs("p",{className:"detail",children:[r("开启后,网关按 OpenCode 官方 CLI 的形状发请求:没填 Key 的账号用匿名凭证"),s.jsx("code",{children:"public"}),r("、补官方会话头、请求体补两个占位工具(上游免费档的三道校验)。"),s.jsx("strong",{children:r("它会改写请求体")}),r(",只对 OpenCode Zen 这类上游有意义,别的家请关掉。")]}),s.jsxs("div",{className:"field-row mt-3",children:[s.jsx(se,{variant:"destructive",onClick:y,children:r("删除提供商")}),s.jsx("span",{className:"detail",children:r("级联删除名下全部账号,不可恢复")})]})]})}function u8({id:e,onClose:t}){const a=Ea(e),[o,c]=x.useState(a?.enabled!==!1),[d,f]=x.useState(a?.name||""),[p,g]=x.useState(()=>vR(a?.proxy)),[v,y]=x.useState(""),[b,j]=x.useState(()=>aj(a)),[w,S]=x.useState(!1),[N,k]=x.useState(""),[E,D]=x.useState(null),[C,A]=x.useState(""),[R,I]=x.useState("chat_completions"),[P,O]=x.useState(""),[_,L]=x.useState(""),[H,B]=x.useState(""),[z,Q]=x.useState(a?.noAuth===!0),[K,X]=x.useState(()=>X$(a)),[q,$]=x.useState(()=>t8(a?.balanceQuery)),[Y,F]=x.useState(()=>G$(a)),[G,W]=x.useState("basic"),[le,M]=x.useState(()=>String(Number(a?.maxConcurrent)||0));if(x.useEffect(()=>{let he=!0;D(null);const ye=Ea(e);return ye?(Promise.resolve(Pe().wbCustomProvidersUi?.find?.(kn(ye))).then(we=>{!he||!we||(D(we),A(we.name||""),I(we.protocol||"chat_completions"),O(we.baseUrl||""),L(typeof we.clientEmulation=="string"?we.clientEmulation:""))}).catch(()=>{}),()=>{he=!1}):()=>{he=!1}},[e]),!a)return s.jsx(Qt,{open:!0,onOpenChange:he=>{he||t()},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("账号设置")})}),s.jsx(Bt,{children:s.jsx("p",{className:"detail",children:r("账号不存在,请刷新后重试。")})}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("关闭")})]})]})});const U=a,Z=a8(U,El()),ae=kn(U)==="catpaw",ce=kn(U).startsWith("custom-"),J=mA(E,U.baseUrl)||p.mode==="rotate",ie=Sf(U.balanceQuery?.scheme),ge={};for(const he of ie?.fields??[])ge[he.key]=J$(U.balanceQuery,he);const ee=!!(ie&&ie.fields.length)&&!e8(U.balanceQuery);async function fe(){if(!w){S(!0);try{await Pe().workbuddyDesktop?.updateAccount?.(e,{balanceToken:null}),y(""),Le(r("✅ 已清除余额查询凭证")),await Pe().wbApp?.refresh?.()}catch(he){Le(r("清除失败:{error}",{error:ut(he)}),"err")}finally{S(!1)}}}async function te(){if(!w){S(!0);try{await Pe().workbuddyDesktop?.updateAccount?.(e,{apiKey:null}),B(""),Le(r("✅ 已清除 API Key(该账号现在没有凭证,转发会被跳过)")),await Pe().wbApp?.refresh?.()}catch(he){Le(r("清除失败:{error}",{error:ut(he)}),"err")}finally{S(!1)}}}async function Ce(he){if(!w){S(!0);try{await Pe().workbuddyDesktop?.updateAccount?.(e,{balanceQuery:{[he]:null}}),$(ye=>({...ye,[he]:""})),Le(r("✅ 已清除查询凭证")),await Pe().wbApp?.refresh?.()}catch(ye){Le(r("清除失败:{error}",{error:ut(ye)}),"err")}finally{S(!1)}}}function re(){if(!ce)return null;const he=H.trim(),ye={};return he?ye.apiKey=he:z!==(U.noAuth===!0)&&(ye.noAuth=z),Object.keys(ye).length?ye:null}function de(){if(!E)return null;const he=C.trim(),ye=P.trim();if(!he)return{error:r("请填写提供商名称")};if(!ye)return{error:r("请填写提供商的 Base URL")};const we=typeof E.clientEmulation=="string"?E.clientEmulation:"";return E.name===he&&E.protocol===R&&E.baseUrl===ye&&we===_?null:{id:E.id,name:he,protocol:R,baseUrl:ye,clientEmulation:_}}async function ke(){if(w)return;let he;try{he=xj(p)}catch(Ct){Le(ut(Ct),"err");return}const ye=de();if(ye&&"error"in ye){k(s.jsx("span",{className:"text-destructive",children:ye.error}));return}const we=Ta(U)?Q$(U,K):null;if(we&&"error"in we){k(s.jsx("span",{className:"text-destructive",children:we.error}));return}const xe=q$(U,Y),Te=n8(U.balanceQuery?.scheme,q),Oe=re()||{},Ne=Number(le);if(!Number.isFinite(Ne)||Ne<0){Le(r("并发上限必须是 0~{max} 的整数",{max:Rl}),"err");return}const _e=Math.min(Rl,Math.round(Ne)),Ye=Number(U.maxConcurrent)||0,kt=_e!==Ye?{maxConcurrent:_e}:{};S(!0);try{const Ct=ae&&v.trim()?{balanceToken:v.trim()}:{},Rt=Fh(U)&&b!==aj(U)?{zcodePlan:b}:{};if(await Pe().workbuddyDesktop?.updateAccount?.(e,{name:d.trim()||U.name,enabled:o,proxy:he,...Ct,...Rt,...Oe,...kt,...Te?{balanceQuery:Te}:{},...we&&"patch"in we?we.patch:{},...xe&&"patch"in xe?xe.patch:{}}),ye)try{await Pe().wbCustomProvidersUi?.update?.(ye)}catch(ot){k(s.jsx("span",{className:"text-destructive",children:r("账号已保存,但提供商未更新:{error}",{error:ut(ot)})})),await Pe().wbApp?.refresh?.(),S(!1);return}t(),Le(r("✅ 账号设置已保存"));try{await Pe().wbApp?.refresh?.()}catch{}}catch(Ct){k(s.jsx("span",{className:"text-destructive",children:ut(Ct)})),Le(r("保存失败:{error}",{error:ut(Ct)}),"err")}finally{S(!1)}}const Ee=Number(ir(kn(U)).concurrencyDefault)||0,ve=ae||ce||Fh(U);return s.jsx(Qt,{open:!0,onOpenChange:he=>{he||w||t()},children:s.jsxs(Zt,{className:"w-[min(900px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("账号设置 · {name}",{name:eg(a)})})}),s.jsx(Bt,{className:"p-0",children:s.jsxs("div",{className:"acct-dlg",children:[s.jsx("aside",{className:"prov-rail acct-dlg-rail","aria-label":r("账号设置分组"),children:s.jsxs("div",{className:"rail-scroll",children:[s.jsx("div",{className:"rail-label",children:r("账号设置")}),[["basic",r("基本")],...ve?[["credential",r("凭证与套餐")]]:[],...Ta(U)?[["query",r("查询设置")],["limiter",r("限制器")]]:[],["network",r("网络")]].map(([he,ye])=>s.jsx(ru,{active:G===he,title:ye,className:"shadow-none",onClick:()=>W(he),children:ye},he))]})}),s.jsxs("div",{className:"acct-dlg-main",children:[G==="basic"?s.jsxs("div",{children:[s.jsxs("div",{className:"acct-dlg-pane-head",children:[s.jsx("h3",{children:r("基本")}),s.jsx("p",{children:r("这条账号是谁、排第几、能不能接请求。")})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("启用")}),s.jsx(ms,{checked:o,onCheckedChange:c,"aria-label":r("启用该账号")}),s.jsx("span",{className:"detail",children:r("关闭则不参与转发(余额查询照常,见「查询设置」)")})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:"account-name-input",children:r("备注名")}),s.jsx($e,{id:"account-name-input",maxLength:100,placeholder:r("账号显示名称"),className:"max-w-[280px]",value:d,onChange:he=>f(he.currentTarget.value)})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("转发顺序")}),s.jsx("span",{className:"detail",children:r("在列表里拖:拖分组带调整整组顺位,拖行首把手调整组内先后(顺序由拖拽表达,不再填数字)")})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:"account-conc-input",children:r("并发上限")}),s.jsx($e,{id:"account-conc-input",type:"number",min:0,max:Rl,step:1,className:"max-w-[110px]",value:le,onChange:he=>M(he.currentTarget.value)}),s.jsx("span",{className:"detail",children:Ee>0?r("0 = 按本家默认 {default}",{default:Ee}):r("0 = 不限")})]}),s.jsx("p",{className:"detail acct-dlg-hint",children:Ee>0?r("并发上限 受上游硬顶约束,达到上限的账号跳过、请求转给其他账号(原列表 ⋯ 菜单的「并发上限」入口已并入这里)"):r("并发上限 0~{max};达到上限的账号跳过、请求转给其他账号(原列表 ⋯ 菜单的「并发上限」入口已并入这里)",{max:Rl})})]}):null,G==="credential"&&ve?s.jsxs("div",{children:[s.jsxs("div",{className:"acct-dlg-pane-head",children:[s.jsx("h3",{children:r("凭证与套餐")}),s.jsx("p",{children:r("这一段按提供商出现:有什么配什么。")})]}),ae?s.jsx(o8,{configured:a.hasBalanceToken===!0,value:v,onChange:y,clearBusy:w,onClear:()=>{fe()}}):null,ce?s.jsx(i8,{hasApiKey:U.hasApiKey===!0,noAuth:z,value:H,onValue:B,onToggleNoAuth:Q,onClear:()=>{te()},clearBusy:w}):null,Fh(U)?s.jsx(l8,{plan:b,hasJwt:a.canClaim===!0,onChange:j}):null,E?s.jsx(c8,{provider:E,count:Z.length+1,name:C,protocol:R,baseUrl:P,emulation:_,onName:A,onProtocol:I,onBaseUrl:O,onEmulation:L,onRemove:()=>{w||Promise.resolve(Pe().wbCustomProvidersUi?.remove?.(E.id)).then(he=>{he&&t()})}}):null]}):null,G==="query"&&Ta(U)?s.jsxs("div",{children:[s.jsxs("div",{className:"acct-dlg-pane-head",children:[s.jsx("h3",{children:r("查询设置")}),s.jsx("p",{children:r("余额列读数的自动刷新;也是「限制器」余额规则的数据来源。")})]}),ie?s.jsx(r8,{spec:ie,values:q,configured:ge,onValue:(he,ye)=>$(we=>({...we,[he]:ye})),onClear:he=>{Ce(he)},clearBusy:w,idPrefix:"account-balance-query"}):null,ee?s.jsx("p",{className:"detail mt-2.5 text-subtle",children:r("查询凭证还没配齐:填好后余额列才有读数,在此之前会显示「未配置」。")}):null,s.jsx(Z$,{account:U,draft:K,onChange:X})]}):null,G==="limiter"&&Ta(U)?s.jsxs("div",{children:[s.jsxs("div",{className:"acct-dlg-pane-head",children:[s.jsx("h3",{children:r("限制器")}),s.jsx("p",{children:r("按规则限制该账号参与转发:没有规则(或全部停用)= 不限制;跳过档自动恢复,禁用档需手动启用。")})]}),s.jsx($$,{account:U,draft:Y,onChange:F})]}):null,G==="network"?s.jsxs("div",{children:[s.jsxs("div",{className:"acct-dlg-pane-head",children:[s.jsx("h3",{children:r("网络")}),s.jsx("p",{children:r("这条账号访问上游走哪条线路。")})]}),s.jsx(jR,{draft:p,onChange:g,idPrefix:"account-proxy",allowRotate:J}),a.proxy?.error?s.jsx("p",{className:"detail text-destructive",children:r("当前代理不可用:{error}(转发时会回退直连)",{error:a.proxy.error})}):null]}):null]})]})}),s.jsxs(nn,{children:[s.jsx("div",{className:"detail mr-auto",style:{minHeight:18},children:N}),s.jsx(se,{variant:"outline",disabled:w,onClick:t,children:r("取消")}),s.jsx(se,{variant:"default",disabled:w,onClick:()=>{ke()},children:r(w?"保存中…":"保存")})]})]})})}const d8=[{value:"enable",label:r("启用")},{value:"disable",label:r("禁用")},{value:"proxy",label:r("修改代理")},{value:"concurrency",label:r("设置并发上限")},{value:"remove",label:r("删除")}];function f8({ids:e,action:t,onClose:a}){const[o,c]=x.useState(t),[d,f]=x.useState(()=>vR(null)),[p,g]=x.useState(""),[v,y]=x.useState(!1),[b,j]=x.useState(""),w=e.map(C=>Ea(C)).filter(C=>C!==null),S=w.reduce((C,A)=>Math.max(C,Number(ir(kn(A)).concurrencyDefault)||0),0),N=w.length>0&&w.every(C=>BF(C));function k(C){return Promise.resolve(Pe().wbConfirm?.ask?.({title:r("删除选中的账号"),html:r("确定删除选中的 {count} 个账号?此操作不可恢复,账号的登录态会一并移除。",{count:C}),okText:r("删除"),okClass:"danger"})??!1)}async function E(){if(v)return;if(!e.length){Le(r("没有选中的账号"),"err");return}let C;if(o==="proxy")try{C=xj(d)}catch(R){Le(ut(R),"err");return}let A;if(o==="concurrency"){const R=Number(p.trim());if(!p.trim()||!Number.isFinite(R)||R<0){Le(r("并发上限必须是 0~{max} 的整数",{max:Rl}),"err");return}A=Math.min(Rl,Math.round(R))}if(!(o==="remove"&&!await k(e.length))){if(o==="disable"||o==="remove"){const R=new Set(e);if(!El().filter(P=>P.enabled!==!1&&!R.has(P.id)).length){const P=r(o==="remove"?"删除":"禁用");if(!await Promise.resolve(Pe().wbConfirm?.ask?.({title:r("全部启用中的账号将被{what}",{what:P}),html:r("这会{what}所有启用中的账号,转发将不可用。确定继续?",{what:P}),okText:P,okClass:o==="remove"?"danger":"primary"})??!1))return}}y(!0),j("");try{const R={action:o,ids:e};o==="proxy"&&(R.proxy=C),o==="concurrency"&&(R.maxConcurrent=A);const I=await Pe().workbuddyDesktop?.batchAccounts?.(R),P=(I?.ok||[]).filter(B=>B.changes?.length).length,O=(I?.removed||[]).length,_=I?.failed||[],L=o==="remove"?O:P,H={enable:r("启用"),disable:r("禁用"),proxy:r("修改代理"),concurrency:r("设置并发上限"),remove:r("删除")}[o]||o;if(_.length){const B=_.slice(0,3).map(z=>eg(Ea(String(z.id)))||z.id).join(r("、"));Le(r("{verb}完成:成功 {ok} 个,失败 {fail} 个({detail}{more})",{verb:H,ok:L,fail:_.length,detail:B,more:_.length>3?r(" 等"):""}),"err"),j(s.jsxs("span",{className:"text-destructive",children:[r("失败 {count} 个:",{count:_.length}),_.map(z=>`${eg(Ea(String(z.id)))||z.id}(${z.error})`).join(r(";"))]}))}else Le(r("✅ {verb}完成:共 {count} 个账号",{verb:H,count:L})),a();await Pe().wbApp?.refresh?.()}catch(R){j(s.jsx("span",{className:"text-destructive",children:ut(R)})),Le(r("批量操作失败:{error}",{error:ut(R)}),"err")}finally{y(!1)}}}const D={enable:r("启用"),disable:r("禁用"),proxy:r("修改代理"),concurrency:r("设置并发上限"),remove:r("删除")}[o]||o;return s.jsx(Qt,{open:!0,onOpenChange:C=>{C||v||a()},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("批量操作 · 已选 {count} 个账号",{count:e.length})})}),s.jsxs(Bt,{children:[s.jsxs(Vn,{children:[s.jsx("h3",{children:r("将作用于以下账号")}),s.jsx("p",{style:{maxHeight:84,overflowY:"auto"},children:w.map(C=>eg(C)).join(r("、"))})]}),s.jsxs(Vn,{children:[s.jsx("h3",{children:r("操作")}),s.jsx(kh,{value:o,onValueChange:c,className:"flex-row flex-wrap items-center gap-5","aria-label":r("批量动作"),children:d8.map(C=>s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(bo,{value:C.value}),C.label]},C.value))}),o==="proxy"?s.jsx("div",{className:"mt-2.5",children:s.jsx(jR,{draft:d,onChange:f,idPrefix:"batch-proxy",allowRotate:N})}):null,o==="concurrency"?s.jsxs("div",{className:"mt-2.5",children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:"batch-conc-input",children:r("并发上限")}),s.jsx($e,{id:"batch-conc-input",type:"number",min:0,max:Rl,step:1,className:"max-w-[110px]",placeholder:r("不限"),value:p,onChange:C=>g(C.currentTarget.value)}),s.jsx("span",{className:"detail",children:r("0 = 不限")})]}),s.jsx("p",{className:"detail acct-dlg-hint",children:S>0?r("并发上限 0~{max};有上游硬顶的家(如 CodeArts)以它的硬顶为准;达到上限的账号会被跳过、请求转给其他账号",{max:Rl}):r("并发上限 0~{max};达到上限的账号会被跳过、请求转给其他账号",{max:Rl})})]}):null]}),s.jsx("div",{className:"detail",style:{minHeight:18},children:b})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:v,onClick:a,children:r("取消")}),s.jsx(se,{variant:o==="remove"?"destructive":"default",disabled:v,onClick:()=>{E()},children:v?r("执行中…"):r("执行({action})",{action:D})})]})]})})}function p8(){const e=Zs();return e.dialog?e.dialog.kind==="settings"?s.jsx(u8,{id:e.dialog.id,onClose:Zh},e.dialog.id):s.jsx(f8,{ids:e.dialog.ids,action:e.dialog.action,onClose:Zh},e.dialog.ids.join(",")):null}var bj={exports:{}},Nf={},vj={exports:{}},yj={};var wR;function m8(){return wR||(wR=1,(function(e){function t(X,q){var $=X.length;X.push(q);e:for(;0<$;){var Y=$-1>>>1,F=X[Y];if(0>>1;Yc(le,$))Mc(U,le)?(X[Y]=U,X[M]=$,Y=M):(X[Y]=le,X[W]=$,Y=W);else if(Mc(U,$))X[Y]=U,X[M]=$,Y=M;else break e}}return q}function c(X,q){var $=X.sortIndex-q.sortIndex;return $!==0?$:X.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var d=performance;e.unstable_now=function(){return d.now()}}else{var f=Date,p=f.now();e.unstable_now=function(){return f.now()-p}}var g=[],v=[],y=1,b=null,j=3,w=!1,S=!1,N=!1,k=!1,E=typeof setTimeout=="function"?setTimeout:null,D=typeof clearTimeout=="function"?clearTimeout:null,C=typeof setImmediate<"u"?setImmediate:null;function A(X){for(var q=a(v);q!==null;){if(q.callback===null)o(v);else if(q.startTime<=X)o(v),q.sortIndex=q.expirationTime,t(g,q);else break;q=a(v)}}function R(X){if(N=!1,A(X),!S)if(a(g)!==null)S=!0,I||(I=!0,B());else{var q=a(v);q!==null&&K(R,q.startTime-X)}}var I=!1,P=-1,O=5,_=-1;function L(){return k?!0:!(e.unstable_now()-_X&&L());){var Y=b.callback;if(typeof Y=="function"){b.callback=null,j=b.priorityLevel;var F=Y(b.expirationTime<=X);if(X=e.unstable_now(),typeof F=="function"){b.callback=F,A(X),q=!0;break t}b===a(g)&&o(g),A(X)}else o(g);b=a(g)}if(b!==null)q=!0;else{var G=a(v);G!==null&&K(R,G.startTime-X),q=!1}}break e}finally{b=null,j=$,w=!1}q=void 0}}finally{q?B():I=!1}}}var B;if(typeof C=="function")B=function(){C(H)};else if(typeof MessageChannel<"u"){var z=new MessageChannel,Q=z.port2;z.port1.onmessage=H,B=function(){Q.postMessage(null)}}else B=function(){E(H,0)};function K(X,q){P=E(function(){X(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(X){X.callback=null},e.unstable_forceFrameRate=function(X){0>X||125Y?(X.sortIndex=$,t(v,X),a(g)===null&&X===a(v)&&(N?(D(P),P=-1):N=!0,K(R,$-Y))):(X.sortIndex=F,t(g,X),S||w||(S=!0,I||(I=!0,B()))),X},e.unstable_shouldYield=L,e.unstable_wrapCallback=function(X){var q=j;return function(){var $=j;j=q;try{return X.apply(this,arguments)}finally{j=$}}}})(yj)),yj}var SR;function h8(){return SR||(SR=1,vj.exports=m8()),vj.exports}var NR;function g8(){if(NR)return Nf;NR=1;var e=h8(),t=Hd(),a=g1();function o(n){var l="https://react.dev/errors/"+n;if(1Ce||(n.current=te[Ce],te[Ce]=null,Ce--)}function ke(n,l){Ce++,te[Ce]=n.current,n.current=l}var Ee=re(null),ve=re(null),he=re(null),ye=re(null);function we(n,l){switch(ke(he,l),ke(ve,n),ke(Ee,null),l.nodeType){case 9:case 11:n=(n=l.documentElement)&&(n=n.namespaceURI)?V3(n):0;break;default:if(n=l.tagName,l=l.namespaceURI)l=V3(l),n=F3(l,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}de(Ee),ke(Ee,n)}function xe(){de(Ee),de(ve),de(he)}function Te(n){var l=n.memoizedState;l!==null&&(_d._currentValue=l.memoizedState,ke(ye,n)),l=Ee.current;var i=F3(l,n.type);l!==i&&(ke(ve,n),ke(Ee,i))}function Oe(n){ve.current===n&&(de(Ee),de(ve)),ye.current===n&&(de(ye),_d._currentValue=fe)}var Ne,_e;function Ye(n){if(Ne===void 0)try{throw Error()}catch(i){var l=i.stack.trim().match(/\n( *(at )?)/);Ne=l&&l[1]||"",_e=-1gl in xi?kse(xi,gl,{enumerable:!0,configurable:!0,writable:!0,value:to}):xi[gl]=to;var ln=(xi,gl,to)=>Cse(xi,typeof gl!="symbol"?gl+"":gl,to);(function(){"use strict";function xi(e,t){for(var a=0;ao[c]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}function gl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var to={exports:{}},Hd={};var eC;function D5(){if(eC)return Hd;eC=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function a(o,c,d){var f=null;if(d!==void 0&&(f=""+d),c.key!==void 0&&(f=""+c.key),"key"in c){d={};for(var p in c)p!=="key"&&(d[p]=c[p])}else d=c;return c=d.ref,{$$typeof:e,type:o,key:f,ref:c!==void 0?c:null,props:d}}return Hd.Fragment=t,Hd.jsx=a,Hd.jsxs=a,Hd}var tC;function I5(){return tC||(tC=1,to.exports=D5()),to.exports}var s=I5(),xv={exports:{}},ct={};var nC;function P5(){if(nC)return ct;nC=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),a=Symbol.for("react.fragment"),o=Symbol.for("react.strict_mode"),c=Symbol.for("react.profiler"),d=Symbol.for("react.consumer"),f=Symbol.for("react.context"),p=Symbol.for("react.forward_ref"),g=Symbol.for("react.suspense"),v=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),b=Symbol.for("react.activity"),j=Symbol.for("react.view_transition"),w=Symbol.iterator;function S(M){return M===null||typeof M!="object"?null:(M=w&&M[w]||M["@@iterator"],typeof M=="function"?M:null)}var N={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},k=Object.assign,E={};function D(M,U,Z){this.props=M,this.context=U,this.refs=E,this.updater=Z||N}D.prototype.isReactComponent={},D.prototype.setState=function(M,U){if(typeof M!="object"&&typeof M!="function"&&M!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,M,U,"setState")},D.prototype.forceUpdate=function(M){this.updater.enqueueForceUpdate(this,M,"forceUpdate")};function C(){}C.prototype=D.prototype;function A(M,U,Z){this.props=M,this.context=U,this.refs=E,this.updater=Z||N}var R=A.prototype=new C;R.constructor=A,k(R,D.prototype),R.isPureReactComponent=!0;var I=Array.isArray;function P(){}var O={H:null,A:null,T:null,S:null},_=Object.prototype.hasOwnProperty;function L(M,U,Z){var ae=Z.ref;return{$$typeof:e,type:M,key:U,ref:ae!==void 0?ae:null,props:Z}}function H(M,U){return L(M.type,U,M.props)}function B(M){return typeof M=="object"&&M!==null&&M.$$typeof===e}function z(M){var U={"=":"=0",":":"=2"};return"$"+M.replace(/[=:]/g,function(Z){return U[Z]})}var Q=/\/+/g;function K(M,U){return typeof M=="object"&&M!==null&&M.key!=null?z(""+M.key):U.toString(36)}function X(M){switch(M.status){case"fulfilled":return M.value;case"rejected":throw M.reason;default:switch(typeof M.status=="string"?M.then(P,P):(M.status="pending",M.then(function(U){M.status==="pending"&&(M.status="fulfilled",M.value=U)},function(U){M.status==="pending"&&(M.status="rejected",M.reason=U)})),M.status){case"fulfilled":return M.value;case"rejected":throw M.reason}}throw M}function q(M,U,Z,ae,ce){var J=typeof M;(J==="undefined"||J==="boolean")&&(M=null);var ie=!1;if(M===null)ie=!0;else switch(J){case"bigint":case"string":case"number":ie=!0;break;case"object":switch(M.$$typeof){case e:case t:ie=!0;break;case y:return ie=M._init,q(ie(M._payload),U,Z,ae,ce)}}if(ie)return ce=ce(M),ie=ae===""?"."+K(M,0):ae,I(ce)?(Z="",ie!=null&&(Z=ie.replace(Q,"$&/")+"/"),q(ce,U,Z,"",function(fe){return fe})):ce!=null&&(B(ce)&&(ce=H(ce,Z+(ce.key==null||M&&M.key===ce.key?"":(""+ce.key).replace(Q,"$&/")+"/")+ie)),U.push(ce)),1;ie=0;var ge=ae===""?".":ae+":";if(I(M))for(var ee=0;ee"u"?!1:e instanceof ShadowRoot||e instanceof Sn(e).ShadowRoot}function Vd(e){const{overflow:t,overflowX:a,overflowY:o,display:c}=xr(e);return/auto|scroll|overlay|hidden|clip/.test(t+o+a)&&c!=="inline"&&c!=="contents"}function L5(e){return/^(table|td|th)$/.test(Bs(e))}function Rm(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const z5=/transform|translate|scale|rotate|perspective|filter/,B5=/paint|layout|strict|content/,bi=e=>!!e&&e!=="none";let vv;function yv(e){const t=At(e)?xr(e):e;return bi(t.transform)||bi(t.translate)||bi(t.scale)||bi(t.rotate)||bi(t.perspective)||!jv()&&(bi(t.backdropFilter)||bi(t.filter))||z5.test(t.willChange||"")||B5.test(t.contain||"")}function H5(e){let t=so(e);for(;dn(t)&&!no(t);){if(yv(t))return t;if(Rm(t))return null;t=so(t)}return null}function jv(){return vv==null&&(vv=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),vv}function no(e){return/^(html|body|#document)$/.test(Bs(e))}function xr(e){return Sn(e).getComputedStyle(e)}function Om(e){return At(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function so(e){if(Bs(e)==="html")return e;const t=e.assignedSlot||e.parentNode||Hc(e)&&e.host||xl(e);return Hc(t)?t.host:t}function rC(e){const t=so(e);return no(t)?(e.ownerDocument||e).body:dn(t)&&Vd(t)?t:rC(t)}function Uc(e,t,a){var o;t===void 0&&(t=[]),a===void 0&&(a=!0);const c=rC(e),d=c===((o=e.ownerDocument)==null?void 0:o.body),f=Sn(c);if(d){const p=wv(f);return t.concat(f,f.visualViewport||[],Vd(c)?c:[],p&&a?Uc(p):[])}else return t.concat(c,Uc(c,[],a))}function wv(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}const Sv={..._5},aC={};function Ms(e,t){const a=x.useRef(aC);return a.current===aC&&(a.current=e(t)),a}const Nv=Sv.useInsertionEffect,U5=Nv&&Nv!==Sv.useLayoutEffect?Nv:e=>e();function Ie(e){const t=Ms(V5).current;return t.next=e,U5(t.effect),t.trampoline}function V5(){const e={next:void 0,callback:F5,trampoline:(...t)=>e.callback?.(...t),effect:()=>{e.callback=e.next}};return e}function F5(){}const De=typeof document<"u"?x.useLayoutEffect:()=>{};function kv(e,t){if(e&&!t)return e;if(!e&&t)return t;if(e||t)return{...e,...t}}const Cv={};function Wr(e,t,a,o,c){if(!a&&!o&&!c&&!e)return Mm(t);let d=Mm(e);return t&&(d=Fd(d,t)),a&&(d=Fd(d,a)),o&&(d=Fd(d,o)),c&&(d=Fd(d,c)),d}function $5(e){if(e.length===0)return Cv;if(e.length===1)return Mm(e[0]);let t=Mm(e[0]);for(let a=1;a=65&&c<=90&&(typeof t=="function"||typeof t>"u")}function Tv(e){return typeof e=="function"}function oC(e,t){return Tv(e)?e(t):e??Cv}function K5(e,t){return t?e?(...a)=>{const o=a[0];if(uC(o)){const d=o;Dm(d);const f=t(...a);return d.baseUIHandlerPrevented||e?.(...a),f}const c=t(...a);return e?.(...a),c}:iC(t):e}function iC(e){return e&&((...t)=>{const a=t[0];return uC(a)&&Dm(a),e(...t)})}function Dm(e){return e.preventBaseUIHandler=()=>{e.baseUIHandlerPrevented=!0},e}function cC(e,t){return t?e?t+" "+e:t:e}function uC(e){return e!=null&&typeof e=="object"&&"nativeEvent"in e}function Y5(e,t){return function(o,...c){const d=new URL(e);return d.searchParams.set("code",o.toString()),c.forEach(f=>d.searchParams.append("args[]",f)),`${t} error #${o}; visit ${d} for the full message.`}}const on=Y5("https://base-ui.com/production-error","Base UI"),dC=x.createContext(void 0);function fC(e=!1){const t=x.useContext(dC);if(t===void 0&&!e)throw new Error(on(16));return t}function X5(e){const{focusableWhenDisabled:t,disabled:a,composite:o=!1,tabIndex:c=0,isNativeButton:d}=e,f=o&&t!==!1,p=o&&t===!1;return{props:x.useMemo(()=>{const v={onKeyDown(y){a&&t&&y.key!=="Tab"&&y.preventDefault()}};return o||(v.tabIndex=c,!d&&a&&(v.tabIndex=t?c:-1)),(d&&(t||f)||!d&&a)&&(v["aria-disabled"]=a),d&&(!t||p)&&(v.disabled=a),v},[o,a,t,f,p,d,c])}}function $t(e){return e?.ownerDocument||document}function Vc(e,t,{detail:a=0}={}){e.dispatchEvent(new(Sn(e)).PointerEvent("click",{bubbles:!0,cancelable:!0,composed:!0,detail:a,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey,metaKey:t.metaKey}))}function Jr(e={}){const{disabled:t=!1,focusableWhenDisabled:a,tabIndex:o=0,native:c=!0,composite:d}=e,f=x.useRef(null),p=fC(!0),g=d??p!==void 0,{props:v}=X5({focusableWhenDisabled:a,disabled:t,composite:g,tabIndex:o,isNativeButton:c}),y=x.useCallback(()=>{const w=f.current;Ev(w)&&g&&t&&v.disabled===void 0&&w.disabled&&(w.disabled=!1)},[t,v.disabled,g]);De(y,[y]);const b=x.useCallback((w={})=>{const{onClick:S,onMouseDown:N,onKeyUp:k,onKeyDown:E,onPointerDown:D,...C}=w;return Wr({onClick(A){if(t){A.preventDefault();return}S?.(A)},onMouseDown(A){t||N?.(A)},onKeyDown(A){if(t||(Dm(A),E?.(A),A.baseUIHandlerPrevented))return;const R=A.target===A.currentTarget,I=A.currentTarget,P=Ev(I),O=!c&&Q5(I),_=R&&(c?P:!O),L=A.key==="Enter",H=A.key===" ",B=I.getAttribute("role"),z=B?.startsWith("menuitem")||B==="option"||B==="gridcell";if(R&&g&&H){if(A.defaultPrevented&&z)return;A.preventDefault(),(!c||P)&&(A.preventBaseUIHandler(),Vc(I,A));return}if(!_||c||!H&&!L){R&&O&&H&&A.preventDefault();return}A.defaultPrevented||(A.preventDefault(),L&&(A.preventBaseUIHandler(),Vc(I,A)))},onKeyUp(A){if(!t){if(Dm(A),k?.(A),A.target===A.currentTarget&&c&&g&&Ev(A.currentTarget)&&A.key===" "){A.preventDefault();return}A.baseUIHandlerPrevented||A.target===A.currentTarget&&!c&&!g&&!A.defaultPrevented&&A.key===" "&&(A.preventBaseUIHandler(),Vc(A.currentTarget,A))}},onPointerDown(A){if(t){A.preventDefault();return}D?.(A)}},c?{type:"button"}:{role:"button"},v,C)},[t,v,g,c]),j=Ie(w=>{f.current=w,y()});return{getButtonProps:b,buttonRef:j}}function Ev(e){return dn(e)&&e.tagName==="BUTTON"}function Q5(e){return dn(e)&&e.tagName==="A"&&!!e.href}function ea(e,t,a,o){const c=Ms(pC).current;return W5(c,e,t,a,o)&&mC(c,[e,t,a,o]),c.callback}function Z5(e){const t=Ms(pC).current;return J5(t,e)&&mC(t,e),t.callback}function pC(){return{callback:null,cleanup:null,refs:[]}}function W5(e,t,a,o,c){return e.refs[0]!==t||e.refs[1]!==a||e.refs[2]!==o||e.refs[3]!==c}function J5(e,t){return e.refs.length!==t.length||e.refs.some((a,o)=>a!==t[o])}function mC(e,t){if(e.refs=t,t.every(a=>a==null)){e.callback=null;return}e.callback=a=>{if(e.cleanup&&(e.cleanup(),e.cleanup=null),a!=null){const o=Array(t.length).fill(null);for(let c=0;c{for(let c=0;c=e}function hC(e){if(!x.isValidElement(e))return null;const t=e,a=t.props;return(Av(19)?a?.ref:t.ref)??null}function qt(){}const Rr=Object.freeze([]),fn=Object.freeze({});function tz(e,t){const a={};for(const o in e){const c=e[o];if(t?.hasOwnProperty(o)){const d=t[o](c);d!=null&&Object.assign(a,d);continue}c===!0?a[`data-${o.toLowerCase()}`]="":c&&(a[`data-${o.toLowerCase()}`]=c.toString())}return a}function nz(e,t){return typeof e=="function"?e(t):e}function sz(e,t){return typeof e=="function"?e(t):e}function vt(e,t,a={}){let o=t.render;a.enabled!==!1&&(o=oz(o));const c=rz(t,a,o);if(a.enabled===!1)return null;const d=a.state??fn;return iz(e,o,c,d)}function rz(e,t,a){const{className:o,style:c}=e,{state:d=fn,ref:f,props:p,stateAttributesMapping:g,enabled:v=!0}=t,y=v?nz(o,d):void 0,b=v?sz(c,d):void 0,j=v?tz(d,g):fn,w=v&&p?az(p):void 0,S=v?kv(j,w)??{}:fn;return typeof document<"u"&&(v?Array.isArray(f)?S.ref=Z5([S.ref,hC(a),...f]):S.ref=ea(S.ref,hC(a),f):ea(null,null)),v?(y!==void 0&&(S.className=cC(S.className,y)),b!==void 0&&(S.style=kv(S.style,b)),S):fn}function az(e){return Array.isArray(e)?$5(e):Wr(void 0,e)}const lz=Symbol.for("react.lazy");function oz(e){if(e?.$$typeof!==lz)return e;const t=x.Children.toArray(e)[0];return x.isValidElement(t)?t:e}function iz(e,t,a,o){if(t){if(typeof t=="function")return t(a,o);const c=Wr(a,t.props);return c.ref=a.ref,x.cloneElement(t,c)}if(e&&typeof e=="string")return cz(e,a);throw new Error(on(8))}function cz(e,t){return e==="button"?x.createElement("button",{type:"button",...t,key:t.key}):e==="img"?x.createElement("img",{alt:"",...t,key:t.key}):x.createElement(e,t)}const uz=x.forwardRef(function(t,a){const{render:o,className:c,disabled:d=!1,focusableWhenDisabled:f=!1,nativeButton:p=!0,style:g,...v}=t,{getButtonProps:y,buttonRef:b}=Jr({disabled:d,focusableWhenDisabled:f,native:p});return vt("button",t,{state:{disabled:d},ref:[a,b],props:[v,y]})});function gC(e){var t,a,o="";if(typeof e=="string"||typeof e=="number")o+=e;else if(typeof e=="object")if(Array.isArray(e)){var c=e.length;for(t=0;ttypeof e=="boolean"?`${e}`:e===0?"0":e,vC=xC,Fc=(e,t)=>a=>{var o;if(t?.variants==null)return vC(e,a?.class,a?.className);const{variants:c,defaultVariants:d}=t,f=Object.keys(c).map(v=>{const y=a?.[v],b=d?.[v];if(y===null)return null;const j=bC(y)||bC(b);return c[v][j]}),p=a&&Object.entries(a).reduce((v,y)=>{let[b,j]=y;return j===void 0||(v[b]=j),v},{}),g=t==null||(o=t.compoundVariants)===null||o===void 0?void 0:o.reduce((v,y)=>{let{class:b,className:j,...w}=y;return Object.entries(w).every(S=>{let[N,k]=S;return Array.isArray(k)?k.includes({...d,...p}[N]):{...d,...p}[N]===k})?[...v,b,j]:v},[]);return vC(e,f,g,a?.class,a?.className)},dz=(e,t)=>{const a=new Array(e.length+t.length);for(let o=0;o({classGroupId:e,validator:t}),yC=(e=new Map,t=null,a)=>({nextPart:e,validators:t,classGroupId:a}),Im="-",jC=[],pz="arbitrary..",mz=e=>{const t=gz(e),{conflictingClassGroups:a,conflictingClassGroupModifiers:o}=e;return{getClassGroupId:f=>{if(f.startsWith("[")&&f.endsWith("]"))return hz(f);const p=f.split(Im),g=p[0]===""&&p.length>1?1:0;return wC(p,g,t)},getConflictingClassGroupIds:(f,p)=>{if(p){const g=o[f],v=a[f];return g?v?dz(v,g):g:v||jC}return a[f]||jC}}},wC=(e,t,a)=>{if(e.length-t===0)return a.classGroupId;const c=e[t],d=a.nextPart.get(c);if(d){const v=wC(e,t+1,d);if(v)return v}const f=a.validators;if(f===null)return;const p=t===0?e.join(Im):e.slice(t).join(Im),g=f.length;for(let v=0;ve.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),a=t.indexOf(":"),o=t.slice(0,a);return o?pz+o:void 0})(),gz=e=>{const{theme:t,classGroups:a}=e;return xz(a,t)},xz=(e,t)=>{const a=yC();for(const o in e){const c=e[o];Rv(c,a,o,t)}return a},Rv=(e,t,a,o)=>{const c=e.length;for(let d=0;d{if(typeof e=="string"){vz(e,t,a);return}if(typeof e=="function"){yz(e,t,a,o);return}jz(e,t,a,o)},vz=(e,t,a)=>{const o=e===""?t:SC(t,e);o.classGroupId=a},yz=(e,t,a,o)=>{if(wz(e)){Rv(e(o),t,a,o);return}t.validators===null&&(t.validators=[]),t.validators.push(fz(a,e))},jz=(e,t,a,o)=>{const c=Object.entries(e),d=c.length;for(let f=0;f{let a=e;const o=t.split(Im),c=o.length;for(let d=0;d"isThemeGetter"in e&&e.isThemeGetter===!0,Sz=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,a=Object.create(null),o=Object.create(null);const c=(d,f)=>{a[d]=f,t++,t>e&&(t=0,o=a,a=Object.create(null))};return{get(d){let f=a[d];if(f!==void 0)return f;if((f=o[d])!==void 0)return c(d,f),f},set(d,f){d in a?a[d]=f:c(d,f)}}},Ov="!",NC=":",Nz=[],kC=(e,t,a,o,c)=>({modifiers:e,hasImportantModifier:t,baseClassName:a,maybePostfixModifierPosition:o,isExternal:c}),kz=e=>{const{prefix:t,experimentalParseClassName:a}=e;let o=c=>{const d=[];let f=0,p=0,g=0,v;const y=c.length;for(let N=0;Ng?v-g:void 0;return kC(d,w,j,S)};if(t){const c=t+NC,d=o;o=f=>f.startsWith(c)?d(f.slice(c.length)):kC(Nz,!1,f,void 0,!0)}if(a){const c=o;o=d=>a({className:d,parseClassName:c})}return o},Cz=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((a,o)=>{t.set(a,1e6+o)}),a=>{const o=[];let c=[];for(let d=0;d0&&(c.sort(),o.push(...c),c=[]),o.push(f)):c.push(f)}return c.length>0&&(c.sort(),o.push(...c)),o}},Tz=e=>({cache:Sz(e.cacheSize),parseClassName:kz(e),sortModifiers:Cz(e),postfixLookupClassGroupIds:Ez(e),...mz(e)}),Ez=e=>{const t=Object.create(null),a=e.postfixLookupClassGroups;if(a)for(let o=0;o{const{parseClassName:a,getClassGroupId:o,getConflictingClassGroupIds:c,sortModifiers:d,postfixLookupClassGroupIds:f}=t,p=[],g=e.trim().split(Az);let v="";for(let y=g.length-1;y>=0;y-=1){const b=g[y],{isExternal:j,modifiers:w,hasImportantModifier:S,baseClassName:N,maybePostfixModifierPosition:k}=a(b);if(j){v=b+(v.length>0?" "+v:v);continue}let E=!!k,D;if(E){const P=N.substring(0,k);D=o(P);const O=D&&f[D]?o(N):void 0;O&&O!==D&&(D=O,E=!1)}else D=o(N);if(!D){if(!E){v=b+(v.length>0?" "+v:v);continue}if(D=o(N),!D){v=b+(v.length>0?" "+v:v);continue}E=!1}const C=w.length===0?"":w.length===1?w[0]:d(w).join(":"),A=S?C+Ov:C,R=A+D;if(p.indexOf(R)>-1)continue;p.push(R);const I=c(D,E);for(let P=0;P0?" "+v:v)}return v},Oz=(...e)=>{let t=0,a,o,c="";for(;t{if(typeof e=="string")return e;let t,a="";for(let o=0;o{let a,o,c,d;const f=g=>{const v=t.reduce((y,b)=>b(y),e());return a=Tz(v),o=a.cache.get,c=a.cache.set,d=p,p(g)},p=g=>{const v=o(g);if(v)return v;const y=Rz(g,a);return c(g,y),y};return d=f,(...g)=>d(Oz(...g))},Dz=[],Ss=e=>{const t=a=>a[e]||Dz;return t.isThemeGetter=!0,t.themeKey=e,t},TC=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,EC=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Iz=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,Pz=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,_z=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Lz=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix|color|light-dark)\(.+\)$/,zz=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Bz=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,ro=e=>Iz.test(e),Nt=e=>!!e&&!Number.isNaN(Number(e)),Fa=e=>!!e&&Number.isInteger(Number(e)),Mv=e=>e.endsWith("%")&&Nt(e.slice(0,-1)),bl=e=>Pz.test(e),AC=()=>!0,Hz=e=>_z.test(e)&&!Lz.test(e),Dv=()=>!1,Uz=e=>zz.test(e),Vz=e=>Bz.test(e),Fz=e=>!Ke(e)&&!Xe(e),$z=e=>e.startsWith("@container")&&(e[10]==="/"&&e[11]!==void 0||e[11]==="s"&&e[16]!==void 0&&e.startsWith("-size/",10)||e[11]==="n"&&e[18]!==void 0&&e.startsWith("-normal/",10)),qz=e=>ao(e,PC,Dv),Ke=e=>TC.test(e),vi=e=>ao(e,_C,Hz),RC=e=>ao(e,Jz,Nt),Gz=e=>ao(e,zC,AC),Kz=e=>ao(e,LC,Dv),OC=e=>ao(e,DC,Dv),Yz=e=>ao(e,IC,Vz),Pm=e=>ao(e,BC,Uz),Xe=e=>EC.test(e),$d=e=>yi(e,_C),Xz=e=>yi(e,LC),MC=e=>yi(e,DC),Qz=e=>yi(e,PC),Zz=e=>yi(e,IC),_m=e=>yi(e,BC,!0),Wz=e=>yi(e,zC,!0),ao=(e,t,a)=>{const o=TC.exec(e);return o?o[1]?t(o[1]):a(o[2]):!1},yi=(e,t,a=!1)=>{const o=EC.exec(e);return o?o[1]?t(o[1]):a:!1},DC=e=>e==="position"||e==="percentage",IC=e=>e==="image"||e==="url",PC=e=>e==="length"||e==="size"||e==="bg-size",_C=e=>e==="length",Jz=e=>e==="number",LC=e=>e==="family-name",zC=e=>e==="number"||e==="weight",BC=e=>e==="shadow",e4=Mz(()=>{const e=Ss("color"),t=Ss("font"),a=Ss("text"),o=Ss("font-weight"),c=Ss("tracking"),d=Ss("leading"),f=Ss("breakpoint"),p=Ss("container"),g=Ss("spacing"),v=Ss("radius"),y=Ss("shadow"),b=Ss("inset-shadow"),j=Ss("text-shadow"),w=Ss("drop-shadow"),S=Ss("blur"),N=Ss("perspective"),k=Ss("aspect"),E=Ss("ease"),D=Ss("animate"),C=()=>["auto","avoid","all","avoid-page","page","left","right","column"],A=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],R=()=>[...A(),Xe,Ke],I=()=>["auto","hidden","clip","visible","scroll"],P=()=>["auto","contain","none"],O=()=>[Xe,Ke,g],_=()=>[ro,"full","auto",...O()],L=()=>[Fa,"none","subgrid",Xe,Ke],H=()=>["auto",{span:["full",Fa,Xe,Ke]},Fa,Xe,Ke],B=()=>[Fa,"auto",Xe,Ke],z=()=>["auto","min","max","fr",Xe,Ke],Q=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],K=()=>["start","end","center","stretch","center-safe","end-safe"],X=()=>["auto",...O()],q=()=>[ro,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...O()],$=()=>[p,ro,"screen","full","dvw","lvw","svw","min","max","fit",...O()],Y=()=>[ro,"screen","full","lh","dvh","lvh","svh","min","max","fit",...O()],F=()=>[e,Xe,Ke],G=()=>[...A(),MC,OC,{position:[Xe,Ke]}],W=()=>["no-repeat",{repeat:["","x","y","space","round"]}],le=()=>["auto","cover","contain",Qz,qz,{size:[Xe,Ke]}],M=()=>[Mv,$d,vi],U=()=>["","none","full",v,Xe,Ke],Z=()=>["",Nt,$d,vi],ae=()=>["solid","dashed","dotted","double"],ce=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>[Nt,Mv,MC,OC],ie=()=>["","none",S,Xe,Ke],ge=()=>["none",Nt,Xe,Ke],ee=()=>["none",Nt,Xe,Ke],fe=()=>[Nt,Xe,Ke],te=()=>[ro,"full",...O()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[bl],breakpoint:[bl],color:[AC],container:[bl],"drop-shadow":[bl],ease:["in","out","in-out"],font:[Fz],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[bl],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[bl],shadow:[bl],spacing:["px",Nt],text:[bl],"text-shadow":[bl],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",ro,Ke,Xe,k]}],container:["container"],"container-type":[{"@container":["","normal","size",Xe,Ke]}],"container-named":[$z],columns:[{columns:[Nt,"auto",Ke,Xe,p]}],"break-after":[{"break-after":C()}],"break-before":[{"break-before":C()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:R()}],overflow:[{overflow:I()}],"overflow-x":[{"overflow-x":I()}],"overflow-y":[{"overflow-y":I()}],overscroll:[{overscroll:P()}],"overscroll-x":[{"overscroll-x":P()}],"overscroll-y":[{"overscroll-y":P()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:_()}],"inset-x":[{"inset-x":_()}],"inset-y":[{"inset-y":_()}],start:[{"inset-s":_(),start:_()}],end:[{"inset-e":_(),end:_()}],"inset-bs":[{"inset-bs":_()}],"inset-be":[{"inset-be":_()}],top:[{top:_()}],right:[{right:_()}],bottom:[{bottom:_()}],left:[{left:_()}],visibility:["visible","invisible","collapse"],z:[{z:[Fa,"auto",Xe,Ke]}],basis:[{basis:[ro,"full","auto",p,...O()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[Nt,ro,"auto","initial","none",Ke]}],grow:[{grow:["",Nt,Xe,Ke]}],shrink:[{shrink:["",Nt,Xe,Ke]}],order:[{order:[Fa,"first","last","none",Xe,Ke]}],"grid-cols":[{"grid-cols":L()}],"col-start-end":[{col:H()}],"col-start":[{"col-start":B()}],"col-end":[{"col-end":B()}],"grid-rows":[{"grid-rows":L()}],"row-start-end":[{row:H()}],"row-start":[{"row-start":B()}],"row-end":[{"row-end":B()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":z()}],"auto-rows":[{"auto-rows":z()}],gap:[{gap:O()}],"gap-x":[{"gap-x":O()}],"gap-y":[{"gap-y":O()}],"justify-content":[{justify:[...Q(),"normal"]}],"justify-items":[{"justify-items":[...K(),"normal"]}],"justify-self":[{"justify-self":["auto",...K()]}],"align-content":[{content:["normal",...Q()]}],"align-items":[{items:[...K(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...K(),{baseline:["","last"]}]}],"place-content":[{"place-content":Q()}],"place-items":[{"place-items":[...K(),"baseline"]}],"place-self":[{"place-self":["auto",...K()]}],p:[{p:O()}],px:[{px:O()}],py:[{py:O()}],ps:[{ps:O()}],pe:[{pe:O()}],pbs:[{pbs:O()}],pbe:[{pbe:O()}],pt:[{pt:O()}],pr:[{pr:O()}],pb:[{pb:O()}],pl:[{pl:O()}],m:[{m:X()}],mx:[{mx:X()}],my:[{my:X()}],ms:[{ms:X()}],me:[{me:X()}],mbs:[{mbs:X()}],mbe:[{mbe:X()}],mt:[{mt:X()}],mr:[{mr:X()}],mb:[{mb:X()}],ml:[{ml:X()}],"space-x":[{"space-x":O()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":O()}],"space-y-reverse":["space-y-reverse"],size:[{size:q()}],"inline-size":[{inline:["auto",...$()]}],"min-inline-size":[{"min-inline":["auto",...$()]}],"max-inline-size":[{"max-inline":["none",...$()]}],"block-size":[{block:["auto",...Y()]}],"min-block-size":[{"min-block":["auto",...Y()]}],"max-block-size":[{"max-block":["none",...Y()]}],w:[{w:[p,"screen",...q()]}],"min-w":[{"min-w":[p,"screen","none",...q()]}],"max-w":[{"max-w":[p,"screen","none","prose",{screen:[f]},...q()]}],h:[{h:["screen","lh",...q()]}],"min-h":[{"min-h":["screen","lh","none",...q()]}],"max-h":[{"max-h":["screen","lh","none",...q()]}],"font-size":[{text:["base",a,$d,vi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[o,Wz,Gz]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Mv,Ke]}],"font-family":[{font:[Xz,Kz,t]}],"font-features":[{"font-features":[Ke]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[c,Xe,Ke]}],"line-clamp":[{"line-clamp":[Nt,"none",Xe,RC]}],leading:[{leading:["none",d,...O()]}],"list-image":[{"list-image":["none",Xe,Ke]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Xe,Ke]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:F()}],"text-color":[{text:F()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ae(),"wavy"]}],"text-decoration-thickness":[{decoration:[Nt,"from-font","auto",Xe,vi]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[Nt,"auto",Xe,Ke]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:O()}],"tab-size":[{tab:[Fa,Xe,Ke]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Xe,Ke]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Xe,Ke]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:G()}],"bg-repeat":[{bg:W()}],"bg-size":[{bg:le()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Fa,Xe,Ke],radial:["",Xe,Ke],conic:["",Fa,Xe,Ke]},Zz,Yz]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:M()}],"gradient-via-pos":[{via:M()}],"gradient-to-pos":[{to:M()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:U()}],"rounded-s":[{"rounded-s":U()}],"rounded-e":[{"rounded-e":U()}],"rounded-t":[{"rounded-t":U()}],"rounded-r":[{"rounded-r":U()}],"rounded-b":[{"rounded-b":U()}],"rounded-l":[{"rounded-l":U()}],"rounded-ss":[{"rounded-ss":U()}],"rounded-se":[{"rounded-se":U()}],"rounded-ee":[{"rounded-ee":U()}],"rounded-es":[{"rounded-es":U()}],"rounded-tl":[{"rounded-tl":U()}],"rounded-tr":[{"rounded-tr":U()}],"rounded-br":[{"rounded-br":U()}],"rounded-bl":[{"rounded-bl":U()}],"border-w":[{border:Z()}],"border-w-x":[{"border-x":Z()}],"border-w-y":[{"border-y":Z()}],"border-w-s":[{"border-s":Z()}],"border-w-e":[{"border-e":Z()}],"border-w-bs":[{"border-bs":Z()}],"border-w-be":[{"border-be":Z()}],"border-w-t":[{"border-t":Z()}],"border-w-r":[{"border-r":Z()}],"border-w-b":[{"border-b":Z()}],"border-w-l":[{"border-l":Z()}],"divide-x":[{"divide-x":Z()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Z()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...ae(),"hidden","none"]}],"divide-style":[{divide:[...ae(),"hidden","none"]}],"border-color":[{border:F()}],"border-color-x":[{"border-x":F()}],"border-color-y":[{"border-y":F()}],"border-color-s":[{"border-s":F()}],"border-color-e":[{"border-e":F()}],"border-color-bs":[{"border-bs":F()}],"border-color-be":[{"border-be":F()}],"border-color-t":[{"border-t":F()}],"border-color-r":[{"border-r":F()}],"border-color-b":[{"border-b":F()}],"border-color-l":[{"border-l":F()}],"divide-color":[{divide:F()}],"outline-style":[{outline:[...ae(),"none","hidden"]}],"outline-offset":[{"outline-offset":[Nt,Xe,Ke]}],"outline-w":[{outline:["",Nt,$d,vi]}],"outline-color":[{outline:F()}],shadow:[{shadow:["","inner","none",y,_m,Pm]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":["none",b,_m,Pm]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:Z()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[Nt,vi]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":Z()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":["none",j,_m,Pm]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[Nt,Xe,Ke]}],"mix-blend":[{"mix-blend":[...ce(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":ce()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[Nt]}],"mask-image-linear-from-pos":[{"mask-linear-from":J()}],"mask-image-linear-to-pos":[{"mask-linear-to":J()}],"mask-image-linear-from-color":[{"mask-linear-from":F()}],"mask-image-linear-to-color":[{"mask-linear-to":F()}],"mask-image-t-from-pos":[{"mask-t-from":J()}],"mask-image-t-to-pos":[{"mask-t-to":J()}],"mask-image-t-from-color":[{"mask-t-from":F()}],"mask-image-t-to-color":[{"mask-t-to":F()}],"mask-image-r-from-pos":[{"mask-r-from":J()}],"mask-image-r-to-pos":[{"mask-r-to":J()}],"mask-image-r-from-color":[{"mask-r-from":F()}],"mask-image-r-to-color":[{"mask-r-to":F()}],"mask-image-b-from-pos":[{"mask-b-from":J()}],"mask-image-b-to-pos":[{"mask-b-to":J()}],"mask-image-b-from-color":[{"mask-b-from":F()}],"mask-image-b-to-color":[{"mask-b-to":F()}],"mask-image-l-from-pos":[{"mask-l-from":J()}],"mask-image-l-to-pos":[{"mask-l-to":J()}],"mask-image-l-from-color":[{"mask-l-from":F()}],"mask-image-l-to-color":[{"mask-l-to":F()}],"mask-image-x-from-pos":[{"mask-x-from":J()}],"mask-image-x-to-pos":[{"mask-x-to":J()}],"mask-image-x-from-color":[{"mask-x-from":F()}],"mask-image-x-to-color":[{"mask-x-to":F()}],"mask-image-y-from-pos":[{"mask-y-from":J()}],"mask-image-y-to-pos":[{"mask-y-to":J()}],"mask-image-y-from-color":[{"mask-y-from":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"mask-image-radial":[{"mask-radial":[Xe,Ke]}],"mask-image-radial-from-pos":[{"mask-radial-from":J()}],"mask-image-radial-to-pos":[{"mask-radial-to":J()}],"mask-image-radial-from-color":[{"mask-radial-from":F()}],"mask-image-radial-to-color":[{"mask-radial-to":F()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":A()}],"mask-image-conic-pos":[{"mask-conic":[Nt]}],"mask-image-conic-from-pos":[{"mask-conic-from":J()}],"mask-image-conic-to-pos":[{"mask-conic-to":J()}],"mask-image-conic-from-color":[{"mask-conic-from":F()}],"mask-image-conic-to-color":[{"mask-conic-to":F()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:G()}],"mask-repeat":[{mask:W()}],"mask-size":[{mask:le()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Xe,Ke]}],filter:[{filter:["","none",Xe,Ke]}],blur:[{blur:ie()}],brightness:[{brightness:[Nt,Xe,Ke]}],contrast:[{contrast:[Nt,Xe,Ke]}],"drop-shadow":[{"drop-shadow":["","none",w,_m,Pm]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:["",Nt,Xe,Ke]}],"hue-rotate":[{"hue-rotate":[Nt,Xe,Ke]}],invert:[{invert:["",Nt,Xe,Ke]}],saturate:[{saturate:[Nt,Xe,Ke]}],sepia:[{sepia:["",Nt,Xe,Ke]}],"backdrop-filter":[{"backdrop-filter":["","none",Xe,Ke]}],"backdrop-blur":[{"backdrop-blur":ie()}],"backdrop-brightness":[{"backdrop-brightness":[Nt,Xe,Ke]}],"backdrop-contrast":[{"backdrop-contrast":[Nt,Xe,Ke]}],"backdrop-grayscale":[{"backdrop-grayscale":["",Nt,Xe,Ke]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Nt,Xe,Ke]}],"backdrop-invert":[{"backdrop-invert":["",Nt,Xe,Ke]}],"backdrop-opacity":[{"backdrop-opacity":[Nt,Xe,Ke]}],"backdrop-saturate":[{"backdrop-saturate":[Nt,Xe,Ke]}],"backdrop-sepia":[{"backdrop-sepia":["",Nt,Xe,Ke]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":O()}],"border-spacing-x":[{"border-spacing-x":O()}],"border-spacing-y":[{"border-spacing-y":O()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",Xe,Ke]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[Nt,"initial",Xe,Ke]}],ease:[{ease:["linear","initial",E,Xe,Ke]}],delay:[{delay:[Nt,Xe,Ke]}],animate:[{animate:["none",D,Xe,Ke]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[N,Xe,Ke]}],"perspective-origin":[{"perspective-origin":R()}],rotate:[{rotate:ge()}],"rotate-x":[{"rotate-x":ge()}],"rotate-y":[{"rotate-y":ge()}],"rotate-z":[{"rotate-z":ge()}],scale:[{scale:ee()}],"scale-x":[{"scale-x":ee()}],"scale-y":[{"scale-y":ee()}],"scale-z":[{"scale-z":ee()}],"scale-3d":["scale-3d"],skew:[{skew:fe()}],"skew-x":[{"skew-x":fe()}],"skew-y":[{"skew-y":fe()}],transform:[{transform:[Xe,Ke,"","none","gpu","cpu"]}],"transform-origin":[{origin:R()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:te()}],"translate-x":[{"translate-x":te()}],"translate-y":[{"translate-y":te()}],"translate-z":[{"translate-z":te()}],"translate-none":["translate-none"],zoom:[{zoom:[Fa,Xe,Ke]}],accent:[{accent:F()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:F()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",Xe,Ke]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scrollbar-thumb-color":[{"scrollbar-thumb":F()}],"scrollbar-track-color":[{"scrollbar-track":F()}],"scrollbar-gutter":[{"scrollbar-gutter":["auto","stable","both"]}],"scrollbar-w":[{scrollbar:["auto","thin","none"]}],"scroll-m":[{"scroll-m":O()}],"scroll-mx":[{"scroll-mx":O()}],"scroll-my":[{"scroll-my":O()}],"scroll-ms":[{"scroll-ms":O()}],"scroll-me":[{"scroll-me":O()}],"scroll-mbs":[{"scroll-mbs":O()}],"scroll-mbe":[{"scroll-mbe":O()}],"scroll-mt":[{"scroll-mt":O()}],"scroll-mr":[{"scroll-mr":O()}],"scroll-mb":[{"scroll-mb":O()}],"scroll-ml":[{"scroll-ml":O()}],"scroll-p":[{"scroll-p":O()}],"scroll-px":[{"scroll-px":O()}],"scroll-py":[{"scroll-py":O()}],"scroll-ps":[{"scroll-ps":O()}],"scroll-pe":[{"scroll-pe":O()}],"scroll-pbs":[{"scroll-pbs":O()}],"scroll-pbe":[{"scroll-pbe":O()}],"scroll-pt":[{"scroll-pt":O()}],"scroll-pr":[{"scroll-pr":O()}],"scroll-pb":[{"scroll-pb":O()}],"scroll-pl":[{"scroll-pl":O()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Xe,Ke]}],fill:[{fill:["none",...F()]}],"stroke-w":[{stroke:[Nt,$d,vi,RC]}],stroke:[{stroke:["none",...F()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{"container-named":["container-type"],overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["start","end","right","left"],"inset-y":["inset-bs","inset-be","top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["ps","pe","pr","pl"],py:["pbs","pbe","pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["ms","me","mr","ml"],my:["mbs","mbe","mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-s","border-w-e","border-w-r","border-w-l"],"border-w-y":["border-w-bs","border-w-be","border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-s","border-color-e","border-color-r","border-color-l"],"border-color-y":["border-color-bs","border-color-be","border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-ms","scroll-me","scroll-mr","scroll-ml"],"scroll-my":["scroll-mbs","scroll-mbe","scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-ps","scroll-pe","scroll-pr","scroll-pl"],"scroll-py":["scroll-pbs","scroll-pbe","scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},postfixLookupClassGroups:["container-type"],orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}});function Ue(...e){return e4(xC(e))}const t4=Fc(["group/button inline-flex shrink-0 items-center justify-center gap-1.5 whitespace-nowrap border","font-medium transition-[background-color,border-color,color,transform,box-shadow] duration-150 ease-out","outline-none select-none active:translate-y-[0.5px]","disabled:pointer-events-none disabled:opacity-45 disabled:shadow-none","[&_svg]:pointer-events-none [&_svg]:shrink-0"],{variants:{variant:{default:"border-primary bg-primary font-semibold text-primary-on shadow-glow hover:border-primary-hover hover:bg-primary-hover",outline:"border-control-border bg-control text-foreground shadow-1 hover:border-control-border-hover hover:bg-control-hover",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"border-transparent bg-transparent text-subtle shadow-none hover:bg-control-hover hover:text-foreground",destructive:"border-destructive-bd bg-destructive-soft text-destructive hover:bg-destructive-hover",dashed:"border-dashed border-border-strong bg-transparent text-muted-foreground shadow-none hover:border-primary hover:text-primary-fg",link:"border-transparent bg-transparent text-primary shadow-none underline-offset-4 hover:underline"},size:{default:"h-[30px] rounded-md px-3 text-[12.5px]","2xs":"h-4 rounded-pill px-1.5 text-[10px]",xs:"h-6 rounded-sm px-2 text-[11.5px]",sm:"h-[26px] rounded-sm px-2.5 text-[12px]",lg:"h-9 rounded-md px-4 text-[13px]",icon:"h-[30px] w-[30px] rounded-md p-0","icon-2xs":"size-4 rounded-pill p-0","icon-xs":"size-6 rounded-sm p-0","icon-sm":"h-[26px] w-[26px] rounded-sm p-0","icon-lg":"size-9 rounded-md p-0"}},defaultVariants:{variant:"default",size:"default"}});function se({className:e,variant:t,size:a,...o}){return s.jsx(uz,{className:Ue(t4({variant:t,size:a}),e),...o})}const n4="data-valid",s4="data-invalid",r4={badInput:!1,customError:!1,patternMismatch:!1,rangeOverflow:!1,rangeUnderflow:!1,stepMismatch:!1,tooLong:!1,tooShort:!1,typeMismatch:!1,valid:null,valueMissing:!1},HC={valid:null,touched:!1,dirty:!1,filled:!1,focused:!1},a4={disabled:!1,...HC},ji={valid(e){return e===null?null:e?{[n4]:""}:{[s4]:""}}},UC={invalid:void 0,name:void 0,validityData:{state:r4,errors:[],error:"",value:"",initialValue:null},setValidityData:qt,disabled:void 0,setTouched:qt,setDirty:qt,setFilled:qt,setFocused:qt,validationMode:"onSubmit",shouldValidateOnChange:()=>!1,state:a4,registerFieldControl:qt,validation:{getValidationProps:(e,t=fn)=>t,inputRef:{current:null},registeredInputs:new Map,registerInput:qt,getInputControl:()=>null,commit:async()=>{},change:qt}},VC=x.createContext(UC);function Sa(e=!0){const t=x.useContext(VC);if(t.setValidityData===qt&&!e)throw new Error(on(28));return t}const l4=x.createContext(void 0);function o4(e=!1){const t=x.useContext(l4);if(!t&&!e)throw new Error(on(86));return t}const i4=x.createContext({elementRef:{current:null},formRef:{current:{fields:new Map}},errors:{},clearErrors:qt,validationMode:"onSubmit",submitCountRef:{current:0}});function $c(){return x.useContext(i4)}let FC=0;function c4(e,t="mui"){const[a,o]=x.useState(e),c=e||a;return x.useEffect(()=>{a==null&&(FC+=1,o(`${t}-${FC}`))},[a,t]),c}const $C=Sv.useId;function qd(e,t){if($C!==void 0){const a=$C();return e??(t?`${t}-${a}`:a)}return c4(e,t)}function Na(e){return qd(e,"base-ui")}const u4=x.createContext({controlId:void 0,registerControlId:qt,resetControlId:qt,labelId:void 0,setLabelId:qt,messageIds:[],setMessageIds:qt,getDescriptionProps:e=>e});function vl(){return x.useContext(u4)}function Iv(e,t,a,o=!0,c){const[d,f]=x.useState(),p=Na(c?`${c}-label`:void 0),g=e??t??d;return De(()=>{const v=e||t||!o?void 0:d4(a.current,p);d!==v&&f(v)}),g}function d4(e,t){const a=f4(e);if(a)return!a.id&&t&&(a.id=t),a.id||void 0}function f4(e){if(!e)return;const t=e.parentElement;if(t&&t.tagName==="LABEL")return t;const a=e.id;if(a){const c=e.nextElementSibling;if(c&&c.htmlFor===a)return c}const o=e.labels;return o&&o[0]}function lo(e={}){const{id:t,enabled:a=!0}=e,{controlId:o,registerControlId:c,resetControlId:d}=vl(),f=Na(),p=Ms(()=>Symbol()),g=x.useRef(!1),v=x.useRef(!1),y=Ie(()=>{!g.current||c===qt||(g.current=!1,c(p.current,void 0))});return De(()=>{if(!a||c===qt){y();return}let b;if(t!==void 0)v.current=!0,b=t;else if(v.current)b=f;else{d();return}if(b===void 0){y();return}g.current=!0,c(p.current,b)},[t,a,c,d,f,p,y]),De(()=>y,[y]),(a?o:void 0)??t??f}function p4(){return typeof navigator>"u"?{userAgent:"",platform:"",maxTouchPoints:0}:{userAgent:navigator.userAgent,platform:navigator.platform??"",maxTouchPoints:navigator.maxTouchPoints??0}}const{userAgent:m4,platform:h4,maxTouchPoints:g4}=p4(),Lm=m4.toLowerCase(),Gd=h4.toLowerCase(),Kd=/^i(os$|p)/.test(Gd)||Gd==="macintel"&&g4>1,qC="android",zm=Gd===qC||Lm.includes(qC),GC=!Kd&&Gd.startsWith("mac");Gd.startsWith("win");const x4=GC||Kd,yl=typeof CSS<"u"&&!!CSS.supports?.("-webkit-backdrop-filter:none"),KC=!yl&&Lm.includes("firefox");!yl&&Lm.includes("chrom");const b4=x4,Pv=/jsdom|happydom/.test(Lm);function or(e){let t=e.activeElement;for(;t?.shadowRoot?.activeElement!=null;)t=t.shadowRoot.activeElement;return t}function Qe(e,t){if(!e||!t)return!1;const a=t.getRootNode?.();if(e.contains(t))return!0;if(a&&Hc(a)){let o=t;for(;o;){if(e===o)return!0;o=o.parentNode||o.host}}return!1}function is(e){return"composedPath"in e?e.composedPath()[0]??e.target:e.target}const _v="data-base-ui-focusable",YC="input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])",wi="ArrowLeft",Si="ArrowRight",Lv="ArrowUp",Bm="ArrowDown",XC="data-starting-style",v4="data-ending-style",y4={[XC]:""},j4={[v4]:""},oo={transitionStatus(e){return e==="starting"?y4:e==="ending"?j4:null}},w4="data-open",S4="data-closed",N4="data-anchor-hidden",QC="data-popup-open",k4="data-pressed",C4={[QC]:""},T4={[QC]:"",[k4]:""},E4={[w4]:""},A4={[S4]:""},R4={[N4]:""},zv={open(e){return e?C4:null}},Bv={open(e){return e?T4:null}},qc={open(e){return e?E4:A4},anchorHidden(e){return e?R4:null}},Hv={...qc,...oo},Uv="data-trigger-disabled";function Hm(e,t){if(!At(e))return!1;const a=e;if(t.hasElement(a))return!a.hasAttribute(Uv);for(const[,o]of t.entries())if(Qe(o,a))return!o.hasAttribute(Uv);return!1}function Vv(e,t){if(t==null)return!1;if("composedPath"in e)return e.composedPath().includes(t);const a=e;return a.target!=null&&t.contains(a.target)}function O4(e){return e.matches("html,body")}function Um(e){return dn(e)&&e.matches(YC)}function M4(e){return e?.closest(`button,a[href],[role="button"],select,[tabindex]:not([tabindex="-1"]),${YC}`)!=null}function Fv(e){return e?e.getAttribute("role")==="combobox"&&Um(e):!1}function D4(e){if(!e||Pv)return!0;try{return e.matches(":focus-visible")}catch{return!0}}function Vm(e){return e?e.hasAttribute(_v)?e:e.querySelector(`[${_v}]`)||e:null}function io(e,t,a=!0){return e.filter(c=>c.parentId===t).flatMap(c=>[...!a||c.context?.open?[c]:[],...io(e,c.id,a)])}function ZC(e,t){let a=[],o=e.find(c=>c.id===t)?.parentId;for(;o;){const c=e.find(d=>d.id===o);o=c?.parentId,c&&(a=a.concat(c))}return a}function Ns(e){e.preventDefault(),e.stopPropagation()}function I4(e){return"nativeEvent"in e}function Fm(e){return e.pointerType===""&&e.isTrusted?!0:zm&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function $v(e){return Pv?!1:!zm&&e.width===0&&e.height===0||zm&&e.width===1&&e.height===1&&e.pressure===0&&e.detail===0&&e.pointerType==="mouse"||e.width<1&&e.height<1&&e.pressure===0&&e.detail===0&&e.pointerType==="touch"}function co(e,t){const a=["mouse","pen"];return t||a.push("",void 0),a.includes(e)}function P4(e){const t=e.type;return t==="click"||t==="mousedown"||t==="keydown"||t==="keyup"}const Gc=Math.min,jl=Math.max,$m=Math.round,Ni=Math.floor,wl=e=>({x:e,y:e}),_4={left:"right",right:"left",bottom:"top",top:"bottom"};function WC(e,t,a){return jl(e,Gc(t,a))}function uo(e,t){return typeof e=="function"?e(t):e}function ta(e){return e.split("-")[0]}function Sl(e){return e.split("-")[1]}function qv(e){return e==="x"?"y":"x"}function Gv(e){return e==="y"?"height":"width"}function na(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function Kv(e){return qv(na(e))}function L4(e,t,a){a===void 0&&(a=!1);const o=Sl(e),c=Kv(e),d=Gv(c);let f=c==="x"?o===(a?"end":"start")?"right":"left":o==="start"?"bottom":"top";return t.reference[d]>t.floating[d]&&(f=qm(f)),[f,qm(f)]}function z4(e){const t=qm(e);return[Yv(e),t,Yv(t)]}function Yv(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const JC=["left","right"],e1=["right","left"],B4=["top","bottom"],H4=["bottom","top"];function U4(e,t,a){switch(e){case"top":case"bottom":return a?t?e1:JC:t?JC:e1;case"left":case"right":return t?B4:H4;default:return[]}}function V4(e,t,a,o){const c=Sl(e);let d=U4(ta(e),a==="start",o);return c&&(d=d.map(f=>f+"-"+c),t&&(d=d.concat(d.map(Yv)))),d}function qm(e){const t=ta(e);return _4[t]+e.slice(t.length)}function F4(e){var t,a,o,c;return{top:(t=e.top)!=null?t:0,right:(a=e.right)!=null?a:0,bottom:(o=e.bottom)!=null?o:0,left:(c=e.left)!=null?c:0}}function t1(e){return typeof e!="number"?F4(e):{top:e,right:e,bottom:e,left:e}}function Yd(e){const{x:t,y:a,width:o,height:c}=e;return{width:o,height:c,top:a,left:t,right:t+o,bottom:a+c,x:t,y:a}}function Gm(e,t,a){return Math.floor(e/t)!==a}function fo(e,t){return t<0||t>=e.length}function Km(e,t){return Ds(e.current,{disabledIndices:t})}function Xv(e,t){return Ds(e.current,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}function Ds(e,{startingIndex:t=-1,decrement:a=!1,disabledIndices:o,amount:c=1}={}){let d=t;do d+=a?-c:c;while(d>=0&&d<=e.length-1&&po(e,d,o));return d}function $4(e,{event:t,orientation:a,loopFocus:o,onLoop:c,rtl:d,cols:f,disabledIndices:p,minIndex:g,maxIndex:v,prevIndex:y,stopEvent:b=!1}){let j=y,w;if(t.key===Lv?w="up":t.key===Bm&&(w="down"),w){const S=[],N=[];let k=!1,E=0;{let _=null,L=-1;e.forEach((H,B)=>{if(H==null)return;E+=1;const z=H.closest('[role="row"]');z&&(k=!0),(z!==_||L===-1)&&(_=z,L+=1,S[L]=[]),S[L].push(B),N[B]=L})}let D=!1,C=0;if(k)for(const _ of S){const L=_.length;L>C&&(C=L),L!==f&&(D=!0)}const A=D&&E{if(!D||y===-1)return;const L=N[y];if(L==null)return;const H=S[L].indexOf(y),B=_==="up"?-1:1;for(let z=L+B,Q=0;Q=S.length){if(!o||A)return;if(z=z<0?S.length-1:0,c){const X=Math.min(H,S[z].length-1),q=S[z][X]??S[z][0],$=c(t,y,q);z=N[$]??z}}const K=S[z];for(let X=Math.min(H,K.length-1);X>=0;X-=1){const q=K[X];if(!po(e,q,p))return q}}},P=_=>{if(!A||y===-1)return;const L=y%R,H=_==="up"?-R:R,B=v-v%R,z=Ni(v/R)+1;for(let Q=y-L+H,K=0;Kv){if(!o)return;Q=Q<0?B:0}const X=Math.min(Q+R-1,v);for(let q=Math.min(Q+L,X);q>=Q;q-=1)if(!po(e,q,p))return q}};b&&Ns(t);const O=I(w)??P(w);if(O!==void 0)j=O;else if(y===-1)j=w==="up"?v:g;else if(j=Ds(e,{startingIndex:y,amount:R,decrement:w==="up",disabledIndices:p}),o){if(w==="up"&&(y-R_?H:H-R,c&&(j=c(t,y,j))}w==="down"&&y+R>v&&(j=Ds(e,{startingIndex:y%R-R,amount:R,disabledIndices:p}),c&&(j=c(t,y,j)))}fo(e,j)&&(j=y)}if(a==="both"){const S=Ni(y/f);t.key===(d?wi:Si)&&(b&&Ns(t),y%f!==f-1?(j=Ds(e,{startingIndex:y,disabledIndices:p}),o&&Gm(j,f,S)&&(j=Ds(e,{startingIndex:y-y%f-1,disabledIndices:p}),c&&(j=c(t,y,j)))):o&&(j=Ds(e,{startingIndex:y-y%f-1,disabledIndices:p}),c&&(j=c(t,y,j))),Gm(j,f,S)&&(j=y)),t.key===(d?Si:wi)&&(b&&Ns(t),y%f!==0?(j=Ds(e,{startingIndex:y,decrement:!0,disabledIndices:p}),o&&Gm(j,f,S)&&(j=Ds(e,{startingIndex:y+(f-y%f),decrement:!0,disabledIndices:p}),c&&(j=c(t,y,j)))):o&&(j=Ds(e,{startingIndex:y+(f-y%f),decrement:!0,disabledIndices:p}),c&&(j=c(t,y,j))),Gm(j,f,S)&&(j=y));const N=Ni(v/f)===S;fo(e,j)&&(o&&N?(j=t.key===(d?Si:wi)?v:Ds(e,{startingIndex:y-y%f-1,disabledIndices:p}),c&&(j=c(t,y,j))):j=y)}return j}function po(e,t,a){if(typeof a=="function"?a(t):a?.includes(t)??!1)return!0;const c=e[t];return c?!Ym(c)||c.matches(":disabled")?!0:!a&&(c.hasAttribute("disabled")||c.getAttribute("aria-disabled")==="true"):!1}function q4(e){return e.visibility==="hidden"||e.visibility==="collapse"}function Ym(e,t=e?xr(e):null){return!e||!e.isConnected||!t||q4(t)?!1:typeof e.checkVisibility=="function"?e.checkVisibility():t.display!=="none"&&t.display!=="contents"}const G4='a[href],button,input,select,textarea,summary,details,iframe,object,embed,[tabindex],[contenteditable]:not([contenteditable="false"]),audio[controls],video[controls]';function K4(e){const t=e.assignedSlot;if(t)return t;if(e.parentElement)return e.parentElement;const a=e.getRootNode();return Hc(a)?a.host:null}function Qv(e){for(const t of Array.from(e.children))if(Bs(t)==="summary")return t;return null}function Y4(e,t){const a=Qv(t);return!!a&&(e===a||Qe(a,e))}function n1(e){const t=e?Bs(e):"";return e!=null&&e.matches(G4)&&(t!=="summary"||e.parentElement!=null&&Bs(e.parentElement)==="details"&&Qv(e.parentElement)===e)&&(t!=="details"||Qv(e)==null)&&(t!=="input"||e.type!=="hidden")}function s1(e){if(!n1(e)||!e.isConnected||e.matches(":disabled"))return!1;for(let t=e;t;t=K4(t)){const a=t!==e,o=Bs(t)==="slot";if(t.hasAttribute("inert")||a&&Bs(t)==="details"&&!t.open&&!Y4(e,t)||t.hasAttribute("hidden")||!o&&!X4(t,a))return!1}return!0}function X4(e,t){const a=xr(e);return t?a.display!=="none":Ym(e,a)}function r1(e){const t=e.tabIndex;if(t<0){const a=Bs(e);if(a==="details"||a==="audio"||a==="video"||dn(e)&&e.isContentEditable)return 0}return t}function Zv(e){if(Bs(e)!=="input")return null;const t=e;return t.type==="radio"&&t.name!==""?t:null}function Q4(e,t){const a=Zv(e);if(!a)return!0;const o=t.find(c=>{const d=Zv(c);return d?.name===a.name&&d.form===a.form&&d.checked});return o?o===a:t.find(c=>{const d=Zv(c);return d?.name===a.name&&d.form===a.form})===a}function a1(e){if(dn(e)&&Bs(e)==="slot"){const t=e.assignedElements({flatten:!0});if(t.length>0)return t}return dn(e)&&e.shadowRoot?Array.from(e.shadowRoot.children):Array.from(e.children)}function l1(e,t){a1(e).forEach(a=>{n1(a)&&t.push(a),l1(a,t)})}function o1(e,t,a){a1(e).forEach(o=>{dn(o)&&o.matches(t)&&a.push(o),o1(o,t,a)})}function Wv(e){return s1(e)&&r1(e)>=0}function i1(e){const t=[];return l1(e,t),t.filter(s1)}function Xd(e){const t=i1(e);return t.filter(a=>r1(a)>=0&&Q4(a,t))}function c1(e,t){const a=Xd(e),o=a.length;if(o===0)return;const c=or($t(e)),d=a.indexOf(c),f=d===-1?t===1?0:o-1:d+t;return a[f]}function Jv(e){return c1($t(e).body,1)||e}function u1(e){return c1($t(e).body,-1)||e}function d1(e,t){if(!e)return null;const a=Xd($t(e).body),o=a.length;if(o===0)return null;const c=a.indexOf(e);if(c===-1)return null;const d=(c+t+o)%o;return a[d]}function Z4(e){return d1(e,1)}function W4(e){return d1(e,-1)}function Kc(e,t){const a=t||e.currentTarget,o=e.relatedTarget;return!o||!Qe(a,o)}function J4(e){Xd(e).forEach(a=>{a.dataset.tabindex=a.getAttribute("tabindex")||"",a.setAttribute("tabindex","-1")})}function f1(e){const t=[];o1(e,"[data-tabindex]",t),t.forEach(a=>{const o=a.dataset.tabindex;delete a.dataset.tabindex,o?a.setAttribute("tabindex",o):a.removeAttribute("tabindex")})}function ey(e){x.useEffect(e,Rr)}const Qd=0;class sa{constructor(){ln(this,"currentId",Qd);ln(this,"clear",()=>{this.currentId!==Qd&&(clearTimeout(this.currentId),this.currentId=Qd)});ln(this,"disposeEffect",()=>this.clear)}static create(){return new sa}start(t,a){this.clear(),this.currentId=setTimeout(()=>{this.currentId=Qd,a()},t)}isStarted(){return this.currentId!==Qd}}function Qs(){const e=Ms(sa.create).current;return ey(e.disposeEffect),e}function eB(e,t){return e.matches(":disabled")?!1:!t||e.form===t?!0:e.form===null&&!e.hasAttribute("form")}const tB=x.createContext({disabled:!1});function p1(){return x.useContext(tB)}var ty={exports:{}},Hs={};var m1;function nB(){if(m1)return Hs;m1=1;var e=Ud();function t(y){var b="https://react.dev/errors/"+y;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),ty.exports=nB(),ty.exports}var ks=g1();const Xm=null;class sB{constructor(){ln(this,"callbacks",[]);ln(this,"callbacksCount",0);ln(this,"nextId",1);ln(this,"startId",1);ln(this,"isScheduled",!1);ln(this,"tick",t=>{this.isScheduled=!1;const a=this.callbacks,o=this.callbacksCount;if(this.callbacks=[],this.callbacksCount=0,this.startId=this.nextId,o>0)for(let c=0;c=this.callbacks.length||this.callbacks[a]!==null&&(this.callbacks[a]=null,this.callbacksCount-=1)}}let Qm=new sB;class $a{constructor(){ln(this,"currentId",Xm);ln(this,"cancel",()=>{this.currentId!==Xm&&(Qm.cancel(this.currentId),this.currentId=Xm)});ln(this,"disposeEffect",()=>this.cancel)}static create(){return new $a}static request(t){return Qm.request(t)}static cancel(t){return Qm.cancel(t)}request(t){this.cancel(),this.currentId=Qm.request(()=>{this.currentId=Xm,t()})}}function Yc(){const e=Ms($a.create).current;return ey(e.disposeEffect),e}function Nl(e){return e==null?e:"current"in e?e.current:e}let Zm=null;function rB(e){if(!Zm){const t=[];Zm=t,queueMicrotask(()=>{Zm=null,ks.flushSync(()=>{for(const a of t)a()})})}Zm.push(e)}function x1(e,t=!1,a=!1){const o=Yc();return Ie((c,d=null)=>{o.cancel();const f=Nl(e);if(f==null)return;const p=f,g=()=>{if(!a){ks.flushSync(c);return}rB(()=>{d?.aborted||c()})};if(typeof p.getAnimations!="function"||globalThis.BASE_UI_ANIMATIONS_DISABLED){c();return}function v(){Promise.all(p.getAnimations().map(y=>y.finished)).then(()=>{d?.aborted||g()},()=>{if(d?.aborted)return;if(p.getAnimations().some(b=>b.pending||b.playState!=="finished")){v();return}g()})}if(t){const y=XC;if(!p.hasAttribute(y)){o.request(v);return}const b=new MutationObserver(()=>{p.hasAttribute(y)||(b.disconnect(),v())});b.observe(p,{attributes:!0,attributeFilter:[y]}),d?.addEventListener("abort",()=>b.disconnect(),{once:!0});return}o.request(v)})}function ra(e){const{enabled:t=!0,open:a,ref:o,batch:c=!1,onComplete:d}=e,f=Ie(d),p=x1(o,a,c);x.useEffect(()=>{if(!t)return;const g=new AbortController;return p(f,g.signal),()=>{g.abort()}},[t,a,f,p])}function ki(e,t=!1,a=!1,o=!1){const[c,d]=x.useState(e&&t?"idle":void 0),[f,p]=x.useState(e&&!o);return e&&!f&&(p(!0),d("starting")),!e&&f&&c!=="ending"&&!a&&d("ending"),!e&&!f&&c==="ending"&&d(void 0),De(()=>{if(!e&&f&&c!=="ending"&&a){const g=$a.request(()=>{d("ending")});return()=>{$a.cancel(g)}}},[e,f,c,a]),De(()=>{if(!e||t)return;const g=$a.request(()=>{d(void 0)});return()=>{$a.cancel(g)}},[t,e]),De(()=>{if(!e||!t)return;e&&f&&c!=="idle"&&d("starting");const g=$a.request(()=>{d("idle")});return()=>{$a.cancel(g)}},[t,e,f,c]),{mounted:f,setMounted:p,transitionStatus:c}}function qa({controlled:e,default:t,name:a,state:o="value"}){const{current:c}=x.useRef(e!==void 0),[d,f]=x.useState(t),p=c&&e!==void 0?e:d,g=x.useCallback(v=>{c||f(v)},[]);return[p,g]}function Xc(e,t,a,o,c=!0,d){const{registerFieldControl:f}=Sa(),p=Ms(()=>Symbol());De(()=>{const g=p.current;if(!c){f(g,void 0);return}f(g,{controlRef:e,getValue:o,id:t,name:d,value:a})},[e,c,o,t,d,f,p,a]),De(()=>{const g=p.current;return()=>{f(g,void 0)}},[f,p])}function aa(e,t){const a=x.useRef(e),o=Ie(t);De(()=>{a.current!==e&&o(a.current),a.current=e},[e,o])}const Yn="none",mo="trigger-press",Us="trigger-hover",Wm="trigger-focus",Jm="outside-press",Zd="item-press",ny="close-press",Wd="input-change",Ga="input-clear",aB="input-press",ho="focus-out",Qc="escape-key",sy="list-navigation",b1="keyboard",v1="pointer",y1="cancel-open",lB="disabled",ry="imperative-action",oB="window-resize";function Fe(e,t,a,o){let c=!1,d=!1;const f=o??fn;return{reason:e,event:t??new Event("base-ui"),cancel(){c=!0},allowPropagation(){d=!0},get isCanceled(){return c},get isPropagationAllowed(){return d},trigger:a,...f}}function iB(e,t,a){const o=a??fn;return{reason:e,event:t??new Event("base-ui"),...o}}const cB=x.forwardRef(function(t,a){const{render:o,className:c,id:d,name:f,value:p,disabled:g=!1,onValueChange:v,defaultValue:y,autoFocus:b=!1,style:j,...w}=t,{state:S,name:N,disabled:k,setTouched:E,setDirty:D,validityData:C,setFocused:A,setFilled:R,validationMode:I,validation:P}=Sa(),{clearErrors:O,elementRef:_,submitCountRef:L}=$c(),H=k||g,B=N??f,z={...S,disabled:H},{labelId:Q}=vl(),K=lo({id:d}),[X]=qa({controlled:p,default:y,name:"FieldControl",state:"value"}),q=p!==void 0,$=q?X:void 0,Y=$==null?void 0:String($),F=Ie(()=>P.inputRef.current?.value);Xc(P.inputRef,K,Y,F,!H,f),De(()=>{const M=Y??P.inputRef.current?.value;M!==void 0&&R(M!=="")},[Y,P.inputRef,R]),aa(Y,()=>{Y!==void 0&&(O(B),D(Y!==(C.initialValue??"")),P.change(Y))});const G=x.useRef(null),W=Qs();return De(()=>{b&&G.current===or($t(G.current))&&A(!0)},[b,A]),vt("input",t,{ref:[a,G],state:z,props:[{id:K,disabled:H,name:B,ref:P.inputRef,"aria-labelledby":Q,autoFocus:b,...q?{value:$}:{defaultValue:y},onChange(M){const U=M.currentTarget.value,Z=Fe(Yn,M.nativeEvent);v?.(U,Z),!q&&(D(U!==(C.initialValue??"")),R(U!==""),!M.nativeEvent.defaultPrevented&&!Z.isCanceled&&(O(B),P.change(U)))},onFocus(){A(!0)},onBlur(M){if(E(!0),A(!1),I==="onBlur"){const U=M.currentTarget.value;P.commit(U),q&&queueMicrotask(()=>{const Z=P.inputRef.current?.value;Z!==void 0&&Z!==U&&Z!==(C.initialValue??"")&&P.commit(Z)})}},onKeyDown(M){if(M.currentTarget.tagName==="INPUT"&&M.key==="Enter"){E(!0);const U=M.currentTarget.value,Z=M.currentTarget.form;if(Z&&Z===_.current&&!M.defaultPrevented){const ae=M.currentTarget,ce=L.current;W.start(0,()=>{L.current===ce&&P.commit(ae.value)})}else P.commit(U)}}},w,M=>P.getValidationProps(H,M)],stateAttributesMapping:ji})}),uB=x.forwardRef(function(t,a){return s.jsx(cB,{ref:a,...t})});function $e({className:e,type:t,ref:a,...o}){return s.jsx(uB,{ref:a,type:t,"data-slot":"input",className:Ue("h-[30px] w-full min-w-0 rounded-md border border-control-border bg-control px-2.5","text-[12.5px] text-foreground outline-none","transition-[border-color,box-shadow] duration-150 ease-out","placeholder:text-muted-foreground","hover:border-control-border-hover","focus:border-primary focus:shadow-focus","disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-surface-3 disabled:text-muted-foreground","file:inline-flex file:border-0 file:bg-transparent file:text-foreground",e),...o})}function Zc({className:e,...t}){return s.jsx("textarea",{"data-slot":"textarea",className:Ue("min-h-26 w-full resize-y rounded-md border border-control-border bg-control px-3 py-2.5","font-mono text-[12px] leading-[1.6] text-foreground outline-none","transition-[border-color,box-shadow] duration-150 ease-out","placeholder:text-muted-foreground","hover:border-control-border-hover","focus:border-primary focus:shadow-focus","disabled:cursor-not-allowed disabled:bg-surface-3 disabled:text-muted-foreground",e),...t})}function Ci({className:e,...t}){return s.jsx("div",{"data-slot":"input-group",role:"group",className:Ue("group/input-group relative flex h-[30px] w-full min-w-0 items-center rounded-md border border-control-border bg-control","transition-[border-color,box-shadow] duration-150 ease-out","outline-none","has-[[data-slot=input-group-control]:focus-visible]:border-primary","has-[[data-slot=input-group-control]:focus-visible]:shadow-focus","has-[[data-slot=input-group-control]:hover:not(:focus-visible)]:border-control-border-hover","has-[>textarea]:h-auto","has-[>[data-align=inline-start]]:[&>[data-slot=input-group-control]]:pl-1.5","has-[>[data-align=inline-end]]:[&>[data-slot=input-group-control]]:pr-1.5","has-[>[data-align=block-start]]:h-auto has-[>[data-align=block-start]]:flex-col","has-[>[data-align=block-start]]:[&>[data-slot=input-group-control]]:pb-1.5","has-[>[data-align=block-end]]:h-auto has-[>[data-align=block-end]]:flex-col","has-[>[data-align=block-end]]:[&>[data-slot=input-group-control]]:pt-1.5",e),...t})}const dB=Fc(["flex h-auto cursor-text items-center justify-center gap-1.5 select-none","text-[12px] font-medium text-muted-foreground","group-data-[disabled=true]/input-group:opacity-50"],{variants:{align:{"inline-start":"order-first pl-[9px] has-[>button]:-ml-1","inline-end":"order-last pr-[9px] has-[>button]:-mr-1","block-start":"order-first w-full justify-start px-2.5 pt-2 group-has-[>input]/input-group:pt-1.5","block-end":"order-last w-full justify-start px-2.5 pb-2 group-has-[>input]/input-group:pb-1.5"}},defaultVariants:{align:"inline-start"}});function Ti({className:e,align:t="inline-start",...a}){return s.jsx("div",{role:"group","data-slot":"input-group-addon","data-align":t,className:Ue(dB({align:t}),e),onClick:o=>{o.target.closest("button")||o.currentTarget.parentElement?.querySelector("input")?.focus()},...a})}const fB=Fc("flex items-center shadow-none",{variants:{size:{xs:"h-6 gap-1 rounded-xs px-1.5",sm:"h-8 gap-1.5 rounded-sm px-2.5","icon-xs":"size-6 rounded-xs p-0","icon-sm":"size-8 rounded-sm p-0"}},defaultVariants:{size:"xs"}});function pB({className:e,type:t="button",variant:a="ghost",size:o="xs",...c}){return s.jsx(se,{type:t,"data-size":o,variant:a,className:Ue(fB({size:o}),e),...c})}function Ei({className:e,...t}){return s.jsx($e,{"data-slot":"input-group-control",className:Ue("flex-1 rounded-none border-0 bg-transparent shadow-none focus:border-0 focus:shadow-none",e),...t})}function mB(e){return vt(e.defaultTagName??"div",e,e)}const hB=Fc("inline-flex w-fit shrink-0 items-center justify-center gap-[5px] overflow-hidden whitespace-nowrap border font-semibold",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground",secondary:"border-transparent bg-secondary text-secondary-foreground",destructive:"border-destructive-bd bg-destructive-soft text-destructive",outline:"border-control-border bg-control text-subtle",ghost:"border-transparent bg-transparent text-muted-foreground",link:"border-transparent bg-transparent text-primary underline-offset-4 hover:underline",success:"border-success-bd bg-success-soft text-success",warning:"border-warning-bd bg-warning-soft text-warning",info:"border-info-bd bg-info-soft text-info",brand:"border-primary-bd bg-primary-soft text-primary-fg",cn:"border-cn-bd bg-cn-soft text-cn",intl:"border-intl-bd bg-intl-soft text-intl",sensitive:"border-sensitive-bd bg-sensitive-soft text-sensitive"},shape:{pill:"min-h-[21px] rounded-pill px-[9px] py-px text-[11.5px]",tag:"min-h-[19px] rounded-xs px-2 py-0 text-[11px]"}},defaultVariants:{variant:"default",shape:"pill"}});function ze({className:e,variant:t,shape:a,render:o,...c}){return mB({render:o,defaultTagName:"span",props:Wr({"data-slot":"badge"},c,{className:Ue(hB({variant:t,shape:a}),e)})})}function ay({className:e,...t}){return s.jsx("span",{className:Ue("size-1.5 flex-none rounded-full bg-current",e),...t})}function go(e,t){if(typeof window>"u")return e;const a=window.wbI18n;return a?a.t(e,t)??e:e}function Jd({className:e,...t}){return s.jsx("svg",{"data-slot":"spinner",role:"status","aria-label":go("加载中"),viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",className:Ue("size-4 animate-spin [animation-duration:0.7s]",e),...t,children:s.jsx("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})}function Je({className:e,...t}){return s.jsx("label",{"data-slot":"label",className:Ue("flex items-center gap-[6px] text-[11.5px] text-muted-foreground",e),...t})}const j1={clipPath:"inset(50%)",overflow:"hidden",whiteSpace:"nowrap",border:0,padding:0,width:1,height:1,margin:-1},Ai={...j1,position:"fixed",top:0,left:0},Wc={...j1,position:"absolute"},w1=x.createContext(void 0);function gB(){const e=x.useContext(w1);if(e===void 0)throw new Error(on(63));return e}const xB="data-checked",bB="data-unchecked",S1={...ji,checked(e){return e?{[xB]:""}:{[bB]:""}}},vB=x.forwardRef(function(t,a){const{checked:o,className:c,defaultChecked:d,"aria-labelledby":f,form:p,id:g,inputRef:v,name:y,nativeButton:b=!1,onCheckedChange:j,readOnly:w=!1,required:S=!1,disabled:N=!1,render:k,uncheckedValue:E,value:D,style:C,...A}=t,{clearErrors:R}=$c(),{state:I,setTouched:P,setDirty:O,validityData:_,setFilled:L,setFocused:H,validationMode:B,disabled:z,name:Q,validation:K}=Sa(),{labelId:X}=vl(),q=z||N,$=Q??y,Y=x.useRef(null),F=ea(Y,v,K.inputRef),G=x.useRef(null),W=Na(),le=lo({id:g}),M=b?void 0:le,[U,Z]=qa({controlled:o,default:!!d,name:"Switch",state:"checked"});Xc(G,W,U,void 0,!q,y),De(()=>{L(U)},[U,L]),aa(U,()=>{R($),O(U!==_.initialValue),K.change(U)});const{getButtonProps:ae,buttonRef:ce}=Jr({disabled:q,native:b}),J=Iv(f,X,Y,!b,M),ie={id:b?le:W,role:"switch","aria-checked":U,"aria-readonly":w||void 0,"aria-required":S||void 0,"aria-labelledby":J,onFocus(){q||H(!0)},onBlur(){const te=Y.current;!te||q||(P(!0),H(!1),B==="onBlur"&&K.commit(te.checked))},onClick(te){if(w||q)return;te.preventDefault();const Ce=Y.current;Ce&&Vc(Ce,te)}},ge={...K.getValidationProps(q),checked:U,disabled:q,form:p,id:M,name:$,required:S,style:$?Wc:Ai,tabIndex:-1,type:"checkbox","aria-hidden":!0,ref:F,onChange(te){if(te.nativeEvent.defaultPrevented)return;if(w){te.preventDefault();return}const Ce=te.currentTarget.checked,re=Fe(Yn,te.nativeEvent);j?.(Ce,re),!re.isCanceled&&Z(Ce)},onClick(te){te.stopPropagation()},onFocus(){G.current?.focus()},...D!==void 0?{value:D}:fn},ee=x.useMemo(()=>({...I,checked:U,disabled:q,readOnly:w,required:S}),[I,U,q,w,S]),fe=vt("span",t,{state:ee,ref:[a,G,ce],props:[ie,A,ae,te=>K.getValidationProps(q,te)],stateAttributesMapping:S1});return s.jsxs(w1.Provider,{value:ee,children:[fe,!U&&$&&E!==void 0&&s.jsx("input",{type:"hidden",form:p,name:$,value:E,disabled:q}),s.jsx("input",{...ge,suppressHydrationWarning:!0})]})}),yB=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t,p=gB();return vt("span",t,{state:p,ref:a,stateAttributesMapping:S1,props:f})});function ms({className:e,size:t="default",...a}){const o=t==="sm";return s.jsx(vB,{"data-slot":"switch",className:Ue("relative inline-flex flex-none cursor-pointer items-center rounded-pill border-0 bg-border-strong p-0","transition-colors duration-[180ms] ease-out","data-checked:bg-primary","focus-visible:shadow-focus focus-visible:outline-none","data-disabled:cursor-not-allowed data-disabled:opacity-50",o?"h-[14px] w-6":"h-[21px] w-9",e),...a,children:s.jsx(yB,{"data-slot":"switch-thumb",className:Ue("block rounded-full bg-primary-on shadow-1","transition-transform duration-[180ms] [transition-timing-function:cubic-bezier(.3,1.4,.6,1)]",o?"size-[10px] translate-x-0.5 data-checked:translate-x-[10px]":"size-[17px] translate-x-0.5 data-checked:translate-x-[15px]")})})}function jB(e){if(!e)return null;for(const t of e.elements){const a=t.tagName;if(a==="BUTTON"||a==="INPUT"){const o=t;if(o.type==="submit")return o}}return null}const wB="data-checked",SB="data-unchecked";function N1(e){return{checked(t){return e.indeterminate?{}:t?{[wB]:""}:{[SB]:""}},...ji}}const NB=x.createContext(void 0);function kB(){return x.useContext(NB)}const k1=x.createContext(void 0);function CB(){const e=x.useContext(k1);if(e===void 0)throw new Error(on(14));return e}const TB="data-parent",EB=x.forwardRef(function(t,a){const{checked:o,className:c,defaultChecked:d=!1,"aria-labelledby":f,disabled:p=!1,form:g,id:v,indeterminate:y=!1,inputRef:b,name:j,onCheckedChange:w,parent:S=!1,readOnly:N=!1,render:k,required:E=!1,uncheckedValue:D,value:C,nativeButton:A=!1,style:R,...I}=t,{clearErrors:P}=$c(),{disabled:O,name:_,setDirty:L,setFilled:H,setFocused:B,setTouched:z,state:Q,validationMode:K,validityData:X,validation:q}=Sa(),$=p1(),{labelId:Y,registerControlId:F,getDescriptionProps:G}=vl(),W=kB(),le=W?.allValues===void 0?void 0:W.parent,M=le!==void 0,U=O||$.disabled||W?.disabled||p,Z=_??j,ae=C??Z,ce=Na(),J=W?.registerControlId!==F,ie=lo({id:v||void 0,enabled:J}),ge=A?ie:ce;let ee={};M&&(S?ee=le.getParentProps():ae!==void 0&&(ee=le.getChildProps(ae)));const{checked:fe=o,indeterminate:te=y,onCheckedChange:Ce,...re}=ee,de=W?.value,ke=x.useRef(null),{getButtonProps:Ee,buttonRef:ve}=Jr({disabled:U,native:A}),he=W?.validation??q,[ye,we]=qa({controlled:ae!==void 0&&de!==void 0&&!S?de.includes(ae):fe,default:d,name:"Checkbox",state:"checked"}),xe=M?!!fe:ye,Te=M&&te||y;Xc(ke,ce,ye,void 0,!W&&!U,j);const Oe=le?.registerChildId,Ne=x.useRef(null),_e=he.registerInput,Ye=W?ae:void 0,kt=x.useCallback(it=>_e(it,{controlRef:ke,value:Ye}),[_e,Ye]),Ct=ea(b,Ne,S?void 0:kt),Rt=Iv(f,Y,Ne,!A,ie);De(()=>{Ne.current&&(Ne.current.indeterminate=Te),W||H(ye)},[ye,Te,W,H]),aa(ye,()=>{W||(P(Z),L(ye!==X.initialValue),he.change(ye))});const ot=Wr({checked:ye,disabled:U,form:g,name:S?void 0:Z,id:A?void 0:ie,required:E,ref:Ct,style:Z?Wc:Ai,tabIndex:-1,type:"checkbox","aria-hidden":!0,onChange(it){if(it.nativeEvent.defaultPrevented)return;if(N){it.preventDefault();return}const Vt=it.currentTarget.checked,Bn=Fe(Yn,it.nativeEvent);if(w?.(Vt,Bn),!Bn.isCanceled&&(Ce?.(Vt,Bn),!Bn.isCanceled&&(we(Vt),ae!==void 0&&W!==void 0&&!S&&!M))){const tn=Vt?[...W.value,ae]:W.value.filter(nt=>nt!==ae);W.setValue(tn,Bn)}},onClick(it){it.stopPropagation()},onFocus(){ke.current?.focus()}},C!==void 0?{value:(W?ye&&C:C)||""}:fn,G,it=>he.getValidationProps(U,it));x.useEffect(()=>{if(!le||ae===void 0)return;const it=le.disabledStatesRef.current;return it.set(ae,U),()=>{it.delete(ae)}},[le,U,ae]);const qn=x.useMemo(()=>({...Q,checked:xe,disabled:U,readOnly:N,required:E,indeterminate:Te}),[Q,xe,U,N,E,Te]),ds=N1(qn),Gn=vt("span",t,{state:qn,ref:[ve,ke,a],props:[{id:ge,role:"checkbox","aria-checked":Te?"mixed":xe,"aria-readonly":N||void 0,"aria-required":E||void 0,"aria-labelledby":Rt,[TB]:S?"":void 0,onFocus(){U||B(!0)},onBlur(){const it=Ne.current;it&&(z(!0),B(!1),K==="onBlur"&&he.commit(W?de:it.checked))},onKeyDown(it){if(it.key!=="Enter"||(it.preventBaseUIHandler(),it.defaultPrevented))return;const Vt=Ne.current?.form??null,Bn=it.currentTarget,tn=it.nativeEvent,nt=it.preventDefault,Ot=tn.preventDefault;let Ft=!1;it.preventDefault=()=>{Ft=!0,nt.call(it)},tn.preventDefault=()=>{Ft=!0,Ot.call(tn)},Ot.call(tn),Sn(Bn).queueMicrotask(()=>{it.preventDefault=nt,tn.preventDefault=Ot,Ft||jB(Vt)?.click()})},onClick(it){if(N||U)return;it.preventDefault();const Vt=Ne.current;Vt&&Vc(Vt,it)}},I,re,Ee,G,it=>he.getValidationProps(U,it)],stateAttributesMapping:ds}),xs=Gn.props.id;return De(()=>{if(!(!Oe||S||ae===void 0||xs===void 0))return Oe(ae,xs)},[Oe,S,ae,xs]),s.jsxs(k1.Provider,{value:qn,children:[Gn,!ye&&!W&&Z&&!S&&D!==void 0&&s.jsx("input",{type:"hidden",form:g,name:Z,value:D,disabled:U}),s.jsx("input",{...ot,suppressHydrationWarning:!0})]})}),AB=x.forwardRef(function(t,a){const{render:o,className:c,style:d,keepMounted:f=!1,...p}=t,g=CB(),v=g.checked||g.indeterminate,{mounted:y,transitionStatus:b,setMounted:j}=ki(v),w=x.useRef(null),S={...g,transitionStatus:b};ra({batch:!0,enabled:!v,open:v,ref:w,onComplete(){v||j(!1)}});const k={...N1(g),...oo},E=f||y,D=vt("span",t,{ref:[a,w],state:S,stateAttributesMapping:k,props:p});return E?D:null});function Or({className:e,...t}){return s.jsx(EB,{"data-slot":"checkbox",className:Ue("group/checkbox relative inline-flex size-3.5 shrink-0 cursor-pointer items-center justify-center rounded-[3px] border border-control-border bg-control","outline-none transition-colors duration-150 ease-out","hover:border-control-border-hover","data-checked:border-primary data-checked:bg-primary","focus-visible:shadow-focus","data-disabled:cursor-not-allowed data-disabled:opacity-45",e),...t,children:s.jsx(AB,{"data-slot":"checkbox-indicator",className:"grid place-content-center text-primary-foreground data-unchecked:hidden",children:s.jsxs("svg",{viewBox:"0 0 12 12",className:"size-2.5","aria-hidden":"true",children:[s.jsx("path",{d:"M2 6h8",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",fill:"none",className:"hidden group-aria-[checked=indeterminate]/checkbox:block"}),s.jsx("path",{d:"M2.5 6.2 4.8 8.5 9.5 3.8",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",fill:"none",className:"group-aria-[checked=indeterminate]/checkbox:hidden"})]})})})}function ly(e){return Array.isArray(e)?e.map(t=>ly(t)).join(","):e==null?"":String(e)}const C1=new Map;function RB(e,t){const a=JSON.stringify({locale:ly(e),options:t}),o=C1.get(a);if(o)return o;const c=new Intl.NumberFormat(e,t);return C1.set(a,c),c}function T1(e,t,a){return e==null?"":RB(t,a).format(e)}function Ri(e,t=Number.MIN_SAFE_INTEGER,a=Number.MAX_SAFE_INTEGER){return Math.max(t,Math.min(e,a))}function OB(e,t,a){return(e-t)*100/(a-t)}const E1=x.createContext(void 0);function A1(){const e=x.useContext(E1);if(e===void 0)throw new Error(on(51));return e}const MB="data-complete",DB="data-indeterminate",IB="data-progressing",oy={status(e){return e==="progressing"?{[IB]:""}:e==="complete"?{[MB]:""}:e==="indeterminate"?{[DB]:""}:null}},PB=x.forwardRef(function(t,a){const{format:o,getAriaValueText:c,locale:d,max:f=100,min:p=0,value:g,render:v,className:y,children:b,style:j,...w}=t,[S,N]=x.useState();let k="indeterminate",E=null,D=null,C="",A="indeterminate progress";if(g!=null&&Number.isFinite(g)){const _=OB(g,p,f);E=Ri(Number.isNaN(_)?0:_,0,100),D=Ri(g,p,f),k=D===f?"complete":"progressing",C=o?T1(D,d,o):T1(E/100,d,{style:"percent"}),A=C}const R=x.useMemo(()=>({status:k}),[k]),I={"aria-labelledby":S,"aria-valuemax":f,"aria-valuemin":p,"aria-valuenow":D??void 0,"aria-valuetext":c?c(C,g):A,role:"progressbar",children:s.jsxs(x.Fragment,{children:[b,s.jsx("span",{role:"presentation",style:Ai,children:"x"})]})},P=x.useMemo(()=>({formattedValue:C,percentageValue:E,setLabelId:N,state:R,value:g}),[C,E,N,R,g]),O=vt("div",t,{state:R,ref:a,props:[I,w],stateAttributesMapping:oy});return s.jsx(E1.Provider,{value:P,children:O})}),_B=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t,{state:p}=A1();return vt("div",t,{state:p,ref:a,props:f,stateAttributesMapping:oy})}),LB=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t,{percentageValue:p,state:g}=A1(),v=p==null?{}:{insetInlineStart:0,height:"inherit",width:`${p}%`};return vt("div",t,{state:g,ref:a,props:[{style:v},f],stateAttributesMapping:oy})});function ef({className:e,children:t,value:a,...o}){return s.jsxs(PB,{value:a,"data-slot":"progress",className:Ue("flex w-full flex-wrap items-center gap-3",e),...o,children:[t,s.jsx(zB,{children:s.jsx(BB,{})})]})}function zB({className:e,...t}){return s.jsx(_B,{"data-slot":"progress-track",className:Ue("relative flex h-1.5 w-full items-center overflow-x-hidden overflow-y-hidden rounded-pill bg-surface-3",e),...t})}function BB({className:e,...t}){return s.jsx(LB,{"data-slot":"progress-indicator",className:Ue("h-full rounded-[inherit] bg-primary transition-[width] duration-300 ease-out",e),...t})}const iy=[];let cy;function HB(){return cy}function UB(e){iy.push(e)}function eh(e){const t=(a,o)=>{const c=Ms(VB).current;let d;try{cy=c;for(const f of iy)f.before(c);d=e(a,o);for(const f of iy)f.after(c);c.didInitialize=!0}finally{cy=void 0}return d};return t.displayName=e.displayName||e.name,t}function R1(e){return x.forwardRef(eh(e))}function VB(){return{didInitialize:!1}}const O1=x.createContext(void 0);function tf(e){const t=x.useContext(O1);if(t===void 0&&!e)throw new Error(on(72));return t}function FB(e,t){return t!=null&&!co(t)?0:typeof e=="function"?e():e}function Oi(e,t,a){const o=FB(e,a);return typeof o=="number"?o:o?.[t]}function M1(e){return typeof e=="function"?e():e}function D1(e,t){return t||e==="click"||e==="mousedown"}function $B(e){return e?.includes("mouse")&&e!=="mousedown"}const I1=x.createContext({hasProvider:!1,timeoutMs:0,delayRef:{current:0},initialDelayRef:{current:0},timeout:new sa,currentIdRef:{current:null},currentContextRef:{current:null}});function qB(e,t){e.current=t.current}function GB(e){const{children:t,delay:a,timeoutMs:o=0}=e,c=x.useRef(a),d=x.useRef(a),f=x.useRef(null),p=x.useRef(null),g=Qs();return De(()=>{if(d.current=a,!f.current){c.current=a;return}c.current={open:Oi(c.current,"open"),close:Oi(a,"close")}},[a,f,c,d]),s.jsx(I1.Provider,{value:x.useMemo(()=>({hasProvider:!0,delayRef:c,initialDelayRef:d,currentIdRef:f,timeoutMs:o,currentContextRef:p,timeout:g}),[o,g]),children:t})}function KB(e,t={open:!1}){const{open:a}=t,o="rootStore"in e?e.rootStore:e,c=o.useState("floatingId"),d=x.useContext(I1),{currentIdRef:f,delayRef:p,timeoutMs:g,initialDelayRef:v,currentContextRef:y,hasProvider:b,timeout:j}=d,[w,S]=x.useState(!1),N=x.useRef(a);return De(()=>{N.current=a},[a]),De(()=>{function k(){y.current?.setIsInstantPhase(!1),f.current=null,y.current=null,p.current=v.current,j.clear()}if(f.current&&!a&&f.current===c){if(S(!1),g){const E=c;return j.start(g,()=>{o.select("open")||f.current&&f.current!==E||k()}),()=>{(N.current||f.current!==E)&&j.clear()}}k()}},[a,c,f,p,g,v,y,j,o]),De(()=>{if(!a)return;const k=y.current,E=f.current;j.clear(),y.current={onOpenChange:o.setOpen,setIsInstantPhase:S},f.current=c,p.current={open:0,close:Oi(v.current,"close")},E!==null&&E!==c?(S(!0),k?.setIsInstantPhase(!0),k?.onOpenChange(!1,Fe(Yn))):(S(!1),k?.setIsInstantPhase(!1))},[a,c,o,f,p,v,y,j]),De(()=>()=>{if(f.current===c){if(y.current=null,!N.current)return;f.current=null,qB(p,v),j.clear()}},[y,f,p,c,v,j]),x.useMemo(()=>({activeIdRef:f,hasProvider:b,delayRef:p,isInstantPhase:w}),[f,b,p,w])}function St(e,t,a,o){return e.addEventListener(t,a,o),()=>{e.removeEventListener(t,a,o)}}function Ka(...e){return()=>{for(let t=0;t{t.current=t.next}};return t}const Jc=x.forwardRef(function(t,a){const[o,c]=x.useState();De(()=>{b4&&yl&&c("button")},[]);const d={tabIndex:0,role:o};return s.jsx("span",{...t,ref:a,style:Ai,"aria-hidden":o?void 0:!0,...d,"data-base-ui-focus-guard":""})});function nf(e){return`data-base-ui-${e}`}let th=0;function nh(e,t={}){const{preventScroll:a=!1,sync:o=!1,shouldFocus:c}=t;cancelAnimationFrame(th);function d(){c&&!c()||e?.focus({preventScroll:a})}if(o)return d(),qt;const f=requestAnimationFrame(d);return th=f,()=>{th===f&&(cancelAnimationFrame(f),th=0)}}const uy={inert:new WeakMap,"aria-hidden":new WeakMap},P1="data-base-ui-inert",dy={inert:new WeakSet,"aria-hidden":new WeakSet};let sf=new WeakMap,fy=0;function XB(e){return dy[e]}function _1(e){return e?Hc(e)?e.host:_1(e.parentNode):null}const L1=(e,t)=>t.map(a=>{if(e.contains(a))return a;const o=_1(a);return e.contains(o)?o:null}).filter(a=>a!=null),z1=e=>{const t=new Set;return e.forEach(a=>{let o=a;for(;o&&!t.has(o);)t.add(o),o=o.parentNode}),t},B1=(e,t,a)=>{const o=[],c=d=>{!d||a.has(d)||Array.from(d.children).forEach(f=>{Bs(f)!=="script"&&(t.has(f)?c(f):o.push(f))})};return c(e),o};function QB(e,t,a,o,{mark:c=!0}){let d=null;o?d="inert":a&&(d="aria-hidden");let f=null,p=null;const g=L1(t,e),v=c?B1(t,z1(g),new Set(g)):[],y=[],b=[];if(d){const j=uy[d],w=XB(d);p=w,f=j;const S=L1(t,Array.from(t.querySelectorAll("[aria-live]"))),N=g.concat(S);B1(t,z1(N),new Set(N)).forEach(E=>{const D=E.getAttribute(d),C=D!==null&&D!=="false",A=(j.get(E)||0)+1;j.set(E,A),y.push(E),A===1&&C&&w.add(E),C||E.setAttribute(d,d==="inert"?"":"true")})}return c&&v.forEach(j=>{const w=(sf.get(j)||0)+1;sf.set(j,w),b.push(j),w===1&&j.setAttribute(P1,"")}),fy+=1,()=>{f&&y.forEach(j=>{const S=(f.get(j)||0)-1;f.set(j,S),S||(!p?.has(j)&&d&&j.removeAttribute(d),p?.delete(j))}),c&&b.forEach(j=>{const w=(sf.get(j)||0)-1;sf.set(j,w),w||j.removeAttribute(P1)}),fy-=1,fy||(uy.inert=new WeakMap,uy["aria-hidden"]=new WeakMap,dy.inert=new WeakSet,dy["aria-hidden"]=new WeakSet,sf=new WeakMap)}}function H1(e,t={}){const{ariaHidden:a=!1,inert:o=!1,mark:c=!0}=t,d=$t(e[0]).body;return QB(e,d,a,o,{mark:c})}const ZB=500,WB={style:{transition:"none"}},U1="data-base-ui-click-trigger",V1={fallbackAxisSide:"none"},F1={fallbackAxisSide:"end"},JB={clipPath:"inset(50%)",position:"fixed",top:0,left:0},$1=x.createContext(null),q1=()=>x.useContext($1),eH=nf("portal");function G1(e={}){const{ref:t,container:a,componentProps:o=fn,elementProps:c}=e,d=qd(),p=q1()?.portalNode,[g,v]=x.useState(null),[y,b]=x.useState(null),j=Ie(k=>{k!==null&&b(k)}),w=x.useRef(null);De(()=>{if(a===null){w.current&&(w.current=null,b(null),v(null));return}const k=(a&&(bv(a)?a:a.current))??p??document.body;if(k==null){w.current&&(w.current=null,b(null),v(null));return}w.current!==k&&(w.current=k,b(null),v(k))},[a,p]);const S=vt("div",o,{ref:[t,j],props:[{id:d,[eH]:""},c]}),N=g&&S?ks.createPortal(S,g):null;return{node:y,nodeId:x.isValidElement(S)?S.props.id:void 0,subtree:N}}const sh=x.forwardRef(function(t,a){const{render:o,className:c,style:d,children:f,container:p,portalOwnerRole:g,...v}=t,{node:y,nodeId:b,subtree:j}=G1({container:p,ref:a,componentProps:t,elementProps:v}),w=x.useRef(null),S=x.useRef(null),N=x.useRef(null),k=x.useRef(null),[E,D]=x.useState(null),C=x.useRef(!1),A=E?.modal,R=E?.open,I=!!E&&!E.modal&&E.open&&!!y;x.useEffect(()=>{if(!y||A)return;function O(_){y&&_.relatedTarget&&Kc(_)&&(_.type==="focusin"?C.current&&(f1(y),C.current=!1):(J4(y),C.current=!0))}return Ka(St(y,"focusin",O,!0),St(y,"focusout",O,!0))},[y,A]),De(()=>{!y||R!==!0||!C.current||(f1(y),C.current=!1)},[R,y]);const P=x.useMemo(()=>({beforeOutsideRef:w,afterOutsideRef:S,beforeInsideRef:N,afterInsideRef:k,portalNode:y,setFocusManagerState:D}),[y]);return s.jsxs(x.Fragment,{children:[j,s.jsxs($1.Provider,{value:P,children:[I&&y&&s.jsx(Jc,{"data-type":"outside",ref:w,onFocus:O=>{if(Kc(O,y))N.current?.focus();else{const _=E?E.domReference:null;u1(_)?.focus()}}}),I&&y&&s.jsx("span",{role:g,"aria-owns":b,style:JB}),y&&ks.createPortal(f,y),I&&y&&s.jsx(Jc,{"data-type":"outside",ref:S,onFocus:O=>{if(Kc(O,y))k.current?.focus();else{const _=E?E.domReference:null;Jv(_)?.focus(),E?.closeOnFocusOut&&E?.onOpenChange(!1,Fe(ho,O.nativeEvent))}}})]})]})});function K1(){const e=new Map;return{emit(t,a){e.get(t)?.forEach(o=>o(a))},on(t,a){e.has(t)||e.set(t,new Set),e.get(t).add(a)},off(t,a){e.get(t)?.delete(a)}}}class tH{constructor(){ln(this,"nodesRef",{current:[]});ln(this,"events",K1())}addNode(t){this.nodesRef.current.push(t)}removeNode(t){const a=this.nodesRef.current.findIndex(o=>o===t);a!==-1&&this.nodesRef.current.splice(a,1)}}const Y1=x.createContext(null),X1=x.createContext(null),eu=()=>x.useContext(Y1)?.id||null,Mi=e=>{const t=x.useContext(X1);return e??t};function nH(e){const t=qd(),a=Mi(e),o=eu();return De(()=>{if(!t)return;const c={id:t,parentId:o};return a?.addNode(c),()=>{a?.removeNode(c)}},[a,t,o]),t}function sH(e){const{children:t,id:a}=e,o=eu();return s.jsx(Y1.Provider,{value:x.useMemo(()=>({id:a,parentId:o}),[a,o]),children:t})}function rH(e){const{children:t,externalTree:a}=e,o=Ms(()=>a??new tH).current;return s.jsx(X1.Provider,{value:o,children:t})}function aH(e,t){const a=Sn(is(e));return e instanceof a.KeyboardEvent?"keyboard":e instanceof a.FocusEvent?t||"keyboard":"pointerType"in e?e.pointerType||"keyboard":"touches"in e?"touch":e instanceof a.MouseEvent?t||(e.detail===0?"keyboard":"mouse"):""}const Q1=20;let xo=[];function py(){xo=xo.filter(e=>e.deref()?.isConnected)}function Z1(e){py(),e&&Bs(e)!=="body"&&(xo.push(new WeakRef(e)),xo.length>Q1&&(xo=xo.slice(-Q1)))}function W1(){return py(),xo[xo.length-1]?.deref()}function lH(e){return e?Wv(e)?e:Xd(e)[0]||e:null}function J1(e){if(e.hasAttribute("tabindex")&&!e.hasAttribute("data-tabindex")||!e.getAttribute("role")?.includes("dialog"))return;const a=i1(e).filter(c=>{const d=c.getAttribute("data-tabindex")||"";return Wv(c)||c.hasAttribute("data-tabindex")&&!d.startsWith("-")}),o=e.getAttribute("tabindex");a.length===0?o!=="0"&&(e.setAttribute("tabindex","0"),e.setAttribute("data-tabindex","0")):(o!=="-1"||e.hasAttribute("data-tabindex")&&e.getAttribute("data-tabindex")!=="-1")&&(e.setAttribute("tabindex","-1"),e.setAttribute("data-tabindex","-1"))}function rh(e){const{context:t,children:a,disabled:o=!1,initialFocus:c=!0,returnFocus:d=!0,restoreFocus:f=!1,modal:p=!0,closeOnFocusOut:g=!0,openInteractionType:v="",nextFocusableElement:y,previousFocusableElement:b,beforeContentFocusGuardRef:j,externalTree:w,getInsideElements:S}=e,N="rootStore"in t?t.rootStore:t,k=N.useState("open"),E=N.useState("domReferenceElement"),D=N.useState("floatingElement"),{events:C,dataRef:A}=N.context,R=Ie(()=>A.current.floatingContext?.nodeId),I=c===!1,P=Fv(E)&&I,O=Xn(c),_=Xn(d),L=Xn(v),H=Xn(k),B=Mi(w),z=q1(),Q=x.useRef(!1),K=x.useRef(!1),X=x.useRef(!1),q=x.useRef(null),$=x.useRef(""),Y=x.useRef(""),F=x.useRef(null),G=x.useRef(null),W=ea(F,j,z?.beforeInsideRef),le=ea(G,z?.afterInsideRef),M=Qs(),U=Qs(),Z=Yc(),ae=z!=null,ce=Vm(D),J=Ie((ee=ce)=>ee?Xd(ee):[]),ie=Ie(()=>S?.().filter(ee=>ee!=null)??[]);x.useEffect(()=>{if(o||!p)return;function ee(te){te.key==="Tab"&&Qe(ce,or($t(ce)))&&J().length===0&&!P&&Ns(te)}const fe=$t(ce);return St(fe,"keydown",ee)},[o,ce,p,P,J]),x.useEffect(()=>{if(o||!k)return;const ee=$t(ce);function fe(){X.current=!1}function te(re){const de=is(re),ke=ie(),Ee=Qe(D,de)||Qe(E,de)||Qe(z?.portalNode,de)||ke.some(ve=>ve===de||Qe(ve,de));X.current=!Ee,Y.current=re.pointerType||"keyboard",de?.closest(`[${U1}]`)&&(K.current=!0,U.start(0,()=>{K.current=!1}))}function Ce(){Y.current="keyboard"}return Ka(St(ee,"pointerdown",te,!0),St(ee,"pointerup",fe,!0),St(ee,"pointercancel",fe,!0),St(ee,"keydown",Ce,!0),fe)},[o,D,E,ce,k,z,U,ie]),x.useEffect(()=>{if(o||!g)return;const ee=$t(ce);function fe(){K.current=!0,U.start(0,()=>{K.current=!1})}function te(ke){const Ee=is(ke);Wv(Ee)&&(q.current=Ee)}function Ce(ke){const Ee=ke.relatedTarget,ve=ke.currentTarget,he=is(ke);p&&Ee==null&&he!=null&&Qe(D,he)&&Z1(he),queueMicrotask(()=>{const ye=R(),we=N.context.triggerElements,xe=ie(),Te=Ee?.hasAttribute(nf("focus-guard"))&&[F.current,G.current,z?.beforeInsideRef.current,z?.afterInsideRef.current,z?.beforeOutsideRef.current,z?.afterOutsideRef.current,Nl(b),Nl(y)].includes(Ee),Oe=!(Qe(E,Ee)||Qe(D,Ee)||Qe(Ee,D)||Qe(z?.portalNode,Ee)||xe.some(Ne=>Ne===Ee||Qe(Ne,Ee))||we.hasMatchingElement(Ne=>Qe(Ne,Ee))||Te||B&&(io(B.nodesRef.current,ye).find(Ne=>Qe(Ne.context?.elements.floating,Ee)||Qe(Ne.context?.elements.domReference,Ee))||ZC(B.nodesRef.current,ye).find(Ne=>[Ne.context?.elements.floating,Vm(Ne.context?.elements.floating)].includes(Ee)||Ne.context?.elements.domReference===Ee)));if(ve===E&&ce&&J1(ce),f&&ve!==E&&!Ym(he)&&or(ee)===ee.body){if(dn(ce)&&(ce.focus(),f==="popup")){Z.request(()=>{ce.focus()});return}const Ne=J(),_e=q.current,Ye=(_e&&Ne.includes(_e)?_e:null)||Ne[Ne.length-1]||ce;dn(Ye)&&Ye.focus()}if(A.current.insideReactTree){A.current.insideReactTree=!1;return}(P||!p)&&Ee&&Oe&&!K.current&&(P||Ee!==W1())&&(Q.current=!0,N.setOpen(!1,Fe(ho,ke)))})}function re(){X.current||(A.current.insideReactTree=!0,M.start(0,()=>{A.current.insideReactTree=!1}))}const de=dn(E)?E:null;if(!(!D&&!de))return Ka(de&&St(de,"focusout",Ce),de&&St(de,"pointerdown",fe),D&&St(D,"focusin",te),D&&St(D,"focusout",Ce),D&&z&&St(D,"focusout",re,!0))},[o,E,D,ce,p,B,z,N,g,f,J,P,R,A,M,U,Z,y,b,ie]),x.useEffect(()=>{if(o||!D||!k)return;const ee=Array.from(z?.portalNode?.querySelectorAll(`[${nf("portal")}]`)||[]),te=(B?ZC(B.nodesRef.current,R()):[]).find(ve=>Fv(ve.context?.elements.domReference||null))?.context?.elements.domReference,re=[...[D,...ee,F.current,G.current,z?.beforeOutsideRef.current,z?.afterOutsideRef.current,...ie()],te,Nl(b),Nl(y),P?E:null].filter(ve=>ve!=null),de=H1(re,{ariaHidden:p||P,mark:!1}),ke=[D,...ee].filter(ve=>ve!=null),Ee=H1(ke);return()=>{Ee(),de()}},[k,o,E,D,p,z,P,B,R,y,b,ie]),De(()=>{if(!k||o||!dn(ce))return;$.current="",Y.current="";const ee=$t(ce),fe=or(ee);queueMicrotask(()=>{const te=O.current,Ce=typeof te=="function"?te(L.current||""):te;if(Ce===void 0||Ce===!1||Qe(ce,fe))return;let de=null;const ke=()=>(de==null&&(de=J(ce)),de[0]||ce);let Ee;Ce===!0||Ce===null?Ee=ke():Ee=Nl(Ce),Ee=Ee||ke();const ve=Qe(ce,or(ee));nh(Ee,{preventScroll:Ee===ce,shouldFocus(){if(!H.current)return!1;if(ve)return!0;const he=or(ee);return!(he!==Ee&&Qe(ce,he))}})})},[o,k,ce,J,O,L,H]),De(()=>{if(o||!ce)return;const ee=$t(ce),fe=or(ee),te=L.current==null;Z1(fe);function Ce(de){if(de.open||($.current=aH(de.nativeEvent,Y.current)),de.reason===Us&&de.nativeEvent.type==="mouseleave"&&(Q.current=!0),de.reason===Jm)if(de.nested)Q.current=!1;else if(Fm(de.nativeEvent)||$v(de.nativeEvent))Q.current=!1;else{let ke=!1;$t(ce).createElement("div").focus({get preventScroll(){return ke=!0,!1}}),ke?Q.current=!1:Q.current=!0}}C.on("openchange",Ce);function re(de){const ke=_.current;let Ee=typeof ke=="function"?ke(de):ke;if(Ee===void 0||Ee===!1)return null;Ee===null&&(Ee=!0);const ve=E?.isConnected?E:null,he=fe?.isConnected&&Bs(fe)!=="body"?fe:null;let ye=te?he||ve:ve||he;return ye||(ye=W1()||null),typeof Ee=="boolean"?ye:Nl(Ee)||ye||null}return()=>{C.off("openchange",Ce);const de=or(ee),ke=ie(),Ee=Qe(D,de)||ke.some(we=>we===de||Qe(we,de))||B&&io(B.nodesRef.current,R(),!1).some(we=>Qe(we.context?.elements.floating,de)),ve=_.current,he=$.current,ye=re(he);queueMicrotask(()=>{const we=lH(ye),xe=typeof ve!="boolean";if(ve&&!Q.current&&dn(we)&&(!(!xe&&we!==de&&de!==ee.body)||Ee)){const Te={preventScroll:!0};he==="keyboard"&&(Te.focusVisible=!0),we.focus(Te)}Q.current=!1})}},[o,D,ce,_,L,C,B,E,R,ie]),De(()=>{if(!yl||k||!D)return;const ee=or($t(D));!dn(ee)||!Um(ee)||Qe(D,ee)&&ee.blur()},[k,D]),De(()=>{if(!(o||!z))return z.setFocusManagerState({modal:p,closeOnFocusOut:g,open:k,onOpenChange:N.setOpen,domReference:E}),()=>{z.setFocusManagerState(null)}},[o,z,p,k,N,g,E]),De(()=>{if(!(o||!ce))return J1(ce),()=>{queueMicrotask(py)}},[o,ce]);const ge=!o&&(p?!P:!0)&&(ae||p);return s.jsxs(x.Fragment,{children:[ge&&s.jsx(Jc,{"data-type":"inside",ref:W,onFocus:ee=>{if(p){const fe=J();nh(fe[fe.length-1])}else z?.portalNode&&(Q.current=!1,Kc(ee,z.portalNode)?Jv(E)?.focus():Nl(b??z.beforeOutsideRef)?.focus())}}),a,ge&&s.jsx(Jc,{"data-type":"inside",ref:le,onFocus:ee=>{p?nh(J()[0]):z?.portalNode&&(g&&(Q.current=!0),Kc(ee,z.portalNode)?u1(E)?.focus():Nl(y??z.afterOutsideRef)?.focus())}})]})}function ah(e,t={}){const{enabled:a=!0,event:o="click",toggle:c=!0,ignoreMouse:d=!1,stickIfOpen:f=!0,touchOpenDelay:p=0,reason:g=mo}=t,v="rootStore"in e?e.rootStore:e,y=v.context.dataRef,b=x.useRef(void 0),j=Yc(),w=Qs(),S=x.useMemo(()=>{function N(E,D,C,A){const R=Fe(g,D,C);E&&A==="touch"&&p>0?w.start(p,()=>{v.setOpen(!0,R)}):v.setOpen(E,R)}function k(E,D,C){const A=y.current.openEvent,R=v.select("domReferenceElement")!==D;return E&&R||!E||!c?!0:A&&f?!C(A.type):!1}return{onPointerDown(E){b.current=co(E.pointerType,!0)&&$v(E.nativeEvent)?"virtual":E.pointerType},onMouseDown(E){const D=b.current,C=E.nativeEvent,A=v.select("open");if(E.button!==0||o==="click"||co(D,!0)&&d)return;const R=k(A,E.currentTarget,O=>O==="click"||O==="mousedown"),I=is(C);if(Um(I)){N(R,C,I,D);return}const P=E.currentTarget;j.request(()=>{N(R,C,P,D)})},onClick(E){if(o==="mousedown-only")return;const D=b.current;if(o==="mousedown"&&D){b.current=void 0;return}if(co(D,!0)&&d)return;const C=v.select("open"),A=k(C,E.currentTarget,R=>R==="click"||R==="mousedown"||R==="keydown"||R==="keyup");N(A,E.nativeEvent,E.currentTarget,D)},onKeyDown(){b.current=void 0}}},[y,o,d,g,v,f,c,j,w,p]);return x.useMemo(()=>a?{reference:S}:fn,[a,S])}function oH(e,t){let a=null,o=null,c=!1;return{contextElement:e||void 0,getBoundingClientRect(){const d=e?.getBoundingClientRect()||{width:0,height:0,x:0,y:0},f=t.axis==="x"||t.axis==="both",p=t.axis==="y"||t.axis==="both",g=["mouseenter","mousemove"].includes(t.dataRef.current.openEvent?.type||"")&&t.pointerType!=="touch";let v=d.width,y=d.height,b=d.x,j=d.y;return a==null&&t.x&&f&&(a=d.x-t.x),o==null&&t.y&&p&&(o=d.y-t.y),b-=a||0,j-=o||0,v=0,y=0,!c||g?(v=t.axis==="y"?d.width:0,y=t.axis==="x"?d.height:0,b=f&&t.x!=null?t.x:b,j=p&&t.y!=null?t.y:j):c&&!g&&(y=t.axis==="x"?d.height:y,v=t.axis==="y"?d.width:v),c=!0,{width:v,height:y,x:b,y:j,top:j,right:b+v,bottom:j+y,left:b}}}}function eT(e){return e!=null&&e.clientX!=null}function iH(e,t={}){const{enabled:a=!0,axis:o="both"}=t,c="rootStore"in e?e.rootStore:e,d=c.useState("open"),f=c.useState("floatingElement"),p=c.useState("domReferenceElement"),g=c.context.dataRef,v=x.useRef(!1),y=x.useRef(null),[b,j]=x.useState(),[w,S]=x.useState([]),N=Ie(A=>{c.set("positionReference",A)}),k=Ie((A,R,I)=>{v.current||g.current.openEvent&&!eT(g.current.openEvent)||c.set("positionReference",oH(I??p,{x:A,y:R,axis:o,dataRef:g,pointerType:b}))}),E=Ie(A=>{d?y.current||(k(A.clientX,A.clientY,A.currentTarget),S([])):k(A.clientX,A.clientY,A.currentTarget)}),D=co(b)?f:d;x.useEffect(()=>{if(!a){N(p);return}if(!D)return;function A(){y.current?.(),y.current=null}const R=Sn(f);function I(P){const O=is(P);Qe(f,O)?A():k(P.clientX,P.clientY)}return!g.current.openEvent||eT(g.current.openEvent)?y.current=St(R,"mousemove",I):N(p),A},[D,a,f,g,p,c,k,N,w]),x.useEffect(()=>()=>{c.set("positionReference",null)},[c]),x.useEffect(()=>{a&&!f&&(v.current=!1)},[a,f]),x.useEffect(()=>{!a&&d&&(v.current=!0)},[a,d]);const C=x.useMemo(()=>{function A(R){j(R.pointerType)}return{onPointerDown:A,onPointerEnter:A,onMouseMove:E,onMouseEnter:E}},[E]);return x.useMemo(()=>a?{reference:C,trigger:C}:{},[a,C])}function cH(){return!1}function uH(e){return{escapeKey:typeof e=="boolean"?e:e?.escapeKey??!1,outsidePress:typeof e=="boolean"?e:e?.outsidePress??!0}}function rf(e,t={}){const{enabled:a=!0,escapeKey:o=!0,outsidePress:c=!0,outsidePressEvent:d="sloppy",referencePress:f=cH,bubbles:p,externalTree:g}=t,v="rootStore"in e?e.rootStore:e,y=v.useState("open"),b=v.useState("floatingElement"),{dataRef:j,events:w}=v.context,S=Mi(g),N=Ie(typeof c=="function"?c:()=>!1),k=typeof c=="function"?N:c,E=k!==!1,D=Ie(()=>d),{escapeKey:C,outsidePress:A}=uH(p),R=x.useRef(!1),I=x.useRef(!1),P=x.useRef(!1),O=x.useRef(!1),_=x.useRef(!1),L=x.useRef(""),H=x.useRef(null),B=Qs(),z=Qs(),Q=Ie(()=>{z.clear(),j.current.insideReactTree=!1}),K=Ie(M=>{const U=j.current.floatingContext?.nodeId;return(S?io(S.nodesRef.current,U):[]).some(ae=>ae.context?.open&&!ae.context.dataRef.current[M])}),X=Ie(M=>Vv(M,v.select("floatingElement"))||Vv(M,v.select("domReferenceElement"))),q=Ie(M=>{f()&&v.setOpen(!1,Fe(mo,M.nativeEvent))}),$=Ie(M=>{if(!y||!a||!o||M.key!=="Escape"||_.current||!C&&K("__escapeKeyBubbles"))return;const U=I4(M)?M.nativeEvent:M,Z=Fe(Qc,U);v.setOpen(!1,Z),Z.isCanceled||M.preventDefault(),!C&&!Z.isPropagationAllowed&&M.stopPropagation()}),Y=Ie(()=>{j.current.insideReactTree=!0,z.start(0,Q)}),F=Ie(M=>{if(!y||!a||M.button!==0)return;const U=is(M.nativeEvent);Qe(v.select("floatingElement"),U)&&(R.current||(R.current=!0,I.current=!1))}),G=Ie(M=>{!y||!a||(M.defaultPrevented||M.nativeEvent.defaultPrevented)&&R.current&&(I.current=!0)});x.useEffect(()=>{function M(U){U.open||(O.current=!1)}return w.on("openchange",M),()=>{w.off("openchange",M)}},[w]),x.useEffect(()=>{if(!y||!a)return y||(O.current=!1),Q;j.current.__escapeKeyBubbles=C,j.current.__outsidePressBubbles=A;const M=new sa,U=new sa,Z=$t(b);function ae(){M.clear(),_.current=!0}function ce(){M.start(yl?5:0,()=>{_.current=!1})}function J(){P.current=!0,U.start(0,()=>{P.current=!1})}function ie(){R.current=!1,I.current=!1}function ge(){const Oe=L.current,Ne=Oe==="pen"||!Oe?"mouse":Oe,_e=D(),Ye=typeof _e=="function"?_e():_e;return typeof Ye=="string"?Ye:Ye[Ne]}function ee(Oe){const Ne=ge();return Ne==="intentional"&&Oe.type!=="click"||Ne==="sloppy"&&Oe.type==="click"}function fe(Oe){const Ne=j.current.floatingContext?.nodeId,_e=S&&io(S.nodesRef.current,Ne).some(Ye=>Vv(Oe,Ye.context?.elements.floating));return X(Oe)||_e}function te(Oe){if(ee(Oe)){Oe.type!=="click"&&!X(Oe)&&(U.clear(),P.current=!1),Q();return}if(j.current.insideReactTree){Q();return}const Ne=is(Oe),_e=`[${nf("inert")}]`,Ye=At(Ne)?Ne.getRootNode():null,kt=Array.from((Hc(Ye)?Ye:$t(v.select("floatingElement"))).querySelectorAll(_e)),Ct=v.context.triggerElements;if(Ne&&(Ct.hasElement(Ne)||Ct.hasMatchingElement(ot=>Qe(ot,Ne))))return;let Rt=At(Ne)?Ne:null;for(;Rt&&!no(Rt);){const ot=so(Rt);if(no(ot)||!At(ot))break;Rt=ot}if(!(kt.length&&At(Ne)&&!O4(Ne)&&!Qe(Ne,v.select("floatingElement"))&&kt.every(ot=>!Qe(Rt,ot)))){if(dn(Ne)&&!("touches"in Oe)){const ot=no(Ne),qn=xr(Ne),ds=/auto|scroll/,Gn=ot||ds.test(qn.overflowX),xs=ot||ds.test(qn.overflowY),it=Gn&&Ne.clientWidth>0&&Ne.scrollWidth>Ne.clientWidth,Vt=xs&&Ne.clientHeight>0&&Ne.scrollHeight>Ne.clientHeight,Bn=qn.direction==="rtl",tn=Vt&&(Bn?Oe.offsetX<=Ne.offsetWidth-Ne.clientWidth:Oe.offsetX>Ne.clientWidth),nt=it&&Oe.offsetY>Ne.clientHeight;if(tn||nt)return}if(!fe(Oe)){if(ge()==="intentional"){if(Oe.detail!==0&&!Fm(Oe)&&!O.current)return;if(P.current){U.clear(),P.current=!1;return}}typeof k=="function"&&!k(Oe)||K("__outsidePressBubbles")||(v.setOpen(!1,Fe(Jm,Oe)),Q())}}}function Ce(Oe){ge()!=="sloppy"||Oe.pointerType==="touch"||!v.select("open")||!a||X(Oe)||te(Oe)}function re(Oe){if(ge()!=="sloppy"||!v.select("open")||!a||X(Oe))return;const Ne=Oe.touches[0];Ne&&(H.current={startTime:Date.now(),startX:Ne.clientX,startY:Ne.clientY,dismissOnTouchEnd:!1,dismissOnMouseDown:!0},B.start(1e3,()=>{H.current&&(H.current.dismissOnTouchEnd=!1,H.current.dismissOnMouseDown=!1)}))}function de(Oe,Ne){const _e=is(Oe);if(!_e)return;const Ye=St(_e,Oe.type,()=>{Ne(Oe),Ye()})}function ke(Oe){L.current="touch",de(Oe,re)}function Ee(Oe){B.clear(),Oe.type==="pointerdown"&&(Oe.button===0&&(O.current=!0),L.current=Oe.pointerType),!(Oe.type==="mousedown"&&H.current&&!H.current.dismissOnMouseDown)&&de(Oe,Ne=>{Ne.type==="pointerdown"?Ce(Ne):te(Ne)})}function ve(Oe){if(Oe.type==="pointercancel"&&(O.current=!1),!R.current)return;const Ne=I.current;if(ie(),ge()==="intentional"){if(Oe.type==="pointercancel"){Ne&&J();return}if(!fe(Oe)){if(Ne){J();return}typeof k=="function"&&!k(Oe)||(U.clear(),P.current=!0,Q())}}}function he(Oe){if(ge()!=="sloppy"||!H.current||X(Oe))return;const Ne=Oe.touches[0];if(!Ne)return;const _e=Math.abs(Ne.clientX-H.current.startX),Ye=Math.abs(Ne.clientY-H.current.startY),kt=Math.sqrt(_e*_e+Ye*Ye);kt>5&&(H.current.dismissOnTouchEnd=!0),kt>10&&(te(Oe),B.clear(),H.current=null)}function ye(Oe){de(Oe,he)}function we(Oe){ge()!=="sloppy"||!H.current||X(Oe)||(H.current.dismissOnTouchEnd&&te(Oe),B.clear(),H.current=null)}function xe(Oe){de(Oe,we)}const Te=Ka(o&&Ka(St(Z,"keydown",$),St(Z,"compositionstart",ae),St(Z,"compositionend",ce)),E&&Ka(St(Z,"click",Ee,!0),St(Z,"pointerdown",Ee,!0),St(Z,"pointerup",ve,!0),St(Z,"pointercancel",ve,!0),St(Z,"mousedown",Ee,!0),St(Z,"mouseup",ve,!0),St(Z,"touchstart",ke,{capture:!0,passive:!0}),St(Z,"touchmove",ye,{capture:!0,passive:!0}),St(Z,"touchend",xe,{capture:!0,passive:!0})));return()=>{Te(),M.clear(),U.clear(),ie(),P.current=!1,Q()}},[j,b,o,E,k,y,a,C,A,$,Q,D,K,X,S,v,B]);const W=x.useMemo(()=>({onKeyDown:$,onPointerDown:q,onClick:q}),[$,q]),le=x.useMemo(()=>({onKeyDown:$,onPointerDown:G,onMouseDown:G,onClickCapture:Y,onMouseDownCapture(M){Y(),F(M)},onPointerDownCapture(M){Y(),F(M)},onMouseUpCapture:Y,onTouchEndCapture:Y,onTouchMoveCapture:Y}),[$,Y,F,G]);return x.useMemo(()=>a?{reference:W,floating:le,trigger:W}:{},[a,W,le])}function tT(e,t,a){let{reference:o,floating:c}=e;const d=na(t),f=Kv(t),p=Gv(f),g=ta(t),v=d==="y",y=o.x+o.width/2-c.width/2,b=o.y+o.height/2-c.height/2,j=o[p]/2-c[p]/2;let w;switch(g){case"top":w={x:y,y:o.y-c.height};break;case"bottom":w={x:y,y:o.y+o.height};break;case"right":w={x:o.x+o.width,y:b};break;case"left":w={x:o.x-c.width,y:b};break;default:w={x:o.x,y:o.y}}const S=Sl(t);return S&&(w[f]+=j*(S==="end"?1:-1)*(a&&v?-1:1)),w}async function dH(e,t){var a;t===void 0&&(t={});const{x:o,y:c,platform:d,rects:f,elements:p,strategy:g}=e,{boundary:v="clippingAncestors",rootBoundary:y="viewport",elementContext:b="floating",altBoundary:j=!1,padding:w=0}=uo(t,e),S=t1(w),k=p[j?b==="floating"?"reference":"floating":b],E=Yd(await d.getClippingRect({element:(a=await(d.isElement==null?void 0:d.isElement(k)))==null||a?k:k.contextElement||await(d.getDocumentElement==null?void 0:d.getDocumentElement(p.floating)),boundary:v,rootBoundary:y,strategy:g})),D=b==="floating"?{x:o,y:c,width:f.floating.width,height:f.floating.height}:f.reference,C=await(d.getOffsetParent==null?void 0:d.getOffsetParent(p.floating)),A=await(d.isElement==null?void 0:d.isElement(C))&&await(d.getScale==null?void 0:d.getScale(C))||{x:1,y:1},R=Yd(d.convertOffsetParentRelativeRectToViewportRelativeRect?await d.convertOffsetParentRelativeRectToViewportRelativeRect({elements:p,rect:D,offsetParent:C,strategy:g}):D);return{top:(E.top-R.top+S.top)/A.y,bottom:(R.bottom-E.bottom+S.bottom)/A.y,left:(E.left-R.left+S.left)/A.x,right:(R.right-E.right+S.right)/A.x}}const fH=50,pH=async(e,t,a)=>{const{placement:o="bottom",strategy:c="absolute",middleware:d=[],platform:f}=a,p=f.detectOverflow?f:{...f,detectOverflow:dH},g=await(f.isRTL==null?void 0:f.isRTL(t));let v=await f.getElementRects({reference:e,floating:t,strategy:c}),{x:y,y:b}=tT(v,o,g),j=o,w=0;const S={};for(let N=0;NQ<=0)){var H,B;const Q=(((H=d.flip)==null?void 0:H.index)||0)+1,K=P[Q];if(K&&(!(b==="alignment"?D!==na(K):!1)||L.every($=>na($.placement)===D?$.overflows[0]>0:!0)))return{data:{index:Q,overflows:L},reset:{placement:K}};let X=(B=L.filter(q=>q.overflows[0]<=0).sort((q,$)=>q.overflows[1]-$.overflows[1])[0])==null?void 0:B.placement;if(!X)switch(w){case"bestFit":{var z;const q=(z=L.filter($=>{if(I){const Y=na($.placement);return Y===D||Y==="y"}return!0}).map($=>[$.placement,$.overflows.filter(Y=>Y>0).reduce((Y,F)=>Y+F,0)]).sort(($,Y)=>$[1]-Y[1])[0])==null?void 0:z[0];q&&(X=q);break}case"initialPlacement":X=p;break}if(c!==X)return{reset:{placement:X}}}return{}}}},nT=new Set(["left","top"]);async function hH(e,t){const{placement:a,platform:o,elements:c}=e,d=await(o.isRTL==null?void 0:o.isRTL(c.floating)),f=ta(a),p=Sl(a),g=na(a)==="y",v=nT.has(f)?-1:1,y=d&&g?-1:1,b=uo(t,e);let{mainAxis:j,crossAxis:w,alignmentAxis:S}=typeof b=="number"?{mainAxis:b,crossAxis:0,alignmentAxis:null}:{mainAxis:b.mainAxis||0,crossAxis:b.crossAxis||0,alignmentAxis:b.alignmentAxis};return p&&typeof S=="number"&&(w=p==="end"?S*-1:S),g?{x:w*y,y:j*v}:{x:j*v,y:w*y}}const gH=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var a,o;const{x:c,y:d,placement:f,middlewareData:p}=t,g=await hH(t,e);return f===((a=p.offset)==null?void 0:a.placement)&&(o=p.arrow)!=null&&o.alignmentOffset?{}:{x:c+g.x,y:d+g.y,data:{...g,placement:f}}}}},xH=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:a,y:o,placement:c,platform:d}=t,{mainAxis:f=!0,crossAxis:p=!1,limiter:g={fn:D=>{let{x:C,y:A}=D;return{x:C,y:A}}},...v}=uo(e,t),y={x:a,y:o},b=await d.detectOverflow(t,v),j=na(c),w=qv(j);let S=y[w],N=y[j];const k=(D,C)=>WC(C+b[D==="y"?"top":"left"],C,C-b[D==="y"?"bottom":"right"]);f&&(S=k(w,S)),p&&(N=k(j,N));const E=g.fn({...t,[w]:S,[j]:N});return{...E,data:{x:E.x-a,y:E.y-o,enabled:{[w]:f,[j]:p}}}}}},bH=function(e){return e===void 0&&(e={}),{options:e,fn(t){var a,o;const{x:c,y:d,placement:f,rects:p,middlewareData:g}=t,{offset:v=0,mainAxis:y=!0,crossAxis:b=!0}=uo(e,t),j={x:c,y:d},w=na(f),S=qv(w);let N=j[S],k=j[w];const E=uo(v,t),D=typeof E=="number"?{mainAxis:E,crossAxis:0}:{mainAxis:(a=E.mainAxis)!=null?a:0,crossAxis:(o=E.crossAxis)!=null?o:0};if(y){const R=S==="y"?"height":"width",I=p.reference[S]-p.floating[R]+D.mainAxis,P=p.reference[S]+p.reference[R]-D.mainAxis;NP&&(N=P)}if(b){var C,A;const R=S==="y"?"width":"height",I=nT.has(ta(f)),P=p.reference[w]-p.floating[R]+(I&&((C=g.offset)==null?void 0:C[w])||0)+(I?0:D.crossAxis),O=p.reference[w]+p.reference[R]+(I?0:((A=g.offset)==null?void 0:A[w])||0)-(I?D.crossAxis:0);kO&&(k=O)}return{[S]:N,[w]:k}}}},vH=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:a,rects:o,platform:c,elements:d}=t,{apply:f=()=>{},...p}=uo(e,t),g=await c.detectOverflow(t,p),v=ta(a),y=Sl(a),b=na(a)==="y",{width:j,height:w}=o.floating;let S,N;v==="top"||v==="bottom"?(S=v,N=y===(await(c.isRTL==null?void 0:c.isRTL(d.floating))?"start":"end")?"left":"right"):(N=v,S=y==="end"?"top":"bottom");const k=w-g.top-g.bottom,E=j-g.left-g.right,D=Gc(w-g[S],k),C=Gc(j-g[N],E),A=t.middlewareData.shift,R=!A;let I=D,P=C;A!=null&&A.enabled.x&&(P=E),A!=null&&A.enabled.y&&(I=k),R&&!y&&(b?P=j-2*jl(g.left,g.right):I=w-2*jl(g.top,g.bottom)),await f({...t,availableWidth:P,availableHeight:I});const O=await c.getDimensions(d.floating);return j!==O.width||w!==O.height?{reset:{rects:!0}}:{}}}};function sT(e){const t=xr(e);let a=parseFloat(t.width)||0,o=parseFloat(t.height)||0;const c=dn(e),d=c?e.offsetWidth:a,f=c?e.offsetHeight:o,p=$m(a)!==d||$m(o)!==f;return p&&(a=d,o=f),{width:a,height:o,$:p}}function my(e){return At(e)?e:e.contextElement}function tu(e){const t=my(e);if(!dn(t))return wl(1);const a=t.getBoundingClientRect(),{width:o,height:c,$:d}=sT(t);let f=(d?$m(a.width):a.width)/o,p=(d?$m(a.height):a.height)/c;return(!f||!Number.isFinite(f))&&(f=1),(!p||!Number.isFinite(p))&&(p=1),{x:f,y:p}}const yH=wl(0);function rT(e){const t=Sn(e);return!jv()||!t.visualViewport?yH:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function jH(e,t,a){return t===void 0&&(t=!1),!!a&&t&&a===Sn(e)}function Di(e,t,a,o){t===void 0&&(t=!1),a===void 0&&(a=!1);const c=e.getBoundingClientRect(),d=my(e);let f=wl(1);t&&(o?At(o)&&(f=tu(o)):f=tu(e));const p=jH(d,a,o)?rT(d):wl(0);let g=(c.left+p.x)/f.x,v=(c.top+p.y)/f.y,y=c.width/f.x,b=c.height/f.y;if(d&&o){const j=Sn(d),w=At(o)?Sn(o):o;let S=j,N=wv(S);for(;N&&w!==S;){const k=tu(N),E=N.getBoundingClientRect(),D=xr(N),C=E.left+(N.clientLeft+parseFloat(D.paddingLeft))*k.x,A=E.top+(N.clientTop+parseFloat(D.paddingTop))*k.y;g*=k.x,v*=k.y,y*=k.x,b*=k.y,g+=C,v+=A,S=Sn(N),N=wv(S)}}return Yd({width:y,height:b,x:g,y:v})}function lh(e,t){const a=Om(e).scrollLeft;return t?t.left+a:Di(xl(e)).left+a}function aT(e,t){const a=e.getBoundingClientRect(),o=a.left+t.scrollLeft-lh(e,a),c=a.top+t.scrollTop;return{x:o,y:c}}function wH(e){let{elements:t,rect:a,offsetParent:o,strategy:c}=e;const d=c==="fixed",f=xl(o),p=t?Rm(t.floating):!1;if(o===f||p&&d)return a;let g={scrollLeft:0,scrollTop:0},v=wl(1);const y=wl(0),b=dn(o);if((b||!d)&&((Bs(o)!=="body"||Vd(f))&&(g=Om(o)),b)){const w=Di(o);v=tu(o),y.x=w.x+o.clientLeft,y.y=w.y+o.clientTop}const j=f&&!b&&!d?aT(f,g):wl(0);return{width:a.width*v.x,height:a.height*v.y,x:a.x*v.x-g.scrollLeft*v.x+y.x+j.x,y:a.y*v.y-g.scrollTop*v.y+y.y+j.y}}function SH(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function NH(e){const t=Om(e),a=e.ownerDocument.body,o=jl(e.scrollWidth,e.clientWidth,a.scrollWidth,a.clientWidth),c=jl(e.scrollHeight,e.clientHeight,a.scrollHeight,a.clientHeight);let d=-t.scrollLeft+lh(e);const f=-t.scrollTop;return xr(a).direction==="rtl"&&(d+=jl(e.clientWidth,a.clientWidth)-o),{width:o,height:c,x:d,y:f}}const kH=25;function CH(e,t,a){a===void 0&&(a="viewport");const o=a==="layoutViewport",c=Sn(e),d=xl(e),f=c.visualViewport;let p=d.clientWidth,g=d.clientHeight,v=0,y=0;if(f){const j=!jv()||t==="fixed";o?j||(v=-f.offsetLeft,y=-f.offsetTop):(p=f.width,g=f.height,j&&(v=f.offsetLeft,y=f.offsetTop))}if(lh(d)<=0){const j=d.ownerDocument,w=j.body,S=getComputedStyle(w),N=j.compatMode==="CSS1Compat"&&parseFloat(S.marginLeft)+parseFloat(S.marginRight)||0,k=Math.abs(d.clientWidth-w.clientWidth-N),E=getComputedStyle(d).scrollbarGutter==="stable both-edges"?k/2:k;E<=kH&&(p-=E)}return{width:p,height:g,x:v,y}}function TH(e,t){const a=Di(e,!0,t==="fixed"),o=a.top+e.clientTop,c=a.left+e.clientLeft,d=tu(e),f=e.clientWidth*d.x,p=e.clientHeight*d.y,g=c*d.x,v=o*d.y;return{width:f,height:p,x:g,y:v}}function lT(e,t,a){let o;if(t==="viewport"||t==="layoutViewport")o=CH(e,a,t);else if(t==="document")o=NH(xl(e));else if(At(t))o=TH(t,a);else{const c=rT(e);o={x:t.x-c.x,y:t.y-c.y,width:t.width,height:t.height}}return Yd(o)}function EH(e,t){const a=t.get(e);if(a)return a;let o=Uc(e,[],!1).filter(p=>At(p)&&Bs(p)!=="body"),c=null;const d=xr(e).position==="fixed";let f=d?so(e):e;for(;At(f)&&!no(f);){const p=xr(f),g=yv(f),v=c?c.position:d?"fixed":"";!g&&(v==="fixed"||v==="absolute"&&p.position==="static")?o=o.filter(b=>b!==f):c=p,f=so(f)}return t.set(e,o),o}function AH(e){let{element:t,boundary:a,rootBoundary:o,strategy:c}=e;const f=[...a==="clippingAncestors"?Rm(t)?[]:EH(t,this._c):[].concat(a),o],p=lT(t,f[0],c);let g=p.top,v=p.right,y=p.bottom,b=p.left;for(let j=1;j{p(!1,1e-7)},1e3)}P=!1}try{o=new IntersectionObserver(O,{...I,root:d.ownerDocument})}catch{o=new IntersectionObserver(O,I)}o.observe(e)}const g=Sn(e),v=()=>p(a);return g.addEventListener("resize",v),p(!0),()=>{g.removeEventListener("resize",v),f()}}function dT(e,t,a,o){o===void 0&&(o={});const{ancestorScroll:c=!0,ancestorResize:d=!0,elementResize:f=typeof ResizeObserver=="function",layoutShift:p=typeof IntersectionObserver=="function",animationFrame:g=!1}=o,v=my(e),y=c||d?[...v?Uc(v):[],...t?Uc(t):[]]:[];y.forEach(E=>{c&&E.addEventListener("scroll",a),d&&E.addEventListener("resize",a)});const b=v&&p?IH(v,a,d):null;let j=-1,w=null;f&&(w=new ResizeObserver(E=>{let[D]=E;D&&D.target===v&&w&&t&&(w.unobserve(t),cancelAnimationFrame(j),j=requestAnimationFrame(()=>{var C;(C=w)==null||C.observe(t)})),a()}),v&&!g&&w.observe(v),t&&w.observe(t));let S,N=g?Di(e):null;g&&k();function k(){const E=Di(e);N&&!uT(N,E)&&a(),N=E,S=requestAnimationFrame(k)}return a(),()=>{var E;y.forEach(D=>{c&&D.removeEventListener("scroll",a),d&&D.removeEventListener("resize",a)}),b?.(),(E=w)==null||E.disconnect(),w=null,g&&cancelAnimationFrame(S)}}const PH=gH,_H=xH,LH=mH,zH=vH,BH=bH,HH=(e,t,a)=>{const o=new Map,c=a??{},d={...cT,...c.platform,_c:o};return pH(e,t,{...c,platform:d})};var UH=typeof document<"u",VH=function(){},oh=UH?x.useLayoutEffect:VH;function ih(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 a,o,c;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(a=e.length,a!==t.length)return!1;for(o=a;o--!==0;)if(!ih(e[o],t[o]))return!1;return!0}if(c=Object.keys(e),a=c.length,a!==Object.keys(t).length)return!1;for(o=a;o--!==0;)if(!{}.hasOwnProperty.call(t,c[o]))return!1;for(o=a;o--!==0;){const d=c[o];if(!(d==="_owner"&&e.$$typeof)&&!ih(e[d],t[d]))return!1}return!0}return e!==e&&t!==t}function fT(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function pT(e,t){const a=fT(e);return Math.round(t*a)/a}function gy(e){const t=x.useRef(e);return oh(()=>{t.current=e}),t}function FH(e){e===void 0&&(e={});const{placement:t="bottom",strategy:a="absolute",middleware:o=[],platform:c,elements:{reference:d,floating:f}={},transform:p=!0,whileElementsMounted:g,open:v}=e,[y,b]=x.useState({x:0,y:0,strategy:a,placement:t,middlewareData:{},isPositioned:!1}),[j,w]=x.useState(o);ih(j,o)||w(o);const[S,N]=x.useState(null),[k,E]=x.useState(null),D=x.useCallback($=>{$!==I.current&&(I.current=$,N($))},[]),C=x.useCallback($=>{$!==P.current&&(P.current=$,E($))},[]),A=d||S,R=f||k,I=x.useRef(null),P=x.useRef(null),O=x.useRef(y),_=g!=null,L=gy(g),H=gy(c),B=gy(v),z=x.useCallback(()=>{if(!I.current||!P.current)return;const $={placement:t,strategy:a,middleware:j};H.current&&($.platform=H.current),HH(I.current,P.current,$).then(Y=>{const F={...Y,isPositioned:B.current!==!1};Q.current&&!ih(O.current,F)&&(O.current=F,ks.flushSync(()=>{b(F)}))})},[j,t,a,H,B]);oh(()=>{v===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,b($=>({...$,isPositioned:!1})))},[v]);const Q=x.useRef(!1);oh(()=>(Q.current=!0,()=>{Q.current=!1}),[]),oh(()=>{if(A&&(I.current=A),R&&(P.current=R),A&&R){if(L.current)return L.current(A,R,z);z()}},[A,R,z,L,_]);const K=x.useMemo(()=>({reference:I,floating:P,setReference:D,setFloating:C}),[D,C]),X=x.useMemo(()=>({reference:A,floating:R}),[A,R]),q=x.useMemo(()=>{const $={position:a,left:0,top:0};if(!X.floating)return $;const Y=pT(X.floating,y.x),F=pT(X.floating,y.y);return p?{...$,transform:"translate("+Y+"px, "+F+"px)",...fT(X.floating)>=1.5&&{willChange:"transform"}}:{position:a,left:Y,top:F}},[a,p,X.floating,y.x,y.y]);return x.useMemo(()=>({...y,update:z,refs:K,elements:X,floatingStyles:q}),[y,z,K,X,q])}const $H=(e,t)=>{const a=PH(e);return{name:a.name,fn:a.fn,options:[e,t]}},qH=(e,t)=>{const a=_H(e);return{name:a.name,fn:a.fn,options:[e,t]}},GH=(e,t)=>({fn:BH(e).fn,options:[e,t]}),KH=(e,t)=>{const a=LH(e);return{name:a.name,fn:a.fn,options:[e,t]}},YH=(e,t)=>{const a=zH(e);return{name:a.name,fn:a.fn,options:[e,t]}};var xy={exports:{}},by={};var mT;function XH(){if(mT)return by;mT=1;var e=Ud();function t(b,j){return b===j&&(b!==0||1/b===1/j)||b!==b&&j!==j}var a=typeof Object.is=="function"?Object.is:t,o=e.useState,c=e.useEffect,d=e.useLayoutEffect,f=e.useDebugValue;function p(b,j){var w=j(),S=o({inst:{value:w,getSnapshot:j}}),N=S[0].inst,k=S[1];return d(function(){N.value=w,N.getSnapshot=j,g(N)&&k({inst:N})},[b,w,j]),c(function(){return g(N)&&k({inst:N}),b(function(){g(N)&&k({inst:N})})},[b]),f(w),w}function g(b){var j=b.getSnapshot;b=b.value;try{var w=j();return!a(b,w)}catch{return!0}}function v(b,j){return j()}var y=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?v:p;return by.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:y,by}var hT;function gT(){return hT||(hT=1,xy.exports=XH()),xy.exports}var vy=gT(),yy={exports:{}},jy={};var xT;function QH(){if(xT)return jy;xT=1;var e=Ud(),t=gT();function a(v,y){return v===y&&(v!==0||1/v===1/y)||v!==v&&y!==y}var o=typeof Object.is=="function"?Object.is:a,c=t.useSyncExternalStore,d=e.useRef,f=e.useEffect,p=e.useMemo,g=e.useDebugValue;return jy.useSyncExternalStoreWithSelector=function(v,y,b,j,w){var S=d(null);if(S.current===null){var N={hasValue:!1,value:null};S.current=N}else N=S.current;S=p(function(){function E(I){if(!D){if(D=!0,C=I,I=j(I),w!==void 0&&N.hasValue){var P=N.value;if(w(P,I))return A=P}return A=I}if(P=A,o(C,I))return P;var O=j(I);return w!==void 0&&w(P,O)?(C=I,P):(C=I,A=O)}var D=!1,C,A,R=b===void 0?null:b;return[function(){return E(y())},R===null?void 0:function(){return E(R())}]},[y,b,j,w]);var k=c(v,S[0],S[1]);return f(function(){N.hasValue=!0,N.value=k},[k]),g(k),k},jy}var bT;function ZH(){return bT||(bT=1,yy.exports=QH()),yy.exports}var WH=ZH();const JH=Av(19)?tU:nU;function vT(e,t,a,o,c){return JH(e,t,a,o,c)}function eU(e,t,a,o,c){const d=x.useCallback(()=>t(e.getSnapshot(),a,o,c),[e,t,a,o,c]);return vy.useSyncExternalStore(e.subscribe,d,d)}UB({before(e){e.syncIndex=0,e.didInitialize||(e.syncTick=1,e.syncHooks=[],e.didChangeStore=!0,e.getSnapshot=()=>{let t=!1;for(let a=0;a0&&(e.didChangeStore&&(e.didChangeStore=!1,e.subscribe=t=>{const a=new Set;for(const c of e.syncHooks)a.add(c.store);const o=[];for(const c of a)o.push(c.subscribe(t));return()=>{for(const c of o)c()}}),vy.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot))}});function tU(e,t,a,o,c){const d=HB();if(!d)return eU(e,t,a,o,c);const f=d.syncIndex;d.syncIndex+=1;let p;return d.didInitialize?(p=d.syncHooks[f],(p.store!==e||p.selector!==t||!Object.is(p.a1,a)||!Object.is(p.a2,o)||!Object.is(p.a3,c))&&(p.store!==e&&(d.didChangeStore=!0),p.store=e,p.selector=t,p.a1=a,p.a2=o,p.a3=c,p.value=t(e.getSnapshot(),a,o,c))):(p={store:e,selector:t,a1:a,a2:o,a3:c,value:t(e.getSnapshot(),a,o,c)},d.syncHooks.push(p)),p.value}function nU(e,t,a,o,c){return WH.useSyncExternalStoreWithSelector(e.subscribe,e.getSnapshot,e.getSnapshot,d=>t(d,a,o,c))}class sU{constructor(t){ln(this,"subscribe",t=>(this.listeners.add(t),()=>{this.listeners.delete(t)}));ln(this,"getSnapshot",()=>this.state);this.state=t,this.listeners=new Set,this.updateTick=0}static create(t){return new this(t)}setState(t){if(this.state===t)return;this.state=t,this.updateTick+=1;const a=this.updateTick;for(const o of this.listeners){if(a!==this.updateTick)return;o(t)}}update(t){for(const a in t)if(!Object.is(this.state[a],t[a])){this.setState({...this.state,...t});return}}set(t,a){Object.is(this.state[t],a)||this.setState({...this.state,[t]:a})}notifyAll(){const t={...this.state};this.setState(t)}use(t,a,o,c){return vT(this,t,a,o,c)}}class nu extends sU{constructor(t,a={},o){super(t),this.context=a,this.selectors=o}useSyncedValue(t,a){x.useDebugValue(t);const o=this;De(()=>{o.state[t]!==a&&o.set(t,a)},[o,t,a])}useSyncedValueWithCleanup(t,a){const o=this;De(()=>(o.state[t]!==a&&o.set(t,a),()=>{o.set(t,void 0)}),[o,t,a])}useSyncedValues(t){const a=this,o=Object.values(t);De(()=>{a.update(t)},[a,...o])}useControlledProp(t,a){x.useDebugValue(t);const o=this,c=a!==void 0;De(()=>{c&&!Object.is(o.state[t],a)&&o.setState({...o.state,[t]:a})},[o,t,a,c])}select(t,a,o,c){const d=this.selectors[t];return d(this.state,a,o,c)}useState(t,a,o,c){return x.useDebugValue(t),vT(this,this.selectors[t],a,o,c)}useContextCallback(t,a){x.useDebugValue(t);const o=Ie(a??qt);this.context[t]=o}useStateSetter(t){const a=x.useRef(void 0);return a.current===void 0&&(a.current=o=>{this.set(t,o)}),a.current}observe(t,a){let o;typeof t=="function"?o=t:o=this.selectors[t];let c=o(this.state);return a(c,c,this),this.subscribe(d=>{const f=o(d);if(!Object.is(c,f)){const p=c;c=f,a(f,p,this)}})}}const rU={open:e=>e.open,transitionStatus:e=>e.transitionStatus,domReferenceElement:e=>e.domReferenceElement,referenceElement:e=>e.positionReference??e.referenceElement,floatingElement:e=>e.floatingElement,floatingId:e=>e.floatingId};class wy extends nu{constructor(a){const{syncOnly:o,nested:c,onOpenChange:d,triggerElements:f,...p}=a;super({...p,positionReference:p.referenceElement,domReferenceElement:p.referenceElement},{onOpenChange:d,dataRef:{current:{}},events:K1(),nested:c,triggerElements:f},rU);ln(this,"syncOpenEvent",(a,o)=>{(!a||!this.state.open||o!=null&&P4(o))&&(this.context.dataRef.current.openEvent=a?o:void 0)});ln(this,"dispatchOpenChange",(a,o)=>{this.syncOpenEvent(a,o.event);const c={open:a,reason:o.reason,nativeEvent:o.event,nested:this.context.nested,triggerElement:o.trigger};this.context.events.emit("openchange",c)});ln(this,"setOpen",(a,o)=>{if(this.syncOnly){this.context.onOpenChange?.(a,o);return}this.dispatchOpenChange(a,o),this.context.onOpenChange?.(a,o)});this.syncOnly=o}}function aU(e){const{popupStore:t,treatPopupAsFloatingElement:a=!1,floatingRootContext:o,floatingId:c,nested:d,onOpenChange:f}=e,p=t.useState("open"),g=t.useState("activeTriggerElement"),v=t.useState(a?"popupElement":"positionerElement"),y=t.context.triggerElements,b=f,j=x.useRef(null);o===void 0&&j.current===null&&(j.current=new wy({open:p,transitionStatus:void 0,referenceElement:g,floatingElement:v,triggerElements:y,onOpenChange:b,floatingId:c,syncOnly:!0,nested:d}));const w=o??j.current;return t.useSyncedValue("floatingId",c),De(()=>{const S={open:p,floatingId:c,referenceElement:g,floatingElement:v};At(g)&&(S.domReferenceElement=g),w.state.positionReference===w.state.referenceElement&&(S.positionReference=g),w.update(S)},[p,c,g,v,w]),w.context.onOpenChange=b,w.context.nested=d,w}const af={tabIndex:-1,[_v]:""};function yT(e){return t=>t==="touch"?e.current:!0}function Sy(e,t=!1){const a=qd(),o=eu()!=null,c=Ms(()=>e(a,o)).current;return aU({popupStore:c,treatPopupAsFloatingElement:t,floatingRootContext:c.state.floatingRootContext,floatingId:a,nested:o,onOpenChange:c.setOpen}),c}function Ny({handle:e,store:t}){return De(()=>e.attachStore(t),[e,t]),null}function jT(e){const t=e.context.triggerElements.size;e.select("open")&&e.state.triggerCount!==t&&e.set("triggerCount",t)}function lU(e,t){const a=x.useRef(null);return Ie(o=>{const c=a.current;if(c!==null){if(c.element===o&&c.store===t&&c.id===e)return;a.current=null;const d=c.store;d.context.triggerElements.getById(c.id)===c.element&&(d.context.triggerElements.delete(c.id),jT(d))}o!==null&&e!==void 0&&(a.current={store:t,id:e,element:o},t.context.triggerElements.add(e,o),jT(t))})}function ky(e,t,a,o=!1){let c=e.preventUnmountingOnClose;t?c=!1:o&&(c=!0);const d=a?.id??null;let f=e.activeTriggerId,p=e.activeTriggerElement;return(d||t)&&(f=d,p=a??null),{open:t,preventUnmountingOnClose:c,activeTriggerId:f,activeTriggerElement:p}}function wT(e){let t=!1;return e.preventUnmountOnClose=()=>{t=!0},()=>t}function oU(e,t,a,o={}){const c=a.reason,d=c===Us,f=t&&c===Wm,p=!t&&(c===mo||c===Qc),g=wT(a);if(e.context.onOpenChange?.(t,a),a.isCanceled)return;o.onBeforeDispatch?.(),e.state.floatingRootContext.dispatchOpenChange(t,a);const v=()=>{const y=ky(e.state,t,a.trigger,g()),b={...o.extraState,...y};f?b.instantType="focus":p?b.instantType="dismiss":d&&(b.instantType=void 0),e.update(b)};d?ks.flushSync(v):v()}function ST(e,t,a,o){const c=a.useState("isMountedByTrigger",e),d=lU(e,a),f=Ie(g=>{const v=a.select("open"),y=a.select("activeTriggerId");if(y===e){const b={activeTriggerElement:g,...v?o:null};a.update(b);return}if(y==null&&v){const b={activeTriggerId:e??null,activeTriggerElement:g,...o};a.update(b)}}),p=Ie(g=>{d(g),g&&f(g)});return De(()=>(p(t.current),()=>p(null)),[p,t,a,e]),De(()=>{if(c){const g={activeTriggerElement:t.current,...o};a.update(g)}},[c,a,t,...Object.values(o)]),{registerTrigger:p,isMountedByThisTrigger:c}}function Cy(e,t={}){const{closeOnActiveTriggerUnmount:a=!1}=t,o=x.useRef(null),c=e.useState("open"),d=e.useState("triggerCount"),f=e.useState("activeTriggerId"),p=e.useState("activeTriggerElement");De(()=>{if(!c){o.current=null,e.state.triggerCount!==0&&e.set("triggerCount",0);return}const g=e.context.triggerElements.size,v={};e.state.triggerCount!==g&&(v.triggerCount=g);const y=e.select("activeTriggerId");let b=null;if(y){const j=e.context.triggerElements.getById(y);if(j)o.current=y,j!==e.state.activeTriggerElement&&(v.activeTriggerElement=j);else{for(const[w,S]of e.context.triggerElements.entries())if(S===e.state.activeTriggerElement){v.activeTriggerId=w,v.activeTriggerElement=S,o.current=w;break}v.activeTriggerId===void 0&&(o.current===y?b=y:o.current=null)}}else o.current=null;if(!b&&!y&&g===1){const j=e.context.triggerElements.entries().next();if(!j.done){const[w,S]=j.value;v.activeTriggerId=w,v.activeTriggerElement=S,o.current=w}}(v.triggerCount!==void 0||v.activeTriggerId!==void 0||v.activeTriggerElement!==void 0)&&e.update(v),b&&a&&queueMicrotask(()=>{if(e.select("open")&&e.select("activeTriggerId")===b&&!e.context.triggerElements.getById(b)){const j=Fe(Yn);e.setOpen(!1,j),j.isCanceled||e.update({activeTriggerId:null,activeTriggerElement:null})}})},[c,e,d,f,p,a])}function Ty(e,t,a,o){const{mounted:c,setMounted:d,transitionStatus:f}=ki(e,!1,!1,o),p=t.useState("preventUnmountingOnClose"),g=e?!1:p;t.useSyncedValues({mounted:c,transitionStatus:f,preventUnmountingOnClose:g});const v=Ie(()=>{d(!1),t.update({activeTriggerId:null,activeTriggerElement:null,mounted:!1,preventUnmountingOnClose:!1}),a?.(),t.context.onOpenChangeComplete?.(!1)});return ra({enabled:c&&!e&&!g,open:e,ref:t.context.popupRef,onComplete(){e||v()}}),{forceUnmount:v,transitionStatus:f}}function Ey(e,t){e.useSyncedValues(t),De(()=>()=>{e.update({activeTriggerProps:fn,inactiveTriggerProps:fn,popupProps:fn})},[e])}function NT(e,t){De(()=>{!t&&e.state.openMethod!==null&&e.set("openMethod",null)},[t,e]),De(()=>()=>{e.state.openMethod!==null&&e.set("openMethod",null)},[e])}class ch{constructor(){this.idMap=new Map}add(t,a){this.idMap.set(t,a)}delete(t){this.idMap.delete(t)}hasElement(t){for(const a of this.idMap.values())if(a===t)return!0;return!1}hasMatchingElement(t){for(const a of this.idMap.values())if(t(a))return!0;return!1}getById(t){return this.idMap.get(t)}entries(){return this.idMap.entries()}elements(){return this.idMap.values()}get size(){return this.idMap.size}}function Ay(e,t,a=!1){return{open:!1,openProp:void 0,mounted:!1,transitionStatus:void 0,floatingRootContext:new wy({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:e,floatingId:t,syncOnly:!0,nested:a,onOpenChange:void 0}),floatingId:t,triggerCount:0,preventUnmountingOnClose:!1,payload:void 0,activeTriggerId:null,activeTriggerElement:null,triggerIdProp:void 0,popupElement:null,positionerElement:null,activeTriggerProps:fn,inactiveTriggerProps:fn,popupProps:fn}}const lf=e=>e.triggerIdProp??e.activeTriggerId,Ry=e=>e.openProp??e.open,kT=e=>(e.popupElement?.id??e.floatingId)||void 0;function CT(e,t){return t!==void 0&&Ry(e)&&lf(e)===t}function iU(e,t){return CT(e,t)?!0:t!==void 0&&Ry(e)&&lf(e)==null&&e.triggerCount===1}const Oy={open:Ry,mounted:e=>e.mounted,transitionStatus:e=>e.transitionStatus,floatingRootContext:e=>e.floatingRootContext,triggerCount:e=>e.triggerCount,preventUnmountingOnClose:e=>e.preventUnmountingOnClose,payload:e=>e.payload,activeTriggerId:lf,activeTriggerElement:e=>e.mounted?e.activeTriggerElement:null,popupId:kT,isTriggerActive:(e,t)=>t!==void 0&&lf(e)===t,isOpenedByTrigger:(e,t)=>CT(e,t),isMountedByTrigger:(e,t)=>t!==void 0&&lf(e)===t&&e.mounted,triggerProps:(e,t)=>t?e.activeTriggerProps:e.inactiveTriggerProps,triggerPopupId:(e,t)=>iU(e,t)?kT(e):void 0,popupProps:e=>e.popupProps,popupElement:e=>e.popupElement,positionerElement:e=>e.positionerElement};function TT(e){const t=x.useCallback(o=>e===void 0?qt:e.subscribeStore(o),[e]),a=x.useCallback(()=>e===void 0?void 0:e.store,[e]);return vy.useSyncExternalStore(t,a,()=>e?.serverStore)}function ET(e){const{open:t=!1,onOpenChange:a,elements:o={}}=e,c=qd(),d=eu()!=null,f=Ms(()=>new wy({open:t,transitionStatus:void 0,onOpenChange:a,referenceElement:o.reference??null,floatingElement:o.floating??null,triggerElements:new ch,floatingId:c,syncOnly:!1,nested:d})).current;return De(()=>{const p={open:t,floatingId:c};o.reference!==void 0&&(p.referenceElement=o.reference,p.domReferenceElement=At(o.reference)?o.reference:null),o.floating!==void 0&&(p.floatingElement=o.floating),f.update(p)},[t,c,o.reference,o.floating,f]),f.context.onOpenChange=a,f.context.nested=d,f}function cU(e){return uU(e,e.rootContext)}function uU(e,t){const{nodeId:a,externalTree:o}=e,c=t.useState("referenceElement"),d=t.useState("floatingElement"),f=t.useState("domReferenceElement"),p=t.useState("open"),g=t.useState("floatingId"),[v,y]=x.useState(null),[b,j]=x.useState(void 0),[w,S]=x.useState(void 0),N=x.useRef(null),k=Mi(o),E=x.useMemo(()=>({reference:c,floating:d,domReference:f}),[c,d,f]),D=FH({...e,elements:{...E,...v&&{reference:v}}}),C=At(b)?b:null,A=w===void 0?t.state.floatingElement:w;t.useSyncedValue("referenceElement",b??null),t.useSyncedValue("domReferenceElement",b===void 0?f:C),t.useSyncedValue("floatingElement",A);const R=x.useCallback(H=>{const B=At(H)?{getBoundingClientRect:()=>H.getBoundingClientRect(),getClientRects:()=>H.getClientRects(),contextElement:H}:H;y(B),D.refs.setReference(B)},[D.refs]),I=x.useCallback(H=>{(At(H)||H===null)&&(N.current=H,j(H)),(At(D.refs.reference.current)||D.refs.reference.current===null||H!==null&&!At(H))&&D.refs.setReference(H)},[D.refs,j]),P=x.useCallback(H=>{S(H),D.refs.setFloating(H)},[D.refs]),O=x.useMemo(()=>({...D.refs,setReference:I,setFloating:P,setPositionReference:R,domReference:N}),[D.refs,I,P,R]),_=x.useMemo(()=>({...D.elements,domReference:f}),[D.elements,f]),L=x.useMemo(()=>({...D,dataRef:t.context.dataRef,open:p,onOpenChange:t.setOpen,events:t.context.events,floatingId:g,refs:O,elements:_,nodeId:a,rootStore:t}),[D,O,_,a,t,p,g]);return De(()=>{f&&(N.current=f)},[f]),De(()=>{t.context.dataRef.current.floatingContext=L;const H=k?.nodesRef.current.find(B=>B.id===a);H&&(H.context=L)}),x.useMemo(()=>({...D,context:L,refs:O,elements:_,rootStore:t}),[D,O,_,L,t])}const My=GC&&yl;function dU(e,t={}){const{enabled:a=!0,delay:o}=t,c="rootStore"in e?e.rootStore:e,{events:d,dataRef:f}=c.context,p=x.useRef(!1),g=x.useRef(null),v=x.useRef(!0),y=Qs();x.useEffect(()=>{const j=c.select("domReferenceElement");if(!a)return;const w=Sn(j);function S(){const E=c.select("domReferenceElement");!c.select("open")&&dn(E)&&E===or($t(E))&&(p.current=!0,g.current=E)}function N(){v.current=!0}function k(){v.current=!1}return Ka(St(w,"blur",S),My&&St(w,"keydown",N,!0),My&&St(w,"pointerdown",k,!0))},[c,a]),x.useEffect(()=>{if(!a)return;function j(w){if(w.reason===mo||w.reason===Qc){const S=c.select("domReferenceElement");At(S)&&(g.current=S,p.current=!0)}}return d.on("openchange",j),()=>{d.off("openchange",j)}},[d,a,c]);const b=x.useMemo(()=>{function j(){p.current=!1,g.current=null}return{onMouseLeave(){j()},onFocus(w){const S=w.currentTarget;if(p.current){if(g.current===S)return;j()}const N=is(w.nativeEvent);if(At(N)){if(My&&!w.relatedTarget){if(!v.current&&!Um(N))return}else if(!D4(N))return}const k=Hm(w.relatedTarget,c.context.triggerElements),{nativeEvent:E,currentTarget:D}=w,C=typeof o=="function"?o():o;if(c.select("open")&&k||C===0||C===void 0){c.setOpen(!0,Fe(Wm,E,D));return}y.start(C,()=>{p.current||c.setOpen(!0,Fe(Wm,E,D))})},onBlur(w){j();const S=w.relatedTarget,N=w.nativeEvent,k=At(S)&&S.hasAttribute(nf("focus-guard"))&&S.getAttribute("data-type")==="outside";y.start(0,()=>{const E=c.select("domReferenceElement"),D=or($t(E));!S&&D===E||Qe(f.current.floatingContext?.refs.floating.current,D)||Qe(E,D)||k||Hm(S??D,c.context.triggerElements)||c.setOpen(!1,Fe(Wm,N))})}}},[f,o,c,y]);return x.useMemo(()=>a?{reference:b,trigger:b}:{},[a,b])}class Dy{constructor(){ln(this,"dispose",()=>{this.openChangeTimeout.clear(),this.restTimeout.clear()});ln(this,"disposeEffect",()=>this.dispose);this.pointerType=void 0,this.interactedInside=!1,this.handler=void 0,this.blockMouseMove=!0,this.performedPointerEventsMutation=!1,this.pointerEventsScopeElement=null,this.pointerEventsReferenceElement=null,this.pointerEventsFloatingElement=null,this.restTimeoutPending=!1,this.openChangeTimeout=new sa,this.restTimeout=new sa,this.handleCloseOptions=void 0}static create(){return new Dy}}const uh=new WeakMap;function dh(e){if(!e.performedPointerEventsMutation)return;const t=e.pointerEventsScopeElement;t&&uh.get(t)===e&&(e.pointerEventsScopeElement?.style.removeProperty("pointer-events"),e.pointerEventsReferenceElement?.style.removeProperty("pointer-events"),e.pointerEventsFloatingElement?.style.removeProperty("pointer-events"),uh.delete(t)),e.performedPointerEventsMutation=!1,e.pointerEventsScopeElement=null,e.pointerEventsReferenceElement=null,e.pointerEventsFloatingElement=null}function AT(e,t){const{scopeElement:a,referenceElement:o,floatingElement:c}=t,d=uh.get(a);d&&d!==e&&dh(d),dh(e),e.performedPointerEventsMutation=!0,e.pointerEventsScopeElement=a,e.pointerEventsReferenceElement=o,e.pointerEventsFloatingElement=c,uh.set(a,e),a.style.pointerEvents="none",o.style.pointerEvents="auto",c.style.pointerEvents="auto"}function Iy(e){const t=e.context.dataRef.current,a=Ms(()=>t.hoverInteractionState??Dy.create()).current;return t.hoverInteractionState||(t.hoverInteractionState=a),ey(t.hoverInteractionState.disposeEffect),t.hoverInteractionState}function RT(e,t={}){const{enabled:a=!0,closeDelay:o=0,nodeId:c}=t,d="rootStore"in e?e.rootStore:e,f=d.useState("open"),p=d.useState("floatingElement"),g=d.useState("domReferenceElement"),{dataRef:v}=d.context,y=Mi(),b=eu(),j=Iy(d),w=Qs(),S=Ie(()=>D1(v.current.openEvent?.type,j.interactedInside)),N=Ie(()=>$B(v.current.openEvent?.type)),k=Ie(()=>{dh(j)});De(()=>{f||(j.pointerType=void 0,j.restTimeoutPending=!1,j.interactedInside=!1,k())},[f,j,k]),x.useEffect(()=>k,[k]),De(()=>{if(a&&f&&j.handleCloseOptions?.blockPointerEvents&&N()&&At(g)&&p){const E=g,D=p,C=$t(p),A=y?.nodesRef.current.find(O=>O.id===b)?.context?.elements.floating;A&&(A.style.pointerEvents="");const R=j.pointerEventsScopeElement!==D?j.pointerEventsScopeElement:null,I=A!==D?A:null,P=j.handleCloseOptions?.getScope?.()??R??I??E.closest("[data-rootownerid]")??C.body;return AT(j,{scopeElement:P,referenceElement:E,floatingElement:D}),()=>{k()}}},[a,f,g,p,j,N,y,b,k]),x.useEffect(()=>{if(!a)return;function E(){return!!(y&&b&&io(y.nodesRef.current,b).length>0)}function D(O){const _=Oi(o,"close",j.pointerType),L=()=>{d.setOpen(!1,Fe(Us,O)),y?.events.emit("floating.closed",O)};_?j.openChangeTimeout.start(_,L):(j.openChangeTimeout.clear(),L())}function C(O){const _=is(O);if(!M4(_)){j.interactedInside=!1;return}j.interactedInside=_?.closest("[aria-haspopup]")!=null}function A(){j.openChangeTimeout.clear(),w.clear(),y?.events.off("floating.closed",I),k()}function R(O){if(E()&&y){y.events.on("floating.closed",I);return}if(Hm(O.relatedTarget,d.context.triggerElements))return;const _=v.current.floatingContext?.nodeId??c,L=O.relatedTarget;if(!(y&&_&&At(L)&&io(y.nodesRef.current,_,!1).some(B=>Qe(B.context?.elements.floating,L)))){if(j.handler){j.handler(O);return}k(),N()&&!S()&&D(O)}}function I(O){!y||!b||E()||w.start(0,()=>{y.events.off("floating.closed",I),d.setOpen(!1,Fe(Us,O)),y.events.emit("floating.closed",O)})}const P=p;return Ka(P&&St(P,"mouseenter",A),P&&St(P,"mouseleave",R),P&&St(P,"pointerdown",C,!0),()=>{y?.events.off("floating.closed",I)})},[a,p,d,v,o,c,N,S,k,j,y,b,w])}const fU={current:null};function OT(e,t={}){const{enabled:a=!0,delay:o=0,handleClose:c=null,mouseOnly:d=!1,restMs:f=0,move:p=!0,triggerElementRef:g=fU,externalTree:v,isActiveTrigger:y=!0,getHandleCloseContext:b,isClosing:j,shouldOpen:w,guardStaleOpen:S=!1}=t,N="rootStore"in e?e.rootStore:e,{dataRef:k,events:E}=N.context,D=Mi(v),C=Iy(N),A=x.useRef(!1),R=Xn(c),I=Xn(o),P=Xn(f),O=Xn(a),_=Xn(w),L=Xn(j),H=Ie(()=>D1(k.current.openEvent?.type,C.interactedInside)),B=Ie(()=>_.current?.()!==!1),z=Ie((X,q,$)=>{const Y=N.context.triggerElements;if(Y.hasElement(q))return!X||!Qe(X,q);if(!At($))return!1;const F=$;return Y.hasMatchingElement(G=>Qe(G,F))&&(!X||!Qe(X,F))}),Q=Ie(()=>{if(!C.handler)return;$t(N.select("domReferenceElement")).removeEventListener("mousemove",C.handler),C.handler=void 0}),K=Ie(()=>{dh(C)});return y&&(C.handleCloseOptions=c?.__options),x.useEffect(()=>Q,[Q]),x.useEffect(()=>{if(!a)return;function X(q){q.open?A.current=!1:(A.current=q.reason===Us,Q(),C.openChangeTimeout.clear(),C.restTimeout.clear(),C.blockMouseMove=!0,C.restTimeoutPending=!1)}return E.on("openchange",X),()=>{E.off("openchange",X)}},[a,E,C,Q]),x.useEffect(()=>{if(!a)return;function X(W,le=!0){const M=Oi(I.current,"close",C.pointerType);M?C.openChangeTimeout.start(M,()=>{N.setOpen(!1,Fe(Us,W)),D?.events.emit("floating.closed",W)}):le&&(C.openChangeTimeout.clear(),N.setOpen(!1,Fe(Us,W)),D?.events.emit("floating.closed",W))}const q=g.current??(y?N.select("domReferenceElement"):null);if(!At(q))return;function $(W){if(C.openChangeTimeout.clear(),C.blockMouseMove=!1,d&&!co(C.pointerType))return;const le=M1(P.current),M=Oi(I.current,"open",C.pointerType),U=is(W),Z=W.currentTarget??null,ae=N.select("domReferenceElement");let ce=Z;if(At(U)&&!N.context.triggerElements.hasElement(U)){for(const de of N.context.triggerElements.elements())if(Qe(de,U)){ce=de;break}}At(Z)&&At(ae)&&!N.context.triggerElements.hasElement(Z)&&Qe(Z,ae)&&(ce=ae);const J=ce==null?!1:z(ae,ce,U),ie=N.select("open"),ge=L.current?.()??N.select("transitionStatus")==="ending",ee=!ie&&ge&&A.current,fe=!J&&At(ce)&&At(ae)&&Qe(ae,ce)&&ee,te=le>0&&!M,Ce=J&&(ie||ee)||fe,re=!ie||J;if(Ce){B()&&N.setOpen(!0,Fe(Us,W,ce));return}te||(M?C.openChangeTimeout.start(M,()=>{re&&B()&&N.setOpen(!0,Fe(Us,W,ce))}):re&&B()&&N.setOpen(!0,Fe(Us,W,ce)))}function Y(W){if(H()){K();return}Q();const le=N.select("domReferenceElement"),M=$t(le);C.restTimeout.clear(),C.restTimeoutPending=!1;const U=k.current.floatingContext??b?.();if(Hm(W.relatedTarget,N.context.triggerElements))return;if(R.current&&U){N.select("open")||C.openChangeTimeout.clear();const ae=g.current;C.handler=R.current({...U,tree:D,x:W.clientX,y:W.clientY,onClose(){K(),Q(),O.current&&!H()&&ae===N.select("domReferenceElement")&&X(W,!0)}}),M.addEventListener("mousemove",C.handler),C.handler(W);return}(C.pointerType!=="touch"||!Qe(N.select("floatingElement"),W.relatedTarget))&&X(W)}function F(W){Qe(q,W.relatedTarget)||(C.openChangeTimeout.clear(),C.restTimeout.clear(),C.restTimeoutPending=!1)}const G=S?St(q,"mouseout",F):void 0;return p?Ka(St(q,"mousemove",$,{once:!0}),St(q,"mouseenter",$),St(q,"mouseleave",Y),G):Ka(St(q,"mouseenter",$),St(q,"mouseleave",Y),G)},[Q,K,k,I,N,a,R,C,y,z,H,d,p,P,g,D,O,b,L,B,S]),x.useMemo(()=>{if(!a)return;function X(q){C.pointerType=q.pointerType}return{onPointerDown:X,onPointerEnter:X,onMouseMove(q){const{nativeEvent:$}=q,Y=q.currentTarget,F=N.select("domReferenceElement"),G=N.select("open"),W=z(F,Y,q.target);if(d&&!co(C.pointerType))return;if(G&&W&&C.handleCloseOptions?.blockPointerEvents){const U=N.select("floatingElement");if(U){const Z=C.handleCloseOptions?.getScope?.()??Y.ownerDocument.body;AT(C,{scopeElement:Z,referenceElement:Y,floatingElement:U})}}const le=M1(P.current);if(G&&!W||le===0||!W&&C.restTimeoutPending&&q.movementX**2+q.movementY**2<2)return;C.restTimeout.clear();function M(){if(C.restTimeoutPending=!1,H())return;const U=N.select("open");!C.blockMouseMove&&(!U||W)&&B()&&N.setOpen(!0,Fe(Us,$,Y))}C.pointerType==="touch"?ks.flushSync(()=>{M()}):W&&G?M():(C.restTimeoutPending=!0,C.restTimeout.start(le,M))}}},[a,C,H,z,d,N,P,B])}const pU="Escape";function MT(e){return yl&&e.movementX===0&&e.movementY===0}function fh(e,t,a){switch(e){case"vertical":return t;case"horizontal":return a;default:return t||a}}function ph(e,t){return fh(t,e===Lv||e===Bm,e===wi||e===Si)}function Py(e,t,a){return fh(t,e===Bm,a?e===wi:e===Si)||e==="Enter"||e===" "||e===""}function mU(e,t,a){return fh(t,a?e===wi:e===Si,e===Bm)}function hU(e,t,a,o){const c=a?e===Si:e===wi,d=e===Lv;return t==="both"||t==="horizontal"&&o?e===pU:fh(t,c,d)}function DT(e,t){const{listRef:a,activeIndex:o,onNavigate:c=()=>{},enabled:d=!0,selectedIndex:f=null,allowEscape:p=!1,loopFocus:g=!1,nested:v=!1,rtl:y=!1,virtual:b=!1,focusItemOnOpen:j="auto",focusItemOnHover:w=!0,openOnArrowKeyDown:S=!0,disabledIndices:N=void 0,orientation:k="vertical",parentOrientation:E,id:D,resetOnPointerLeave:C=!0,externalTree:A,grid:R}=t,I=R!=null,P="rootStore"in e?e.rootStore:e,O=P.useState("open"),_=P.useState("floatingElement"),L=P.useState("domReferenceElement"),H=P.context.dataRef,B=Vm(_),z=Fv(L),Q=Xn(B),K=eu(),X=Mi(A),q=x.useRef(j),$=x.useRef(f??-1),Y=x.useRef(null),F=x.useRef(!0),G=Ie(xe=>{c($.current===-1?null:$.current,xe)}),W=x.useRef(!!_),le=x.useRef(O),M=x.useRef(!1),U=x.useRef(!1),Z=x.useRef(null),ae=Xn(N),ce=Xn(O),J=Xn(f),ie=Xn(C),ge=Yc(),ee=Yc(),fe=Ie(()=>{function xe(_e){b?X?.events.emit("virtualfocus",_e):Z.current=nh(_e,{sync:M.current,preventScroll:!0})}const Te=a.current[$.current],Oe=U.current;Te&&xe(Te),(M.current?_e=>_e():_e=>ge.request(_e))(()=>{const _e=a.current[$.current]||Te;if(!_e)return;Te||xe(_e),Ee&&(Oe||!F.current)&&_e.scrollIntoView?.({block:"nearest",inline:"nearest"})})});De(()=>{H.current.orientation=k},[H,k]),De(()=>{d&&(O&&_?($.current=f??-1,q.current&&f!=null&&(U.current=!0,G())):W.current&&($.current=-1,G()))},[d,O,_,f,G]),De(()=>{if(d){if(!O){M.current=!1;return}if(_)if(o==null){if(M.current=!1,J.current!=null)return;if(W.current&&($.current=-1,fe()),(!le.current||!W.current)&&q.current&&(Y.current!=null||q.current===!0&&Y.current==null)){let xe=0;const Te=()=>{a.current[0]==null?(xe<2&&(xe?Ne=>ee.request(Ne):queueMicrotask)(Te),xe+=1):($.current=Y.current==null||Py(Y.current,k,y)||v?Km(a):Xv(a),Y.current=null,G())};Te()}}else fo(a.current,o)||($.current=o,fe(),U.current=!1)}},[d,O,_,o,J,v,a,k,y,G,fe,ee]),De(()=>{if(!d||_||!X||b||!W.current)return;const xe=X.nodesRef.current,Te=xe.find(_e=>_e.id===K)?.context?.elements.floating,Oe=or($t(L??Te??null)),Ne=xe.some(_e=>_e.context&&Qe(_e.context.elements.floating,Oe));Te&&!Ne&&F.current&&Te.focus({preventScroll:!0})},[d,_,L,X,K,b]),De(()=>{le.current=O,W.current=!!_}),De(()=>{O||(Y.current=null,q.current=j)},[O,j]);const te=o!=null,Ce=Ie(xe=>{if(!ce.current)return;const Te=a.current.indexOf(xe.currentTarget);Te!==-1&&($.current!==Te||o!==Te)&&($.current=Te,G(xe))}),re=Ie(()=>E??X?.nodesRef.current.find(xe=>xe.id===K)?.context?.dataRef?.current.orientation),de=Ie(()=>Km(a,ae.current)),ke=Ie(xe=>{if(F.current=!1,M.current=!0,xe.which===229||!ce.current&&xe.currentTarget===Q.current)return;if(v&&hU(xe.key,k,y,I)){ph(xe.key,re())||Ns(xe),P.setOpen(!1,Fe(sy,xe.nativeEvent)),dn(L)&&(b?X?.events.emit("virtualfocus",L):L.focus());return}const Te=$.current,Oe=Km(a,N),Ne=Xv(a,N);if(z||(xe.key==="Home"&&(Ns(xe),$.current=Oe,G(xe)),xe.key==="End"&&(Ns(xe),$.current=Ne,G(xe))),R!=null){const _e=R(xe,$.current,a,k,g,y,N,Oe,Ne);if(_e!=null&&($.current=_e,G(xe)),k==="both")return}if(ph(xe.key,k)){if(Ns(xe),O&&!b&&or(xe.currentTarget.ownerDocument)===xe.currentTarget){$.current=Py(xe.key,k,y)?Oe:Ne,G(xe);return}Py(xe.key,k,y)?g?Te>=Ne?p&&Te!==a.current.length?$.current=-1:(M.current=!1,$.current=Oe):$.current=Ds(a.current,{startingIndex:Te,disabledIndices:N}):$.current=Math.min(Ne,Ds(a.current,{startingIndex:Te,disabledIndices:N})):g?Te<=Oe?p&&Te!==-1?$.current=a.current.length:(M.current=!1,$.current=Ne):$.current=Ds(a.current,{startingIndex:Te,decrement:!0,disabledIndices:N}):$.current=Math.max(Oe,Ds(a.current,{startingIndex:Te,decrement:!0,disabledIndices:N})),fo(a.current,$.current)&&($.current=-1),G(xe)}}),Ee=x.useMemo(()=>({onFocus(Te){M.current=!0,Ce(Te)},onClick:({currentTarget:Te})=>Te.focus({preventScroll:!0}),onMouseMove(Te){MT(Te)||(M.current=!0,U.current=!1,w&&Ce(Te))},onPointerLeave(Te){if(!ce.current||!F.current||Te.pointerType==="touch")return;M.current=!0;const Oe=Te.relatedTarget;if(!(!w||a.current.includes(Oe))&&ie.current&&(Z.current?.(),Z.current=null,$.current=-1,G(Te),!b)){const Ne=Q.current,_e=or($t(Ne));Ne&&Qe(Ne,_e)&&Ne.focus({preventScroll:!0})}}}),[Ce,ce,Q,w,a,G,ie,b]),ve=x.useMemo(()=>b&&O&&te&&{"aria-activedescendant":`${D}-${o}`},[b,O,te,D,o]),he=x.useMemo(()=>({...z?{}:ve,onKeyDown(xe){if(xe.key==="Tab"&&xe.shiftKey&&O&&!b){const Te=is(xe.nativeEvent);if(Te&&!Qe(Q.current,Te))return;Ns(xe),P.setOpen(!1,Fe(ho,xe.nativeEvent)),dn(L)&&L.focus();return}ke(xe)},onPointerMove(xe){MT(xe)||(F.current=!0)}}),[ve,ke,Q,z,P,O,b,L]),ye=x.useMemo(()=>{function xe(Ne){P.setOpen(!0,Fe(sy,Ne.nativeEvent,Ne.currentTarget))}function Te(Ne){j==="auto"&&Fm(Ne.nativeEvent)&&(q.current=!b)}function Oe(Ne){q.current=j,j==="auto"&&$v(Ne.nativeEvent)&&(q.current=!0)}return{onKeyDown(Ne){const _e=P.select("open");F.current=!1;const Ye=Ne.key.startsWith("Arrow"),kt=mU(Ne.key,re(),y),Ct=ph(Ne.key,k),Rt=(v?kt:Ct)||Ne.key==="Enter"||Ne.key.trim()==="";if(b&&_e)return ke(Ne);if(!(!_e&&!S&&Ye)){if(Rt){const ot=ph(Ne.key,re());Y.current=v&&ot?null:Ne.key}if(v){kt&&(Ns(Ne),_e?($.current=de(),G(Ne)):xe(Ne));return}Ct&&(J.current!=null&&($.current=J.current),Ns(Ne),!_e&&S?xe(Ne):ke(Ne),_e&&G(Ne))}},onFocus(Ne){P.select("open")&&!b&&($.current=-1,G(Ne))},onPointerDown:Oe,onPointerEnter:Oe,onMouseDown:Te,onClick:Te}},[ke,j,de,v,G,P,S,k,re,y,J,b]),we=x.useMemo(()=>({...ve,...ye}),[ve,ye]);return x.useMemo(()=>d?{reference:we,floating:he,item:Ee,trigger:ye}:{},[d,we,he,ye,Ee])}function IT(e,t){const{listRef:a,elementsRef:o,activeIndex:c,onMatch:d,disabledIndices:f,onTyping:p,enabled:g=!0,resetMs:v=750,selectedIndex:y=null}=t,b="rootStore"in e?e.rootStore:e,j=b.useState("open"),w=Qs(),S=x.useRef(""),N=x.useRef(y??c??-1),k=x.useRef(null),E=Ie(A=>{function R(Q){return o?.current[Q]}function I(Q){const K=R(Q);return K&&!Ym(K)||K?.matches(":disabled")?!1:f==null||!po(Rr,Q,f)}function P(Q,K,X=0){if(Q.length===0)return-1;const q=(X%Q.length+Q.length)%Q.length,$=K.toLowerCase();for(let Y=0;Y0&&A.key===" "&&(Ns(A),p?.(!0)),S.current.length>0&&S.current[0]!==" "&&P(O,S.current)===-1&&A.key!==" "&&p?.(!1),O==null||A.key.length!==1||A.ctrlKey||A.metaKey||A.altKey)return;j&&A.key!==" "&&(Ns(A),p?.(!0));const _=S.current==="";_&&(N.current=y??c??-1),O.every((Q,K)=>Q&&I(K)?Q[0]?.toLowerCase()!==Q[1]?.toLowerCase():!0)&&S.current===A.key&&(S.current="",N.current=k.current),S.current+=A.key,w.start(v,()=>{S.current="",N.current=k.current,p?.(!1)});const B=((_?y??c??-1:N.current)??0)+1,z=P(O,S.current,B);z!==-1?(d?.(z),k.current=z):A.key!==" "&&(S.current="",p?.(!1))}),D=Ie(A=>{const R=A.relatedTarget,I=b.select("domReferenceElement"),P=b.select("floatingElement");Qe(I,R)||Qe(P,R)||(w.clear(),S.current="",N.current=k.current,p?.(!1))});De(()=>{!j&&y!==null||(w.clear(),k.current=null,S.current!==""&&(S.current=""))},[j,y,w]);const C=x.useMemo(()=>({onKeyDown:E,onBlur:D}),[E,D]);return x.useMemo(()=>g?{reference:C,floating:C}:{},[g,C])}const PT=.1,gU=PT*PT,bn=.5;function mh(e,t,a,o,c,d){return o>=t!=d>=t&&e<=(c-a)*(t-o)/(d-o)+a}function hh(e,t,a,o,c,d,f,p,g,v){let y=!1;return mh(e,t,a,o,c,d)&&(y=!y),mh(e,t,c,d,f,p)&&(y=!y),mh(e,t,f,p,g,v)&&(y=!y),mh(e,t,g,v,a,o)&&(y=!y),y}function xU(e,t,a){return e>=a.x&&e<=a.x+a.width&&t>=a.y&&t<=a.y+a.height}function gh(e,t,a,o,c,d){const f=Math.min(a,c),p=Math.max(a,c),g=Math.min(o,d),v=Math.max(o,d);return e>=f&&e<=p&&t>=g&&t<=v}function _T(e={}){const{blockPointerEvents:t=!1}=e,a=new sa,o=({x:c,y:d,placement:f,elements:p,onClose:g,nodeId:v,tree:y})=>{const b=f?.split("-")[0];let j=!1,w=null,S=null,N=typeof performance<"u"?performance.now():0;function k(D,C){const A=performance.now(),R=A-N;if(w===null||S===null||R===0)return w=D,S=C,N=A,!1;const I=D-w,P=C-S,O=I*I+P*P,_=R*R*gU;return w=D,S=C,N=A,O<_}function E(){a.clear(),g()}return function(C){a.clear();const A=p.domReference,R=p.floating;if(!A||!R||b==null||c==null||d==null)return;const{clientX:I,clientY:P}=C,O=is(C),_=C.type==="mouseleave",L=Qe(R,O),H=Qe(A,O);if(L&&(j=!0,!_))return;if(H&&(j=!1,!_)){j=!0;return}if(_&&At(C.relatedTarget)&&Qe(R,C.relatedTarget))return;function B(){return!!(y&&io(y.nodesRef.current,v).length>0)}function z(){B()||E()}if(B())return;const Q=A.getBoundingClientRect(),K=R.getBoundingClientRect(),X=c>K.right-K.width/2,q=d>K.bottom-K.height/2,$=K.width>Q.width,Y=K.height>Q.height,F=($?Q:K).left,G=($?Q:K).right,W=(Y?Q:K).top,le=(Y?Q:K).bottom;if(b==="top"&&d>=Q.bottom-1||b==="bottom"&&d<=Q.top+1||b==="left"&&c>=Q.right-1||b==="right"&&c<=Q.left+1){z();return}let M=!1;switch(b){case"top":M=gh(I,P,F,Q.top+1,G,K.bottom-1);break;case"bottom":M=gh(I,P,F,K.top+1,G,Q.bottom-1);break;case"left":M=gh(I,P,K.right-1,le,Q.left+1,W);break;case"right":M=gh(I,P,Q.right-1,le,K.left+1,W);break}if(M)return;if(j&&!xU(I,P,Q)){z();return}if(!_&&k(I,P)){z();return}let U=!1;switch(b){case"top":{const Z=$?bn/2:bn*4,ae=$||X?c+Z:c-Z,ce=$?c-Z:X?c+Z:c-Z,J=d+bn+1,ie=X||$?K.bottom-bn:K.top,ge=X?$?K.bottom-bn:K.top:K.bottom-bn;U=hh(I,P,ae,J,ce,J,K.left,ie,K.right,ge);break}case"bottom":{const Z=$?bn/2:bn*4,ae=$||X?c+Z:c-Z,ce=$?c-Z:X?c+Z:c-Z,J=d-bn,ie=X||$?K.top+bn:K.bottom,ge=X?$?K.top+bn:K.bottom:K.top+bn;U=hh(I,P,ae,J,ce,J,K.left,ie,K.right,ge);break}case"left":{const Z=Y?bn/2:bn*4,ae=Y||q?d+Z:d-Z,ce=Y?d-Z:q?d+Z:d-Z,J=c+bn+1,ie=q||Y?K.right-bn:K.left,ge=q?Y?K.right-bn:K.left:K.right-bn;U=hh(I,P,ie,K.top,ge,K.bottom,J,ae,J,ce);break}case"right":{const Z=Y?bn/2:bn*4,ae=Y||q?d+Z:d-Z,ce=Y?d-Z:q?d+Z:d-Z,J=c-bn,ie=q||Y?K.left+bn:K.right,ge=q?Y?K.left+bn:K.right:K.left+bn;U=hh(I,P,J,ae,J,ce,ie,K.top,ge,K.bottom);break}}U?j||a.start(40,z):z()}};return o.__options={...e,blockPointerEvents:t},o}const bU={...Oy,disabled:e=>e.disabled,instantType:e=>e.instantType,isInstantPhase:e=>e.isInstantPhase,trackCursorAxis:e=>e.trackCursorAxis,disableHoverablePopup:e=>e.disableHoverablePopup,lastOpenChangeReason:e=>e.openChangeReason,closeOnClick:e=>e.closeOnClick,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin};class vU extends nu{constructor(a,o,c){const d=new ch;super(yU(a,d,o,c),jU(d),bU);ln(this,"setOpen",(a,o)=>{oU(this,a,o,{extraState:{openChangeReason:o.reason}})})}cancelPendingOpen(a){this.state.floatingRootContext.dispatchOpenChange(!1,Fe(mo,a))}}function yU(e,t,a,o=!1){return{...Ay(t,a,o),disabled:!1,instantType:void 0,isInstantPhase:!1,trackCursorAxis:"none",disableHoverablePopup:!1,openChangeReason:null,closeOnClick:!0,closeDelay:0,adaptiveOrigin:void 0,...e}}function jU(e){return{popupRef:x.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerElements:e}}const wU=eh(function(t){const{disabled:a=!1,defaultOpen:o=!1,open:c,disableHoverablePopup:d=!1,trackCursorAxis:f="none",actionsRef:p,onOpenChange:g,onOpenChangeComplete:v,handle:y,triggerId:b,defaultTriggerId:j=null,children:w}=t,S=Sy((H,B)=>new vU({open:o,openProp:c,activeTriggerId:j,triggerIdProp:b},H,B));S.useControlledProp("openProp",c),S.useControlledProp("triggerIdProp",b),S.useContextCallback("onOpenChange",g),S.useContextCallback("onOpenChangeComplete",v);const N=S.useState("open"),k=!a&&N,E=S.useState("activeTriggerId"),D=S.useState("mounted"),C=S.useState("payload");S.useSyncedValues({trackCursorAxis:f,disableHoverablePopup:d,disabled:a}),Cy(S,{closeOnActiveTriggerUnmount:!0});const{forceUnmount:A,transitionStatus:R}=Ty(k,S),I=S.useState("isInstantPhase"),P=S.useState("instantType"),O=S.useState("lastOpenChangeReason"),_=x.useRef(null);De(()=>{N&&a&&S.setOpen(!1,Fe(lB))},[N,a,S]),De(()=>{R==="ending"&&O===Yn||R!=="ending"&&I?(P!=="delay"&&(_.current=P),S.set("instantType","delay")):_.current!==null&&(S.set("instantType",_.current),_.current=null)},[R,I,O,P,S]),De(()=>{k&&E==null&&S.set("payload",void 0)},[S,E,k]),x.useImperativeHandle(p,()=>({unmount:A,close:()=>S.setOpen(!1,Fe(ry))}),[A,S]);const L=k||D||!a&&f!=="none";return s.jsxs(O1.Provider,{value:S,children:[y&&s.jsx(Ny,{handle:y,store:S}),L&&s.jsx(SU,{store:S,disabled:a,trackCursorAxis:f}),typeof w=="function"?w({payload:C}):w]})});function SU({store:e,disabled:t,trackCursorAxis:a}){const o=e.useState("floatingRootContext"),c=rf(o,{enabled:!t,referencePress:()=>e.select("closeOnClick")}),d=iH(o,{enabled:!t&&a!=="none",axis:a==="none"?void 0:a}),f=x.useMemo(()=>Wr(d.reference,c.reference),[d.reference,c.reference]);return Ey(e,{activeTriggerProps:f,inactiveTriggerProps:f,popupProps:c.floating??fn}),null}const LT=x.createContext(void 0);function NU(){return x.useContext(LT)}const kU=600,zT="data-base-ui-tooltip-trigger";function BT(e){if("composedPath"in e){const a=e.composedPath();for(let o=0;ok.select("transitionStatus")==="ending",shouldOpen(){return!F.current}}),ae=dU(A,{enabled:!X}).reference,ce=fe=>{const te=F.current,Ce=BT(fe),re=U(Ce),de=R.current,ke=de&&Ce&&Qe(de,Ce);if(re&&k.select("open")&&k.select("lastOpenChangeReason")===Us){k.setOpen(!1,Fe(Us,fe));return}if(te&&!re&&ke&&!q.current&&!k.select("open")&&de&&co(W.current)){const Ee=()=>{!F.current&&!q.current&&!k.select("open")&&k.setOpen(!0,Fe(Us,fe,de))},ve=le();ve===0?(G.clear(),Ee()):G.start(ve,Ee)}},J=k.useState("triggerProps",O);return vt("button",t,{state:{open:C},ref:[a,P,R],props:[Z,ae,O||$!=="none"?J:void 0,{onMouseOver(fe){ce(fe.nativeEvent)},onFocus(fe){M(BT(fe.nativeEvent))&&fe.preventBaseUIHandler()},onMouseLeave(){F.current=!1,G.clear(),W.current=void 0},onPointerEnter(fe){W.current=fe.pointerType},onPointerDown(fe){W.current=fe.pointerType,k.set("closeOnClick",y),y&&!k.select("open")&&k.cancelPendingOpen(fe.nativeEvent)},onClick(fe){y&&!k.select("open")&&k.cancelPendingOpen(fe.nativeEvent)},id:E,[Uv]:X?"":void 0,[zT]:X?void 0:""},w],stateAttributesMapping:zv})}),HT=x.createContext(void 0);function EU(){const e=x.useContext(HT);if(e===void 0)throw new Error(on(70));return e}const AU=x.forwardRef(function(t,a){const{children:o,container:c,className:d,render:f,style:p,...g}=t,{node:v,subtree:y}=G1({container:c,ref:a,componentProps:t,elementProps:g});return!y&&!v?null:s.jsxs(x.Fragment,{children:[y,v&&ks.createPortal(o,v)]})}),RU=x.forwardRef(function(t,a){const{keepMounted:o=!1,...c}=t;return tf().useState("mounted")||o?s.jsx(HT.Provider,{value:o,children:s.jsx(AU,{ref:a,...c})}):null}),UT=x.createContext(void 0);function VT(){const e=x.useContext(UT);if(e===void 0)throw new Error(on(71));return e}const OU=x.createContext(void 0);function of(){return x.useContext(OU)?.direction??"ltr"}const MU=e=>({name:"arrow",options:e,async fn(t){const{x:a,y:o,placement:c,rects:d,platform:f,elements:p,middlewareData:g}=t,{element:v,padding:y=0,offsetParent:b="real"}=uo(e,t)||{};if(v==null)return{};const j=t1(y),w={x:a,y:o},S=Kv(c),N=Gv(S),k=await f.getDimensions(v),E=S==="y",D=E?"top":"left",C=E?"bottom":"right",A=E?"clientHeight":"clientWidth",R=d.reference[N]+d.reference[S]-w[S]-d.floating[N],I=w[S]-d.reference[S],P=b==="real"?await f.getOffsetParent?.(v):p.floating;let O=p.floating[A]||d.floating[N];(!O||!await f.isElement?.(P))&&(O=p.floating[A]||d.floating[N]);const _=R/2-I/2,L=O/2-k[N]/2-1,H=Math.min(j[D],L),B=Math.min(j[C],L),z=H,Q=O-k[N]-B,K=O/2-k[N]/2+_,X=WC(z,K,Q),q=!g.arrow&&Sl(c)!=null&&K!==X&&d.reference[N]/2-(K{const{name:a,fn:o}=MU(e);return{name:a,fn:o,options:[e,t]}},IU={name:"hide",async fn(e){const{width:t,height:a,x:o,y:c}=e.rects.reference,d=t===0&&a===0&&o===0&&c===0,f=await e.platform.detectOverflow(e,{elementContext:"reference"});return{data:{referenceHidden:f.top-a>=0||f.right-t>=0||f.bottom-a>=0||f.left-t>=0||d}}}},PU={sideX:"left",sideY:"top"},_U="--available-width",LU="--available-height",zU="--anchor-width",BU="--anchor-height",HU="--transform-origin",FT=_U,$T=LU;function qT(e,t,a){const o=e==="inline-start"||e==="inline-end";return{top:"top",right:o?a?"inline-start":"inline-end":"right",bottom:"bottom",left:o?a?"inline-end":"inline-start":"left"}[t]}function GT(e,t,a){const{rects:o,placement:c}=e;return{side:qT(t,ta(c),a),align:Sl(c)||"center",anchor:{width:o.reference.width,height:o.reference.height},positioner:{width:o.floating.width,height:o.floating.height}}}function xh(e){return UU(e,cU)}function UU(e,t){const{anchor:a,positionMethod:o="absolute",side:c="bottom",sideOffset:d=0,align:f="center",alignOffset:p=0,collisionBoundary:g,collisionPadding:v=5,sticky:y=!1,arrowPadding:b=5,disableAnchorTracking:j=!1,inline:w,keepMounted:S=!1,floatingRootContext:N,mounted:k,collisionAvoidance:E,shift:D,nodeId:C,adaptiveOrigin:A,lazyFlip:R=!1,externalTree:I}=e,[P,O]=x.useState(null);!k&&P!==null&&O(null);const _=E.side||"flip",L=E.align||"flip",H=E.fallbackAxisSide||"end",B=D?.crossAxis??!1,z=D?.rootBoundary,Q=typeof a=="function"?a:void 0,K=Ie(Q),X=Q?K:a,q=Xn(a),$=Xn(k),F=of()==="rtl",G=P||{top:"top",right:"right",bottom:"bottom",left:"left","inline-end":F?"left":"right","inline-start":F?"right":"left"}[c],W=f==="center"?G:`${G}-${f}`;let le=v;typeof le=="number"?le={top:le,right:le,bottom:le,left:le}:le&&(le={top:le.top||0,right:le.right||0,bottom:le.bottom||0,left:le.left||0});const M=1,U=c==="bottom"?M:0,Z=c==="top"?M:0,ae=c==="right"?M:0,ce=c==="left"?M:0,J={boundary:g==="clipping-ancestors"?"clippingAncestors":g,padding:le},ie=x.useRef(null),ge=Xn(d),ee=Xn(p),fe=typeof d!="function"?d:0,te=typeof p!="function"?p:0,Ce=[];w&&Ce.push(w),Ce.push($H(nt=>{const Ot=GT(nt,c,F),Ft=typeof ge.current=="function"?ge.current(Ot):ge.current,Zn=typeof ee.current=="function"?ee.current(Ot):ee.current;return{mainAxis:Ft,crossAxis:Zn,alignmentAxis:Zn}},[fe,te,F,c]));const re=L==="none"&&_!=="shift",de=!re&&(y||B||_==="shift"),ke=_==="none"?null:KH({...J,padding:{top:le.top+M+U,right:le.right+M+ce,bottom:le.bottom+M+Z,left:le.left+M+ae},mainAxis:!B&&_==="flip",crossAxis:L==="flip"?"alignment":!1,fallbackAxisSideDirection:H}),Ee=re?null:qH({...J,rootBoundary:z,mainAxis:L!=="none",crossAxis:de,limiter:y||B?void 0:GH(nt=>{if(!ie.current)return{};const{width:Ot,height:Ft}=ie.current.getBoundingClientRect(),Zn=na(ta(nt.placement)),Hn=Zn==="y"?Ot:Ft,Un=Zn==="y"?le.left+le.right:le.top+le.bottom;return{offset:Hn/2+Un/2}})},[J,y,B,z,le,L]);_==="shift"||L==="shift"||f==="center"?Ce.push(Ee,ke):Ce.push(ke,Ee),Ce.push(YH({...J,apply({elements:{floating:nt},availableWidth:Ot,availableHeight:Ft,rects:Zn}){if(!$.current)return;const Hn=nt.style;Hn.setProperty(FT,`${Ot}px`),Hn.setProperty($T,`${Ft}px`);const Un=Sn(nt).devicePixelRatio||1,{x:Rn,y:Jt,width:as,height:Tt}=Zn.reference,gt=(Math.round((Rn+as)*Un)-Math.round(Rn*Un))/Un,jt=(Math.round((Jt+Tt)*Un)-Math.round(Jt*Un))/Un;Hn.setProperty(zU,`${gt}px`),Hn.setProperty(BU,`${jt}px`)}}),DU(nt=>({element:ie.current||$t(nt.elements.floating).createElement("div"),padding:ie.current?b:0,offsetParent:"floating"}),[b]),{name:"transformOrigin",fn(nt){const{elements:{floating:Ot},middlewareData:Ft,placement:Zn,platform:Hn,rects:Un,y:Rn}=nt,Jt=ta(Zn),as=Sl(Zn),Tt=na(Jt)==="y",gt=ie.current,jt=typeof d=="function"?d(GT(nt,c,F)):d;let wt;if(!gt&&as&&Math.abs(Tt?Ft.shift?.x||0:Ft.shift?.y||0)<=1)wt=as==="start"===(Tt&&Hn.isRTL?.(Ot)===!0)?"100%":"0%";else{const rr=Tt?Ft.arrow?.x||0:Ft.arrow?.y||0,Hr=Tt?gt?.clientWidth||0:gt?.clientHeight||0;wt=`${rr+Hr/2}px`}let Sr=Jt==="top"||Jt==="left"?`calc(100% + ${jt}px)`:`${-jt}px`;return de&&Tt&&Math.abs(Ft.shift?.y||0)>jt&&(Sr=`${Un.reference.y+Un.reference.height/2-Rn}px`),Ot.style.setProperty(HU,Tt?`${wt} ${Sr}`:`${Sr} ${wt}`),{}}},IU,A),De(()=>{!k&&N&&N.update({referenceElement:null,floatingElement:null,domReferenceElement:null,positionReference:null})},[k,N]);const ve=x.useMemo(()=>({ancestorScroll:!j,elementResize:!j&&typeof ResizeObserver<"u",layoutShift:!j&&typeof IntersectionObserver<"u"}),[j]),{refs:he,elements:ye,x:we,y:xe,middlewareData:Te,update:Oe,placement:Ne,context:_e,isPositioned:Ye,floatingStyles:kt}=t({rootContext:N,open:S?k:void 0,placement:W,middleware:Ce,strategy:o,whileElementsMounted:S?void 0:(...nt)=>dT(...nt,ve),nodeId:C,externalTree:I}),{sideX:Ct,sideY:Rt}=Te.adaptiveOrigin||PU,ot=Ye?o:"fixed",qn=x.useMemo(()=>{let nt;return Ye?A?nt={position:ot,[Ct]:we,[Rt]:xe}:nt={...kt,position:ot}:nt={position:ot,top:0,left:0},nt[FT]="100vw",nt[$T]="100vh",Ye||(nt.opacity=0),nt},[A,ot,Ct,we,Rt,xe,kt,Ye]),ds=x.useRef(null);De(()=>{if(!k)return;const nt=q.current,Ot=typeof nt=="function"?nt():nt,Zn=(KT(Ot)?Ot.current:Ot)||null||null;Zn!==ds.current&&(he.setPositionReference(Zn),ds.current=Zn)},[k,he,X,q]),x.useEffect(()=>{if(!k)return;const nt=q.current;typeof nt!="function"&&KT(nt)&&nt.current!==ds.current&&(he.setPositionReference(nt.current),ds.current=nt.current)},[k,he,X,q]),x.useEffect(()=>{if(S&&k&&ye.reference&&ye.floating)return dT(ye.reference,ye.floating,Oe,ve)},[S,k,ye,Oe,ve]);const Gn=ta(Ne),xs=qT(c,Gn,F),it=Sl(Ne)||"center",Vt=!!Te.hide?.referenceHidden;De(()=>{R&&k&&Ye&&Gn!==G&&O(Gn)},[R,k,Ye,Gn,G]);const Bn=x.useMemo(()=>({position:"absolute",top:Te.arrow?.y,left:Te.arrow?.x}),[Te.arrow]),tn=Te.arrow?.centerOffset!==0;return x.useMemo(()=>({positionerStyles:qn,arrowStyles:Bn,arrowRef:ie,arrowUncentered:tn,side:xs,align:it,physicalSide:Gn,anchorHidden:Vt,refs:he,context:_e,isPositioned:Ye,update:Oe}),[qn,Bn,ie,tn,xs,it,Gn,Vt,he,_e,Ye,Oe])}function KT(e){return e!=null&&"current"in e}function cf(e){return e==="starting"?WB:fn}function bh(e,t,{styles:a,transitionStatus:o,props:c,refs:d,hidden:f,inert:p=!1}){const g={...a};return p&&(g.pointerEvents="none"),vt("div",e,{state:t,ref:d,props:[{role:"presentation",hidden:f,style:g},cf(o),c],stateAttributesMapping:qc})}const VU=x.forwardRef(function(t,a){const{render:o,className:c,anchor:d,positionMethod:f="absolute",side:p="top",align:g="center",sideOffset:v=0,alignOffset:y=0,collisionBoundary:b="clipping-ancestors",collisionPadding:j=5,arrowPadding:w=5,sticky:S=!1,disableAnchorTracking:N=!1,collisionAvoidance:k=F1,style:E,...D}=t,C=tf(),A=EU(),R=C.useState("open"),I=C.useState("mounted"),P=C.useState("trackCursorAxis"),O=C.useState("disableHoverablePopup"),_=C.useState("floatingRootContext"),L=C.useState("instantType"),H=C.useState("transitionStatus"),B=C.useState("adaptiveOrigin"),z=xh({anchor:d,positionMethod:f,floatingRootContext:_,mounted:I,side:p,sideOffset:v,align:g,alignOffset:y,collisionBoundary:b,collisionPadding:j,sticky:S,arrowPadding:w,disableAnchorTracking:N,keepMounted:A,collisionAvoidance:k,adaptiveOrigin:B}),Q=x.useMemo(()=>({open:R,side:z.side,align:z.align,anchorHidden:z.anchorHidden,instant:P!=="none"?"tracking-cursor":L}),[R,z.side,z.align,z.anchorHidden,P,L]),K=bh(t,Q,{styles:z.positionerStyles,transitionStatus:H,props:D,refs:[a,C.useStateSetter("positionerElement")],hidden:!I,inert:!R||P==="both"||O});return s.jsx(UT.Provider,{value:z,children:K})}),FU=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t,p=tf(),{side:g,align:v}=VT(),y=p.useState("open"),b=p.useState("instantType"),j=p.useState("transitionStatus"),w=p.useState("popupProps"),S=p.useState("floatingRootContext"),N=p.useState("disabled"),k=p.useState("closeDelay");ra({open:y,ref:p.context.popupRef,onComplete(){y&&p.context.onOpenChangeComplete?.(!0)}}),RT(S,{enabled:!N,closeDelay:k});const E=p.useStateSetter("popupElement");return vt("div",t,{state:{open:y,side:g,align:v,instant:b,transitionStatus:j},ref:[a,p.context.popupRef,E],props:[af,w,cf(j),f],stateAttributesMapping:Hv})}),$U=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t,p=tf(),{arrowRef:g,side:v,align:y,arrowUncentered:b,arrowStyles:j}=VT(),w=p.useState("open"),S=p.useState("instantType");return vt("div",t,{state:{open:w,side:v,align:y,uncentered:b,instant:S},ref:[a,g],props:[{style:j,"aria-hidden":!0},f],stateAttributesMapping:qc})}),qU=function(t){const{delay:a,closeDelay:o,timeout:c=400}=t,d=x.useMemo(()=>({open:a,close:o}),[a,o]);return s.jsx(LT.Provider,{value:a,children:s.jsx(GB,{delay:d,timeoutMs:c,children:t.children})})};function vh(e){return Av(19)?e:e?"true":void 0}function GU(e){const[t,a]=x.useState({current:e,previous:null});return Object.is(e,t.current)||a({current:e,previous:t.current}),t.previous}function KU(e){return s.jsx(qU,{"data-slot":"tooltip-provider",...e})}function Ii(e){return s.jsx(wU,{"data-slot":"tooltip",...e})}function Pi(e){return s.jsx(TU,{"data-slot":"tooltip-trigger",...e})}function _i({className:e,sideOffset:t=8,side:a="top",children:o,...c}){return s.jsx(RU,{children:s.jsx(VU,{sideOffset:t,side:a,className:"z-[35]",children:s.jsx(FU,{"data-slot":"tooltip-content",className:Ue("max-w-[288px] rounded-md bg-primary px-2.5 py-2 text-[11.5px] leading-[1.55] text-primary-on shadow-3","break-words outline-none","transition-[opacity,transform] duration-150 ease-out","data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95","data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",e),...c,children:o})})})}function YU({className:e,...t}){return s.jsx($U,{className:Ue("size-2 rotate-45 rounded-[1px] bg-primary","data-[side=top]:-bottom-1 data-[side=bottom]:-top-1",e),...t})}const YT=x.createContext(void 0);function su(e){const t=x.useContext(YT);if(!e&&t===void 0)throw new Error(on(27));return t}const XT=x.forwardRef(function(t,a){const{render:o,className:c,style:d,forceRender:f=!1,...p}=t,g=su(),v=g.useState("open"),y=g.useState("nested"),b=g.useState("mounted"),j=g.useState("transitionStatus");return vt("div",t,{state:{open:v,transitionStatus:j},ref:[g.context.backdropRef,a],stateAttributesMapping:Hv,props:[{role:"presentation",hidden:!b,style:{userSelect:"none",WebkitUserSelect:"none"}},p],enabled:f||!y})}),QT=x.forwardRef(function(t,a){const{render:o,className:c,style:d,disabled:f=!1,nativeButton:p=!0,...g}=t,v=su(),y=v.useState("open"),{getButtonProps:b,buttonRef:j}=Jr({disabled:f,native:p}),w={disabled:f};function S(N){y&&v.setOpen(!1,Fe(ny,N.nativeEvent))}return vt("button",t,{state:w,ref:[a,j],props:[{onClick:S},g,b]})}),ZT=x.createContext(void 0);function XU(){const e=x.useContext(ZT);if(e===void 0)throw new Error(on(26));return e}const _y="ArrowUp",Ly="ArrowDown",zy="ArrowLeft",By="ArrowRight",Hy="Home",Uy="End",yh=new Set([_y,Ly,zy,By,Hy,Uy]),WT="Shift",QU=[WT,"Control","Alt","Meta"];function ZU(e){return dn(e)&&e.tagName==="INPUT"}function JT(e){return!!(ZU(e)&&e.selectionStart!=null||dn(e)&&e.tagName==="TEXTAREA")}function eE(e,t,a,o){if(!e||!t||!t.scrollTo)return;let c=e.scrollLeft,d=e.scrollTop;const f=e.clientWidthe.scrollLeft+e.clientWidth-v.scrollPaddingRight?c=g+t.offsetWidth+y.scrollMarginRight-e.clientWidth+v.scrollPaddingRight:g-y.scrollMarginLefte.scrollLeft+e.clientWidth-v.scrollPaddingRight&&(c=g+t.offsetWidth+y.scrollMarginRight-e.clientWidth+v.scrollPaddingRight))}if(p&&o!=="horizontal"){const g=tE(e,t,"top"),v=jh(e),y=jh(t);g-y.scrollMarginTope.scrollTop+e.clientHeight-v.scrollPaddingBottom&&(d=g+t.offsetHeight+y.scrollMarginBottom-e.clientHeight+v.scrollPaddingBottom)}e.scrollTo({left:c,top:d,behavior:"auto"})}function tE(e,t,a){const o=a==="left"?"offsetLeft":"offsetTop";let c=0;for(;t.offsetParent&&(c+=t[o],t.offsetParent!==e);)t=t.offsetParent;return c}function jh(e){const t=getComputedStyle(e);return{scrollMarginTop:parseFloat(t.scrollMarginTop)||0,scrollMarginRight:parseFloat(t.scrollMarginRight)||0,scrollMarginBottom:parseFloat(t.scrollMarginBottom)||0,scrollMarginLeft:parseFloat(t.scrollMarginLeft)||0,scrollPaddingTop:parseFloat(t.scrollPaddingTop)||0,scrollPaddingRight:parseFloat(t.scrollPaddingRight)||0,scrollPaddingBottom:parseFloat(t.scrollPaddingBottom)||0,scrollPaddingLeft:parseFloat(t.scrollPaddingLeft)||0}}const WU="--nested-dialogs",JU="data-nested-dialog-open",eV={...qc,...oo,nestedDialogOpen(e){return e?{[JU]:""}:null}},nE=x.forwardRef(function(t,a){const{render:o,className:c,style:d,finalFocus:f,initialFocus:p,...g}=t,v=su(),y=v.useState("descriptionElementId"),b=v.useState("disablePointerDismissal"),j=v.useState("floatingRootContext"),w=v.useState("popupProps"),S=v.useState("modal"),N=v.useState("mounted"),k=v.useState("nested"),E=v.useState("nestedOpenDialogCount"),D=v.useState("open"),C=v.useState("openMethod"),A=v.useState("titleElementId"),R=v.useState("transitionStatus"),I=v.useState("role"),P=j.useState("floatingId");XU(),ra({open:D,ref:v.context.popupRef,onComplete(){D&&v.context.onOpenChangeComplete?.(!0)}});const O=p===void 0?yT(v.context.popupRef):p,_=E>0,L=v.useStateSetter("popupElement"),B=vt("div",t,{state:{open:D,nested:k,transitionStatus:R,nestedDialogOpen:_},props:[w,{id:P,"aria-labelledby":A,"aria-describedby":y,role:I,...af,hidden:!N,onKeyDown(z){yh.has(z.key)&&z.stopPropagation()},style:{[WU]:E}},g],ref:[a,v.context.popupRef,L],stateAttributesMapping:eV});return s.jsx(rh,{context:j,openInteractionType:C,disabled:!N,closeOnFocusOut:!b,initialFocus:O,returnFocus:f,modal:S!==!1,restoreFocus:"popup",children:B})}),wh=x.forwardRef(function(t,a){const{cutout:o,...c}=t;let d;if(o){const f=o.getBoundingClientRect();d=`polygon(0% 0%,100% 0%,100% 100%,0% 100%,0% 0%,${f.left}px ${f.top}px,${f.left}px ${f.bottom}px,${f.right}px ${f.bottom}px,${f.right}px ${f.top}px,${f.left}px ${f.top}px)`}return s.jsx("div",{ref:a,role:"presentation","data-base-ui-inert":"",...c,style:{position:"fixed",inset:0,userSelect:"none",WebkitUserSelect:"none",clipPath:d}})}),sE=x.forwardRef(function(t,a){const{keepMounted:o=!1,...c}=t,d=su(),f=d.useState("mounted"),p=d.useState("modal"),g=d.useState("open");return f||o?s.jsx(ZT.Provider,{value:o,children:s.jsxs(sh,{ref:a,...c,children:[f&&p===!0&&s.jsx(wh,{ref:d.context.internalBackdropRef,inert:vh(!g)}),t.children]})}):null});let rE={},aE={},lE="";function Sh(e,t){return Vd(e)?e:t}function oE(e,t,a){return/hidden|clip/.test(e.getComputedStyle(Sh(t,a)).overflowY)}function tV(e){if(typeof document>"u")return!1;const t=$t(e);return Sn(t).innerWidth-t.documentElement.clientWidth>0}function nV(e){if(!(typeof CSS<"u"&&CSS.supports&&CSS.supports("scrollbar-gutter","stable"))||typeof document>"u")return!1;const a=$t(e),o=a.documentElement,c=a.body,d=Sh(o,c),f=d.style.overflowY,p=o.style.scrollbarGutter;o.style.scrollbarGutter="stable",d.style.overflowY="scroll";const g=d.offsetWidth;d.style.overflowY="hidden";const v=d.offsetWidth;return d.style.overflowY=f,o.style.scrollbarGutter=p,g===v}function sV(e){const t=$t(e),a=t.documentElement,o=t.body,c=Sh(a,o),d={overflowY:c.style.overflowY,overflowX:c.style.overflowX};return Object.assign(c.style,{overflowY:"hidden",overflowX:"hidden"}),()=>{Object.assign(c.style,d)}}function rV(e){const t=$t(e),a=t.documentElement,o=t.body,c=Sn(a);let d=0,f=0,p=!1;const g=$a.create();if(yl&&(c.visualViewport?.scale??1)!==1)return()=>{};function v(){const w=c.getComputedStyle(a),S=c.getComputedStyle(o),E=(w.scrollbarGutter||"").includes("both-edges")?"stable both-edges":"stable";d=a.scrollTop,f=a.scrollLeft,rE={scrollbarGutter:a.style.scrollbarGutter,overflowY:a.style.overflowY,overflowX:a.style.overflowX},lE=a.style.scrollBehavior,aE={position:o.style.position,height:o.style.height,width:o.style.width,boxSizing:o.style.boxSizing,overflowY:o.style.overflowY,overflowX:o.style.overflowX,scrollBehavior:o.style.scrollBehavior};const D=a.scrollHeight>a.clientHeight,C=a.scrollWidth>a.clientWidth,A=w.overflowY==="scroll"||S.overflowY==="scroll",R=w.overflowX==="scroll"||S.overflowX==="scroll",I=Math.max(0,c.innerWidth-o.clientWidth),P=Math.max(0,c.innerHeight-o.clientHeight),O=parseFloat(S.marginTop)+parseFloat(S.marginBottom),_=parseFloat(S.marginLeft)+parseFloat(S.marginRight),L=Sh(a,o);if(p=nV(e),p){a.style.scrollbarGutter=E,L.style.overflowY="hidden",L.style.overflowX="hidden";return}Object.assign(a.style,{scrollbarGutter:E,overflowY:"hidden",overflowX:"hidden"}),(D||A)&&(a.style.overflowY="scroll"),(C||R)&&(a.style.overflowX="scroll"),Object.assign(o.style,{position:"relative",height:O||P?`calc(100dvh - ${O+P}px)`:"100dvh",width:_||I?`calc(100vw - ${_+I}px)`:"100vw",boxSizing:"border-box",overflowY:"hidden",overflowX:"hidden",scrollBehavior:"unset"}),o.scrollTop=d,o.scrollLeft=f,a.setAttribute("data-base-ui-scroll-locked",""),a.style.scrollBehavior="unset"}function y(){Object.assign(a.style,rE),Object.assign(o.style,aE),p||(a.scrollTop=d,a.scrollLeft=f,a.removeAttribute("data-base-ui-scroll-locked"),a.style.scrollBehavior=lE)}function b(){y(),g.request(v)}v();const j=St(c,"resize",b);return()=>{g.cancel(),y(),typeof c.removeEventListener=="function"&&j()}}class aV{constructor(){ln(this,"lockCount",0);ln(this,"restore",null);ln(this,"timeoutLock",sa.create());ln(this,"timeoutUnlock",sa.create());ln(this,"release",()=>{this.lockCount-=1,this.lockCount===0&&this.restore&&this.timeoutUnlock.start(0,this.unlock)});ln(this,"unlock",()=>{this.lockCount===0&&this.restore&&(this.restore?.(),this.restore=null)})}acquire(t){return this.lockCount+=1,this.lockCount===1&&this.restore===null&&this.timeoutLock.start(0,()=>this.lock(t)),this.release}lock(t){if(this.lockCount===0||this.restore!==null)return;const a=$t(t),o=a.documentElement,c=a.body,d=Sn(o);if(oE(d,o,c)){const p=new d.MutationObserver(()=>{oE(d,o,c)||(p.disconnect(),this.restore=null,this.lock(t))}),g={attributes:!0};p.observe(o,g),p.observe(c,g),this.restore=()=>p.disconnect();return}const f=Kd||!tV(t);this.restore=f?sV(t):rV(t)}}const lV=new aV;function iE(e=!0,t=null){De(()=>{if(e)return lV.acquire(t)},[e,t])}function oV({store:e,parentContext:t,isDrawer:a}){const o=e.useState("open"),c=e.useState("disablePointerDismissal"),d=e.useState("modal"),f=e.useState("popupElement"),p=e.useState("floatingRootContext"),[g,v]=x.useState(0),[y,b]=x.useState(0),j=g===0,w=rf(p,{outsidePressEvent(){return e.context.internalBackdropRef.current||e.context.backdropRef.current?"intentional":{mouse:d==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}},outsidePress(S){if(!e.context.outsidePressEnabledRef.current||"button"in S&&S.button!==0)return!1;if("touches"in S){if(S.type==="touchend"){if(S.changedTouches.length!==1||S.touches.length!==0)return!1}else if(S.touches.length!==1)return!1}const N=is(S);if(j&&!c){if(d){const k=e.context.internalBackdropRef.current,E=e.context.backdropRef.current;return k||E?k===N||E===N||Qe(N,f)&&!N?.hasAttribute("data-base-ui-portal"):!0}return!0}return!1},escapeKey:j});return iE(o&&d===!0,f),e.useContextCallback("onNestedDialogOpen",(S,N)=>{v(S),b(N)}),De(()=>(t?.onNestedDialogOpen&&(o?t.onNestedDialogOpen(g+1,y+(a?1:0)):t.onNestedDialogOpen(0,0)),()=>{t?.onNestedDialogOpen&&o&&t.onNestedDialogOpen(0,0)}),[a,o,g,y,t]),Ey(e,{activeTriggerProps:w.reference,inactiveTriggerProps:w.trigger,popupProps:w.floating,nestedOpenDialogCount:g,nestedOpenDrawerCount:y}),null}const iV={...Oy,modal:e=>e.modal,nested:e=>e.nested,nestedOpenDialogCount:e=>e.nestedOpenDialogCount,nestedOpenDrawerCount:e=>e.nestedOpenDrawerCount,disablePointerDismissal:e=>e.disablePointerDismissal,openMethod:e=>e.openMethod,descriptionElementId:e=>e.descriptionElementId,titleElementId:e=>e.titleElementId,viewportElement:e=>e.viewportElement,role:e=>e.role};class cV extends nu{constructor(a,o,c){const d=new ch,f=uV(a,d,o,c);super(f,dV(d),iV);ln(this,"setOpen",(a,o)=>{o.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},!a&&o.trigger==null&&this.state.activeTriggerId!=null&&(o.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(a,o),!o.isCanceled&&(this.state.floatingRootContext.dispatchOpenChange(a,o),this.update(ky(this.state,a,o.trigger)))})}}function uV(e,t,a,o=!1){return{...Ay(t,a,o),modal:!0,disablePointerDismissal:!1,viewportElement:null,descriptionElementId:void 0,titleElementId:void 0,openMethod:null,nested:!1,nestedOpenDialogCount:0,nestedOpenDrawerCount:0,role:"dialog",...e}}function dV(e){return{popupRef:x.createRef(),backdropRef:x.createRef(),internalBackdropRef:x.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:e,onOpenChange:void 0,onOpenChangeComplete:void 0}}function cE(e,t){const{children:a,open:o,defaultOpen:c=!1,onOpenChange:d,onOpenChangeComplete:f,disablePointerDismissal:p=!1,modal:g=!0,actionsRef:v,handle:y,triggerId:b,defaultTriggerId:j=null}=t,w=e==="drawer",S=e==="alert-dialog",N=S?!0:g,k=S||p,E=S?"alertdialog":"dialog",D=su(!0),C=D!=null,A={modal:N,disablePointerDismissal:k,nested:C,role:E},R=Sy((H,B)=>new cV({open:c,openProp:o,activeTriggerId:j,triggerIdProp:b,...A},H,B),!0);R.useControlledProp("openProp",o),R.useControlledProp("triggerIdProp",b),R.useSyncedValues(A),R.useContextCallback("onOpenChange",d),R.useContextCallback("onOpenChangeComplete",f);const I=R.useState("open"),P=R.useState("mounted"),O=R.useState("payload");NT(R,I),Cy(R);const{forceUnmount:_}=Ty(I,R);x.useImperativeHandle(v,()=>({unmount:_,close:()=>R.setOpen(!1,Fe(ry))}),[_,R]);const L=I||P;return s.jsxs(YT.Provider,{value:R,children:[y&&s.jsx(Ny,{handle:y,store:R}),L&&s.jsx(oV,{store:R,parentContext:D?.context,isDrawer:w}),typeof a=="function"?a({payload:O}):a]})}const fV=eh(function(t){return cE("dialog",t)}),uE=x.forwardRef(function(t,a){const{render:o,className:c,style:d,id:f,...p}=t,g=su(),v=Na(f);return g.useSyncedValueWithCleanup("titleElementId",v),vt("h2",t,{ref:a,props:[{id:v},p]})});function pV(e){const t=x.useRef(""),a=x.useCallback(c=>{c.defaultPrevented||(t.current=c.pointerType,e(c,c.pointerType))},[e]);return{onClick:x.useCallback(c=>{if(c.detail===0){e(c,"keyboard");return}"pointerType"in c?e(c,c.pointerType):e(c,t.current),t.current=""},[e]),onPointerDown:a}}function dE(e,t){const a=Ie((d,f)=>{(typeof e=="function"?e():e)||t(f||(Kd?"touch":""))}),{onClick:o,onPointerDown:c}=pV(a);return x.useMemo(()=>({onClick:o,onPointerDown:c}),[o,c])}function fE(e){const[t,a]=x.useState(null),o=dE(e,a);return aa(e,c=>{c&&!e&&a(null)}),x.useMemo(()=>({openMethod:t,triggerProps:o}),[t,o])}function Qt(e){return s.jsx(fV,{"data-slot":"dialog",...e})}function mV(e){return s.jsx(sE,{"data-slot":"dialog-portal",...e})}const Gt=e=>s.jsx(uE,{"data-slot":"dialog-title",...e});function hV({className:e,...t}){return s.jsx(XT,{"data-slot":"dialog-overlay",className:Ue("fixed inset-0 isolate z-30 bg-mask backdrop-blur-[3px]","transition-opacity duration-150","data-open:animate-in data-open:fade-in-0","data-closed:animate-out data-closed:fade-out-0 data-closed:fill-mode-forwards",e),...t})}function Zt({className:e,children:t,showCloseButton:a=!0,keepMounted:o=!1,overlayForceRender:c=!1,...d}){return s.jsxs(mV,{keepMounted:o,children:[s.jsx(hV,{forceRender:c}),s.jsxs(nE,{"data-slot":"dialog-content",className:Ue("fixed top-1/2 left-1/2 z-30 flex max-h-[calc(100vh-48px)] w-[min(620px,calc(100vw-48px))] -translate-x-1/2 -translate-y-1/2 flex-col","overflow-hidden rounded-lg border border-border bg-surface shadow-3 outline-none","transition-[opacity,transform] duration-200 [transition-timing-function:cubic-bezier(.2,.9,.3,1)]","data-open:animate-in data-open:fade-in-0 data-open:zoom-in-[.985] data-open:slide-in-from-bottom-2.5","data-closed:animate-out data-closed:fade-out-0 data-closed:fill-mode-forwards",e),...d,children:[t,a&&s.jsxs(QT,{"data-slot":"dialog-close",render:s.jsx(se,{variant:"ghost",size:"icon-sm",className:"absolute top-3 right-3"}),children:[s.jsx("svg",{viewBox:"0 0 12 12",className:"size-3","aria-hidden":"true",children:s.jsx("path",{d:"M2.5 2.5l7 7M9.5 2.5l-7 7",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",fill:"none"})}),s.jsx("span",{className:"sr-only",children:go("关闭")})]})]})]})}function Kt({className:e,...t}){return s.jsx("div",{"data-slot":"dialog-header",className:Ue("flex items-center gap-2.5 border-b border-hairline px-5 py-[15px] pr-10","[&_h2]:flex-1 [&_h2]:text-[14.5px] [&_h2]:font-semibold",e),...t})}function Bt({className:e,...t}){return s.jsx("div",{"data-slot":"dialog-body",className:Ue("flex flex-col gap-4 overflow-y-auto px-5 py-[18px]",e),...t})}function nn({className:e,...t}){return s.jsx("div",{"data-slot":"dialog-footer",className:Ue("flex items-center gap-2 border-t border-hairline bg-surface-2 px-5 py-[13px]",e),...t})}function Vn({className:e,...t}){return s.jsx("div",{"data-slot":"dialog-section",className:Ue("flex flex-col gap-2.5 rounded-md border border-border bg-surface-inset p-3.5","[&_h3]:text-[12.5px] [&_h3]:font-semibold","[&_p]:text-xs [&_p]:leading-[1.65] [&_p]:text-subtle",e),...t})}function gV(e){return cE("alert-dialog",e)}const xV=gV,bV=sE,vV=e=>s.jsx(uE,{"data-slot":"alert-dialog-title",...e});function yV({className:e,...t}){return s.jsx(XT,{"data-slot":"alert-dialog-overlay",className:Ue("fixed inset-0 isolate z-[38] bg-mask backdrop-blur-[3px]","transition-opacity duration-150","data-open:animate-in data-open:fade-in-0","data-closed:animate-out data-closed:fade-out-0 data-closed:fill-mode-forwards",e),...t})}function jV({className:e,children:t,showCloseButton:a=!1,...o}){return s.jsxs(bV,{children:[s.jsx(yV,{}),s.jsxs(nE,{"data-slot":"alert-dialog-content",className:Ue("fixed top-1/2 left-1/2 z-[38] flex max-h-[calc(100vh-48px)] w-[min(440px,calc(100vw-48px))] -translate-x-1/2 -translate-y-1/2 flex-col","overflow-hidden rounded-lg border border-border bg-surface shadow-3 outline-none","transition-[opacity,transform] duration-200 [transition-timing-function:cubic-bezier(.2,.9,.3,1)]","data-open:animate-in data-open:fade-in-0 data-open:zoom-in-[.985] data-open:slide-in-from-bottom-2.5","data-closed:animate-out data-closed:fade-out-0 data-closed:fill-mode-forwards",e),...o,children:[t,a&&s.jsxs(QT,{"data-slot":"alert-dialog-close",render:s.jsx(se,{variant:"ghost",size:"icon-sm",className:"absolute top-3 right-3"}),children:[s.jsx("svg",{viewBox:"0 0 12 12",className:"size-3","aria-hidden":"true",children:s.jsx("path",{d:"M2.5 2.5l7 7M9.5 2.5l-7 7",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",fill:"none"})}),s.jsx("span",{className:"sr-only",children:go("关闭")})]})]})]})}function wV({className:e,...t}){return s.jsx("div",{"data-slot":"alert-dialog-header",className:Ue("flex items-center gap-2.5 border-b border-hairline px-5 py-[15px]","[&_h2]:flex-1 [&_h2]:text-[14.5px] [&_h2]:font-semibold",e),...t})}function SV({className:e,...t}){return s.jsx("div",{"data-slot":"alert-dialog-body",className:Ue("flex flex-col gap-4 overflow-y-auto px-5 py-[18px]",e),...t})}function NV({className:e,...t}){return s.jsx("div",{"data-slot":"alert-dialog-footer",className:Ue("flex items-center gap-2 border-t border-hairline bg-surface-2 px-5 py-[13px]",e),...t})}function kV({className:e,tone:t="danger",...a}){return s.jsx("div",{"data-slot":"alert-dialog-banner","data-tone":t,className:Ue("rounded-md border px-3.5 py-3 text-xs leading-[1.65] text-subtle","[&_strong]:font-semibold",t==="danger"?"border-destructive-bd bg-destructive-soft [&_strong]:text-destructive":"border-border bg-surface-inset [&_strong]:text-foreground",e),...a})}function Vy({className:e,containerClassName:t,...a}){return s.jsx("div",{"data-slot":"table-container",className:Ue("relative w-full overflow-auto",t),children:s.jsx("table",{"data-slot":"table",className:Ue("w-full caption-bottom border-collapse text-[12.5px]",e),...a})})}function pE({className:e,...t}){return s.jsx("thead",{"data-slot":"table-header",className:Ue(e),...t})}function Fy({className:e,...t}){return s.jsx("tbody",{"data-slot":"table-body",className:Ue(e),...t})}function kl({className:e,...t}){return s.jsx("tr",{"data-slot":"table-row",className:Ue("transition-colors duration-100 hover:[&>td]:bg-control-hover",e),...t})}function mE({className:e,...t}){return s.jsx("th",{"data-slot":"table-head",className:Ue("sticky top-0 z-[2] whitespace-nowrap border-b border-border bg-surface-2 px-3.5 py-2","text-left text-[10.5px] font-semibold tracking-[.05em] text-muted-foreground",e),...t})}function Nn({className:e,...t}){return s.jsx("td",{"data-slot":"table-cell",className:Ue("border-b border-hairline px-3.5 py-2 align-middle",e),...t})}const CV="data-checked",TV="data-unchecked",$y={checked(e){return e?{[CV]:""}:{[TV]:""}},...oo,...ji},qy="data-composite-item-active",hE=x.createContext({register:()=>{},unregister:()=>{},subscribeMapChange:()=>()=>{},nextIndexRef:{current:0}});function EV(){return x.useContext(hE)}function Gy(e={}){const{guess:t,label:a,metadata:o,textRef:c,index:d}=e,{register:f,unregister:p,subscribeMapChange:g,nextIndexRef:v}=EV(),y=x.useRef(-1),[b,j]=x.useState(d==null&&t?()=>{if(y.current===-1){const k=v.current;v.current+=1,y.current=k}return y.current}:-1),w=d??b,S=x.useRef(null),N=x.useCallback(k=>{const E=S.current;E&&p(E),S.current=k,k&&f(k,{metadata:o??null,index:d??null,label:a,textRef:c})},[d,f,p,o,a,c]);return De(()=>{if(d==null)return g(k=>{const E=S.current?k.get(S.current)?.index:null;E!=null&&j(E)})},[d,g]),{ref:N,index:w}}function AV(e={}){const{highlightItemOnHover:t,highlightedIndex:a,onHighlightedIndexChange:o}=fC(),{ref:c,index:d}=Gy(e),f=a===d,p=x.useRef(null),g=ea(c,p);return{compositeProps:{tabIndex:f?0:-1,onFocus(){o(d)},onMouseMove(){const y=p.current;if(!t||!y)return;const b=y.hasAttribute("disabled")||y.ariaDisabled==="true";!f&&!b&&y.focus()}},compositeRef:g,index:d}}function gE(e){const{render:t,className:a,style:o,state:c=fn,props:d=Rr,refs:f=Rr,metadata:p,stateAttributesMapping:g,tag:v="div",...y}=e,{compositeProps:b,compositeRef:j}=AV({metadata:p});return vt(v,e,{state:c,ref:[j,...f],props:[b,...d,y],stateAttributesMapping:g})}const xE=x.createContext(void 0);function RV(){return x.useContext(xE)}function Nh(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}const bE=x.createContext(void 0);function OV(){const e=x.useContext(bE);if(e===void 0)throw new Error(on(52));return e}const vE=x.forwardRef(function(t,a){const{render:o,className:c,disabled:d=!1,readOnly:f=!1,required:p=!1,"aria-labelledby":g,value:v,inputRef:y,nativeButton:b=!1,id:j,style:w,...S}=t,N=RV(),{disabled:k,readOnly:E,required:D,form:C,checkedValue:A,touched:R=!1,validation:I,name:P,setCheckedValue:O=qt,setTouched:_=qt,registerInputRef:L=qt}=N??{},{setTouched:H,setFilled:B,state:z,disabled:Q}=Sa(),K=p1(),{labelId:X,getDescriptionProps:q}=vl(),$=Q||K.disabled||k||d,Y=E||f,F=D||p,G=C,W=N?A===v:v==="",le=x.useRef(null),M=x.useRef(null),U=I?.registerInput,Z=x.useCallback(ye=>U?.(ye,{controlRef:le,value:void 0}),[U]),ae=ea(y,M,L,Z);De(()=>{M.current?.checked&&B(!0)},[B]),De(()=>{if(M.current){if($&&W){L(null);return}L(M.current)}},[W,$,L]);const ce=Na(),J=lo({id:j}),ie=b?void 0:J,ge=Iv(g,X,M,!b,ie),ee={role:"radio","aria-checked":W,"aria-labelledby":ge,[qy]:W?"":void 0,id:b?J:ce,onKeyDown(ye){ye.key==="Enter"&&ye.preventDefault()},onClick(ye){if(ye.defaultPrevented||$||Y)return;ye.preventDefault();const we=M.current;we&&Vc(we,ye)},onFocus(ye){ye.defaultPrevented||$||Y||!R||(M.current?.click(),_(!1))}},{getButtonProps:fe,buttonRef:te}=Jr({disabled:$,native:b,composite:!1}),Ce={type:"radio",ref:ae,form:G,id:ie,name:P,tabIndex:-1,style:P?Wc:Ai,"aria-hidden":!0,...v!==void 0?{value:Nh(v)}:fn,disabled:$,checked:W,required:F,readOnly:Y,onChange(ye){if(ye.nativeEvent.defaultPrevented||$||Y||v===void 0)return;const we=Fe(Yn,ye.nativeEvent);O(v,we),!we.isCanceled&&H(!0)},onClick(ye){ye.stopPropagation()},onFocus(){le.current?.focus()}},re=x.useMemo(()=>({...z,required:F,disabled:$,readOnly:Y,checked:W}),[z,$,Y,W,F]),de=re,ke=N!==void 0,Ee=[a,le,te],ve=[ee,S,fe,q,I?ye=>I.getValidationProps($,ye):fn],he=vt("span",t,{enabled:!ke,state:re,ref:Ee,props:ve,stateAttributesMapping:$y});return s.jsxs(bE.Provider,{value:de,children:[ke?s.jsx(gE,{tag:"span",render:o,className:c,style:w,state:re,refs:Ee,props:ve,stateAttributesMapping:$y}):he,s.jsx("input",{...Ce,suppressHydrationWarning:!0})]})}),MV=x.forwardRef(function(t,a){const{render:o,className:c,style:d,keepMounted:f=!1,...p}=t,g=OV(),v=g.checked,{mounted:y,transitionStatus:b,setMounted:j}=ki(v),w={...g,transitionStatus:b},S=x.useRef(null),N=f||y,k=vt("span",t,{ref:[a,S],state:w,props:p,stateAttributesMapping:$y});return ra({batch:!0,enabled:!v,open:v,ref:S,onComplete(){v||j(!1)}}),N?k:null});function Ky(e){const{children:t,elementsRef:a,labelsRef:o,onMapChange:c}=e,d=Ie(c),[,f]=x.useState(!1),p=Ms(IV).current,g=Ms(DV).current,v=x.useRef(0),y=x.useRef(!0),b=x.useRef(null),j=x.useRef(null),w=Ie(()=>{y.current||(y.current=!0,f(R=>!R))}),S=Ie((R,I)=>{g.set(R,I),w()}),N=Ie(R=>{g.delete(R),w()}),k=Ie(R=>{const I=new Map;return a.current.length=0,o&&(o.current.length=0),R.forEach(P=>{I.set(P.element,{...P.registration.metadata??{},index:P.index}),a.current[P.index]=P.element,o&&(o.current[P.index]=P.registration.label!==void 0?P.registration.label:P.registration.textRef?.current?.textContent??P.element.textContent)}),v.current=a.current.length,I});function E(R){if(j.current?.disconnect(),j.current=null,typeof MutationObserver!="function"||R.length<2)return;const I=new MutationObserver(O=>{if(!LV(O))return;let _=null;for(const L of R)if(L.isConnected){if(_&&yE(_,L)>0){I.disconnect(),w();return}_=L}});j.current=I;const P=new Set;for(let O=1;OI.observe(O,{childList:!0}))}const D=Ie(()=>{const[R,I]=PV(g),P=k(R),O=b.current,_=!O||O.length!==R.length||R.some((L,H)=>{const B=O[H];return L.index!==B.index||L.element!==B.element||L.registration.index!==B.registration.index||L.registration.metadata!==B.registration.metadata});E(I),b.current=R,y.current=!1,_&&(p.forEach(L=>L(P)),d(P))});De(()=>(!y.current&&b.current&&k(b.current),()=>{a.current=[],o&&(o.current=[])}),[a,o,k]),De(()=>{y.current&&D()}),De(()=>()=>{j.current?.disconnect(),y.current=!0},[]);const C=Ie(R=>(p.add(R),()=>{p.delete(R)})),A=x.useMemo(()=>({register:S,unregister:N,subscribeMapChange:C,nextIndexRef:v}),[S,N,C,v]);return s.jsx(hE.Provider,{value:A,children:t})}function DV(){return new Map}function IV(){return new Set}function PV(e){const t=new Set,a=[],o=[];e.forEach((d,f)=>{if(!f.isConnected)return;const p=d.index,g={index:p??-1,element:f,registration:d};p===null?o.push(g):p>=0&&(t.add(p),a.push(g))});let c=0;return o.sort((d,f)=>yE(d.element,f.element)),o.forEach(d=>{for(;t.has(c);)c+=1;d.index=c,a.push(d),c+=1}),t.size>0&&a.sort((d,f)=>d.index-f.index),[a,o.map(d=>d.element)]}function _V(e,t){let a=e.parentElement;for(;a&&!a.contains(t);)a=a.parentElement;return a}function LV(e){for(const t of e)for(let a=0;a{if(A.current=D.current[H]??null,(p??S)(H),B){const z=D.current[H];eE(k.current,z,d,a)}}),P=Ie(H=>{if(H.size===0)return;if(C.current){const K=D.current,X=K.indexOf(A.current);if(X===-1){const q=K[R];!q||po(K,R,b)?I(BV(K,b)):A.current=q}else X!==R&&I(X);return}C.current=!0;const B=Array.from(H.keys()),z=B.find(K=>K?.hasAttribute(qy))??null,Q=z?H.get(z)?.index??-1:-1;if(Q!==-1)I(Q);else if(po(B,R,b)){const K=Ds(B,{disabledIndices:b});fo(B,K)||I(K)}eE(k.current,z,d,a)});De(()=>{if(b==null||f!=null||!C.current)return;const H=D.current;if(po(H,R,b)){const B=Ds(H,{disabledIndices:b});fo(H,B)||I(B)}},[b,f,R,D,I]);const O=Ie((H,B,z)=>c?c(H,B,z,D):z),_=Ie(H=>{const B=H.key===Hy||H.key===Uy;if(!yh.has(H.key)||!v&&B||HV(H,j)||!k.current)return;const Q=d==="rtl",K=Q?zy:By,X=Q?By:zy,q=a==="vertical"?Ly:K,$=a==="vertical"?_y:X,Y=is(H.nativeEvent);if(Y!=null&&JT(Y)&&!jE(Y)){const U=Y.selectionStart,Z=Y.selectionEnd,ae=Y.value;if(U==null||H.shiftKey||U!==Z||H.key!==$&&U0)return}let F=R;const G=Km(D,b),W=Xv(D,b);o!=null&&(F=o({disabledIndices:b,elementsRef:D,event:H,highlightedIndex:R,loopFocus:t,maxIndex:W,minIndex:G,onLoop:O,orientation:a,rtl:Q}));const le=a!=="vertical"&&H.key===K||a!=="horizontal"&&H.key===Ly,M=a!=="vertical"&&H.key===X||a!=="horizontal"&&H.key===_y;v&&(H.key===Hy?F=G:H.key===Uy&&(F=W)),F===R&&(le||M)&&(t&&F===W&&le?(F=G,c&&(F=c(H,R,F,D))):t&&F===G&&M?(F=W,c&&(F=c(H,R,F,D))):F=Ds(D.current,{startingIndex:F,decrement:M,disabledIndices:b})),F!==R&&!fo(D.current,F)&&(y&&H.stopPropagation(),(N||B||le||M)&&H.preventDefault(),I(F,!0),queueMicrotask(()=>{D.current[F]?.focus()}))});return{props:{ref:E,onFocus(H){const B=k.current,z=is(H.nativeEvent);!B||z==null||!JT(z)||z.setSelectionRange(0,z.value.length)},onKeyDown:_},highlightedIndex:R,onHighlightedIndexChange:I,elementsRef:D,onMapChange:P,relayKeyboardEvent:_}}function BV(e,t){let a=-1;for(let o=0;o({highlightedIndex:_,onHighlightedIndexChange:L,highlightItemOnHover:A,relayKeyboardEvent:z}),[_,L,A,z]);return s.jsx(dC.Provider,{value:K,children:s.jsx(Ky,{elementsRef:H,onMapChange:X=>{N?.(X),B(X)},children:Q})})}const VV=[WT],wE=x.forwardRef(function(t,a){const{render:o,className:c,disabled:d,readOnly:f,required:p,onValueChange:g,value:v,defaultValue:y,form:b,name:j,inputRef:w,id:S,style:N,...k}=t,{setTouched:E,setFocused:D,validationMode:C,name:A,disabled:R,state:I,validation:P,setDirty:O,setFilled:_,validityData:L}=Sa(),{labelId:H}=vl(),{clearErrors:B,elementRef:z}=$c(),Q=o4(!0),K=R||d,X=A??j,q=Na(S),[$,Y]=qa({controlled:v,default:y,name:"RadioGroup",state:"value"}),[F,G]=x.useState(!1),W=Ie((te,Ce)=>{g?.(te,Ce),!Ce.isCanceled&&Y(te)}),le=P.getInputControl,M=x.useMemo(()=>({get current(){return le()}}),[le]),U=x.useRef(null),Z=x.useRef(null);function ae(te){let Ce;return w&&(typeof w=="function"?Ce=w(te):w.current=te),U.current=te,Ce}const ce=Ie(te=>{if(!te||te.disabled)return;Z.current||(Z.current=te);const Ce=U.current,re=te.checked||Ce==null||Ce.disabled?ae(te):void 0;return()=>{Z.current===te&&(Z.current=null),U.current===te?re?(re(),U.current=null):ae(null):re?.()}}),J=Ie(()=>{const te=z.current;if(!te)return $??null;for(const Ce of P.registeredInputs.keys())if(Ce.checked&&eB(Ce,te))return $??null;return null});Xc(M,q,$??null,J,!K,j),aa($,()=>{B(X),O($!==L.initialValue),_($!=null),P.change($);const te=Z.current;$==null&&te&&!te.disabled&&ae(te)});const ie=H??Q?.legendId,ge={...I,disabled:K??!1,required:p??!1,readOnly:f??!1},ee=x.useMemo(()=>({checkedValue:$,disabled:K,form:b,validation:P,name:X,readOnly:f,registerInputRef:ce,required:p,setCheckedValue:W,setTouched:G,touched:F}),[$,K,b,P,X,f,ce,p,W,G,F]),fe={id:S,role:"radiogroup","aria-required":p||void 0,"aria-disabled":K||void 0,"aria-readonly":f||void 0,"aria-labelledby":ie,onFocus(){D(!0)},onBlur(te){Qe(te.currentTarget,te.relatedTarget)||(E(!0),D(!1),C==="onBlur"&&P.commit($))},onKeyDownCapture(te){te.key.startsWith("Arrow")&&(G(!0),D(!0))}};return s.jsx(xE.Provider,{value:ee,children:s.jsx(UV,{render:o,className:c,style:N,state:ge,props:[fe,k,te=>P.getValidationProps(K??!1,te)],refs:[a],stateAttributesMapping:ji,enableHomeAndEndKeys:!1,modifierKeys:VV})})});function kh({className:e,...t}){return s.jsx(wE,{"data-slot":"radio-group",className:Ue("flex flex-col gap-2",e),...t})}function bo({className:e,...t}){return s.jsx(vE,{"data-slot":"radio-group-item",className:Ue("relative inline-flex size-3.5 flex-none cursor-pointer items-center justify-center rounded-full border border-control-border bg-control","outline-none transition-colors duration-150 ease-out","hover:border-control-border-hover","data-checked:border-primary data-checked:bg-primary","focus-visible:shadow-focus","data-disabled:cursor-not-allowed data-disabled:opacity-45",e),...t,children:s.jsx(MV,{"data-slot":"radio-group-indicator",className:"grid place-content-center data-unchecked:hidden",children:s.jsx("span",{className:"block size-[5px] rounded-full bg-primary-foreground"})})})}function SE(e){const t=x.useRef(!0);t.current&&(t.current=!1,e())}const NE=x.createContext(void 0),kE=x.createContext(void 0),CE=x.createContext(void 0);function vo(){const e=x.useContext(NE);if(e===void 0)throw new Error(on(60));return e}function Yy(){const e=x.useContext(kE);if(e===void 0)throw new Error(on(101));return e}function TE(){const e=x.useContext(CE);if(e===void 0)throw new Error(on(61));return e}function FV(e,t,a=Object.is){const{length:o}=e;if(o!==t.length)return!1;for(let c=0;cObject.is(e,t);function la(e,t,a){return e==null||t==null?Object.is(e,t):a(e,t)}function EE(e,t,a){return Array.isArray(e)&&Array.isArray(t)?!FV(e,t,(o,c)=>la(o,c,a)):e!==t}function Th(e,t,a){return e?e.some(o=>o===void 0?!1:la(t,o,a)):!1}function ru(e,t,a){return e?e.findIndex(o=>o===void 0?!1:la(o,t,a)):-1}function $V(e,t){if(t!==Ch)return o=>Th(e,o,t);const a=new Set(e);return a.delete(void 0),o=>a.has(o)&&(o!==0||e.some(c=>Object.is(o,c)))}function uf(e,t,a,o){const c=o&&Array.isArray(t)?e.findIndex($V(t,a)):ru(e,t,a);return c===-1?null:c}function AE(e,t,a,o,c,d){return Th(o,t,c)?d!=null&&e>d&&Th(o,a[d],c)?d:e:e===d?uf(a,o,c,!0):d}function RE(e,t,a){return e.filter(o=>!la(t,o,a))}function qV(e){return typeof e=="object"&&e!=null&&Array.isArray(e.items)}function Xy(e){return qV(e?.[0])}function Eh(e){return Xy(e)?e.flatMap(t=>t.items):e}function OE(e){if(!Array.isArray(e))return e!=null&&"null"in e;const t=e;if(Xy(t)){for(const a of t)for(const o of a.items)if(o&&o.value==null&&o.label!=null)return!0;return!1}for(const a of t)if(a&&a.value==null&&a.label!=null)return!0;return!1}function yo(e,t){if(t&&e!=null)return t(e)??"";if(e&&typeof e=="object"){if("label"in e&&e.label!=null)return String(e.label);if("value"in e)return String(e.value)}return Nh(e)}function ka(e,t){return t&&e!=null?t(e)??"":e&&typeof e=="object"&&"value"in e&&"label"in e?Nh(e.value):Nh(e)}function ME(e,t,a){function o(){return yo(e,a)}if(a&&e!=null)return a(e);if(e&&typeof e=="object"&&"label"in e&&e.label!=null)return e.label;if(t&&!Array.isArray(t))return(Object.hasOwn(t,e)?t[e]:void 0)??o();if(Array.isArray(t)){const d=Eh(t);if(e==null||typeof e!="object"){const f=d.find(p=>p.value===e);return f&&f.label!=null?f.label:o()}if("value"in e){const f=d.find(p=>p&&p.value===e.value);if(f&&f.label!=null)return f.label}}return o()}function GV(e,t,a){return e.reduce((o,c,d)=>(d>0&&o.push(", "),o.push(s.jsx(x.Fragment,{children:ME(c,t,a)},d)),o),[])}const KV={id:e=>e.id,labelId:e=>e.labelId,modal:e=>e.modal,items:e=>e.items,itemToStringLabel:e=>e.itemToStringLabel,isItemEqualToValue:e=>e.isItemEqualToValue,value:e=>e.value,hasSelectedValue:e=>{const{value:t,multiple:a,itemToStringValue:o}=e;return t==null?!1:a&&Array.isArray(t)?t.length>0:ka(t,o)!==""},hasNullItemLabel:(e,t)=>t?OE(e.items):!1,open:e=>e.open,mounted:e=>e.mounted,forceMount:e=>e.forceMount,transitionStatus:e=>e.transitionStatus,openMethod:e=>e.openMethod,activeIndex:e=>e.activeIndex,selectedIndex:e=>e.selectedIndex,isActive:(e,t)=>e.activeIndex===t,isSelected:(e,t)=>{const a=e.isItemEqualToValue,o=e.value;return e.multiple?Array.isArray(o)&&o.some(c=>la(t,c,a)):la(t,o,a)},isSelectedByFocus:(e,t)=>e.selectedIndex===t,popupProps:e=>e.popupProps,triggerProps:e=>e.triggerProps,triggerElement:e=>e.triggerElement,positionerElement:e=>e.positionerElement,listElement:e=>e.listElement,popupSide:e=>e.popupSide,scrollUpArrowVisible:e=>e.scrollUpArrowVisible,scrollDownArrowVisible:e=>e.scrollDownArrowVisible,hasScrollArrows:e=>e.hasScrollArrows},Cl=1;function DE(e,t){return Math.max(0,e-t)}function YV(e,t){if(t<=0)return 0;const a=Ri(e,0,t),o=a,c=t-a,d=o<=Cl,f=c<=Cl;return d&&f?o<=c?0:t:d?0:f?t:a}function XV(e){const{id:t,value:a,defaultValue:o=null,onValueChange:c,open:d,defaultOpen:f=!1,onOpenChange:p,name:g,form:v,autoComplete:y,disabled:b=!1,readOnly:j=!1,required:w=!1,modal:S=!0,actionsRef:N,inputRef:k,onOpenChangeComplete:E,items:D,multiple:C=!1,itemToStringLabel:A,itemToStringValue:R,isItemEqualToValue:I=Ch,highlightItemOnHover:P=!0,children:O}=e,{clearErrors:_}=$c(),{setDirty:L,setTouched:H,setFocused:B,validityData:z,setFilled:Q,name:K,disabled:X,validation:q,validationMode:$}=Sa(),Y=lo({id:t}),F=X||b,G=K??g,[W,le]=qa({controlled:a,default:C?o??Rr:o,name:"Select",state:"value"}),[M,U]=qa({controlled:d,default:f,name:"Select",state:"open"}),Z=x.useRef([]),ae=x.useRef([]),ce=x.useRef(null),J=x.useRef(null),ie=x.useRef(0),ge=x.useRef(null),ee=x.useRef([]),fe=x.useRef(!1),te=x.useRef(null),Ce=x.useRef(null),re=x.useRef({allowSelectedMouseUp:!1,allowUnselectedMouseUp:!1,dragY:0}),de=x.useRef(!1),ke=x.useRef(W),{mounted:Ee,setMounted:ve,transitionStatus:he}=ki(M),{openMethod:ye,triggerProps:we}=fE(M),xe=Ms(()=>new nu({id:Y,labelId:void 0,modal:S,multiple:C,itemToStringLabel:A,itemToStringValue:R,isItemEqualToValue:I,value:W,open:M,mounted:Ee,transitionStatus:he,items:D,forceMount:!1,openMethod:null,activeIndex:null,selectedIndex:null,popupProps:fn,triggerProps:fn,triggerElement:null,positionerElement:null,listElement:null,popupSide:null,scrollUpArrowVisible:!1,scrollDownArrowVisible:!1,hasScrollArrows:!1},{setValue:qt,setOpen:qt,handleScrollArrowVisibility:qt,onOpenChangeComplete:qt,listRef:Z,popupRef:ce,scrollHandlerRef:J,scrollArrowsMountedCountRef:ie,valueRef:ge,valuesRef:ee,labelsRef:ae,typingRef:fe,selectionRef:re,firstItemTextRef:te,selectedItemTextRef:Ce,alignItemWithTriggerActiveRef:de,initialValueRef:ke},KV)).current,Te=xe.useState("activeIndex"),Oe=xe.useState("selectedIndex"),Ne=xe.useState("triggerElement"),_e=xe.useState("positionerElement"),Ye=GU(ye),kt=ye??Ye,Ct=x.useMemo(()=>C?"":ka(W,R),[C,W,R]),Rt=x.useMemo(()=>C&&Array.isArray(W)?W.map(gt=>ka(gt,R)):ka(W,R),[C,W,R]),ot=Xn(Ne),qn=Ie(()=>Rt);Xc(ot,Y,W,qn,!F,g);const ds=C?Array.isArray(W)&&W.length>0:W!=null&&Ct!=="";De(()=>{Q(ds)},[ds,Q]),De(function(){const jt=uf(ee.current,W,I,C);jt===null&&(Ce.current=null),!M&&xe.set("selectedIndex",jt)},[C,M,W,I,xe]),aa(W,()=>{_(G),L(EE(W,z.initialValue,I)),q.change(W)});const Gn=Ie((gt,jt)=>{p?.(gt,jt),!jt.isCanceled&&(U(gt),!gt&&(jt.reason===ho||jt.reason===Jm)&&(H(!0),B(!1),$==="onBlur"&&q.commit(W)))}),xs=Ie(()=>{ve(!1),xe.update({activeIndex:null,openMethod:null,scrollUpArrowVisible:!1,scrollDownArrowVisible:!1}),E?.(!1)});ra({enabled:!N,open:M,ref:ce,onComplete(){M||xs()}}),x.useImperativeHandle(N,()=>({unmount:xs}),[xs]);const it=Ie((gt,jt)=>{c?.(gt,jt),!jt.isCanceled&&le(gt)}),Vt=Ie(gt=>{const jt=DE(gt.scrollHeight,gt.clientHeight),wt=YV(gt.scrollTop,jt),Sr=wt>0,rr=wtjE(Z.current[gt]),onMatch(gt){M?xe.set("activeIndex",gt):it(ee.current[gt],Fe(Yn))},onTyping(gt){fe.current=gt}}),Zn=x.useMemo(()=>Wr(Ft.reference,Ot.reference,nt.reference,tn.reference,we),[tn.reference,Ft.reference,Ot.reference,nt.reference,we]),Hn=x.useMemo(()=>Wr(af,Ft.floating,Ot.floating,nt.floating),[Ft.floating,Ot.floating,nt.floating]),Un=Ot.item??fn;xe.useContextCallback("setValue",it),xe.useContextCallback("setOpen",Gn),xe.useContextCallback("handleScrollArrowVisibility",Vt),xe.useContextCallback("onOpenChangeComplete",E),SE(()=>{xe.update({popupProps:Hn,triggerProps:Zn})}),xe.useSyncedValues({id:Y,modal:S,multiple:C,value:W,open:M,mounted:Ee,transitionStatus:he,popupProps:Hn,triggerProps:Zn,items:D,itemToStringLabel:A,itemToStringValue:R,isItemEqualToValue:I,openMethod:kt});const Rn=x.useMemo(()=>({disabled:F,readOnly:j,required:w,multiple:C,highlightItemOnHover:P,itemProps:Un}),[F,j,w,C,P,Un]),Jt=ea(k,q.inputRef),as=C?void 0:G,Tt=x.useMemo(()=>!C||!Array.isArray(W)||!G?null:W.map(gt=>{const jt=ka(gt,R);return s.jsx("input",{type:"hidden",form:v,name:G,value:jt,disabled:F},jt)}),[C,W,v,G,R,F]);return s.jsxs(NE.Provider,{value:xe,children:[s.jsx(kE.Provider,{value:Rn,children:s.jsx(CE.Provider,{value:Bn,children:O})}),s.jsx("input",{...q.getValidationProps(F,{onFocus(){xe.state.triggerElement?.focus({focusVisible:!0})},onChange(gt){if(gt.nativeEvent.defaultPrevented||F||j)return;const jt=gt.currentTarget.value,wt=Fe(Yn,gt.nativeEvent);function Sr(){if(C)return;const rr=jt.toLowerCase();let Hr=ee.current.findIndex(rl=>ka(rl,R).toLowerCase()===rr||yo(rl,A).toLowerCase()===rr);Hr===-1&&(Hr=ee.current.findIndex((rl,rn)=>{const cc=ae.current[rn];return cc!=null&&cc.toLowerCase()===rr}));const jn=ee.current[Hr];jn!=null&&it(jn,wt)}xe.set("forceMount",!0),queueMicrotask(Sr)}}),id:Y&&as==null?`${Y}-hidden-input`:void 0,form:v,name:as,autoComplete:y,value:Ct,disabled:F,required:w&&!(C&&ds),readOnly:j,ref:Jt,style:G?Wc:Ai,tabIndex:-1,"aria-hidden":!0,suppressHydrationWarning:!0}),Tt]})}function IE(e,t){return e??t}const Ah=5;function PE(e,t){const a=QV(t);return e.clientX>=a.left-Ah&&e.clientX<=a.right+Ah&&e.clientY>=a.top-Ah&&e.clientY<=a.bottom+Ah}function QV(e){const t=e.getBoundingClientRect(),a=Sn(e);if(Pv)return t;const o=a.getComputedStyle(e,"::before"),c=a.getComputedStyle(e,"::after");if(!(o.content!=="none"||c.content!=="none"))return t;const f=parseFloat(o.width)||0,p=parseFloat(o.height)||0,g=parseFloat(c.width)||0,v=parseFloat(c.height)||0,y=Math.max(t.width,f,g),b=Math.max(t.height,p,v),j=y-t.width,w=b-t.height;return{left:t.left-j/2,right:t.right+j/2,top:t.top-w/2,bottom:t.bottom+w/2}}const ZV="data-popup-side",WV=400,JV={...Bv,...ji,popupSide:e=>e?{[ZV]:e}:null,value:()=>null},e6=x.forwardRef(function(t,a){const{render:o,className:c,id:d,disabled:f=!1,nativeButton:p=!0,style:g,...v}=t,{setTouched:y,setFocused:b,validationMode:j,validation:w,state:S,disabled:N}=Sa(),{labelId:k}=vl(),E=vo(),{readOnly:D,required:C,disabled:A}=Yy(),R=N||A||f,I=E.useState("open"),P=E.useState("mounted"),O=E.useState("value"),_=E.useState("triggerProps"),L=E.useState("positionerElement"),H=E.useState("listElement"),B=E.useState("popupSide"),z=E.useState("id"),Q=E.useState("labelId"),K=E.useState("hasSelectedValue"),X=P&&L?B:null,q=d??z,$=IE(k,Q);lo({id:d});const Y=Xn(L),F=x.useRef(null),{getButtonProps:G,buttonRef:W}=Jr({disabled:R,native:p}),le=E.useStateSetter("triggerElement"),M=Qs(),U=Qs(),Z=Qs();x.useEffect(()=>{if(I)return Z.start(WV,()=>{E.context.selectionRef.current.allowUnselectedMouseUp=!0,E.context.selectionRef.current.allowSelectedMouseUp=!0}),()=>{Z.clear()};E.context.selectionRef.current={allowSelectedMouseUp:!1,allowUnselectedMouseUp:!1,dragY:0},U.clear()},[I,E,U,Z]);const ae=Wr(_,{id:q,role:"combobox","aria-expanded":I,"aria-haspopup":"listbox","aria-controls":I?H?.id??Vm(L)?.id:void 0,"aria-labelledby":$,"aria-readonly":D||void 0,"aria-required":C||void 0,tabIndex:R?-1:0,onFocus(ie){b(!0),I&&E.context.alignItemWithTriggerActiveRef.current&&E.context.setOpen(!1,Fe(Yn,ie.nativeEvent)),M.start(0,()=>{E.set("forceMount",!0)})},onBlur(ie){Qe(L,ie.relatedTarget)||(y(!0),b(!1),j==="onBlur"&&w.commit(O))},onMouseDown(ie){if(I)return;const ge=$t(ie.currentTarget);function ee(fe){if(!F.current)return;const te=fe.target;Qe(F.current,te)||Qe(Y.current,te)||PE(fe,F.current)||E.context.setOpen(!1,Fe(y1,fe))}U.start(0,()=>{ge.addEventListener("mouseup",ee,{once:!0})})}},v,G),ce=w.getValidationProps(R,ae);ce.role="combobox";const J={...S,open:I,disabled:R,value:O,readOnly:D,popupSide:X,placeholder:!K};return vt("button",t,{ref:[a,F,W,le],state:J,stateAttributesMapping:JV,props:ce})}),t6={value:()=>null},n6=x.forwardRef(function(t,a){const{className:o,render:c,children:d,placeholder:f,style:p,...g}=t,v=vo(),y=v.useState("value"),b=v.useState("items"),j=v.useState("itemToStringLabel"),w=v.useState("hasSelectedValue"),S=!w&&f!=null&&d==null,N=v.useState("hasNullItemLabel",S),k={value:y,placeholder:!w};let E=null;return typeof d=="function"?E=d(y):d!=null?E=d:S&&!N?E=f:Array.isArray(y)?E=GV(y,b,j):E=ME(y,b,j),vt("span",t,{state:k,ref:[a,v.context.valueRef],props:[{children:E},g],stateAttributesMapping:t6})}),s6=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t,v={open:vo().useState("open")};return vt("span",t,{state:v,ref:a,props:[{"aria-hidden":!0,children:"▼"},f],stateAttributesMapping:zv})}),r6=x.forwardRef(function(t,a){const o=vo(),c=o.useState("mounted"),d=o.useState("forceMount");return c||d?s.jsx(sh,{ref:a,...t}):null}),_E=x.createContext(void 0);function a6(){const e=x.useContext(_E);if(!e)throw new Error(on(59));return e}function Rh(e,t){e&&Object.assign(e.style,t)}const l6={position:"relative",maxHeight:"100%",overflowX:"hidden",overflowY:"auto"},o6=20;function Qy(e,t,a,o){const[c,d]=x.useState(!1);De(()=>{if(!e||!t||a==null){d(!1);return}const f=$t(a).documentElement.clientWidth,p=a.offsetWidth;d(f>0&&p>0&&p>=f-o6)},[e,t,a]),iE(e&&(!t||c),o)}const i6={position:"fixed"},c6=x.forwardRef(function(t,a){const{anchor:o,className:c,render:d,positionMethod:f,side:p,align:g,sideOffset:v,alignOffset:y,collisionBoundary:b="clipping-ancestors",collisionPadding:j,arrowPadding:w,sticky:S,disableAnchorTracking:N,alignItemWithTrigger:k=!0,collisionAvoidance:E=V1,style:D,...C}=t,A=vo(),R=TE(),I=A.useState("open"),P=A.useState("mounted"),O=A.useState("modal"),_=A.useState("value"),L=A.useState("openMethod"),H=A.useState("positionerElement"),B=A.useState("triggerElement"),z=A.useState("isItemEqualToValue"),Q=A.useState("transitionStatus"),K=x.useRef(null),X=x.useRef(null),[q,$]=x.useState(k),Y=P&&q&&L!=="touch";!P&&q!==k&&$(k),x.useImperativeHandle(A.context.alignItemWithTriggerActiveRef,()=>Y),Qy((Y||O)&&I,L==="touch",H,B);const F=xh({anchor:o,floatingRootContext:R,positionMethod:f,mounted:P,side:p,sideOffset:v,align:g,alignOffset:y,arrowPadding:w,collisionBoundary:b,collisionPadding:j,sticky:S,disableAnchorTracking:N??Y,collisionAvoidance:E,keepMounted:!0}),G=Y?"none":F.side,W=Y?i6:F.positionerStyles,le={open:I,side:G,align:F.align,anchorHidden:F.anchorHidden};De(()=>{A.set("popupSide",F.side)},[A,F.side]);const M=A.useStateSetter("positionerElement"),U=bh(t,le,{styles:W,transitionStatus:Q,props:C,refs:[a,M],hidden:!P,inert:!I}),Z=x.useRef(0),ae=Ie(J=>{if(A.context.valuesRef.current.length===0)return;const ie=Z.current;Z.current=J.size;const ge=Fe(Yn);if(ie!==0&&!A.state.multiple&&_!==null&&ru(A.context.valuesRef.current,_,z)===-1){const fe=A.context.initialValueRef.current,Ce=fe!=null&&ru(A.context.valuesRef.current,fe,z)!==-1?fe:null;A.context.setValue(Ce,ge),Ce===null&&(A.set("selectedIndex",null),A.context.selectedItemTextRef.current=null)}if(ie!==0&&A.state.multiple&&Array.isArray(_)){const ee=_.filter(fe=>ru(A.context.valuesRef.current,fe,z)!==-1);ee.length!==_.length&&(A.context.setValue(ee,ge),ee.length===0&&(A.set("selectedIndex",null),A.context.selectedItemTextRef.current=null))}if(I&&Y){A.update({scrollUpArrowVisible:!1,scrollDownArrowVisible:!1});const ee={height:""};Rh(H,ee),Rh(A.context.popupRef.current,ee)}}),ce=x.useMemo(()=>({...F,side:G,alignItemWithTriggerActive:Y,setControlledAlignItemWithTrigger:$,scrollUpArrowRef:K,scrollDownArrowRef:X}),[F,G,Y,$]);return s.jsx(Ky,{elementsRef:A.context.listRef,labelsRef:A.context.labelsRef,onMapChange:ae,children:s.jsxs(_E.Provider,{value:ce,children:[P&&O&&s.jsx(wh,{inert:vh(!I),cutout:B}),U]})})}),Oh="base-ui-disable-scrollbar",LE={className:Oh,getElement(e){return s.jsx("style",{nonce:e,href:Oh,precedence:"base-ui:low",children:`.${Oh}{scrollbar-width:none}.${Oh}::-webkit-scrollbar{display:none}`})}},u6=x.createContext(void 0);function zE(e){return x.useContext(u6)}const d6=x.createContext(void 0),f6={disableStyleElements:!1};function p6(){return x.useContext(d6)??f6}const BE="--transform-origin",m6={...qc,...oo},h6=x.forwardRef(function(t,a){const{render:o,className:c,style:d,finalFocus:f,...p}=t,g=vo(),{multiple:v,readOnly:y,highlightItemOnHover:b}=Yy(),j=TE(),{side:w,align:S,alignItemWithTriggerActive:N,isPositioned:k,setControlledAlignItemWithTrigger:E}=a6(),D=zE()!=null,C=of(),{nonce:A,disableStyleElements:R}=p6(),I=g.useState("id"),P=g.useState("open"),O=g.useState("openMethod"),_=g.useState("mounted"),L=g.useState("popupProps"),H=g.useState("transitionStatus"),B=g.useState("triggerElement"),z=g.useState("positionerElement"),Q=g.useState("listElement"),K=x.useRef(!1),X=x.useRef(!1),q=x.useRef({}),$=Yc(),Y=Ie(le=>{if(!z||!g.context.popupRef.current||!X.current)return;const M=z.style.top==="0px",U=z.style.bottom==="0px";if(K.current||!N||!M&&!U){g.context.handleScrollArrowVisibility(le);return}const Z=UE(z),ae=df(z.getBoundingClientRect().height,"y",Z),ce=$t(z),J=Sn(z),ie=J.getComputedStyle(z),ge=parseFloat(ie.marginTop),ee=parseFloat(ie.marginBottom),fe=HE(J.getComputedStyle(g.context.popupRef.current)),te=Math.min(ce.documentElement.clientHeight-ge-ee,fe),Ce=le.scrollTop,re=Mh(le);let de=null;const ke=ye=>{z.style.height=`${ye}px`},Ee=M?re-Ce:Ce,ve=Math.min(ae+Ee,te);if(Ee<=Cl){const ye=Ri(Ee,0,te-ae);ye>0&&ke(ae+ye),le.scrollTop=M?re:0,te-(ae+ye)<=Cl&&(K.current=!0),g.context.handleScrollArrowVisibility(le);return}if(te-ve>Cl)de=M?1/0:0;else if(U&&CeCl&&(le.scrollTop=ye)}he>=te-Cl&&(K.current=!0),g.context.handleScrollArrowVisibility(le)});x.useImperativeHandle(g.context.scrollHandlerRef,()=>Y,[Y]),ra({open:P,ref:g.context.popupRef,onComplete(){P&&g.context.onOpenChangeComplete(!0)}});const F={open:P,transitionStatus:H,side:w,align:S};De(()=>{!z||!g.context.popupRef.current||Object.keys(q.current).length||(q.current={top:z.style.top||"0",left:z.style.left||"0",right:z.style.right,height:z.style.height,bottom:z.style.bottom,minHeight:z.style.minHeight,maxHeight:z.style.maxHeight,marginTop:z.style.marginTop,marginBottom:z.style.marginBottom})},[g,z]),De(()=>{P||N||(X.current=!1,K.current=!1,Rh(z,q.current))},[P,N,z]),De(()=>{const le=g.context.popupRef.current;if(!P||!B||!z||!le||N&&!k||g.state.transitionStatus==="ending")return;if(X.current=!0,le.style.removeProperty(BE),!N){$.request(()=>g.context.handleScrollArrowVisibility(Q||le));return}const M=g6(le);try{let U=g.context.selectedItemTextRef.current;U?.isConnected||(U=!g.select("hasSelectedValue")&&g.context.firstItemTextRef.current?.isConnected?g.context.firstItemTextRef.current:null);const Z=g.context.valueRef.current,ae=Sn(z),ce=ae.getComputedStyle(z),J=ae.getComputedStyle(le),ie=$t(B),ge=UE(B),ee=Dh(B.getBoundingClientRect(),ge),fe=Dh(z.getBoundingClientRect(),ge),te=ee.height,Ce=Q||le,re=Ce.scrollHeight,de=parseFloat(J.borderBottomWidth),ke=parseFloat(ce.marginTop)||10,Ee=parseFloat(ce.marginBottom)||10,ve=parseFloat(ce.minHeight)||100,he=HE(J),ye=5,we=5,xe=20,Te=ie.documentElement.clientHeight-ke-Ee,Oe=ie.documentElement.clientWidth,Ne=Te-ee.bottom+te;let _e,Ye=C==="rtl"?ee.right-fe.width:ee.left,kt=0;if(U&&Z){const tn=Dh(Z.getBoundingClientRect(),ge);_e=Dh(U.getBoundingClientRect(),ge),Ye=fe.left+(C==="rtl"?tn.right-_e.right:tn.left-_e.left);const nt=tn.top-ee.top+tn.height/2;kt=_e.top-fe.top+_e.height/2-nt}const Ct=Ne+kt+Ee+de;let Rt=Math.min(Te,Ct);const ot=Te-ke-Ee,qn=Ct-Rt,ds=Oe-we;z.style.left=`${Ri(Ye,ye,ds-fe.width)}px`,z.style.height=`${Rt}px`,z.style.maxHeight="none",z.style.marginTop=`${ke}px`,z.style.marginBottom=`${Ee}px`,le.style.height="100%";const Gn=Mh(Ce),xs=qn>=Gn-Cl;xs&&(Rt=Math.min(Te,fe.height)-(qn-Gn));const it=ee.topTe-xe||Math.ceil(Rt)+Cl=ot?"0":`${tn}px`,z.style.height=`${Rt}px`,Ce.scrollTop=Mh(Ce)}else z.style.bottom="0",Ce.scrollTop=qn;if(_e){const tn=fe.top,nt=fe.height,Ot=_e.top+_e.height/2,Ft=Ri(nt>0?(Ot-tn)/nt*100:50,0,100);le.style.setProperty(BE,`50% ${Ft}%`)}(Bn===Te||Rt>=he)&&(K.current=!0),g.context.handleScrollArrowVisibility(Ce),b&&g.state.selectedIndex===null&&g.state.activeIndex===null&&g.context.listRef.current[0]!=null&&g.set("activeIndex",0)}finally{M()}},[g,P,z,B,N,E,$,Q,b,C,k]),x.useEffect(()=>{if(!N||!z||!P)return;const le=Sn(z);function M(U){g.context.setOpen(!1,Fe(oB,U))}return St(le,"resize",M)},[g,N,z,P]);const G={...Q?{role:"presentation"}:{role:"listbox","aria-multiselectable":v||void 0,"aria-readonly":y||void 0,id:`${I}-list`},onKeyDown(le){D&&yh.has(le.key)&&le.stopPropagation()},onScroll(le){Q||Y(le.currentTarget)},...N&&{style:Q?{height:"100%"}:l6},className:!Q&&N?LE.className:void 0},W=vt("div",t,{ref:[a,g.context.popupRef],state:F,stateAttributesMapping:m6,props:[L,G,cf(H),p]});return s.jsxs(x.Fragment,{children:[!R&&LE.getElement(A),s.jsx(rh,{context:j,modal:!1,disabled:!_,openInteractionType:O,returnFocus:f,restoreFocus:!0,children:W})]})});function HE(e){const t=e.maxHeight;return t.endsWith("px")&&parseFloat(t)||1/0}function Mh(e){return DE(e.scrollHeight,e.clientHeight)}function UE(e){return cT.getScale(e)}function df(e,t,a){return e/a[t]}function Dh(e,t){return Yd({x:df(e.x,"x",t),y:df(e.y,"y",t),width:df(e.width,"x",t),height:df(e.height,"y",t)})}const VE=[["transform","none"],["scale","1"],["translate","0 0"]];function g6(e){const{style:t}=e,a={};for(const[o,c]of VE)a[o]=t.getPropertyValue(o),t.setProperty(o,c,"important");return()=>{for(const[o]of VE){const c=a[o];c?t.setProperty(o,c):t.removeProperty(o)}}}const FE=x.createContext(void 0);function Zy(){const e=x.useContext(FE);if(!e)throw new Error(on(57));return e}const x6=x.memo(x.forwardRef(function(t,a){const{render:o,className:c,style:d,value:f=null,label:p,disabled:g=!1,nativeButton:v=!1,...y}=t,b=x.useRef(null),j=Gy({guess:!0,label:p,textRef:b}),w=vo(),{itemProps:S,multiple:N,disabled:k,readOnly:E}=Yy(),D=k||g,C=w.useState("isActive",j.index),A=w.useState("open"),R=w.useState("isSelected",f),I=w.useState("isSelectedByFocus",j.index),P=w.useState("isItemEqualToValue"),O=j.index,_=x.useRef(null);De(()=>{const F=w.context.valuesRef.current;return F[O]=f,()=>{delete F[O]}},[O,f,w]),De(()=>{const F=w.state.value,G=w.state.selectedIndex;let W=G,le;N&&Array.isArray(F)?(W=AE(O,f,w.context.valuesRef.current,F,P,G),le=W===O,O===G&&!le&&(w.context.selectedItemTextRef.current=null)):(le=F!==void 0&&la(f,F,P),le&&(W=O)),w.set("selectedIndex",W),le&&b.current&&(w.context.selectedItemTextRef.current=b.current)},[O,N,P,w,f]);const L=x.useRef("mouse"),H=x.useRef(!1),{getButtonProps:B,buttonRef:z}=Jr({disabled:D,focusableWhenDisabled:!0,native:v,composite:!0}),Q={disabled:D,selected:R,highlighted:C};function K(F){if(k||E)return;const G=w.state.value;if(N){const W=Array.isArray(G)?G:[],le=R?RE(W,f,P):[...W,f];w.context.setValue(le,Fe(Zd,F))}else w.context.setValue(f,Fe(Zd,F)),w.context.setOpen(!1,Fe(Zd,F))}function X(){w.context.selectionRef.current.dragY=0}const q={role:"option","aria-selected":R,tabIndex:A&&C?0:-1,onKeyDown(F){w.set("activeIndex",O),F.key===" "&&w.context.typingRef.current&&F.preventDefault()},onClick(F){const G=L.current!=="touch",W=F.nativeEvent.pointerType,le=G&&Fm(F.nativeEvent)&&(W!==void 0||C),M=G&&!le&&!H.current;H.current=!1,!(D||M)&&K(F.nativeEvent)},onPointerEnter(F){L.current=F.pointerType},onPointerMove(F){if(F.pointerType==="mouse"&&F.buttons===1){const G=w.context.selectionRef.current;G.dragY+=F.movementY,G.dragY**2>=64&&(G.allowUnselectedMouseUp=!0)}},onPointerDown(F){L.current=F.pointerType,H.current=!0,X()},onMouseUp(){if(X(),D||L.current==="touch"||H.current)return;const F=!w.context.selectionRef.current.allowSelectedMouseUp&&R,G=!w.context.selectionRef.current.allowUnselectedMouseUp&&!R;F||G||(H.current=!0,_.current?.click(),H.current=!1)}},$=vt("div",t,{ref:[z,a,j.ref,_],state:Q,props:[S,q,y,B]}),Y=x.useMemo(()=>({selected:R,index:O,textRef:b,selectedByFocus:I}),[R,O,b,I]);return s.jsx(FE.Provider,{value:Y,children:$})})),b6=x.forwardRef(function(t,a){const{selected:o}=Zy();return t.keepMounted||o?s.jsx(v6,{...t,ref:a}):null}),v6=x.memo(x.forwardRef((e,t)=>{const{render:a,className:o,style:c,keepMounted:d,...f}=e,{selected:p}=Zy(),g=x.useRef(null),{transitionStatus:v,setMounted:y}=ki(p),j=vt("span",e,{ref:[t,g],state:{selected:p,transitionStatus:v},props:[{"aria-hidden":!0,children:"✔️"},f],stateAttributesMapping:oo});return ra({batch:!0,enabled:!p,open:p,ref:g,onComplete(){p||y(!1)}}),j})),y6=x.memo(x.forwardRef(function(t,a){const{index:o,textRef:c,selectedByFocus:d}=Zy(),f=vo(),{render:p,className:g,style:v,...y}=t,b=x.useCallback(w=>{w&&(o===0&&(f.context.firstItemTextRef.current=w),d&&(f.context.selectedItemTextRef.current=w))},[f,o,d]);return vt("div",t,{ref:[b,a,c],props:y})})),ft=XV,pt=n6;function mt({className:e,children:t,...a}){return s.jsxs(e6,{"data-slot":"select-trigger",className:Ue("inline-flex h-[30px] min-w-0 cursor-pointer items-center justify-between gap-1.5 rounded-md border border-control-border bg-control px-2.5","[&>span]:min-w-0 [&>span]:truncate","text-[12.5px] font-normal text-foreground","transition-colors duration-150 ease-out","hover:border-control-border-hover hover:bg-control-hover","focus-visible:border-primary focus-visible:shadow-focus focus-visible:outline-none","data-disabled:cursor-not-allowed data-disabled:bg-control data-disabled:text-muted-foreground data-disabled:opacity-60",e),...a,children:[t,s.jsx(s6,{className:"flex flex-none text-muted-foreground transition-transform duration-[180ms] data-popup-open:rotate-180",children:s.jsx("svg",{viewBox:"0 0 10 6",className:"size-2.5","aria-hidden":"true",children:s.jsx("path",{d:"M1 1l4 4 4-4",stroke:"currentColor",strokeWidth:"1.4",fill:"none",strokeLinecap:"round",strokeLinejoin:"round"})})})]})}function ht({className:e,sideOffset:t=4,children:a,...o}){return s.jsx(r6,{children:s.jsx(c6,{sideOffset:t,alignItemWithTrigger:!1,className:"z-[35]",children:s.jsx(h6,{"data-slot":"select-content",className:Ue("max-h-[260px] min-w-[var(--anchor-width)] overflow-y-auto overscroll-contain rounded-lg border border-border-strong bg-raised p-[5px] shadow-3","outline-none","data-open:animate-in data-open:fade-in-0","data-closed:animate-out data-closed:fade-out-0",e),...o,children:a})})})}function qe({className:e,children:t,...a}){return s.jsxs(x6,{"data-slot":"select-item",className:Ue("flex min-h-7 cursor-pointer items-center gap-2 rounded-sm px-[9px] text-[12.5px] leading-[1.4] text-foreground select-none","transition-colors duration-[120ms] ease-out","data-[highlighted]:bg-nav-hover","data-[selected]:bg-primary-soft data-[selected]:font-semibold data-[selected]:text-primary-fg","data-[highlighted]:data-[selected]:bg-primary-tint","data-disabled:pointer-events-none data-disabled:font-normal data-disabled:text-muted-foreground",e),...a,children:[s.jsx(y6,{className:"min-w-0 flex-1 truncate",children:t}),s.jsx(b6,{className:"flex flex-none text-primary",children:s.jsx("svg",{viewBox:"0 0 12 12",className:"size-3","aria-hidden":"true",children:s.jsx("path",{d:"M2.5 6.2 4.8 8.5 9.5 3.8",stroke:"currentColor",strokeWidth:"1.8",fill:"none",strokeLinecap:"round",strokeLinejoin:"round"})})})]})}function In({options:e,value:t,onValueChange:a,disabled:o=!1,className:c,...d}){const f=x.useRef(null),p=x.useRef(new Map),[g,v]=x.useState({left:0,width:0,ready:!1}),[y,b]=x.useState(!1),j=x.useCallback(()=>{const w=f.current,S=p.current.get(t);if(!w||!S){v(C=>C.ready?{...C,ready:!1}:C);return}const N=w.getBoundingClientRect(),k=S.getBoundingClientRect(),E=k.left-N.left-w.clientLeft,D=k.width;v(C=>C.ready&&C.left===E&&C.width===D?C:{left:E,width:D,ready:!0})},[t]);return x.useLayoutEffect(()=>{j();const w=f.current;if(!w||typeof ResizeObserver>"u")return;const S=new ResizeObserver(()=>j());S.observe(w);for(const N of p.current.values())S.observe(N);return()=>S.disconnect()},[j,e]),x.useEffect(()=>{if(!g.ready||y)return;const w=requestAnimationFrame(()=>b(!0));return()=>cancelAnimationFrame(w)},[g.ready,y]),s.jsxs(wE,{ref:f,"data-slot":"segmented-control",className:Ue("relative inline-flex gap-0.5 rounded-md border border-control-border bg-control p-0.5",c),value:t,disabled:o,onValueChange:w=>a(w),...d,children:[s.jsx("span",{"aria-hidden":"true","data-slot":"segmented-thumb","data-ready":g.ready?"true":"false","data-animate":y?"true":"false",className:Ue("pointer-events-none absolute top-0.5 bottom-0.5 left-0 rounded-sm bg-primary-soft","data-[ready=false]:opacity-0","data-[animate=true]:transition-[transform,width] data-[animate=true]:duration-200 data-[animate=true]:ease-in-out"),style:{transform:`translateX(${g.left}px)`,width:g.width}}),e.map(w=>s.jsxs(vE,{value:w.value,"data-slot":"segmented-item",disabled:w.disabled,"data-zero":w.count===0?"true":void 0,className:Ue("group/seg relative z-[1] inline-flex h-6 items-center gap-[5px] rounded-sm border-0 bg-transparent px-2.5","text-xs font-medium whitespace-nowrap text-subtle select-none","transition-[background-color,color] duration-150 ease-out","hover:bg-nav-hover hover:text-foreground","data-checked:bg-transparent data-checked:text-primary-fg data-checked:hover:bg-transparent","data-disabled:cursor-not-allowed data-disabled:opacity-40","data-[zero=true]:data-unchecked:opacity-45"),ref:S=>{S?p.current.set(w.value,S):p.current.delete(w.value)},children:[w.label,w.count!==void 0&&s.jsx("span",{className:Ue("min-w-4 rounded-pill bg-surface-3 px-[5px] text-center text-[10.5px] font-semibold tabular-nums text-muted-foreground","group-data-checked/seg:bg-primary-tint group-data-checked/seg:text-primary-fg"),children:w.count})]},w.value))]})}const j6=x.createContext(void 0);function w6(){return x.useContext(j6)}const S6=x.forwardRef(function(t,a){const{className:o,defaultPressed:c=!1,disabled:d=!1,form:f,onPressedChange:p,pressed:g,render:v,type:y,value:b,nativeButton:j=!0,style:w,...S}=t,N=Na(b||void 0),k=w6(),E=k?.value??[],D=(d||k?.disabled)??!1,[C,A]=qa({controlled:k?N!==void 0&&E.indexOf(N)>-1:g,default:c,name:"Toggle",state:"pressed"}),{getButtonProps:R,buttonRef:I}=Jr({disabled:D,native:j}),P={disabled:D,pressed:C},O=[I,a],_=[{"aria-pressed":C,onClick(B){const z=!C,Q=Fe(Yn,B.nativeEvent);p?.(z,Q),!Q.isCanceled&&(N&&k?.setGroupValue?.(N,z,Q),!Q.isCanceled&&A(z))}},S,R],L=vt("button",t,{enabled:!k,state:P,ref:O,props:_}),H=x.useMemo(()=>({disabled:D,focusableWhenDisabled:!1}),[D]);return k?s.jsx(gE,{tag:"button",render:v,className:o,style:w,metadata:H,state:P,refs:O,props:_}):L}),N6=Fc(["inline-flex shrink-0 cursor-pointer items-center justify-center gap-1.5 whitespace-nowrap border","font-medium transition-[background-color,border-color,color] duration-150 ease-out","outline-none select-none disabled:pointer-events-none disabled:opacity-45","[&_svg]:pointer-events-none [&_svg]:shrink-0","data-pressed:border-primary-bd data-pressed:bg-primary-soft data-pressed:font-semibold data-pressed:text-primary-fg","data-pressed:hover:bg-primary-tint"],{variants:{variant:{default:"border-transparent bg-transparent text-subtle hover:bg-nav-hover hover:text-foreground",outline:"border-control-border bg-control text-foreground shadow-1 hover:border-control-border-hover hover:bg-control-hover"},size:{default:"h-[30px] rounded-md px-3 text-[12.5px]",xs:"h-6 rounded-sm px-2 text-[11.5px]",sm:"h-[26px] rounded-sm px-2.5 text-[12px]",lg:"h-9 rounded-md px-4 text-[13px]"}},defaultVariants:{variant:"default",size:"default"}});function k6({className:e,variant:t,size:a,...o}){return s.jsx(S6,{"data-slot":"toggle",className:Ue(N6({variant:t,size:a}),e),...o})}function C6(e,t,a,o,c,d,f,p,g,v=2){const y=$4(a.current,{event:e,orientation:o,loopFocus:c,rtl:d,cols:v,disabledIndices:f,minIndex:p,maxIndex:g,prevIndex:t>g?p:t,stopEvent:!0});return fo(a.current,y)?void 0:y}const $E=x.createContext(void 0),qE=x.createContext(void 0),GE=x.createContext(void 0),KE=x.createContext(!1),YE=x.createContext("");function Ca(){const e=x.useContext($E);if(!e)throw new Error(on(22));return e}function Ih(){const e=x.useContext(qE);if(!e)throw new Error(on(23));return e}function ff(){const e=x.useContext(GE);if(!e)throw new Error(on(24));return e}function XE(){return x.useContext(YE)}function T6(){return x.useContext(KE)}const E6={id:e=>e.id,labelId:e=>e.labelId,items:e=>e.items,selectedValue:e=>e.selectedValue,hasSelectionChips:e=>{const t=e.selectedValue;return Array.isArray(t)&&t.length>0},hasSelectedValue:e=>{const{selectedValue:t,selectionMode:a}=e;return t==null?!1:a==="multiple"&&Array.isArray(t)?t.length>0:!0},hasNullItemLabel:(e,t)=>t?OE(e.items):!1,open:e=>e.open,mounted:e=>e.mounted,forceMounted:e=>e.forceMounted,inline:e=>e.inline,activeIndex:e=>e.activeIndex,selectedIndex:e=>e.selectedIndex,isActive:(e,t)=>e.activeIndex===t,isSelected:(e,t)=>{const a=e.isItemEqualToValue,o=e.selectedValue;return Array.isArray(o)?o.some(c=>la(t,c,a)):la(t,o,a)},transitionStatus:e=>e.transitionStatus,popupProps:e=>e.popupProps,listProps:e=>e.listProps,inputProps:e=>e.inputProps,triggerProps:e=>e.triggerProps,itemProps:e=>e.itemProps,positionerElement:e=>e.positionerElement,listElement:e=>e.listElement,popupId:e=>e.popupId,triggerElement:e=>e.triggerElement,inputElement:e=>e.inputElement,inputGroupElement:e=>e.inputGroupElement,popupSide:e=>e.popupSide,openMethod:e=>e.openMethod,inputInsidePopup:e=>e.inputInsidePopup,inputOwnsFormValue:e=>e.inputOwnsFormValue,selectionMode:e=>e.selectionMode,name:e=>e.name,form:e=>e.form,disabled:e=>e.disabled,readOnly:e=>e.readOnly,required:e=>e.required,grid:e=>e.grid,virtualized:e=>e.virtualized,itemToStringLabel:e=>e.itemToStringLabel,isItemEqualToValue:e=>e.isItemEqualToValue,modal:e=>e.modal,autoHighlight:e=>e.autoHighlight};function QE(e){return e==null?void 0:`${e}-popup`}function A6(e,t){return(a,o)=>a==null?!1:e.contains(a,o,t)}const ZE=new Map;function R6(e={}){const t={usage:"search",sensitivity:"base",ignorePunctuation:!0,...e},a=`${ly(e.locale)}|${JSON.stringify(t)}`,o=ZE.get(a);if(o)return o;const c=new Intl.Collator(e.locale,t),d={contains(f,p,g){if(!p)return!0;const v=yo(f,g);for(let y=0;y<=v.length-p.length;y+=1)if(c.compare(v.slice(y,y+p.length),p)===0)return!0;return!1},startsWith(f,p,g){if(!p)return!0;const v=yo(f,g);return c.compare(v.slice(0,p.length),p)===0},endsWith(f,p,g){if(!p)return!0;const v=yo(f,g),y=p.length;return v.length>=y&&c.compare(v.slice(v.length-y),p)===0}};return ZE.set(a,d),d}const O6=R6;function M6(e,t=!1){const{overflowY:a}=xr(e);return a!=="auto"&&a!=="scroll"?!1:t?e.clientHeight>0:e.scrollHeight>e.clientHeight}const WE=Symbol("none"),Wy={value:WE,index:-1};function D6(e,t,a){const o=e.get(t);if(o!==void 0||a===Ch)return o;for(const[c,d]of e)if(la(c,t,a))return d}function I6(e){const{id:t,onOpenChangeComplete:a,defaultSelectedValue:o=null,selectedValue:c,onSelectedValueChange:d,defaultInputValue:f,inputValue:p,open:g,defaultOpen:v=!1,selectionMode:y,onItemHighlighted:b,name:j,form:w,disabled:S=!1,readOnly:N=!1,required:k=!1,inputRef:E,grid:D=!1,items:C,filteredItems:A,filter:R,filterQuery:I,openOnInputClick:P=!0,autoHighlight:O=!1,keepHighlight:_=!1,highlightItemOnHover:L=!0,loopFocus:H=!0,itemToStringLabel:B,itemToStringValue:z,isItemEqualToValue:Q=Ch,virtualized:K=!1,inline:X=!1,fillInputOnItemPress:q=!0,modal:$=!1,limit:Y=-1,autoComplete:F="list",formAutoComplete:G,locale:W,submitOnItemClick:le=!1}=e,{clearErrors:M}=$c(),{setDirty:U,validityData:Z,setFilled:ae,name:ce,disabled:J,setTouched:ie,setFocused:ge,validationMode:ee,validation:fe}=Sa(),te=of(),Ce=lo({id:t}),re=O6({locale:W}),de=Array.isArray(C)?null:C;if(de&&typeof de.label!="function")throw new Error(on(100));const ke=de?de.data:C,Ee=de?.value,ve=Ee?void 0:ke,he=x.useMemo(()=>{if(!A||!Ee)return;const Me=Eh(A),Be=Me.map(Ee);let lt;return{values:Be,findItem(Yt,On){if(!lt){lt=new Map;for(let mn=0;mnde?Me=>de.label(Me,Q,Be=>{const lt=he?.findItem(Be,Q);return lt!=null?de.itemLabel(lt):yo(Be,B)}):B,[de,B,he,Q]),we=x.useMemo(()=>de?Object.assign(Me=>de.itemLabel(Me),{selected:Me=>yo(Me,ye)}):B,[de,ye,B]);function xe(Me){return yo(Me,ye)}const[Te,Oe]=x.useState(!1),[Ne,_e]=x.useState(null),Ye=x.useRef(Ne),kt=x.useRef([]),Ct=x.useRef([]),Rt=x.useRef(null),ot=x.useRef(null),qn=x.useRef(null),ds=x.useRef(null),Gn=x.useRef(null),xs=x.useRef(!0),it=x.useRef(!1),Vt=x.useRef(null),Bn=x.useRef(null),tn=x.useRef(null),nt=x.useRef(Wy),Ot=x.useRef(null),Ft=x.useRef([]),Zn=x.useRef(null),Hn=J||S,Un=ce??j,Rn=y==="multiple",Jt=y==="single",as=p!==void 0||f!==void 0,Tt=ke!==void 0,gt=A!==void 0;let jt;O==="always"?jt="always":jt=O?"input-change":!1;const[wt,Sr]=qa({controlled:c,default:Rn?o??Rr:o,name:"Combobox",state:"selectedValue"}),rr=x.useMemo(()=>R===null?()=>!0:R!==void 0?R:A6(re,we),[R,re,we]),Hr=Ms(()=>as?f??"":Jt?xe(wt):"").current,[jn,rl]=qa({controlled:p,default:Hr,name:"Combobox",state:"inputValue"}),[rn,cc]=qa({controlled:g,default:v,name:"Combobox",state:"open"}),Yx=Xy(ke),dr=!rn&&Ne!==null?Ne:String(jn).trim(),Da=Jt?xe(wt):"",Ho=Jt&&!Te&&dr!==""&&Da.length===dr.length&&re.contains(Da,dr),Uo=Ho?"":I??dr,Dp=Tt&>&&Ho&&(!de||de.hasValue(wt,Q)),uc=x.useMemo(()=>ke?Eh(ke):Rr,[ke]),Vo=x.useMemo(()=>{if(A&&!Dp)return A;if(!ke)return Rr;if(Yx){const Be=ke,lt=[];let Yt=0;for(const On of Be){if(Y>-1&&Yt>=Y)break;const mn=Y>-1?Y-Yt:1/0,Mn=Uo===""?On.items.slice(0,mn):[];if(Uo!=="")for(const fs of On.items){if(Mn.length>=mn)break;rr(fs,Uo,we)&&Mn.push(fs)}if(Mn.length>0){const fs={...On,items:Mn};lt.push(fs),Yt+=Mn.length}}return lt}if(Uo==="")return Y>-1?uc.slice(0,Y):uc;const Me=[];for(const Be of uc){if(Y>-1&&Me.length>=Y)break;rr(Be,Uo,we)&&Me.push(Be)}return Me},[A,Dp,ke,Yx,Uo,Y,rr,we,uc]),Es=x.useMemo(()=>{if(he&&Vo===A)return he.values;const Me=Eh(Vo);return Ee?Me.map(Be=>Ee(Be)):Me},[Vo,A,he,Ee]),et=Ms(()=>{let Me=null;return X&&rn&&Tt&&y!=="none"&&(Me=uf(Es,wt,Q,Rn)),new nu({id:Ce,labelId:void 0,selectedValue:wt,open:rn,items:ve,selectionMode:y,name:Un,form:w,disabled:Hn,readOnly:N,required:k,grid:D,virtualized:K,openOnInputClick:P,itemToStringLabel:ye,isItemEqualToValue:Q,modal:$,autoHighlight:jt,submitOnItemClick:le,hasInputValue:as,mounted:!1,forceMounted:!1,transitionStatus:"idle",inline:X,activeIndex:null,selectedIndex:Me,popupProps:{},listProps:{},inputProps:{},triggerProps:{},itemProps:fn,positionerElement:null,listElement:null,popupId:void 0,triggerElement:null,inputElement:null,inputGroupElement:null,popupSide:null,openMethod:null,inputInsidePopup:!0,inputOwnsFormValue:y==="none"},{onOpenChangeComplete:qt,setOpen:qt,setInputValue:qt,setSelectedValue:qt,setIndices:qt,handleSelection:qt,forceMount:qt,requestSubmit:qt,listRef:kt,labelsRef:Ct,popupRef:Rt,emptyRef:Gn,inputRef:ot,startDismissRef:qn,endDismissRef:ds,keyboardActiveRef:xs,chipsContainerRef:Vt,clearRef:Bn,valuesRef:Ft,pointerDownItemRef:Zn,selectionEventRef:tn},E6)}).current,_l=y==="none"?jn:wt,Xx=x.useMemo(()=>y==="none"?_l:Array.isArray(wt)?wt.map(Me=>ka(Me,z)):ka(wt,z),[_l,z,y,wt]),Ia=Ie(b),As=Ie(a),$s=et.useState("activeIndex"),Fo=et.useState("selectedIndex"),dc=et.useState("positionerElement"),Qx=et.useState("listElement"),fc=et.useState("triggerElement"),pc=et.useState("inputElement"),mc=et.useState("inputGroupElement"),Rs=et.useState("inline"),ar=et.useState("inputInsidePopup"),Ll=et.useState("inputOwnsFormValue"),zl=Jt&&!ar&&jn===Da,hc=Xn(fc),{mounted:$o,setMounted:bs,transitionStatus:Ip}=ki(rn),{openMethod:Zx,triggerProps:Pp}=fE(rn),Bl=Ie(()=>Xx);Xc(ar?hc:ot,Ce,_l,Bl,!Hn,j);const Hl=Ie(()=>{ke?Ct.current=Es.map(xe):et.set("forceMounted",!0)}),qo=Ie((Me,Be,lt)=>{if(Be===-1){if(nt.current===Wy)return;nt.current=Wy}else nt.current={value:Me,index:Be};Ia(Me,iB(lt,void 0,{index:Be}))}),Ur=Ie(Me=>{const Be={};Me.activeIndex!==void 0&&(Be.activeIndex=Me.activeIndex),Me.selectedIndex!==void 0&&(Be.selectedIndex=Me.selectedIndex),et.update(Be);const lt=Me.activeIndex;if(lt===void 0)return;const Yt=Me.type||Yn;lt===null?qo(void 0,-1,Yt):qo(Ft.current[lt],lt,Yt)}),Vr=Ie((Me,Be)=>{if(e.onInputValueChange?.(Me,Be),!Be.isCanceled){if(it.current=Be.reason===Ga,Be.reason===Wd){rn&&Ne!==null&&_e(null);const lt=Be.event,Yt=lt.inputType;if(lt.type==="compositionend"||Yt!=null&&Yt!==""&&Yt!=="insertReplacementText"){const mn=Me.trim()!=="";mn&&Oe(!0),Ot.current={hasQuery:mn};const Mn=et.state.listElement;if(!et.state.virtualized&&Mn){const fs=Rt.current;for(const Nr of Uc(Mn.firstElementChild??Mn)){if(!dn(Nr)||(fs?!Qe(fs,Nr):Nr.getAttribute("role")==="dialog"))break;if(M6(Nr)){Nr.scrollTop=0;break}}}mn&&jt&&et.state.activeIndex==null&&(rn||Rs)&&et.set("activeIndex",0)}}else Be.reason===Ga&&Me===""&&et.state.inputInsidePopup&&(Ot.current={hasQuery:!1,selection:!0});rl(Me)}}),Wx=Ie(Me=>{const Be=!Me&&ar&&!Rs&&jn!==""&&(String(jn).trim()===Ne||jn===Da);!Me&&(Be||jn===""||zl)&&Oe(!1),_e(null),Be&&Vr("",Fe(Ga))}),Mt=Ie((Me,Be)=>{if(rn!==Me&&(Be.reason===Qc&&Tt&&Es.length===0&&!Gn.current&&Be.allowPropagation(),e.onOpenChange?.(Me,Be),!Be.isCanceled&&(Me&&Ne!==null&&Wx(Be.reason===Wd),!Me&&Te&&(Jt?(Rs||_e(dr),dr===""&&Oe(!1)):Rn&&(Rs||_e(dr),ar&&Ur({activeIndex:null}),(!ar||Rs)&&Vr("",Fe(Ga,Be.event,void 0,{isItemPress:Be.reason===Zd})))),cc(Me),!Me&&ar&&(Be.reason===ho||Be.reason===Jm)&&(ie(!0),ge(!1),ee==="onBlur")))){const lt=y==="none"?jn:wt;fe.commit(lt)}}),gc=Ie((Me,Be)=>{if(d?.(Me,Be),Be.isCanceled)return;Sr(Me),(y==="none"&&Rt.current&&q||Jt&&!et.state.inputInsidePopup)&&Vr(xe(Me),Fe(Be.reason,Be.event))}),Ju=Ie((Me,Be)=>{const lt=is(Me),Yt=tn.current??Me;tn.current=null;const On=Fe(Zd,Yt),mn=lt?.closest("a")?.getAttribute("href");if(mn){mn.startsWith("#")&&Mt(!1,On);return}if(Rn){const Mn=Array.isArray(wt)?wt:[],fs=Th(Mn,Be,Q),Nr=fs?RE(Mn,Be,Q):[...Mn,Be];if(gc(Nr,On),On.isCanceled||!(ot.current?ot.current.value.trim()!=="":!1))return;if(et.state.inputInsidePopup){Vr("",Fe(Ga,On.event,void 0,{isItemPress:!0}));const $r=Ot.current;$r&&!fs&&($r.toggledValue=Be)}else Mt(!1,On)}else{if(gc(Be,On),On.isCanceled)return;Mt(!1,On)}}),ed=Ie(()=>{const Me=fe.inputRef.current?.form??et.state.inputElement?.form;Me&&typeof Me.requestSubmit=="function"&&Me.requestSubmit()}),Fr=Ie(()=>{if(bs(!1),As?.(!1),Oe(!1),_e(null),Ur(y==="none"?{activeIndex:null,selectedIndex:null}:{activeIndex:null}),Rn&&ot.current&&ot.current.value!==""&&!it.current&&Vr("",Fe(Ga)),Jt)if(et.state.inputInsidePopup)ot.current&&ot.current.value!==""&&Vr("",Fe(Ga));else{const Me=xe(wt);ot.current&&ot.current.value!==Me&&Vr(Me,Fe(Me===""?Ga:Yn))}}),fr=x.useMemo(()=>Rs&&dc?{current:dc.closest('[role="dialog"]')}:Rt,[Rs,dc]);ra({enabled:!e.actionsRef,open:rn,ref:fr,onComplete(){rn||Fr()}}),x.useImperativeHandle(e.actionsRef,()=>({unmount:Fr}),[Fr]),De(function(){const Be=Ye.current!==null&&Ne===null;if(Ye.current=Ne,rn&&(!Be||!Tt)||(rn||(Zn.current=null),y==="none"))return;const lt=Tt?Es:Ft.current;Ur({selectedIndex:uf(lt,wt,Q,Rn)})},[rn,Ne,wt,y,Rn,Tt,Es,Q,Ur]),De(()=>{ke&&(Ft.current=Es,kt.current.length=Es.length)},[ke,Es]),De(()=>{const Me=Ot.current;if(Me){const fs=rn||Rs||et.state.positionerElement?.hidden===!1;if(Me.hasQuery)jt&&fs&&et.set("activeIndex",0),Ot.current=null;else if(String(jn).trim()===""&&(Ot.current=null,fs)){const Nr=Me.selection;jt==="always"&&!Nr&&et.state.selectionMode==="none"&&et.set("activeIndex",0),queueMicrotask(()=>{if(!et.state.open&&!et.state.inline||ot.current&&ot.current.value.trim()!=="")return;const ma=et.state.selectedValue,$r=et.state.selectionMode==="multiple";if($r&&Array.isArray(ma)?ma.length>0:et.state.selectionMode!=="none"&&ma!=null){const Ps=Tt||gt?Es:Ft.current,_a=ru(Ps,Me.toggledValue,et.state.isItemEqualToValue);et.set("activeIndex",_a!==-1?_a:uf(Ps,ma,et.state.isItemEqualToValue,$r))}else Nr?et.set("activeIndex",null):jt==="always"&&et.set("activeIndex",0)})}}if(!rn&&!Rs)return;const lt=Tt||gt?Es:Ft.current,Yt=et.state.activeIndex;if(Yt==null){if(jt==="always"&<.length>0){et.set("activeIndex",0);return}qo(void 0,-1,Yn);return}if(Yt>=lt.length){qo(void 0,-1,Yn),et.set("activeIndex",null);return}const On=lt[Yt],mn=nt.current.value,Mn=mn!==WE&&la(On,mn,et.state.isItemEqualToValue);(nt.current.index!==Yt||!Mn)&&qo(On,Yt,Yn)},[$s,jt,qo,gt,Tt,Es,Rs,rn,et,jn]),De(()=>{if(y==="none"){ae(String(jn)!=="");return}ae(Rn?Array.isArray(wt)&&wt.length>0:wt!=null)},[ae,y,jn,wt,Rn]),x.useEffect(()=>{Tt&&jt&&Es.length===0&&Ur({activeIndex:null})},[Tt,jt,Es.length,Ur]);function Jx(){rn&&dr!==""&&dr!==String(Hr)&&!zl&&Oe(!0)}function _S(){rn&&Ne!==null&&Wx(!1)}let td=!1;function _p(){!td&&jn!==Da&&(td=!0,Vr(Da,Fe(Yn)))}function LS(){y!=="none"&&(M(Un),U(EE(wt,Z.initialValue,Q)),fe.change(wt),Jt&&!as&&!ar&&_p())}function pr(){Jt&&!as&&!ar&&!Te&&_p()}function Lp(){y==="none"&&(M(Un),U(jn!==Z.initialValue),fe.change(jn))}aa(dr,Jx),aa(rn,_S),aa(wt,LS),aa(Da,pr),aa(ke,pr),aa(jn,Lp);const xc=ET({open:Rs?!0:rn,onOpenChange:Mt,elements:{reference:ar?fc:pc,floating:dc}}),nd=D?"grid":"listbox",Pa=rn||Rs,zp=Pa?"true":"false",bc=x.useMemo(()=>{const Me=pc?.tagName==="INPUT",Be=pc==null||Me,lt=Be||Pa,Yt=Be?{autoComplete:"off",spellCheck:"false",autoCorrect:"off",autoCapitalize:"none"}:{};return lt&&(Yt.role="combobox",Yt["aria-expanded"]=zp,Yt["aria-haspopup"]=nd,Yt["aria-controls"]=Pa?Qx?.id:void 0,Yt["aria-autocomplete"]=N?"none":F),{reference:Yt,floating:{role:"presentation"}}},[pc,Pa,zp,nd,Qx?.id,F,N]),Ul=ah(xc,{enabled:!Hn&&P,event:"mousedown-only",toggle:!1,touchOpenDelay:ar?0:100,reason:aB}),sd=rf(xc,{enabled:!Hn&&!Rs,outsidePressEvent:{mouse:"sloppy",touch:"intentional"},bubbles:Rs?!0:void 0,outsidePress(Me){const Be=is(Me);return!Qe(fc,Be)&&!Qe(Bn.current,Be)&&!Qe(Vt.current,Be)&&!Qe(mc,Be)}}),Vl=DT(xc,{enabled:!Hn,id:Ce,listRef:kt,activeIndex:$s,selectedIndex:Fo,virtual:!0,loopFocus:H,allowEscape:H&&!jt,focusItemOnOpen:Te||y==="none"&&!jt?!1:"auto",focusItemOnHover:L,resetOnPointerLeave:!_,orientation:D?"horizontal":void 0,rtl:te==="rtl",disabledIndices:Rr,grid:D?C6:void 0,onNavigate(Me,Be){!Be&&!rn||Ip==="ending"||Ur(Be?{activeIndex:Me,type:xs.current?b1:v1}:{activeIndex:Me})}}),Bp=x.useMemo(()=>Wr(Vl.reference,{onKeyDown(Me){D&&et.state.activeIndex==null&&(Me.key==="ArrowLeft"||Me.key==="ArrowRight")&&Me.preventBaseUIHandler()}},sd.reference,Ul.reference,bc.reference),[Vl.reference,sd.reference,Ul.reference,bc.reference,D,et]),rd=x.useMemo(()=>Wr(af,sd.floating),[sd.floating]),eb=x.useMemo(()=>Wr(Vl.floating,bc.floating),[Vl.floating,bc.floating]),tb=x.useMemo(()=>{const Me=Vl.item;return Me?{...Me,onFocus:void 0}:fn},[Vl.item]);et.useContextCallback("setOpen",Mt),et.useContextCallback("setInputValue",Vr),et.useContextCallback("setSelectedValue",gc),et.useContextCallback("setIndices",Ur),et.useContextCallback("handleSelection",Ju),et.useContextCallback("forceMount",Hl),et.useContextCallback("requestSubmit",ed),et.useContextCallback("onOpenChangeComplete",a),SE(()=>{et.update({inline:X,popupProps:rd,listProps:eb,inputProps:Bp,triggerProps:Pp,itemProps:tb})});const vc={id:Ce,selectedValue:wt,open:rn,mounted:$o,transitionStatus:Ip,items:ve,inline:X,popupProps:rd,listProps:eb,inputProps:Bp,triggerProps:Pp,itemProps:tb,openMethod:Zx,selectionMode:y,name:Un,form:w,disabled:Hn,readOnly:N,required:k,grid:D,virtualized:K,openOnInputClick:P,itemToStringLabel:ye,modal:$,autoHighlight:jt,isItemEqualToValue:Q,submitOnItemClick:le,hasInputValue:as};De(()=>{et.update({...vc,inputOwnsFormValue:y==="none"&&(X||!et.state.inputInsidePopup)})},[et,...Object.values(vc)]);const pa=ea(E,fe.inputRef),Hp=x.useMemo(()=>({query:dr,hasItems:Tt,filteredItems:Vo,flatFilteredValues:Es}),[dr,Tt,Vo,Es]),Up=x.useMemo(()=>Array.isArray(_l)?"":ka(_l,z),[_l,z]),Go=Rn&&Array.isArray(wt)&&wt.length>0,al=Rn||y==="none"&&Ll?void 0:Un,nb=x.useMemo(()=>!Rn||!Array.isArray(wt)||!Un?null:wt.map(Me=>{const Be=ka(Me,z);return s.jsx("input",{type:"hidden",form:w,name:Un,value:Be,disabled:Hn},Be)}),[Rn,wt,w,Un,z,Hn]),Vp=s.jsxs(x.Fragment,{children:[e.children,s.jsx("input",{...fe.getValidationProps(Hn,{onFocus(){if(ar){fc?.focus();return}(ot.current||fc)?.focus()},onChange(Me){if(Me.nativeEvent.defaultPrevented||Hn||N)return;const Be=Me.currentTarget.value,lt=Be.toLowerCase(),Yt=Fe(Yn,Me.nativeEvent),On=()=>Ft.current.findIndex(Mn=>ka(Mn,z).toLowerCase()===lt||xe(Mn).toLowerCase()===lt);function mn(){if(Rn)return;if(y==="none"){Vr(Be,Yt);return}let Mn=On();Mn===-1&&(Mn=Ft.current.findIndex((Nr,ma)=>{const $r=Ct.current[ma];return $r!=null&&$r.toLowerCase()===lt}));const fs=Mn===-1?void 0:Ft.current[Mn];fs!=null&&gc?.(fs,Yt)}Jt&&(Hl(),ke&&On()===-1&&et.set("forceMounted",!0)),queueMicrotask(mn)}}),id:Ce&&al==null?`${Ce}-hidden-input`:void 0,form:w,name:al,autoComplete:G,disabled:Hn,required:k&&!Go,readOnly:N,value:Up,ref:pa,style:al?Wc:Ai,tabIndex:-1,"aria-hidden":!0,suppressHydrationWarning:!0}),nb]});return s.jsx($E.Provider,{value:et,children:s.jsx(qE.Provider,{value:xc,children:s.jsx(KE.Provider,{value:Tt,children:s.jsx(GE.Provider,{value:Hp,children:s.jsx(YE.Provider,{value:jn,children:Vp})})})})})}function P6(e){const{multiple:t=!1,defaultValue:a,value:o,onValueChange:c,autoComplete:d,...f}=e;return s.jsx(I6,{...f,selectionMode:t?"multiple":"single",selectedValue:o,defaultSelectedValue:a,onSelectedValueChange:c,formAutoComplete:d})}const _6="data-popup-side",L6="data-list-empty",JE={...Bv,...ji,popupSide:e=>e?{[_6]:e}:null,listEmpty:e=>e?{[L6]:""}:null},z6=x.createContext(void 0);function B6(){return x.useContext(z6)}const eA=x.createContext(void 0);function Jy(e){const t=x.useContext(eA);if(t===void 0&&!e)throw new Error(on(21));return t}const tA=x.forwardRef(function(t,a){const o=Ca(),{buttonRef:c,getButtonProps:d}=Jr({native:!1}),f=ea(a,c);function p(v){o.context.setOpen(!1,Fe(ny,v.nativeEvent,v.currentTarget))}const g=d({onClick:p});return s.jsx("span",{ref:f,...g,"aria-label":"Dismiss",tabIndex:void 0,style:Wc})});function nA(e){const t=e.useState("mounted"),a=e.useState("popupSide"),o=e.useState("positionerElement");return t&&o?a:null}function Ph(){return ff().filteredItems.length===0}function H6(e){return e==="rtl"?["ArrowRight","ArrowLeft"]:["ArrowLeft","ArrowRight"]}function U6(e,t){const a=e>=t-1?t-2:e;return a>=0?a:void 0}function sA(e,t,a){const o=e.context.listRef.current[t];o&&(e.context.selectionEventRef.current=a,o.click(),e.context.selectionEventRef.current=null)}const V6=x.forwardRef(function(t,a){const{render:o,className:c,disabled:d=!1,id:f,style:p,...g}=t,{state:v,disabled:y,setTouched:b,setFocused:j,validationMode:w,validation:S}=Sa(),{labelId:N}=vl(),k=B6(),D=!!Jy(!0),C=Ca(),A=XE(),R=of(),I=C.useState("required"),P=C.useState("disabled"),O=C.useState("readOnly"),_=C.useState("name"),L=C.useState("form"),H=C.useState("selectionMode"),B=C.useState("autoHighlight"),z=C.useState("inputProps"),Q=C.useState("triggerProps"),K=C.useState("open"),X=C.useState("mounted"),q=C.useState("selectedValue"),$=C.useState("id"),Y=C.useState("inline"),F=C.useState("modal"),G=!!B,W=nA(C),le=y||P||d,M=Ph(),U=D||Y,Z=!U||F,ae=Na(f??(U?void 0:$)),ce=D?HC:v,[J,ie]=x.useState(null),ge=x.useRef(!1),ee=x.useRef(null),fe=x.useRef(!1),te=H==="none"&&!D,Ce=Ie(we=>{const xe=D||C.state.inline;xe&&!C.state.hasInputValue&&C.context.setInputValue("",Fe(Yn)),C.update({inputElement:we,inputInsidePopup:xe,inputOwnsFormValue:te})}),re=D?g:S.getValidationProps(le,g);function de(){C.context.setIndices({activeIndex:null,selectedIndex:null,type:C.context.keyboardActiveRef.current?b1:v1})}function ke(){C.context.keyboardActiveRef.current=!1}const Ee={...ce,open:K,disabled:le,readOnly:O,popupSide:W,listEmpty:M};function ve(we){if(!k)return;let xe;const{highlightedChipIndex:Te}=k,Oe=k.chipsRef.current.length,[Ne,_e]=H6(R);return Te!==void 0?(we.key===Ne?(we.preventDefault(),Te>0?xe=Te-1:xe=void 0):we.key===_e?(we.preventDefault(),Te0&&(we.preventDefault(),xe=Oe>0?Oe-1:void 0),xe)}const he=vt("input",t,{state:Ee,ref:[a,C.context.inputRef,Ce],props:[z,Q,{value:J??A,"aria-readonly":O||void 0,"aria-required":I||void 0,"aria-labelledby":N,disabled:le,readOnly:O,required:H==="none"?I:void 0,form:L,...te&&_&&{name:_},id:ae,onFocus(){if(j(!0),!Y||!fe.current)return;fe.current=!1;const we=ee.current;we==null||!Object.hasOwn(C.context.valuesRef.current,we)||C.context.setIndices({activeIndex:we})},onBlur(){b(!0),j(!1);const we=C.state.activeIndex;if(Y&&we!==null&&B!=="always"&&(ee.current=we,fe.current=!0,C.context.setIndices({activeIndex:null})),w==="onBlur"){const xe=H==="none"?A:q;S.commit(xe)}},onCompositionStart(we){zm||(ge.current=!0,ie(we.currentTarget.value))},onCompositionEnd(we){ge.current=!1;const xe=we.currentTarget.value;ie(null),C.context.setInputValue(xe,Fe(Wd,we.nativeEvent))},onChange(we){const xe=we.nativeEvent,Te=xe.inputType,Oe=!Te||Te==="insertReplacementText",Ne=ge.current||!Oe;function _e(Rt){O||le||!Rt||!Ne||(C.context.setOpen(!0,Fe(Wd,xe)),G||de())}if(ge.current){const Rt=we.currentTarget.value;ie(Rt),Rt===""&&!C.state.openOnInputClick&&!C.state.inputInsidePopup&&C.context.setOpen(!1,Fe(Ga,xe));const ot=Rt.trim(),qn=G&&ot!=="";_e(ot),K&&C.state.activeIndex!==null&&!qn&&de();return}const Ye=Fe(Wd,xe);if(C.context.setInputValue(we.currentTarget.value,Ye),Ye.isCanceled)return;const kt=we.currentTarget.value==="",Ct=Fe(Ga,xe);kt&&!C.state.inputInsidePopup&&(H==="single"&&C.context.setSelectedValue(null,Ct),C.state.openOnInputClick||C.context.setOpen(!1,Ct)),_e(we.currentTarget.value.trim()),K&&C.state.activeIndex!==null&&!G&&de()},onKeyDown(we){if(we.ctrlKey||we.shiftKey||we.altKey||we.metaKey)return;if(C.context.keyboardActiveRef.current=!0,le||O){O&&we.key==="Enter"&&K&&C.state.activeIndex!==null&&Ns(we);return}const xe=we.currentTarget,Te=xe.scrollWidth-xe.clientWidth,Oe=R==="rtl";if(we.key==="Home"){Ns(we);const Ye=KC&&Oe?xe.value.length:0;xe.setSelectionRange(Ye,Ye),xe.scrollLeft=0;return}if(we.key==="End"){Ns(we);const Ye=KC&&Oe?0:xe.value.length;xe.setSelectionRange(Ye,Ye),xe.scrollLeft=Oe?-Te:Te;return}if(!X&&we.key==="Escape"){const Ye=H==="multiple"&&Array.isArray(q)?q.length===0:q===null,kt=Fe(Qc,we.nativeEvent),Ct=H==="multiple"?[]:null;C.context.setInputValue("",kt),C.context.setSelectedValue(Ct,kt),!Ye&&!C.state.inline&&!kt.isPropagationAllowed&&we.stopPropagation();return}if(k&&we.key==="Backspace"&&xe.value===""&&k.highlightedChipIndex===void 0&&Array.isArray(q)&&q.length>0){const Ye=k.chipsRef.current.length,kt=Ye>0?Ye-1:q.length-1,Ct=q.filter((Rt,ot)=>ot!==kt);de(),C.context.setSelectedValue(Ct,Fe(Yn,we.nativeEvent));return}const Ne=k?.highlightedChipIndex!==void 0,_e=ve(we);if(k?.setHighlightedChipIndex(_e),_e!==void 0?k?.chipsRef.current[_e]?.focus():Ne&&C.context.inputRef.current?.focus(),we.which!==229&&we.key==="Enter"&&K){const Ye=C.state.activeIndex,kt=we.nativeEvent;if(Ye===null){if(Y)return;C.context.setOpen(!1,Fe(Yn,kt));return}Ns(we),sA(C,Ye,kt)}},onPointerMove:ke,onPointerDown:ke},re],stateAttributesMapping:JE}),ye=D?s.jsx(VC.Provider,{value:UC,children:he}):he;return s.jsxs(x.Fragment,{children:[K&&Z&&s.jsx(tA,{ref:C.context.startDismissRef}),ye]})}),F6=x.forwardRef(function(t,a){const{render:o,className:c,nativeButton:d=!0,disabled:f=!1,id:p,style:g,...v}=t,{state:y,disabled:b,setTouched:j,setFocused:w,validationMode:S,validation:N}=Sa(),{labelId:k}=vl(),E=Ca(),D=E.useState("selectionMode"),C=E.useState("disabled"),A=E.useState("readOnly"),R=E.useState("required"),I=E.useState("positionerElement"),P=E.useState("listElement"),O=E.useState("popupId"),_=E.useState("triggerProps"),L=E.useState("inputInsidePopup"),H=E.useState("id"),B=E.useState("labelId"),z=E.useState("open"),Q=E.useState("selectedValue"),K=E.useState("activeIndex"),X=E.useState("selectedIndex"),q=E.useState("hasSelectedValue"),$=Ih(),Y=XE(),F=Qs(),G=b||C||f,W=Ph(),le=nA(E);lo({id:L?p:void 0});const M=L?p??H:p,U=IE(k,B);let Z;z&&L?Z=O??QE(H):z&&(Z=P?.id);const ae=x.useRef("");function ce(re){ae.current=re.pointerType}const{reference:J}=IT($,{enabled:!z&&!A&&!C&&D==="single",listRef:E.context.labelsRef,activeIndex:K,selectedIndex:X,onMatch(re){const de=E.context.valuesRef.current[re];de!==void 0&&E.context.setSelectedValue(de,Fe(Yn))}}),{reference:ie}=ah($,{enabled:!C,event:"mousedown"}),{buttonRef:ge,getButtonProps:ee}=Jr({native:d,disabled:G}),fe={...y,readOnly:A,open:z,disabled:G,popupSide:le,listEmpty:W,placeholder:D==="none"?!1:!q},te=Ie(re=>{E.set("triggerElement",re)});return vt("button",t,{ref:[a,ge,te],state:fe,props:[_,ie,J,{id:M,tabIndex:L?0:-1,role:L?"combobox":void 0,"aria-expanded":z,"aria-haspopup":L?"dialog":"listbox","aria-controls":Z,"aria-required":L&&R||void 0,"aria-readonly":L&&A||void 0,"aria-labelledby":U,onPointerDown:ce,onPointerEnter:ce,onFocus(){w(!0),!G&&F.start(0,E.context.forceMount)},onBlur(re){if(!Qe(I,re.relatedTarget)&&(j(!0),w(!1),S==="onBlur")){const de=D==="none"?Y:Q;N.commit(de)}},onMouseDown(re){if(G||(L||$.set("domReferenceElement",re.currentTarget),E.context.forceMount(),ae.current!=="touch"&&(E.context.inputRef.current?.focus(),L||re.preventDefault()),z))return;const de=$t(re.currentTarget);function ke(Ee){const ve=E.state.triggerElement;if(!ve)return;const he=is(Ee),ye=E.state.positionerElement,we=E.state.listElement;Qe(ve,he)||Qe(ye,he)||Qe(we,he)||PE(Ee,ve)||E.context.setOpen(!1,Fe(y1,Ee))}L&&de.addEventListener("mouseup",ke,{once:!0})},onKeyDown(re){(re.key==="ArrowDown"||re.key==="ArrowUp")&&(Ns(re),E.context.setOpen(!0,Fe(sy,re.nativeEvent)),E.context.inputRef.current?.focus())}},N.getValidationProps(G,v),ee],stateAttributesMapping:JE})}),$6=x.createContext(null);function q6(){return x.useContext($6)}function G6(e){const{children:t}=e,{filteredItems:a}=ff(),o=q6(),c=o?o.items:a;return s.jsx(x.Fragment,{children:c.map(t)})}const K6=x.forwardRef(function(t,a){var o;const{render:c,className:d,style:f,children:p,...g}=t,v=Ca(),y=Ih(),b=!!Jy(!0),{filteredItems:j,hasItems:w}=ff(),S=v.useState("selectionMode"),N=v.useState("grid"),k=v.useState("readOnly"),E=v.useState("listProps"),D=v.useState("virtualized"),C=v.useState("forceMounted"),A=S==="multiple",R=j.length===0,I=Ie(z=>{v.set("positionerElement",z)}),P=Ie(z=>{v.set("listElement",z)}),O=x.useMemo(()=>typeof p=="function"?o||(o=s.jsx(G6,{children:p})):p,[p]),_={empty:R},L=y.useState("floatingId"),H=vt("div",t,{state:_,ref:[a,P,b?null:I],props:[E,{children:O,tabIndex:-1,id:L,role:N?"grid":"listbox","aria-multiselectable":A?"true":void 0,"aria-readonly":!N&&k?!0:void 0,onKeyDown(z){if(!(v.state.disabled||v.state.readOnly)&&z.key==="Enter"){const Q=v.state.activeIndex;if(Q==null)return;Ns(z),sA(v,Q,z.nativeEvent)}},onKeyDownCapture(){v.context.keyboardActiveRef.current=!0},onPointerMoveCapture(){v.context.keyboardActiveRef.current=!1}},g]});if(D)return H;const B=w&&!C?void 0:v.context.labelsRef;return s.jsx(Ky,{elementsRef:v.context.listRef,labelsRef:B,children:H})}),Y6="⁠",X6=200;function Q6(e){const t=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT);let a=null;for(;t.nextNode();){const o=t.currentNode;o.nodeValue!==""&&(a=o)}return a}function Z6(){const e=Qs(),t=x.useRef(null);return x.useEffect(()=>{if(Kd)return;const a=t.current;if(a==null)return;const o=Q6(a);if(o==null)return;const c=o.data,d=`${c}${Y6}`;return o.nodeValue=d,e.start(X6,()=>{o.nodeValue===d&&(o.nodeValue=c)}),()=>{e.clear(),o.nodeValue===d&&(o.nodeValue=c)}},[t,e]),t}const rA=x.createContext(void 0);function W6(){const e=x.useContext(rA);if(e===void 0)throw new Error(on(20));return e}const J6=x.forwardRef(function(t,a){const{keepMounted:o=!1,...c}=t,d=Ca(),f=d.useState("mounted"),p=d.useState("forceMounted");return f||o||p?s.jsx(rA.Provider,{value:o,children:s.jsx(sh,{ref:a,...c})}):null}),eF=x.forwardRef(function(t,a){const{render:o,className:c,anchor:d,positionMethod:f,side:p,align:g,sideOffset:v,alignOffset:y,collisionBoundary:b="clipping-ancestors",collisionPadding:j,arrowPadding:w,sticky:S,disableAnchorTracking:N=!1,collisionAvoidance:k=V1,style:E,...D}=t,C=Ca(),A=Ih(),R=W6(),I=C.useState("modal"),P=C.useState("open"),O=C.useState("mounted"),_=C.useState("openMethod"),L=C.useState("positionerElement"),H=C.useState("triggerElement"),B=C.useState("inputElement"),z=C.useState("inputGroupElement"),Q=C.useState("inputInsidePopup"),K=C.useState("transitionStatus"),X=Ph(),$=xh({anchor:d??(Q?H:z??B),floatingRootContext:A,positionMethod:f,mounted:O,side:p,sideOffset:v,align:g,alignOffset:y,arrowPadding:w,collisionBoundary:b,collisionPadding:j,sticky:S,disableAnchorTracking:N,keepMounted:R,collisionAvoidance:k,lazyFlip:!0});Qy(P&&I,_==="touch",L,H);const Y={open:P,side:$.side,align:$.align,anchorHidden:$.anchorHidden,empty:X};De(()=>{C.set("popupSide",$.side)},[C,$.side]);const F=Ie(W=>{C.set("positionerElement",W)}),G=bh(t,Y,{styles:$.positionerStyles,transitionStatus:K,props:D,refs:[a,F],hidden:!O,inert:!P});return s.jsxs(eA.Provider,{value:$,children:[O&&I&&s.jsx(wh,{inert:vh(!P),cutout:z??B??H}),G]})}),tF={...qc,...oo},nF=x.forwardRef(function(t,a){const{render:o,className:c,style:d,initialFocus:f,finalFocus:p,...g}=t,v=Ca(),y=Jy(),b=Ih(),j=v.useState("mounted"),w=v.useState("open"),S=v.useState("openMethod"),N=v.useState("popupProps"),k=v.useState("transitionStatus"),E=v.useState("inputInsidePopup"),D=v.useState("inputElement"),C=v.useState("modal"),A=v.useState("id"),R=Ph(),I=g.id??(E?QE(A):void 0);De(()=>(v.set("popupId",v.context.popupRef.current?.id||I),()=>{v.set("popupId",void 0)}),[v,I]),ra({open:w,ref:v.context.popupRef,onComplete(){w&&v.context.onOpenChangeComplete(!0)}});const P={open:w,side:y.side,align:y.align,anchorHidden:y.anchorHidden,transitionStatus:k,empty:R},O=vt("div",t,{state:P,ref:[a,v.context.popupRef],props:[N,{id:I,role:E?"dialog":"presentation",onFocus(z){const Q=is(z.nativeEvent);S!=="touch"&&(Qe(v.state.listElement,Q)||Q===z.currentTarget)&&v.context.inputRef.current?.focus()}},cf(k),g],stateAttributesMapping:tF}),L=f===void 0?E?z=>z==="touch"?v.context.popupRef.current:D:!1:f;let H;p!=null?H=p:H=E?void 0:!1;const B=!E||C;return s.jsx(rh,{context:b,disabled:!j,modal:B,openInteractionType:S,initialFocus:L,returnFocus:H,getInsideElements:()=>[v.context.startDismissRef.current,v.context.endDismissRef.current],children:s.jsxs(x.Fragment,{children:[O,B&&s.jsx(tA,{ref:v.context.endDismissRef})]})})}),sF=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t;return vt("span",t,{ref:a,props:[{"aria-hidden":!0,children:"▼"},f]})}),aA=x.createContext(void 0);function lA(){const e=x.useContext(aA);if(!e)throw new Error(on(19));return e}const rF=x.createContext(!1);function aF(){return x.useContext(rF)}function oA(e){const{componentProps:t,forwardedRef:a,virtualized:o,indexFromFilter:c}=e,{render:d,className:f,style:p,value:g=null,index:v,disabled:y=!1,nativeButton:b=!1,...j}=t,w=x.useRef(null),S=Gy({guess:!0,index:v,textRef:w}),N=Ca(),k=aF(),E=T6(),D=N.useState("selectionMode"),C=N.useState("disabled"),A=N.useState("readOnly"),R=N.useState("isItemEqualToValue"),I=C||y,P=D!=="none",O=v??c??S.index,_=O!==-1,L=N.useState("id"),H=N.useState("isActive",O),B=N.useState("isSelected",g),z=N.useState("itemProps"),Q=x.useRef(null),K=L!=null&&_?`${L}-${O}`:void 0,X=B&&P;De(()=>{if(!(_&&(o||v!=null)))return;const U=N.context.listRef.current;return U[O]=Q.current,()=>{delete U[O]}},[_,o,O,v,N]),De(()=>{if(!_||E)return;const M=N.context.valuesRef.current;return M[O]=g,()=>{delete M[O]}},[_,E,O,g,N]),De(()=>{if(!_||E)return;const M=N.state.selectedValue;let U=N.state.selectedIndex;N.state.selectionMode==="multiple"&&Array.isArray(M)?U=AE(O,g,N.context.valuesRef.current,M,R,U):la(g,M,R)&&(U=O),N.set("selectedIndex",U)},[_,E,N,O,g,R]);const{getButtonProps:q,buttonRef:$}=Jr({disabled:I,focusableWhenDisabled:!0,native:b,composite:!0}),Y={disabled:I,selected:X,highlighted:H};function F(M){function U(){N.context.handleSelection(M,g)}N.state.submitOnItemClick?(ks.flushSync(U),N.context.requestSubmit()):U()}const G={id:K,role:k?"gridcell":"option","aria-selected":P?X:void 0,tabIndex:void 0,onPointerDownCapture(M){M.isPrimary&&(N.context.pointerDownItemRef.current=M.currentTarget),M.preventDefault()},onMouseDown(M){M.preventDefault()},onClick(M){I||A||F(M.nativeEvent)},onMouseUp(M){const U=N.context.pointerDownItemRef.current===M.currentTarget;N.context.pointerDownItemRef.current=null,!(I||A||M.button!==0||U||!H)&&F(M.nativeEvent)}},W=vt("div",t,{ref:[$,a,S.ref,Q],state:Y,props:[z,G,j,q]}),le=x.useMemo(()=>({selected:X,textRef:w}),[X,w]);return s.jsx(aA.Provider,{value:le,children:W})}function lF(e){const{componentProps:t,forwardedRef:a}=e,c=Ca().useState("isItemEqualToValue"),{flatFilteredValues:d}=ff(),f=t.value??null,p=ru(d,f,c);return s.jsx(oA,{componentProps:t,forwardedRef:a,virtualized:!0,indexFromFilter:p})}const oF=x.memo(x.forwardRef(function(t,a){const c=Ca().useState("virtualized");return c&&t.index==null?s.jsx(lF,{componentProps:t,forwardedRef:a}):s.jsx(oA,{componentProps:t,forwardedRef:a,virtualized:c,indexFromFilter:void 0})})),iF=x.forwardRef(function(t,a){const{selected:o}=lA();return t.keepMounted||o?s.jsx(cF,{...t,ref:a}):null}),cF=x.memo(x.forwardRef((e,t)=>{const{render:a,className:o,style:c,keepMounted:d,...f}=e,{selected:p}=lA(),g=x.useRef(null),{transitionStatus:v,setMounted:y}=ki(p),j=vt("span",e,{ref:[t,g],state:{selected:p,transitionStatus:v},props:[{"aria-hidden":!0,children:"✔️"},f],stateAttributesMapping:oo});return ra({batch:!0,enabled:!p,open:p,ref:g,onComplete(){p||y(!1)}}),j})),uF=x.forwardRef(function(t,a){const{render:o,className:c,style:d,children:f,...p}=t,{filteredItems:g}=ff(),v=Ca(),y=Z6(),b=g.length===0?f:null;return vt("div",t,{ref:[a,v.context.emptyRef,y],props:[{children:b,role:"status","aria-live":"polite","aria-atomic":!0},p]})}),dF="、";function _h({value:e,onValueChange:t,options:a,placeholder:o="",emptyHint:c=go("没有匹配的选项"),searchPlaceholder:d=go("搜索…"),disabled:f=!1,className:p,id:g,title:v,...y}){const b=x.useMemo(()=>a.filter(w=>e.includes(w.value)),[a,e]),j=b.length?b.map(w=>w.label).join(dF):o;return s.jsxs(P6,{items:a,multiple:!0,value:b,onValueChange:w=>t(w.map(S=>S.value)),isItemEqualToValue:(w,S)=>w?.value===S?.value,disabled:f,children:[s.jsxs(F6,{"data-slot":"multi-select-trigger",id:g,title:v,"aria-label":y["aria-label"],className:Ue("inline-flex h-[30px] min-w-0 cursor-pointer items-center justify-between gap-1.5 rounded-md border border-control-border bg-control px-2.5","text-[12.5px] font-normal text-foreground","transition-colors duration-150 ease-out","hover:border-control-border-hover hover:bg-control-hover","focus-visible:border-primary focus-visible:shadow-focus focus-visible:outline-none","data-disabled:cursor-not-allowed data-disabled:bg-control data-disabled:text-muted-foreground data-disabled:opacity-60",p),children:[s.jsx("span",{"data-slot":"multi-select-value",className:"min-w-0 flex-1 truncate text-left data-[placeholder]:text-muted-foreground","data-placeholder":b.length?void 0:"",title:j,children:j}),s.jsx(sF,{className:"flex flex-none text-muted-foreground transition-transform duration-[180ms] data-popup-open:rotate-180",children:s.jsx("svg",{viewBox:"0 0 10 6",className:"size-2.5","aria-hidden":"true",children:s.jsx("path",{d:"M1 1l4 4 4-4",stroke:"currentColor",strokeWidth:"1.4",fill:"none",strokeLinecap:"round",strokeLinejoin:"round"})})})]}),s.jsx(J6,{children:s.jsx(eF,{sideOffset:4,className:"z-[35]",children:s.jsxs(nF,{"data-slot":"multi-select-content",className:Ue("flex max-h-[280px] w-[max(var(--anchor-width),220px)] flex-col overflow-hidden","rounded-lg border border-border-strong bg-raised shadow-3 outline-none","data-open:animate-in data-open:fade-in-0","data-closed:animate-out data-closed:fade-out-0"),children:[s.jsxs("div",{className:"flex flex-none items-center gap-1.5 border-b border-hairline px-2.5 py-1.5",children:[s.jsxs("svg",{viewBox:"0 0 12 12",className:"size-3 flex-none text-muted-foreground","aria-hidden":"true",children:[s.jsx("circle",{cx:"5",cy:"5",r:"3.4",stroke:"currentColor",strokeWidth:"1.3",fill:"none"}),s.jsx("path",{d:"M7.6 7.6 10.5 10.5",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"})]}),s.jsx(V6,{placeholder:d,className:"min-w-0 flex-1 border-0 bg-transparent p-0 text-[12.5px] text-foreground outline-none placeholder:text-muted-foreground"})]}),s.jsx(uF,{children:s.jsx("div",{className:"px-2.5 py-3 text-[11.5px] leading-[1.5] text-muted-foreground",children:c})}),s.jsx(K6,{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain p-[5px]",children:w=>s.jsxs(oF,{value:w,className:Ue("grid cursor-pointer grid-cols-[14px_minmax(0,1fr)] items-center gap-2 rounded-sm px-[9px] py-[5px]","text-[12.5px] leading-[1.4] text-foreground select-none outline-none","transition-colors duration-[120ms] ease-out","data-[highlighted]:bg-nav-hover","data-[selected]:bg-primary-soft data-[selected]:font-semibold data-[selected]:text-primary-fg","data-[highlighted]:data-[selected]:bg-primary-tint","data-disabled:pointer-events-none data-disabled:text-muted-foreground"),children:[s.jsx(iF,{className:"col-start-1 flex text-primary",children:s.jsx("svg",{viewBox:"0 0 12 12",className:"size-3","aria-hidden":"true",children:s.jsx("path",{d:"M2.5 6.2 4.8 8.5 9.5 3.8",stroke:"currentColor",strokeWidth:"1.8",fill:"none",strokeLinecap:"round",strokeLinejoin:"round"})})}),s.jsx("span",{className:"col-start-2 min-w-0 truncate",children:w.label})]},w.value)})]})})})]})}const iA=x.createContext(void 0);function pf(e){const t=x.useContext(iA);if(t===void 0&&!e)throw new Error(on(47));return t}const fF={...Oy,disabled:e=>e.disabled,instantType:e=>e.instantType,openMethod:e=>e.openMethod,openChangeReason:e=>e.openChangeReason,modal:e=>e.modal,focusManagerModal:e=>e.focusManagerModal,stickIfOpen:e=>e.stickIfOpen,titleElementId:e=>e.titleElementId,descriptionElementId:e=>e.descriptionElementId,openOnHover:e=>e.openOnHover,closeDelay:e=>e.closeDelay,adaptiveOrigin:e=>e.adaptiveOrigin};class pF extends nu{constructor(a,o,c){const d=new ch;super(mF(a,d,o,c),hF(d),fF);ln(this,"setOpen",(a,o)=>{const c=o.reason===Us,d=o.reason===mo&&o.event.detail===0,f=!a&&(o.reason===Qc||o.reason==null),p=wT(o),g=this.select("activeTriggerId");if(!a&&o.reason===ny&&o.trigger==null&&g!=null&&(o.trigger=this.context.triggerElements.getById(g)??this.select("activeTriggerElement")??void 0),this.context.onOpenChange?.(a,o),o.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(a,o);const v=()=>{const b=ky(this.state,a,o.trigger,p());b.openChangeReason=o.reason,this.update(b)};c?(this.set("stickIfOpen",!0),this.context.stickIfOpenTimeout.start(ZB,()=>{this.set("stickIfOpen",!1)}),ks.flushSync(v)):v();let y;d?y="click":f?y="dismiss":o.reason===ho&&(y="focus"),this.set("instantType",y)})}}function mF(e,t,a,o=!1){const c={...Ay(t,a,o),disabled:!1,modal:!1,focusManagerModal:!1,instantType:void 0,openMethod:null,openChangeReason:null,titleElementId:void 0,descriptionElementId:void 0,stickIfOpen:!0,openOnHover:!1,closeDelay:0,adaptiveOrigin:void 0,...e};return c.open&&e?.mounted===void 0&&(c.mounted=!0),c}function hF(e){return{popupRef:x.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:x.createRef(),beforeContentFocusGuardRef:x.createRef(),stickIfOpenTimeout:new sa,triggerElements:e}}const cA=eh(function({props:t}){const{children:a,open:o,defaultOpen:c=!1,onOpenChange:d,onOpenChangeComplete:f,modal:p=!1,handle:g,triggerId:v,defaultTriggerId:y=null}=t,b=xF(g,{modal:p,open:c,openProp:o,activeTriggerId:y,triggerIdProp:v});b.useControlledProp("openProp",o),b.useControlledProp("triggerIdProp",v);const j=b.useState("open"),w=b.useState("mounted"),S=b.useState("payload");b.useContextCallback("onOpenChange",d),b.useContextCallback("onOpenChangeComplete",f),NT(b,j),Cy(b);const{forceUnmount:N}=Ty(j,b,()=>{b.update({stickIfOpen:!0,openChangeReason:null})});b.useSyncedValues({modal:p}),x.useEffect(()=>{j||b.context.stickIfOpenTimeout.clear()},[b,j]),x.useImperativeHandle(t.actionsRef,()=>({unmount:N,close:()=>b.setOpen(!1,Fe(ry))}),[N,b]);const k=j||w;return s.jsxs(iA.Provider,{value:b,children:[g&&s.jsx(Ny,{handle:g,store:b}),k&&s.jsx(bF,{store:b,modal:p}),typeof a=="function"?a({payload:S}):a]})});function gF(e){return pf(!0)?s.jsx(cA,{props:e}):s.jsx(rH,{children:s.jsx(cA,{props:e})})}function xF(e,t){const a=Sy((o,c)=>new pF(t,o,c));return x.useEffect(()=>a.context.stickIfOpenTimeout.disposeEffect(),[a]),a}function bF({store:e,modal:t}){const a=e.useState("floatingRootContext"),o=rf(a,{outsidePressEvent:{mouse:t==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}}),c=o.reference,d=o.floating;return Ey(e,{activeTriggerProps:c,inactiveTriggerProps:c,popupProps:d}),null}const vF=300;function yF(e,t){const a=x.useRef(null);function o(d){ks.flushSync(()=>{e.setOpen(!1,Fe(ho,d.nativeEvent,d.currentTarget))}),W4(a.current)?.focus()}function c(d){const f=e.select("positionerElement");if(f&&Kc(d,f))e.context.beforeContentFocusGuardRef.current?.focus();else{ks.flushSync(()=>{e.setOpen(!1,Fe(ho,d.nativeEvent,d.currentTarget))});let p=Z4(e.context.triggerFocusTargetRef.current||t.current);for(;p!==null&&Qe(f,p);){const g=p;if(p=Jv(p),p===g)break}p?.focus()}}return{preFocusGuardRef:a,handlePreFocusGuardFocus:o,handleFocusTargetFocus:c}}const jF=R1(function(t,a){const{render:o,className:c,style:d,disabled:f=!1,nativeButton:p=!0,handle:g,payload:v,openOnHover:y=!1,delay:b=vF,closeDelay:j=0,id:w,...S}=t,N=pf(!0),E=TT(g)??N;if(!E)throw new Error(on(74));const D=Na(w),C=E.useState("isTriggerActive",D),A=E.useState("floatingRootContext"),R=E.useState("isOpenedByTrigger",D),I=E.useState("triggerPopupId",D),P=x.useRef(null),{registerTrigger:O,isMountedByThisTrigger:_}=ST(D,P,E,{payload:v,disabled:f,openOnHover:y,closeDelay:j}),L=E.useState("openChangeReason"),H=E.useState("stickIfOpen"),B=E.useState("openMethod"),z=E.useState("focusManagerModal"),Q=OT(A,{enabled:!f&&y&&(B!=="touch"||L!==mo),mouseOnly:!0,move:!1,handleClose:_T(),restMs:b,delay:{close:j},triggerElementRef:P,isActiveTrigger:C,isClosing:()=>E.select("transitionStatus")==="ending"}),K=ah(A,{stickIfOpen:H}),X=dE(()=>E.select("open"),ae=>{E.set("openMethod",ae)}),q=E.useState("triggerProps",_),{getButtonProps:$,buttonRef:Y}=Jr({disabled:f,native:p}),F={open(ae){return ae&&L===mo?Bv.open(ae):zv.open(ae)}},{preFocusGuardRef:G,handlePreFocusGuardFocus:W,handleFocusTargetFocus:le}=yF(E,P),U=vt("button",t,{state:{disabled:f,open:R},ref:[Y,a,O,P],props:[K.reference,Q,q,X,{[U1]:"",id:D,"aria-haspopup":"dialog","aria-expanded":R,"aria-controls":I},S,$],stateAttributesMapping:F}),Z=s.jsx(x.Fragment,{children:U},D);return _&&!z?s.jsxs(x.Fragment,{children:[s.jsx(Jc,{ref:G,onFocus:W}),Z,s.jsx(Jc,{ref:E.context.triggerFocusTargetRef,onFocus:le})]}):Z}),uA=x.createContext(void 0);function wF(){const e=x.useContext(uA);if(e===void 0)throw new Error(on(45));return e}const SF=x.forwardRef(function(t,a){const{keepMounted:o=!1,...c}=t;return pf().useState("mounted")||o?s.jsx(uA.Provider,{value:o,children:s.jsx(sh,{ref:a,...c})}):null}),dA=x.createContext(void 0);function NF(){const e=x.useContext(dA);if(!e)throw new Error(on(46));return e}const kF=x.forwardRef(function(t,a){const{render:o,className:c,style:d,anchor:f,positionMethod:p,side:g,align:v,sideOffset:y,alignOffset:b,collisionBoundary:j="clipping-ancestors",collisionPadding:w,arrowPadding:S,sticky:N,disableAnchorTracking:k=!1,collisionAvoidance:E=F1,...D}=t,C=pf(),A=wF(),R=nH(),I=C.useState("floatingRootContext"),P=C.useState("mounted"),O=C.useState("open"),_=C.useState("openChangeReason"),L=C.useState("activeTriggerElement"),H=C.useState("modal"),B=C.useState("openMethod"),z=C.useState("positionerElement"),Q=C.useState("instantType"),K=C.useState("transitionStatus"),X=C.useState("adaptiveOrigin"),q=x.useRef(null),$=x1(z),Y=xh({anchor:f,floatingRootContext:I,positionMethod:p,mounted:P,side:g,sideOffset:y,align:v,alignOffset:b,arrowPadding:S,collisionBoundary:j,collisionPadding:w,sticky:N,disableAnchorTracking:k,keepMounted:A,nodeId:R,collisionAvoidance:E,adaptiveOrigin:X}),F=I.useState("domReferenceElement");De(()=>{const U=F,Z=q.current;if(U&&(q.current=U),Z&&U&&U!==Z){C.set("instantType",void 0);const ae=new AbortController;return $(()=>{C.set("instantType","trigger-change")},ae.signal),()=>{ae.abort()}}},[F,$,C]);const G=H===!0&&_!==Us;Qy(O&&G,B==="touch",z,L);const W=C.useStateSetter("positionerElement"),le={open:O,side:Y.side,align:Y.align,anchorHidden:Y.anchorHidden,instant:Q},M=bh(t,le,{styles:Y.positionerStyles,transitionStatus:K,props:D,refs:[a,W],hidden:!P,inert:!O});return s.jsxs(dA.Provider,{value:Y,children:[P&&G&&s.jsx(wh,{inert:vh(!O),cutout:L}),s.jsx(sH,{id:R,children:M})]})}),CF=x.createContext(void 0);function TF(){const[e,t]=x.useState(0),a=Ie(()=>(t(c=>c+1),()=>{t(c=>Math.max(0,c-1))}));return{context:x.useMemo(()=>({register:a}),[a]),hasClosePart:e>0}}const EF=x.forwardRef(function(t,a){const{render:o,className:c,style:d,initialFocus:f,finalFocus:p,...g}=t,v=pf(),y=NF(),b=zE()!=null,{context:j,hasClosePart:w}=TF(),S=v.useState("open"),N=v.useState("openMethod"),k=v.useState("instantType"),E=v.useState("transitionStatus"),D=v.useState("popupProps"),C=v.useState("titleElementId"),A=v.useState("descriptionElementId"),R=v.useState("modal"),I=v.useState("mounted"),P=v.useState("openChangeReason"),O=v.useState("activeTriggerElement"),_=v.useState("floatingRootContext"),L=_.useState("floatingId"),H=v.useState("disabled"),B=v.useState("openOnHover"),z=v.useState("closeDelay");ra({open:S,ref:v.context.popupRef,onComplete(){S&&v.context.onOpenChangeComplete?.(!0)}}),RT(_,{enabled:B&&!H,closeDelay:z});const Q=f===void 0?yT(v.context.popupRef):f,K=R!==!1&&w;v.useSyncedValue("focusManagerModal",K);const X=v.useStateSetter("popupElement"),q={open:S,side:y.side,align:y.align,instant:k,transitionStatus:E},$=vt("div",t,{state:q,ref:[a,v.context.popupRef,X],props:[D,{id:L,role:"dialog",...af,"aria-labelledby":C,"aria-describedby":A,onKeyDown(Y){b&&yh.has(Y.key)&&Y.stopPropagation()}},cf(E),g],stateAttributesMapping:Hv});return s.jsx(rh,{context:_,openInteractionType:N,modal:K,disabled:!I||P===Us,initialFocus:Q,returnFocus:p,restoreFocus:"popup",previousFocusableElement:dn(O)?O:void 0,nextFocusableElement:v.context.triggerFocusTargetRef,beforeContentFocusGuardRef:v.context.beforeContentFocusGuardRef,children:s.jsx(CF.Provider,{value:j,children:$})})});function mf(e){return s.jsx(gF,{"data-slot":"popover",...e})}function Lh(e){return s.jsx(jF,{"data-slot":"popover-trigger",...e})}function hf({className:e,sideOffset:t=6,align:a="start",side:o,alignOffset:c,collisionPadding:d=8,anchor:f,children:p,...g}){return s.jsx(SF,{children:s.jsx(kF,{className:"z-[35] outline-none",sideOffset:t,align:a,side:o,alignOffset:c,collisionPadding:d,anchor:f,children:s.jsx(EF,{"data-slot":"popover-content",className:Ue("flex max-h-[min(70vh,560px)] flex-col overflow-hidden rounded-lg border border-border-strong bg-raised text-foreground shadow-3","outline-none","data-open:animate-in data-open:fade-in-0 data-open:slide-in-from-top-1","data-closed:animate-out data-closed:fade-out-0",e),...g,children:p})})})}function AF({page:e,pageCount:t,onPageChange:a,disabled:o=!1,className:c,infoFirst:d=!1}){const f=Math.max(1,Number(t)||1),p=Math.min(Math.max(1,Number(e)||1),f),g=s.jsx("span",{"data-slot":"pager-info",className:"text-[11.5px] text-subtle [font-variant-numeric:tabular-nums]",children:go("第 {current} / {total} 页",{current:p,total:f})});return s.jsxs("div",{"data-slot":"pager",className:Ue("flex items-center gap-2",c),children:[d&&g,s.jsx(se,{type:"button",variant:"outline",size:"sm",disabled:o||p<=1,onClick:()=>a(p-1),children:go("上一页")}),s.jsx(se,{type:"button",variant:"outline",size:"sm",disabled:o||p>=f,onClick:()=>a(p+1),children:go("下一页")}),!d&&g]})}const RF=Fc(["relative flex w-full items-center gap-2.5 text-left","border border-transparent rounded-sm","shadow-none","transition-[background-color,border-color,color] duration-150 ease-out","outline-none focus-visible:shadow-focus","disabled:pointer-events-none disabled:opacity-45","[&_svg]:pointer-events-none [&_svg]:shrink-0"],{variants:{variant:{default:["cursor-pointer px-2.5 py-2","text-[12.5px] font-medium text-sidebar-fg","hover:bg-nav-hover hover:text-foreground","data-[active]:border-nav-selected-border data-[active]:bg-nav-selected-bg data-[active]:font-semibold data-[active]:text-nav-selected-fg"],add:["cursor-pointer justify-center px-2 py-1.5","border-dashed border-border-strong bg-transparent","text-[11.5px] text-muted-foreground","hover:border-primary hover:text-primary-fg"]}},defaultVariants:{variant:"default"}});function au({className:e,variant:t,active:a=!1,count:o,icon:c,trailing:d,children:f,...p}){return s.jsxs("button",{type:"button","data-slot":"nav-item","data-active":a?"":void 0,"aria-current":a?"true":void 0,className:Ue(RF({variant:t}),e),...p,children:[c,s.jsx("span",{"data-slot":"nav-item-label",className:"min-w-0 flex-1 truncate",children:f}),d,o!=null&&s.jsx("span",{"data-slot":"nav-item-count",className:Ue("flex-none text-[10.5px] text-sidebar-muted [font-variant-numeric:tabular-nums]",a&&"text-inherit"),children:o})]})}function r(e,t){const a=typeof window<"u"?window.wbI18n:void 0;return a&&typeof a.t=="function"?a.t(e,t):e}function zh(e){if(e.source==="subscription"&&(e.port===null||e.port===void 0))return r("未分配端口");const t=e.resolved;return t?.protocol&&t.host&&t.port?`${String(t.protocol).toUpperCase()} ${t.host}:${t.port}`:t?.label||""}function lu(e){const t=e.name||e.id,o=[e.resolveError?r("解析失败"):zh(e),e.enabled===!1?r("已禁用"):""].filter(Boolean);return o.length?r("{name}({parts})",{name:t,parts:o.join(" · ")}):t}const Ya="pool:";function Pe(){return window}function Le(e,t){Pe().wbApp?.toast?.(e,t)}function Xa(e){const t=Pe().wbApp?.esc;return t?t(e):String(e??"").replace(/[&<>"']/g,a=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[a]||a)}function Vs(e){const t=Pe().wbApp?.formatTime;if(t)return t(e);const a=Number(e);return!Number.isFinite(a)||a<=0?"":new Date(a).toLocaleString("zh-CN")}function ut(e){return e instanceof Error?e.message:String(e)}function ou(e){if(e==null||e==="")return null;const t=Number(e);return Number.isFinite(t)?t:null}function ej(e){const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const a=o=>String(o).padStart(2,"0");return`${a(t.getMonth()+1)}-${a(t.getDate())} ${a(t.getHours())}:${a(t.getMinutes())}`}function OF(e){return e==="积分"?r("积分"):e==="额度"?r("额度"):e}function MF(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=e,a=Array.isArray(t.credits)?t.credits:[],o=Date.now();return a.map(c=>{const d=String(c?.name||"").trim()||r("积分包"),f=String(c?.unit||"").trim(),p=ou(c?.total),g=ou(c?.used),v=ou(c?.remain),y=c?.unlimited===!0,b=ou(c?.grantAt),j=ou(c?.startAt),w=ou(c?.expireAt),S=c?.daily===!0,N=String(c?.grantReason||"").trim(),k=w!==null&&w>0&&w<=o,E=p!==null&&p>0,D=y?r("不限"):v!==null?E?r("剩 {remaining} / {total}",{remaining:v,total:p}):r("剩 {remaining}",{remaining:v}):g!==null?r("已用 {used}",{used:g}):"—",C=!y&&f&&D!=="—"?`${D} ${OF(f)}`:D,A=E&&v!==null?Math.max(0,Math.min(100,v/p*100)):null,R=v!==null&&v<=0||v===null&&g!==null&&E&&g>=p,I=!y&&!S&&(R||k),P=[];b!==null&&b>0?P.push(r("{time} 领取",{time:ej(b)})):j!==null&&j>0&&P.push(r("{time} 生效",{time:ej(j)})),S?P.push(r("每日重置")):w!==null&&w>0&&P.push(k?r("已过期"):r("{time} 到期",{time:ej(w)})),N&&P.push(N);const O=k||v===0?"muted":A!==null&&A<20?"warn":v===null&&g===null&&!y?"muted":"ok",_=[d,C,b!==null&&b>0?r("领取 {time}",{time:Vs(b)}):j!==null&&j>0?r("生效 {time}",{time:Vs(j)}):"",w!==null&&w>0?k?r("已过期({time})",{time:Vs(w)}):r("到期 {time}",{time:Vs(w)}):"",S?r("每日重置(额度按周期回满,不是作废)"):"",N,A===null&&v!==null?r("上游未给总量,画不出剩余比例"):"",g!==null&&p!==null?r("已用 {used} / 共 {total}",{used:g,total:p}):""].filter(Boolean).join(" · ");return{name:d,view:C,tone:O,percent:A,window:P.length?P.join(" · "):null,title:_,spent:I}})}function fA({row:e}){return s.jsxs("div",{className:"usage-pop-row",title:e.title,children:[s.jsxs("div",{className:"usage-pop-line",children:[s.jsx("span",{className:"usage-pop-name",children:e.name}),s.jsx("span",{className:`usage-pop-view ${e.tone}`,children:e.view})]}),e.window?s.jsx("div",{className:"usage-pop-window",children:e.window}):null,e.percent!==null?s.jsx("span",{className:"usage-pop-track",children:s.jsx("i",{style:{width:`${e.percent}%`},"aria-label":r("剩余 {percent}%",{percent:Math.round(e.percent)})})}):null]})}function pA({rows:e,subscriptionLine:t,variant:a,kind:o,title:c,children:d}){const[f,p]=x.useState(!1),[g,v]=x.useState(!1),y=e.filter(k=>!k.spent),b=e.filter(k=>k.spent),j=a==="pool"?`usage-toggle usage-pool-line ${o}`:`usage-toggle ${o}`,w=x.useRef(null),S=x.useCallback(k=>{w.current=k,k&&(k.scrollTop=0)},[]),N=x.useCallback(()=>w.current??null,[]);return x.useLayoutEffect(()=>{if(!g)return;const k=w.current?.querySelector(".usage-pop-spent .usage-pop-row");k instanceof HTMLElement&&k.scrollIntoView({block:"nearest"})},[g]),s.jsxs(mf,{open:f,onOpenChange:p,children:[s.jsxs(Lh,{render:s.jsx("button",{type:"button",className:j,title:c,"aria-label":r("积分明细")}),children:[a==="pool"?d:s.jsx("span",{className:"val",children:d}),s.jsx("span",{className:"caret","aria-hidden":!0,children:"▾"})]}),s.jsx(hf,{align:"end",sideOffset:6,className:"w-[320px]",initialFocus:N,children:s.jsxs("div",{className:"usage-pop-credit",ref:S,tabIndex:-1,children:[t?s.jsx("div",{className:"usage-pop-sub",children:t}):null,s.jsx("div",{className:"usage-pop-group",children:r("积分明细")}),y.map((k,E)=>s.jsx(fA,{row:k},`${k.name}-${E}`)),b.length>0?s.jsxs("div",{className:"usage-pop-spent",children:[s.jsxs("button",{type:"button",className:"usage-pop-spent-head","aria-expanded":g,title:r("展开或收起(默认收起)"),onClick:()=>v(k=>!k),children:[s.jsx("span",{className:"caret","aria-hidden":!0,children:"▾"}),s.jsx("span",{children:r("已用完 / 已过期")}),s.jsx("span",{className:"n",children:r("{count} 份",{count:b.length})})]}),g?b.map((k,E)=>s.jsx(fA,{row:k},`spent-${k.name}-${E}`)):null]}):null]})})]})}const iu="workbuddy",DF="raccoon",IF={workbuddy:{usage:!0,creditDetail:!0,edition:!0,identifier:"uid",expiry:"expiresAt"},"workbuddy-intl":{usage:!0,creditDetail:!0,edition:!1,identifier:"uid",expiry:"expiresAt"},raccoon:{usage:!0,creditDetail:!0,edition:!1,identifier:"userId",expiry:"tokenExpiresAt"},catpaw:{usage:!0,edition:!1,identifier:"uid",expiry:"tokenExpiresAt"},autoclaw:{usage:!0,creditDetail:!0,edition:!1,identifier:"userId",expiry:"tokenExpiresAt"},"autoclaw-intl":{usage:!0,creditDetail:!0,edition:!1,identifier:"userId",expiry:"tokenExpiresAt",emailAsName:!0},qoder:{usage:!0,creditDetail:!0,edition:!0,identifier:"userId",expiry:"expiresAt",emailAsName:!0},"qoder-intl":{usage:!0,creditDetail:!0,edition:!0,identifier:"userId",expiry:"expiresAt",emailAsName:!0},"cline-free":{usage:!0,edition:!1,identifier:"account",expiry:"expiresAt"},"cline-pass":{usage:!0,edition:!1,identifier:"account",expiry:"expiresAt"},accio:{usage:!0,edition:!0,identifier:"userId",expiry:"expiresAt",emailAsName:!0},"accio-cn":{usage:!0,edition:!0,identifier:"userId",expiry:"expiresAt",emailAsName:!0},zcode:{usage:!0,creditDetail:!0,claim:!0,planChannel:!0,edition:!0,identifier:"userId",expiry:"expiresAt"},"zcode-intl":{usage:!0,creditDetail:!0,claim:!0,planChannel:!0,edition:!0,identifier:"userId",expiry:"expiresAt"},codearts:{usage:!0,usageDetail:!0,edition:!1,identifier:"userId",expiry:"expiresAt",concurrencyDefault:3},trae:{usage:!0,creditDetail:!0,edition:!1,identifier:"uid",expiry:"expiresAt"},loomy:{usage:!0,creditDetail:!0,edition:!1,identifier:"userId",expiry:"expiresAt"},kuku:{usage:!0,edition:!1,identifier:"uid",expiry:""},officeace:{usage:!0,creditDetail:!0,edition:!1,identifier:"id",expiry:"expiresAt"},antigravity:{usage:!0,edition:!1,identifier:"userId",expiry:""}},PF={usage:!1,edition:!1,identifier:"userId",expiry:"tokenExpiresAt",emailAsName:!1};function kn(e){const t=e?.provider;return typeof t=="string"&&t?t:iu}function ir(e){return e&&IF[e]||PF}const _F="opencode",LF="https://opencode.ai/zen/go/v1";function mA(e,t){if(!e||e.clientEmulation!==_F)return!1;const o=((typeof t=="string"?t.trim():"")||String(e.baseUrl||"")).trim().replace(/\/+$/,"").toLowerCase();return o?o!==LF:!1}function zF(e){const t=e?kn(e):"";return t.startsWith("custom-")&&(Pe().wbProviders?.customList?.()||[]).find(o=>o?.id===t)||null}function BF(e){return e?mA(zF(e),e.baseUrl):!1}function hA(e){const t=Array.isArray(e?.providers)?e.providers:[],a=Array.isArray(e?.accounts)?e.accounts:[],o=new Map;a.forEach(d=>{const f=kn(d);o.set(f,(o.get(f)||0)+1)});const c=new Map;return t.forEach(d=>{d?.id&&c.set(String(d.id),{id:String(d.id),label:String(d.label||d.id),count:Number(d.count)||0})}),o.forEach((d,f)=>{c.has(f)||c.set(f,{id:f,label:Pe().wbProviders?.labelOf?.(f)||f,count:d})}),c.size||c.set(iu,{id:iu,label:Pe().wbProviders?.labelOf?.(iu)||"WorkBuddy 国内版",count:0}),[...c.values()]}function Bh(e){const t=ir(kn(e)).identifier;return String(e?.[t]||"")}function gA(e){const t=Number(e)||0;return t<=0?0:t<1e11?t*1e3:t}function HF(e){const t=ir(kn(e)).expiry;return gA(e?.[t])}function Ta(e){const t=kn(e);return t.startsWith("custom-")?!!e?.balanceQuery?.scheme:ir(t).usage}const tj=30,xA=86400,bA=60,vA=1800,yA=86400,jA=1,UF=95e5;function VF(e){return e==="codearts"?[{type:"token",action:"skip",threshold:UF,reset:"daily",enabled:!0}]:e==="cline-free"?[]:[{type:"balance",action:"skip",threshold:jA,enabled:!0}]}function wA(e){const t=e?.usageQuery;if(!t||typeof t!="object")return{enabled:!0,interval:bA};const a=t.enabled===void 0?!0:t.enabled===!0,o=Number(t.interval)||0,c=o>=tj&&o<=xA;return{enabled:a,interval:a&&!c?bA:o}}function FF(e){if(!e||typeof e!="object")return!1;const t=e;if(t.type!=="balance"&&t.type!=="token"||t.action!=="skip"&&t.action!=="disable")return!1;const a=Number(t.threshold);if(!Number.isFinite(a)||a<=0)return!1;if(t.type==="token"&&t.reset!=="daily"){const o=Number(t.period);if(!Number.isInteger(o)||oyA)return!1}return!0}function $F(e){const t=e?.lowBalance;if(!t||typeof t!="object"||!t.mode)return VF(kn(e));const a=Number(t.threshold),o=Number.isFinite(a)&&a>0?a:jA;return t.mode!=="skip"&&t.mode!=="disable"?[]:[{type:"balance",action:t.mode,threshold:o,enabled:!0}]}function cu(e){const t=e?.limiters;return Array.isArray(t)?t.filter(FF):$F(e)}function qF(e){return cu(e).filter(t=>t.type==="token")}function GF(e,t){const a=t*1e3;return e-e%a}function SA(e){return e.reset==="daily"?0:e.period??0}function nj(e,t=Date.now()){if(e===0){const a=new Date(t);return a.setHours(0,0,0,0),a.getTime()}return GF(t,e)}function gf(e,t,a=Date.now()){if(e.type!=="token")return null;const o=SA(e),c=(t||[]).find(d=>Number(d.kind)===o);return c&&Number(c.windowStart)===nj(o,a)?c:null}function Hh(e,t){const a=cu(e).filter(f=>f.type==="balance"&&f.action==="skip"&&f.enabled!==!1&&f.threshold>0);if(!a.length||!t||typeof t!="object")return!1;const o=t;if(o.unlimited)return!1;const c=o.totalLeft??o.available;if(c==null||c==="")return!1;const d=Number(c);return Number.isFinite(d)&&a.some(f=>dc.type==="token"&&c.action==="skip"&&c.enabled!==!1);if(!a.length||!t?.length)return!1;const o=Date.now();return a.some(c=>{const d=gf(c,t,o);return d!==null&&Number(d.used)>=c.threshold})}function KF(e,t){return cu(e).some(a=>{if(a.type!=="token"||a.action!=="disable"||a.enabled===!1)return!1;const o=gf(a,t);return o!==null&&Number(o.used)>=a.threshold})}function rj(e,t=Date.now()){const a=SA(e),o=nj(a,t),c=a===0?Math.max(0,nj(0,o+864e5+36e5)-t):Math.max(0,o+a*1e3-t);return{kind:a,startMs:o,remainingMs:c,daily:a===0}}function Uh(e,t){if(e<=0)return"";const a=Math.ceil(e/6e4);if(t){const o=Math.ceil(e/36e5);return o>=1?r("今日剩 {n} 小时",{n:o}):r("今日剩 {n} 分钟",{n:a})}return a>=1?r("剩 {n} 分钟",{n:a}):r("剩不到 1 分钟")}function Tl(e){const t=Number(e);if(!Number.isFinite(t))return"—";const a=window.wbUnits;return a?.formatTokens?a.formatTokens(t):String(Math.round(t))}function NA(e){return e>0&&e%3600===0?r("{n} 小时",{n:e/3600}):e>0&&e%60===0?r("{n} 分钟",{n:e/60}):r("{n} 秒",{n:e})}function xf(e){return e?.desktop===!0}function kA(e){return e?.chatSupported!==!1}function YF(e){return typeof e=="string"&&e.startsWith("custom-")}function XF(e){return r(e==="enterprise"?"企业":e==="ultimate"?"旗舰":"个人")}function Vh(e,t){const a=Number(e?.priority??100)-Number(t?.priority??100);return a!==0?a:(Number(e?.addedAt)||0)-(Number(t?.addedAt)||0)}function cr(e){return e?.enabled!==!1}function bf(e,t=""){const a=e?.rateLimits||{},o=Date.now();return t?Number(a[t]?.resetAt)>o:Object.values(a).some(c=>Number(c?.resetAt)>o)}function CA(e){return e?.edition==="intl"?"intl":"cn"}function TA(e){return ir(kn(e)).claim?e?.canClaim!==!1:!1}const EA="coding-plan",jo="start-plan";function Fh(e){return!!ir(kn(e)).planChannel}function aj(e){return Fh(e)?String(e?.zcodePlan||"").trim()===jo?jo:EA:""}function QF(e){return r(e===jo?"活动套餐(Start Plan)":"编码套餐(Coding Plan)")}function AA(e){switch(String(e??"").trim()){case"pending":return r("待生效");case"active":return r("生效中");case"expired":return r("已过期");case"unknown":return r("状态未知");default:return String(e??"")}}function $h(e){const t=e?.claimPlans;if(!t||typeof t!="object"||Array.isArray(t))return[];const a=lj();return Object.entries(t).filter(([,o])=>Number(o)>0&&lj(Number(o))===a).map(([o])=>o)}function ZF(e){return $h(e).length>0}function WF(e){const t=$h(e),a=t.length?r("({plans})",{plans:t.join(r("、"))}):"";return r("今天(北京时间 {day})已领取 {n} 份{names};还有其他可领套餐时,点这里可以继续领;活动按自然日发新套餐,明天可再领",{day:lj(),n:t.length,names:a})}function JF(e){return!!ir(kn(e)).usageDetail}function RA(e){return!!ir(kn(e)).creditDetail}function OA(e){return/^free$/i.test(String(e??"").trim())}function e$(e){const t=String(e??"").trim();return/^trial$/i.test(t)?r("试用版"):OA(t)?r("免费版"):t}function lj(e=Date.now()){return new Date(e+8*3600*1e3).toISOString().slice(0,10)}function vf(e,t,a){return bf(e)||Hh(e,t)||sj(e,a)}function MA(e,t){const a=String(t.q||"").trim().toLowerCase();return a?[uu(e),e?.name,e?.nickname,e?.email,Bh(e),e?.id].some(c=>String(c||"").toLowerCase().includes(a)):!0}function DA(e,t){return t.provider==="all"||kn(e)===t.provider}function oj(e,t){return t.enabled==="all"?!0:t.enabled==="enabled"?cr(e):!cr(e)}function IA(e,t,a,o){if(t.limit==="all")return!0;if(!cr(e))return!1;const c=vf(e,a?.(e),o?.(e));return t.limit==="limited"?c:!c}function PA(e,t,a,o){return DA(e,t)&&oj(e,t)&&IA(e,t,a,o)&&MA(e,t)}function t$(e,t,a,o){return(e||[]).filter(c=>PA(c,t,a,o))}function _A(e,t,a,o){const c=e||[],d=g=>c.filter(v=>DA(v,t)&&(g==="enabled"||oj(v,t))&&MA(v,t)),f=d("enabled"),p=d("limit");return{enabledAll:f.length,enabled:f.filter(cr).length,disabled:f.filter(g=>!cr(g)).length,limitAll:p.length,normal:p.filter(g=>cr(g)&&!vf(g,a?.(g),o?.(g))).length,limited:p.filter(g=>cr(g)&&vf(g,a?.(g),o?.(g))).length}}function ij(e){const t=e?.rateLimits;if(!t||typeof t!="object")return[];const a=Date.now();return Object.entries(t).map(([o,c])=>({model:o,...c&&typeof c=="object"?c:{}})).filter(o=>Number(o.resetAt)>a).sort((o,c)=>Number(o.resetAt)-Number(c.resetAt))}function cj(e){const t=(e||[]).slice().sort(Vh),a=new Map;return t.forEach((o,c)=>a.set(o.id,{position:c+1,total:t.length})),a}function n$(e,t,a,o){const c=(e||[]).slice().sort(Vh),d=[],f=new Map;for(const p of c){const g=kn(p);f.has(g)||(f.set(g,[]),d.push(g)),f.get(g).push(p)}return d.map((p,g)=>{const v=f.get(p)||[];return{provider:p,label:Pe().wbProviders?.labelOf?.(p)||p,rank:g+1,members:v,accounts:t?v.filter(t):v,enabled:v.filter(cr).length,disabled:v.filter(y=>!cr(y)).length,limited:v.filter(y=>cr(y)&&vf(y,a?.(y),o?.(y))).length}})}function uu(e){if(!e)return"";const t=String(e.name||"").trim();if(e.nameCustom===!0&&t)return t;const a=String(e.email||"").trim();return ir(kn(e)).emailAsName&&a?a:e?.nickname||t||Bh(e)||e?.id||""}const uj="已限流",LA=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime();function dj(e){const t=Number(e);if(!Number.isFinite(t)||t<=0||t<=Date.now())return uj;const a=new Date(t),o=a.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",hour12:!1}),c=Math.round((LA(a)-LA(new Date))/864e5);return c===0?r("今天 {clock}",{clock:o}):c===1?r("明天 {clock}",{clock:o}):r("{month}月{day}日 {clock}",{month:a.getMonth()+1,day:a.getDate(),clock:o})}function s$(e){const t=kn(e);if(!ir(t).edition)return"";const a=CA(e),o=e?.editionLabel,c=o||(a==="intl"?"国际版":"国内版");return(Pe().wbProviders?.labelOf?.(t)||"").includes(c)?"":o||r(a==="intl"?"国际版":"国内版")}function r$(e){return[kA(e)?null:{text:r("仅账号管理"),kind:"plain",title:r("该提供商的推理转发尚未接入,账号不参与转发")},YF(kn(e))&&e.hasCredentials===!1?{text:r("未配置凭证"),kind:"bad",title:r("这条自定义账号既没有 API Key,也没有勾选「无需鉴权」:转发时会被跳过,该提供商下的模型也不会出现在模型列表里。去账号「设置」里补上 Key,或勾选「该上游无需鉴权」")}:null,e.proxy?.error?{text:r("代理异常"),kind:"bad",title:r("{error}(转发时会回退直连)",{error:e.proxy.error})}:null,aj(e)===jo?{text:r("活动套餐"),kind:"plain",title:r("转发走活动套餐通道(zcode.z.ai 的 Anthropic 端点,用账号里领到的额度);在账号设置里可切回编码套餐")}:null].filter(t=>t!==null)}const zA="workbuddy-desktop-accounts-filters",BA="workbuddy-desktop-accounts-collapsed",HA="workbuddy-desktop-accounts-names-hidden";function a$(){const e={provider:"all",enabled:"all",limit:"all",q:""},t=Pe().wbFilterMemory?.load(zA,e)||e;return{provider:String(t.provider||"all"),enabled:String(t.enabled||"all"),limit:String(t.limit||"all"),q:""}}function l$(){try{const e=JSON.parse(localStorage.getItem(BA)||"[]");return new Set(Array.isArray(e)?e.map(t=>String(t)).filter(Boolean):[])}catch{return new Set}}function o$(){try{return localStorage.getItem(HA)==="1"}catch{return!1}}let pn={version:0,filter:a$(),collapsed:l$(),selected:new Set,panels:new Map,connections:new Map,clash:null,dialog:null,namesHidden:o$(),usageBusy:!1,usageInflight:new Set};const fj=new Set;function UA(e){return fj.add(e),()=>{fj.delete(e)}}function Zs(){return pn}function Cn(e){pn={...pn,...e,version:pn.version+1},fj.forEach(t=>t())}function br(){Cn({})}function pj(){return Pe().wbApp?.getState?.()?.accounts}function El(){const e=pj()?.accounts;return Array.isArray(e)?e:[]}function Ea(e){return El().find(t=>t.id===e)||null}function i$(e,t){const a=n$(El(),c=>PA(c,pn.filter,e,t),e,t);return{groups:a.filter(c=>c.accounts.length>0),allGroups:a}}function VA(){return hA(pj())}function c$(e,t){return _A(El(),pn.filter,e,t)}function u$(){return cj(El())}function qh(){Pe().wbFilterMemory?.save(zA,{provider:pn.filter.provider,enabled:pn.filter.enabled,limit:pn.filter.limit})}function d$(e){pn.filter.q!==e&&Cn({filter:{...pn.filter,q:e}})}function f$(e){const t=e||"all";pn.filter.provider!==t&&(Cn({filter:{...pn.filter,provider:t}}),qh())}function FA(e,t){const a={...pn.filter,[e]:t};a.enabled==="disabled"&&a.limit!=="all"&&(a.limit="all"),Cn({filter:a}),qh()}function Gh(){return pn.filter.provider!=="all"||pn.filter.enabled!=="all"||pn.filter.limit!=="all"||pn.filter.q.trim()!==""}function $A(){Cn({filter:{provider:"all",enabled:"all",limit:"all",q:""}}),qh()}function p$(){const e=pn.filter.provider;e!=="all"&&(VA().some(t=>t.id===e)||(Cn({filter:{...pn.filter,provider:"all"}}),qh()))}function qA(e){try{localStorage.setItem(BA,JSON.stringify([...e]))}catch{}}function GA(e){const t=new Set(pn.collapsed);t.has(e)?t.delete(e):t.add(e),qA(t),Cn({collapsed:t})}function m$(e,t){const a=new Set(pn.collapsed);for(const o of e)t?a.add(o):a.delete(o);qA(a),Cn({collapsed:a})}function h$(e){return pn.selected.has(e)}function g$(e,t){const a=new Set(pn.selected);t?a.add(e):a.delete(e),Cn({selected:a})}function KA(e,t){const a=new Set(pn.selected);for(const o of e)t?a.add(o):a.delete(o);Cn({selected:a})}function x$(){Cn({selected:new Set})}function YA(e,t){return pn.panels.get(e)?.has(t)===!0}function XA(e,t,a){if(!e)return;const o=new Map(pn.panels),c=new Set(o.get(e)||[]);a?c.add(t):c.delete(t),c.size?o.set(e,c):o.delete(e),Cn({panels:o})}function b$(e,t){const a=new Map(pn.panels);for(const o of e){const c=new Set(a.get(o)||[]);c.add(t),a.set(o,c)}Cn({panels:a})}function v$(){const e=!pn.namesHidden;try{localStorage.setItem(HA,e?"1":"0")}catch{}Cn({namesHidden:e})}function y$(e){return"*".repeat(Math.min(Math.max(e.length,4),12))}const QA="usage_not_configured",wo=new Map,yf=new Map;function oa(e,t,a){wo.set(e,t),t!=null&&du(t)?yf.set(e,a):yf.delete(e)}function Qa(e){const t=wo.get(e.id);if(t===void 0)return;if(!du(t))return t;const a=Math.max(Number(e.addedAt)||0,Number(e.updatedAt)||0);return(yf.get(e.id)||0)>=a?t:void 0}const jf=new Map;let ZA=0;function Al(e){return e?jf.get(e.id)||[]:[]}function j$(e){const t=Number(e?.tokenAt)||0;if(!t||t===ZA)return!1;const a=e?.tokenUsage;if(!a||typeof a!="object")return!1;ZA=t;const o=new Map;for(const[d,f]of Object.entries(a)){if(!Array.isArray(f))continue;const p=[];for(const g of f){if(!g||typeof g!="object")continue;const v=Number(g.kind),y=Number(g.windowStart),b=Number(g.used);!Number.isFinite(v)||v<0||!Number.isFinite(y)||y<=0||!Number.isFinite(b)||b<0||p.push({kind:v,windowStart:y,used:b})}o.set(d,p)}const c=o.size!==jf.size||[...o].some(([d,f])=>{const p=jf.get(d);return!p||p.length!==f.length||f.some((g,v)=>g.used!==p[v]?.used||g.windowStart!==p[v]?.windowStart)});jf.clear();for(const[d,f]of o)jf.set(d,f);return c}let Kh=null;async function WA(e={}){const t=Zs().clash;if(!e.force&&t)return t;Kh||(Kh=(async()=>{try{const o=await Pe().workbuddyDesktop?.getProxies?.();if(!o||typeof o!="object"||!o.clash)throw new Error(r("代理列表响应异常({type})",{type:typeof o}));return o.clash}finally{Kh=null}})());const a=await Kh;return Cn({clash:a}),a}function w$(){Cn({clash:null})}let wf=null,Yh=null;function S$(){return wf}async function JA(e={}){if(!e.force&&wf)return wf;Yh||(Yh=(async()=>{try{const a=await Pe().workbuddyDesktop?.getProxyPool?.();if(!a||typeof a!="object"||!Array.isArray(a.items))throw new Error(r("代理池响应异常({type})",{type:typeof a}));return a.items}finally{Yh=null}})());const t=await Yh;return wf=t,t}let mj=null;function N$(){return mj}let Xh=0,eR=!1;function k$(){if(!(wf||Date.now(){Xh=0,mj=null,br()}).catch(e=>{mj=ut(e),br()})}}function Qh(e){if(!Ea(e)){Le(r("账号不存在,请刷新后重试"),"err");return}Cn({dialog:{kind:"settings",id:e}})}function Zh(){Cn({dialog:null})}function hj(e,t="enable"){const a=(Array.isArray(e)?e:[]).filter(o=>Ea(o));if(!a.length){Le(r("请先勾选要操作的账号"),"err");return}Cn({dialog:{kind:"batch",ids:a,action:t}})}function C$(e){let t=!1;for(const f of[...wo.keys()])e.has(f)||(wo.delete(f),t=!0);for(const f of[...yf.keys()])e.has(f)||yf.delete(f);const a=new Map(Zs().panels);for(const f of[...a.keys()])e.has(f)||(a.delete(f),t=!0);const o=new Map(Zs().connections);for(const f of[...o.keys()])e.has(f)||(o.delete(f),t=!0);const c=new Set(Zs().usageInflight);for(const f of[...c])e.has(f)||(c.delete(f),t=!0);const d=new Set(Zs().selected);for(const f of[...d])e.has(f)||(d.delete(f),t=!0);t&&Cn({panels:a,connections:o,usageInflight:c,selected:d})}const T$=2e3;function tR(e){return Zs().connections.get(e)||0}async function nR(){try{const e=await Pe().workbuddyDesktop?.getAccountConnections?.(),t=e?.counts&&typeof e.counts=="object"?e.counts:{},a=new Map;for(const[o,c]of Object.entries(t)){const d=Number(c)||0;d>0&&a.set(o,d)}return Cn({connections:a}),!0}catch{return!1}}let sR=null;function E$(){sR||(sR=setInterval(()=>{document.hidden||Pe().wbApp?.currentPage!=="accounts"||nR()},T$))}function gj(){return El().filter(e=>Ta(e)&&e.available!==!1)}function du(e){if(e==null)return null;if(typeof e=="string")return{message:e,notConfigured:!1};if(typeof e!="object")return null;const t=e.error;return t?{message:String(t),notConfigured:e.code===QA}:null}function rR(e){return e.usage?e.usage:{error:e.error?String(e.error):r("余额响应为空"),code:e.code}}function aR(e){const t=Array.isArray(e?.results)?e.results:[],a=Number(e?.at)||Date.now();let o=0;for(const c of t)c?.id&&(oa(String(c.id),rR(c),Number(c.at)||a),o++);return o&&(br(),Pe().wbApp?.renderTopbarStatus?.()),o}let lR=!1;function A$(e){if(!RA(e))return!1;const t=Qa(e);return!t||typeof t!="object"||Array.isArray(t)||du(t)?!1:!Array.isArray(t.credits)}async function R$(){if(!lR){lR=!0;for(const e of El().filter(A$)){const t=wo.get(e.id);try{await Sf(e.id)}catch{}const a=wo.get(e.id);t!==void 0&&(!a||du(a))&&oa(e.id,t,Date.now()),br()}}}let oR=0;async function O$(){try{const e=await Pe().workbuddyDesktop?.getBalancesSnapshot?.(),t=j$(e);t&&(br(),Pe().wbApp?.renderTopbarStatus?.());const a=Number(e?.at)||0;return!a||a===oR||(oR=a,!aR(e))?t:(R$(),!0)}catch{return!1}}async function Sf(e){const t=await Pe().workbuddyDesktop?.getAllBalances?.(e||void 0),a=Array.isArray(t?.results)?t.results:[],o=Date.now(),c=new Set;for(const d of a){if(!d?.id)continue;const f=String(d.id);e&&f!==e||(c.add(f),oa(f,rR(d),o))}if(e)return c.has(e)||oa(e,r("未返回余额数据"),o),br(),t;for(const d of gj())c.has(d.id)||oa(d.id,r("未返回余额数据"),o);return br(),t}async function iR(){if(Zs().usageBusy)return;const e=gj();if(!e.length){Le(r("暂无可查询余额的账号"),"err");return}Cn({usageBusy:!0}),e.forEach(t=>oa(t.id,null,Date.now())),br();try{const t=(await Sf(null))?.results||[],a=t.filter(f=>f.usage).length,o=t.filter(f=>f.code===QA).length,c=o?r("({n} 个未配置查询凭证)",{n:o}):"",d=t.length-a-o;Le(a+o===t.length?r("✅ 已更新 {n} 个账号的余额{suffix}",{n:a,suffix:c}):r("已更新 {ok}/{total} 个账号,{failed} 个失败",{ok:a,total:t.length,failed:d}),d?"err":"ok")}catch(t){const a=ut(t);e.forEach(o=>oa(o.id,r("查询失败:{message}",{message:a}),Date.now())),br(),Le(r("余额查询失败:{message}",{message:a}),"err")}finally{Cn({usageBusy:!1})}}async function cR(e){if(Zs().usageInflight.has(e))return;const t=new Set(Zs().usageInflight);t.add(e),oa(e,null,Date.now()),Cn({usageInflight:t});try{await Sf(e)}finally{const a=new Set(Zs().usageInflight);a.delete(e),Cn({usageInflight:a})}}async function M$(e){if(!Zs().usageInflight.has(e))try{await cR(e);const t=du(wo.get(e));t?.notConfigured?Le(t.message,"ok"):t?Le(r("余额查询失败:{message}",{message:t.message}),"err"):Le(r("✅ 已更新余额"))}catch(t){oa(e,r("查询失败:{message}",{message:ut(t)}),Date.now()),br(),Le(r("余额查询失败:{message}",{message:ut(t)}),"err")}}async function Wh(e){if(e){const a=Ea(e);if(!a||!Ta(a))return;try{await cR(e)}catch(o){oa(e,r("查询失败:{message}",{message:ut(o)}),Date.now()),br()}return}if(Zs().usageBusy)return;const t=gj();if(t.length){Cn({usageBusy:!0}),t.forEach(a=>oa(a.id,null,Date.now())),br();try{await Sf(null)}catch(a){const o=ut(a);t.forEach(c=>oa(c.id,r("查询失败:{message}",{message:o}),Date.now())),br()}finally{Cn({usageBusy:!1})}}}async function uR(e,t){try{await Pe().workbuddyDesktop?.updateAccount?.(e,{enabled:t}),await Pe().wbApp?.refresh?.(),Le(r(t?"✅ 已启用":"✅ 已禁用"))}catch(a){Le(r("操作失败:{message}",{message:ut(a)}),"err"),Pe().wbApp?.refresh?.()}}async function dR(e,t){if(!e.length)return!1;try{return await Pe().workbuddyDesktop?.reorderAccounts?.(e),Le(t?r("✅ 已保存:{note}",{note:t}):r("✅ 顺序已保存")),await Pe().wbApp?.refresh?.(),!0}catch(a){return Le(r("顺序未保存:{message}",{message:ut(a)}),"err"),Pe().wbApp?.refresh?.(),!1}}async function fR(e,t){if(e.length)try{await Pe().workbuddyDesktop?.batchAccounts?.({action:t?"enable":"disable",ids:e}),Le(t?r("✅ 已启用 {n} 个账号",{n:e.length}):r("✅ 已禁用 {n} 个账号",{n:e.length})),await Pe().wbApp?.refresh?.()}catch(a){Le(r("操作失败:{message}",{message:ut(a)}),"err"),Pe().wbApp?.refresh?.()}}async function D$(e,t){try{await Pe().workbuddyDesktop?.clearRateLimits?.(e,t||null),Le(t?r("✅ 已清除 {model} 的限流标记",{model:t}):r("✅ 已清除该账号全部限流标记")),await Pe().wbApp?.refresh?.()}catch(a){Le(r("清除失败:{message}",{message:ut(a)}),"err")}}async function I$(e,t,a){if(t===pR){Qh(e);return}if(t!==Jh&&t!==a)try{const o=t===""?null:{source:"pool",proxyId:t.slice(Ya.length)},d=(await Pe().workbuddyDesktop?.updateAccount?.(e,{proxy:o}))?.changes,f=Array.isArray(d)&&d.length?d[0]:r("代理已更新");Le(`✅ ${f}`)}catch(o){Le(r("保存失败:{message}",{message:ut(o)}),"err")}finally{await Pe().wbApp?.refresh?.()}}const Jh="__proxy_custom__",pR="__proxy_custom_edit__";function mR(e,t){const a=Ea(e);if(!a){Le(r("账号不存在,请刷新后重试"),"err");return}const o=Pe().wbZcodePlans;if(!o?.open){Le(r("套餐明细弹窗未加载,请重启应用后重试"),"err");return}o.open({id:e,name:t||a.name})}function P$(e,t,a=1){return{seat:t.get(e.id)||{position:1,total:1},rank:a,picked:h$(e.id),usageEntry:wo.get(e.id),limitsOpen:YA(e.id,"limits"),connections:tR(e.id)}}const _$={DEFAULT_PROVIDER_ID:iu,RACCOON_PROVIDER_ID:DF,providerOf:kn,providerFeatures:ir,providerSummaries:hA,identifierOf:Bh,tokenExpiryOf:HF,supportsUsage:Ta,isDesktopAccount:xf,supportsChat:kA,byPriorityOrder:Vh,typeLabel:XF,isEnabled:cr,isRateLimited:bf,isLimited:e=>vf(e,e?Qa(e):void 0,Al(e)),accountEdition:CA,supportsClaim:TA,matchEnabled:oj,matchLimit:IA,visibleAccounts:t$,filterCounts:_A,positionMap:cj,activeLimits:ij,editionSuffix:s$,formatResetText:dj};function L$(){window.wbAccountsView={render:()=>br(),refreshCaches:C$,openPanels:b$,syncConnections:nR,applyBalances:aR,syncBalancesSnapshot:O$,queryUsageFor:Sf,queryAllUsage:iR,refreshUsageAfterCheckin:Wh,supportsUsage:Ta,isDesktopAccount:xf,isEnabled:cr,isRateLimited:bf},window.wbAccountsModel=_$,window.wbAccountPanel={open:Qh,close:Zh,openBatch:hj,closeBatch:Zh,syncAddProvider:()=>Pe().wbAccountAddForms?.syncAddProvider?.(),invalidate:w$}}function z$(e){return e.type==="balance"?r("余额 < {threshold}",{threshold:e.threshold}):e.reset==="daily"?r("每日消耗 ≥ {count} Token(每天 0 点重置)",{count:Tl(e.threshold)}):r("每 {period}消耗 ≥ {count} Token",{period:NA(e.period??0),count:Tl(e.threshold)})}function B$(e){return e.action==="disable"?r("禁用该账号(需手动重新启用)"):r("跳过该账号(自动恢复)")}function H$(e){return`${Math.round(e.threshold).toLocaleString("en-US")} Token`}function U$(e,t){if(t.enabled===!1)return{text:r("已停用"),kind:"off"};if(t.type==="balance"){const v=Qa(e),y=Hh(e,v),b=v&&typeof v=="object"?v:null,j=b?b.totalLeft??b.available:void 0,w=j==null||j===""||b?.unlimited?"":r(" · 当前 {n}",{n:Number(j)});return y?{text:r("已跳过{current}",{current:w}),kind:"warn",title:r("余额低于阈值,转发时会跳过该账号(余额回升自动恢复)")}:{text:r("未触发{current}",{current:w}),kind:"ok"}}const a=Al(e),o=gf(t,a),c=o?o.used:0,d=Tl(t.threshold),f=t.reset==="daily"?r(" · 今日 {used} / {quota}",{used:Tl(c),quota:d}):r(" · 本周期 {used} / {quota}",{used:Tl(c),quota:d}),p=o?` · ${Uh(rj(t).remainingMs,t.reset==="daily")}`:"";return o!==null&&c>=t.threshold?t.action==="disable"?e.enabled===!1?{text:r("已触发 · 账号已禁用"),kind:"danger",title:r("重置也不恢复,需手动启用")}:{text:r("已达上限{usage}",{usage:f}),kind:"warn",title:r("稍后由后台判定自动禁用")}:{text:r("已跳过{usage}{countdown}",{usage:f,countdown:p}),kind:"warn",title:r("窗口内已用 {used} / {limit} Token,转发时会跳过该账号(重置后自动恢复)",{used:Math.round(c).toLocaleString("en-US"),limit:Math.round(t.threshold).toLocaleString("en-US")})}:{text:r("未触发{usage}{countdown}",{usage:f,countdown:p}),kind:"ok",title:H$(t)}}function V$(e){return e>0&&e%3600===0?{value:String(e/3600),unit:"hours"}:e>0&&e%60===0?{value:String(e/60),unit:"minutes"}:{value:"1",unit:"hours"}}function hR(e){const t={type:"balance",action:"skip",thresholdInput:"",tokenUnit:"wan",reset:"fixed",periodInput:"1",periodUnit:"hours"};if(!e)return t;if(e.type==="balance")return{...t,type:"balance",action:e.action,thresholdInput:String(e.threshold)};if(e.reset==="daily")return{...t,type:"token",action:e.action,reset:"daily",thresholdInput:String(e.threshold%1e4===0?e.threshold/1e4:e.threshold),tokenUnit:e.threshold%1e4===0?"wan":"unit"};const a=V$(e.period??0);return{...t,type:"token",action:e.action,reset:"fixed",thresholdInput:String(e.threshold%1e4===0?e.threshold/1e4:e.threshold),tokenUnit:e.threshold%1e4===0?"wan":"unit",periodInput:a.value,periodUnit:a.unit}}function gR(e){const t=Number(e.thresholdInput);if(!Number.isFinite(t)||t<=0)return{error:r("限制阈值必须是大于 0 的数字")};if(e.type==="balance")return{rule:{type:"balance",action:e.action,threshold:t,enabled:!0}};const a=Math.round(e.tokenUnit==="wan"?t*1e4:t);if(e.reset==="daily")return{rule:{type:"token",action:e.action,threshold:a,reset:"daily",enabled:!0}};const o=Number(e.periodInput)*(e.periodUnit==="hours"?3600:60);if(!Number.isFinite(o)||o<=0)return{error:r("请填写重置周期")};const c=Math.round(o);return cyA?{error:r("重置周期必须是 30 分钟 ~ 24 小时")}:{rule:{type:"token",action:e.action,threshold:a,period:c,reset:"fixed",enabled:!0}}}function F$({account:e,target:t,onClose:a,onSave:o}){const[c,d]=x.useState(""),[f,p]=x.useState(t?.draft??null);if(x.useEffect(()=>{p(t?.draft??null),d("")},[t]),!t||!f)return null;const g=b=>{d(""),p({...f,...b})},v=()=>{const b=gR(f);if("error"in b){d(b.error);return}o(b.rule,t.index)},y=()=>{if(f.type==="balance"){const D=Qa(e);if(D&&typeof D=="object"){const C=D;if(C.unlimited)return r("当前可用 ∞(不参与余额不足判定)");const A=C.totalLeft??C.available;if(A!=null&&A!=="")return r("当前余额 {n};与余额列同一数字口径,严格小于才触发(等于阈值仍可用)",{n:Number(A)})}return r("读数来自自动余额查询;与余额列同一数字口径,严格小于才触发(等于阈值仍可用)")}const b=gR(f);if(!("rule"in b))return"";const j=b.rule,w=gf(j,Al(e));if(!w)return j.reset==="daily"?r("窗口 = 今天 0 点起(本地时区),0 点重置即清零恢复;按账号在 requests 表聚合"):r("窗口对齐自然时间(整点 / 整 N 分钟一轮回),重置即清零恢复;按账号在 requests 表聚合");const S=rj(j),N=Tl(w.used),k=Tl(j.threshold),E=j.reset==="daily"?r("今日已用"):r("本周期已用");return r("{scope} {used} / {quota} Token,{countdown}重置",{scope:E,used:N,quota:k,countdown:Uh(S.remainingMs,S.daily)})};return s.jsx(Qt,{open:!0,onOpenChange:b=>{b||a()},children:s.jsxs(Zt,{className:"w-[min(580px,calc(100vw-48px))]",showCloseButton:!0,children:[s.jsx(Kt,{children:s.jsx(Gt,{children:t.index>=0?r("编辑限制"):r("添加限制")})}),s.jsxs(Bt,{children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("限制类型")}),s.jsxs(ft,{value:f.type,onValueChange:b=>g({type:b,thresholdInput:""}),children:[s.jsx(mt,{className:"w-[150px]","aria-label":r("限制类型"),children:s.jsx(pt,{children:f.type==="balance"?r("余额"):r("Token 消耗")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"balance",children:r("余额")}),s.jsx(qe,{value:"token",children:r("Token 消耗")})]})]}),s.jsx("span",{className:"detail",children:r("余额沿用现有口径;Token 按重置方式内的累计消耗判定(切换类型会清空阈值)")})]}),f.type==="balance"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("触发条件")}),s.jsx("span",{className:"detail",style:{fontSize:13},children:r("余额低于")}),s.jsx($e,{type:"number",min:0,step:1,className:"max-w-[120px]",placeholder:r("阈值"),value:f.thresholdInput,onChange:b=>g({thresholdInput:b.currentTarget.value})}),s.jsx("span",{className:"detail",style:{fontSize:13},children:r("时")})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("触发后")}),s.jsxs(ft,{value:f.action,onValueChange:b=>g({action:b}),children:[s.jsx(mt,{className:"min-w-[280px]","aria-label":r("触发动作"),children:s.jsx(pt,{children:f.action==="disable"?r("禁用该账号(需手动重新启用)"):r("跳过该账号(余额回升自动恢复)")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"skip",children:r("跳过该账号(余额回升自动恢复)")}),s.jsx(qe,{value:"disable",children:r("禁用该账号(需手动重新启用)")})]})]})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("重置方式")}),s.jsxs(ft,{value:f.reset,onValueChange:b=>g({reset:b}),children:[s.jsx(mt,{className:"w-[190px]","aria-label":r("重置方式"),children:s.jsx(pt,{children:f.reset==="daily"?r("自然日(每天 0 点)"):r("固定周期")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"fixed",children:r("固定周期")}),s.jsx(qe,{value:"daily",children:r("自然日(每天 0 点)")})]})]}),s.jsx("span",{className:"detail",children:r("有的账号过了 0 点额度就回来 —— 选「自然日」")})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("触发条件")}),f.reset==="daily"?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"detail",style:{fontSize:13},children:r("每日消耗 ≥")}),s.jsx($e,{type:"number",min:0,step:1,className:"max-w-[110px]",placeholder:r("阈值"),value:f.thresholdInput,onChange:b=>g({thresholdInput:b.currentTarget.value})}),s.jsxs(ft,{value:f.tokenUnit,onValueChange:b=>g({tokenUnit:b}),children:[s.jsx(mt,{className:"w-[92px]","aria-label":r("Token 单位"),children:s.jsx(pt,{children:f.tokenUnit==="wan"?r("万"):r("个")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"wan",children:r("万")}),s.jsx(qe,{value:"unit",children:r("个")})]})]}),s.jsx("span",{className:"detail",style:{fontSize:13},children:r("Token 时")})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"detail",style:{fontSize:13},children:r("每")}),s.jsx($e,{type:"number",min:1,step:1,className:"max-w-[90px]",placeholder:r("周期"),value:f.periodInput,onChange:b=>g({periodInput:b.currentTarget.value})}),s.jsxs(ft,{value:f.periodUnit,onValueChange:b=>g({periodUnit:b}),children:[s.jsx(mt,{className:"w-[92px]","aria-label":r("周期单位"),children:s.jsx(pt,{children:f.periodUnit==="hours"?r("小时"):r("分钟")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"minutes",children:r("分钟")}),s.jsx(qe,{value:"hours",children:r("小时")})]})]}),s.jsx("span",{className:"detail",style:{fontSize:13},children:r("内消耗 ≥")}),s.jsx($e,{type:"number",min:0,step:1,className:"max-w-[110px]",placeholder:r("阈值"),value:f.thresholdInput,onChange:b=>g({thresholdInput:b.currentTarget.value})}),s.jsxs(ft,{value:f.tokenUnit,onValueChange:b=>g({tokenUnit:b}),children:[s.jsx(mt,{className:"w-[92px]","aria-label":r("Token 单位"),children:s.jsx(pt,{children:f.tokenUnit==="wan"?r("万"):r("个")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"wan",children:r("万")}),s.jsx(qe,{value:"unit",children:r("个")})]})]}),s.jsx("span",{className:"detail",style:{fontSize:13},children:r("Token 时")})]})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("触发后")}),s.jsxs(ft,{value:f.action,onValueChange:b=>g({action:b}),children:[s.jsx(mt,{className:"min-w-[280px]","aria-label":r("触发动作"),children:s.jsx(pt,{children:f.action==="disable"?r("禁用该账号(需手动重新启用)"):r("跳过该账号(重置后自动恢复)")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"skip",children:r("跳过该账号(重置后自动恢复)")}),s.jsx(qe,{value:"disable",children:r("禁用该账号(需手动重新启用)")})]})]})]})]}),s.jsx("p",{className:"detail limiter-hint",children:y()}),c?s.jsx("p",{className:"detail text-destructive",children:c}):null]}),s.jsxs(nn,{children:[s.jsx(se,{variant:"outline",onClick:a,children:r("取消")}),s.jsx(se,{variant:"default",onClick:v,children:t.index>=0?r("保存规则"):r("添加规则")})]})]})})}function $$({account:e,draft:t,onChange:a}){const[o,c]=x.useState(null),d=()=>c({index:-1,draft:hR(null)}),f=y=>c({index:y,draft:hR(t[y])}),p=(y,b)=>{const j=[...t];b>=0?j[b]=y:j.push(y),a(j),c(null)},g=y=>{a(t.filter((b,j)=>j!==y)),o&&c(null)},v=(y,b)=>{const j=[...t];j[y]={...j[y],enabled:b},a(j)};return s.jsxs(s.Fragment,{children:[t.length?s.jsx("div",{className:"limiter-rules mt-2.5",children:t.map((y,b)=>{const j=U$(e,y);return s.jsxs("div",{className:"limiter-rule","data-off":y.enabled===!1||void 0,children:[s.jsx(ms,{checked:y.enabled!==!1,"aria-label":r("启用该规则"),onCheckedChange:w=>v(b,w===!0)}),s.jsx("div",{className:"limiter-rule-main",children:s.jsxs("span",{className:"limiter-rule-cond",children:[s.jsx(ze,{variant:"secondary",shape:"tag",children:y.type==="balance"?r("余额"):"Token"})," ",r("{cond} 时 → {action}",{cond:z$(y),action:B$(y)})]})}),s.jsx(ze,{variant:j.kind==="ok"?"success":j.kind==="warn"?"warning":j.kind==="danger"?"destructive":"secondary",shape:"tag",title:j.title,children:j.text}),s.jsxs("div",{className:"limiter-rule-ops",children:[s.jsx(se,{variant:"ghost",onClick:()=>f(b),children:r("编辑")}),s.jsx(se,{variant:"ghost",onClick:()=>g(b),children:r("删除")})]})]},b)})}):s.jsx("p",{className:"detail mt-2.5",children:r("还没有限制规则:账号照常参与转发,余额与 Token 消耗都不设上限。")}),s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx(se,{variant:"outline",onClick:d,children:r("+ 添加限制")}),s.jsx("span",{className:"detail",children:r("可添加多条;同类规则也允许并存(例如一条按余额、两条不同重置方式的 Token)")})]}),s.jsx(F$,{account:e,target:o,onClose:()=>c(null),onSave:p})]})}function q$(e,t){const a=cu(e);return JSON.stringify(t)===JSON.stringify(a)?null:{patch:{limiters:t}}}function G$(e){return cu(e).map(t=>({...t}))}const K$={seconds:1,minutes:60,hours:3600};function Y$(e){return e>0&&e%3600===0?{value:String(e/3600),unit:"hours"}:e>0&&e%60===0?{value:String(e/60),unit:"minutes"}:e>0?{value:String(e),unit:"seconds"}:{value:"5",unit:"minutes"}}function X$(e){const{enabled:t,interval:a}=wA(e),o=Y$(t?a:0);return{enabled:t,intervalInput:o.value,unit:o.unit}}function Q$(e,t){const a=Math.round(Number(t.intervalInput)*K$[t.unit]);if(t.enabled){if(!Number.isFinite(Number(t.intervalInput))||Number(t.intervalInput)<=0)return{error:r("请填写查询间隔")};if(axA)return{error:r("查询间隔必须是 {min} 秒 ~ 24 小时",{min:tj})}}const o={},c=wA(e);return(t.enabled!==c.enabled||t.enabled&&a!==c.interval)&&(o.usageQuery={enabled:t.enabled,interval:t.enabled?a:c.interval}),o.usageQuery?{patch:o}:null}function Z$({account:e,draft:t,onChange:a}){const o=c=>a({...t,...c});return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"field-row mt-2.5",children:s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2.5 font-normal",children:[s.jsx(ms,{checked:t.enabled,onCheckedChange:c=>o({enabled:c===!0}),"aria-label":r("自动查询余额")}),s.jsx("span",{className:"text-xs text-subtle",children:r("自动查询余额(按下面的间隔自动刷新余额列的读数)")})]})}),t.enabled?s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:"account-usage-interval",children:r("查询间隔")}),s.jsx($e,{id:"account-usage-interval",type:"number",min:1,step:1,className:"max-w-[110px]",value:t.intervalInput,onChange:c=>o({intervalInput:c.currentTarget.value})}),s.jsxs(ft,{value:t.unit,onValueChange:c=>o({unit:c}),children:[s.jsx(mt,{className:"w-[92px]","aria-label":r("间隔单位"),children:s.jsx(pt,{children:t.unit==="hours"?r("小时"):t.unit==="minutes"?r("分钟"):r("秒")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"seconds",children:r("秒")}),s.jsx(qe,{value:"minutes",children:r("分钟")}),s.jsx(qe,{value:"hours",children:r("小时")})]})]}),s.jsx("span",{className:"detail",children:r("30 秒 ~ 24 小时;手动查询会顺延下一轮")})]}):null]})}const W$={sub2api:{label:"Sub2API",endpoint:"{base}/v1/usage",note:r("用这条账号的 API Key 查询,不需要额外配置。"),fields:[]},new_api:{label:"NewAPI",endpoint:"{base}/api/user/self + /api/status",note:r("用 NewAPI 站点的个人访问令牌查询账户余额(不是这条账号的上游 API Key)。令牌在站点的「个人设置」里生成,只有旧版 / 定制站点才需要额外填用户 ID。"),fields:[{key:"accessToken",label:r("NewAPI 个人访问令牌"),secret:!0,placeholder:r("在 NewAPI 站点「个人设置」里生成的访问令牌"),hint:r("必填;留空 = 不修改,清除用右边的按钮")},{key:"userId",label:r("NewAPI 用户 ID"),placeholder:r("旧版 / 定制站点才需要,新版可留空"),hint:r("可留空:新版请求头只认令牌;旧版会把用户 ID 放进 New-Api-User 头")}]},deepseek:{label:"DeepSeek",endpoint:"{base}/user/balance",note:r("用这条账号的 API Key 查询,不需要额外配置。"),fields:[]},opencode:{label:"OpenCode Go",endpoint:"{base}/v1/usage",note:r("用这条账号的 API Key 查询订阅用量,不需要额外配置;读数展开成 5 小时 / 每周 / 每月三个窗口。"),fields:[]},sensenova:{label:"商汤日日新",endpoint:"platform.sensenova.cn 控制台",note:r("用商汤日日新控制台的账号密码查询(与推理用的 API Key 不是同一套)。网关会自动换取登录票并缓存,过期后自动重登,不需要手动维护。"),fields:[{key:"username",label:r("账号"),placeholder:r("商汤日日新控制台的登录账号"),hint:r("必填")},{key:"password",label:r("密码"),secret:!0,placeholder:r("商汤日日新控制台的登录密码"),hint:r("留空 = 不修改,清除用右边的按钮")}]},zhipu:{label:"智谱",endpoint:"bigmodel.cn 控制台",note:r("用 bigmodel.cn 控制台的访问令牌查询账户余额(人民币元)。令牌是登录后浏览器 Cookie `bigmodel_token_production` 的值:开发者工具 → 应用(Application)→ Cookie 里复制。"),fields:[{key:"token",label:r("访问令牌"),secret:!0,placeholder:r("bigmodel_token_production 的值"),hint:r("必填;留空 = 不修改,清除用右边的按钮")}]},zhipu_zai:{label:"智谱(z.ai 国际)",endpoint:"api.z.ai 控制台",note:r("用这条账号的 API Key 生成签名后查询账户余额(美元),不需要额外配置。要求 API Key 是 z.ai 的「id.secret」形态(控制台生成的 Key 就是)。"),fields:[]}};function Nf(e){return e?W$[e]??null:null}function J$(e,t){return t.secret?t.key==="accessToken"?e?.hasAccessToken===!0:t.key==="password"?e?.hasPassword===!0:t.key==="token"?e?.hasToken===!0:!1:!1}function e8(e){const t=String(e?.scheme||"");return t==="new_api"?e?.hasAccessToken===!0:t==="sensenova"?String(e?.username||"").trim()!==""&&e?.hasPassword===!0:t==="zhipu"?e?.hasToken===!0:!0}function t8(e){return{userId:String(e?.userId||""),username:String(e?.username||""),accessToken:"",password:"",token:""}}function n8(e,t){const a=Nf(e);if(!a||!a.fields.length)return null;const o={};for(const c of a.fields){const d=String(t[c.key]??"").trim();if(c.secret){d&&(o[c.key]=d);continue}o[c.key]=d}return Object.keys(o).length?o:null}function s8({field:e,value:t,configured:a,onValue:o,onClear:c,clearBusy:d,idPrefix:f}){const p=`${f}-${e.key}`;return s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:p,children:e.label}),s.jsx($e,{id:p,className:"min-w-[220px]",type:e.secret?"password":"text",autoComplete:e.secret?"new-password":"off",placeholder:a?r("已配置,留空则不修改"):e.placeholder,title:e.hint,value:t,onChange:g=>o(g.currentTarget.value)}),a&&c?s.jsx(se,{variant:"outline",size:"sm",disabled:d===!0,onClick:c,title:r("清除已配置的 {label}",{label:e.label}),children:r("清除")}):null]})}function r8({spec:e,values:t,configured:a,onValue:o,onClear:c,clearBusy:d,idPrefix:f}){return s.jsxs(s.Fragment,{children:[s.jsxs("p",{className:"detail mt-2.5",children:[r("余额查询方案:{label}",{label:e.label}),s.jsx("span",{className:"ml-1 text-subtle",children:e.endpoint})," — ",e.note]}),e.fields.map(p=>s.jsx(s8,{field:p,idPrefix:f,value:t[p.key]||"",configured:a[p.key]===!0,onValue:g=>o(p.key,g),onClear:c?()=>c(p.key):void 0,clearBusy:d},p.key))]})}const xR=64;function a8(e,t){const a=kn(e);return t.filter(o=>o.id!==e.id&&kn(o)===a)}const Rl=999,bR=8;function eg(e){return uu(e)||e?.id||""}function vR(e){const t=e?.config?.source||e?.source,a=e?.config||null,o=t==="rotate";return{mode:t==="pool"?"pool":o?"rotate":t==="clash"?"clash":t==="custom"?"custom":"none",proxyId:t==="pool"?String(a?.proxyId||""):"",rotateAll:o?a?.all!==!1:!0,rotateIds:o&&Array.isArray(a?.proxyIds)?a.proxyIds.map(String):[],listenerUid:a?.source==="clash"||t==="clash"?String(a?.listenerUid||""):"",protocol:a?.protocol==="socks5"?"socks5":"http",host:a?.host||"",port:a?.port===void 0||a?.port===null?"":String(a.port),username:a?.username||"",password:a?.password||""}}function xj(e){if(e.mode==="none")return null;if(e.mode==="pool"){if(!e.proxyId)throw new Error(r("请先选择已保存的代理"));return{source:"pool",proxyId:e.proxyId}}if(e.mode==="rotate"){if(e.rotateAll)return{source:"rotate",all:!0};if(!e.rotateIds.length)throw new Error(r("轮询至少要选择一条代理(或改选「全部」)"));return{source:"rotate",all:!1,proxyIds:[...e.rotateIds]}}if(e.mode==="clash"){if(!e.listenerUid)throw new Error(r("请先选择 Clash Verge 出口"));return{source:"clash",listenerUid:e.listenerUid}}const t=e.host.trim(),a=Number(e.port);if(!t)throw new Error(r("请填写代理主机地址"));if(!Number.isInteger(a)||a<1||a>65535)throw new Error(r("代理端口必须是 1-65535 的整数"));return{source:"custom",protocol:e.protocol==="socks5"?"socks5":"http",host:t,port:a,username:e.username.trim(),password:e.password}}function yR(e){const t=e.profileActive===!1?r("(其他订阅,可能未生效)"):"",a=e.enabled===!1?r("(已在 Clash 中禁用)"):"";return`${e.name} :${e.port}${t}${a}`}function jR({draft:e,onChange:t,idPrefix:a,allowRotate:o=!1}){const d=Zs().clash,f=Array.isArray(d?.options)?d.options:[],p=e.mode==="clash",[g,v]=x.useState(!1),[y,b]=x.useState(null),[j,w]=x.useState(null),[S,N]=x.useState(""),k=A=>t({...e,...A});x.useEffect(()=>{p&&WA().catch(()=>{})},[p]);const E=x.useCallback((A=!1)=>{N(""),JA({force:A}).then(R=>w(R)).catch(R=>{w([]),N(ut(R))})},[]);x.useEffect(()=>{(e.mode==="pool"||e.mode==="rotate")&&j===null&&E()},[e.mode,j,E]);function D(){return e.rotateAll?(j??[]).filter(A=>A.enabled!==!1).map(A=>A.id):[...e.rotateIds]}async function C(){if(g)return;if(e.mode==="rotate"){const R=D();if(!R.length){Le(r("轮询至少要选择一条代理(或改选「全部」)"),"err");return}const I=R.slice(0,bR);v(!0),b(r("正在连接上游…"));let P=0;const O=[];for(const H of I){const B=j?.find(z=>z.id===H)?.name||H;try{const z=await Pe().workbuddyDesktop?.testProxyPoolItem?.(H);z?.success?P+=1:O.push(`${B}(${z?.error||r("连接失败")})`)}catch(z){O.push(`${B}(${ut(z)})`)}}const _=R.length-I.length,L=r("✅ {ok}/{total} 个出口可用",{ok:P,total:I.length})+(_>0?r("(只测了前 {limit} 个,还有 {rest} 个未测)",{limit:bR,rest:_}):"");b(s.jsxs("span",{className:O.length?"text-destructive":"text-success",children:[L,O.length?` ${Xa(O.join(r(";")))}`:""]})),v(!1);return}if(e.mode==="pool"){if(!e.proxyId){Le(r("请先选择已保存的代理"),"err");return}v(!0),b(r("正在连接上游…"));try{const R=await Pe().workbuddyDesktop?.testProxyPoolItem?.(e.proxyId);b(R?.success?s.jsxs("span",{className:"text-success",children:[r("✅ 出口可用"),R.ip?r(" 出口 IP {ip}",{ip:Xa(R.ip)}):"",R.durationMs!==void 0&&R.durationMs!==""?` ${Xa(String(R.durationMs))}ms`:""]}):s.jsxs("span",{className:"text-destructive",children:["❌ ",Xa(R?.error||r("连接失败"))]}))}catch(R){b(s.jsxs("span",{className:"text-destructive",children:["❌ ",Xa(ut(R))]}))}finally{v(!1)}return}let A;try{A=xj(e)}catch(R){Le(ut(R),"err");return}v(!0),b(r("正在连接上游…"));try{const R=await Pe().workbuddyDesktop?.testProxy?.({proxy:A});R?.success?b(s.jsxs("span",{className:"text-success",children:[r("✅ 出口可用"),R.status!==void 0&&R.status!==""?` HTTP ${Xa(String(R.status))}`:"",R.ip?r(" 出口 IP {ip}",{ip:Xa(R.ip)}):"",R.durationMs!==void 0&&R.durationMs!==""?` ${Xa(String(R.durationMs))}ms`:""]})):b(s.jsxs("span",{className:"text-destructive",children:["❌ ",Xa(R?.error||r("连接失败"))]}))}catch(R){b(s.jsxs("span",{className:"text-destructive",children:["❌ ",Xa(ut(R))]}))}finally{v(!1)}}return s.jsxs("div",{className:"flex flex-col",children:[s.jsxs(kh,{value:e.mode,onValueChange:A=>k({mode:A}),className:"flex-row flex-wrap items-center gap-5","aria-label":r("代理方式"),children:[s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(bo,{value:"none"}),r("无代理(直连)")]}),s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(bo,{value:"pool"}),r("已保存的代理")]}),o?s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",title:r("逐请求轮换出口(换 IP):OpenCode Zen 免费档按 IP 限流,单个 IP 的额度用完会对它一律 429"),children:[s.jsx(bo,{value:"rotate"}),r("轮询(换 IP)")]}):null,p?s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(bo,{value:"clash"}),"Clash Verge"]}):null,s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(bo,{value:"custom"}),r("自定义")]})]}),e.mode==="pool"?s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:`${a}-pool-exit`,children:r("代理")}),s.jsxs(ft,{value:e.proxyId,disabled:!j?.length,onValueChange:A=>k({proxyId:String(A)}),children:[s.jsx(mt,{id:`${a}-pool-exit`,className:"min-w-[220px]",children:s.jsx(pt,{children:j?.find(A=>A.id===e.proxyId)?lu(j.find(A=>A.id===e.proxyId)):j===null?r("正在读取…"):j.length?r("请选择代理"):r("还没有保存的代理")})}),s.jsx(ht,{children:(j??[]).map(A=>s.jsx(qe,{value:A.id,children:lu(A)},A.id))})]}),s.jsx(se,{variant:"outline",size:"sm",onClick:()=>E(!0),children:r("重新读取")})]}),s.jsx("div",{className:"detail mt-1.5",children:S?r("读取失败:{error}",{error:S}):j===null?r("正在读取代理列表…"):j.length?r("地址与端口由「网络代理」页管理:那边改一次、测一次,所有引用它的账号一起生效"):r("「网络代理」页还没有出口 —— 去那里新增,或点「同步 Clash Verge」把 Clash 的出口导进来")})]}):null,e.mode==="rotate"?s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-x-2.5 gap-y-1",children:[s.jsx(Or,{id:`${a}-rotate-all`,checked:e.rotateAll,"aria-label":r("轮询全部代理节点"),onCheckedChange:A=>k({rotateAll:A===!0})}),s.jsx("label",{htmlFor:`${a}-rotate-all`,className:"cursor-pointer text-xs text-subtle",children:r("全部代理节点(推荐)")}),s.jsx("span",{className:"detail",children:r("「网络代理」页里每个启用的出口轮流使用;之后新加的出口自动加入")})]}),e.rotateAll?null:s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:`${a}-rotate-exits`,children:r("轮询的代理")}),s.jsx(_h,{id:`${a}-rotate-exits`,value:e.rotateIds,onValueChange:A=>k({rotateIds:A.map(String)}),options:(j??[]).map(A=>({value:A.id,label:lu(A)})),placeholder:r("选择要轮询的代理(可多选)"),"aria-label":r("轮询的代理")}),s.jsx(se,{variant:"outline",size:"sm",onClick:()=>E(!0),children:r("重新读取")})]}),s.jsx("div",{className:"detail mt-1.5",children:S?r("读取失败:{error}",{error:S}):j===null?r("正在读取代理列表…"):j.length?r("每条请求换一个出口(按顺序轮流),上游看到的 IP 因此是变化的;出口的地址与端口由「网络代理」页管理"):r("「网络代理」页还没有出口 —— 去那里新增,或点「同步 Clash Verge」把 Clash 的出口导进来")})]}):null,e.mode==="clash"?s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:`${a}-clash-exit`,children:r("出口")}),s.jsxs(ft,{value:e.listenerUid,disabled:!f.length,onValueChange:A=>k({listenerUid:String(A)}),children:[s.jsx(mt,{id:`${a}-clash-exit`,className:"min-w-[220px]",children:s.jsx(pt,{children:f.find(A=>String(A.uid)===e.listenerUid)?yR(f.find(A=>String(A.uid)===e.listenerUid)):d?.available===!1?r("未检测到 Clash Verge"):f.length?r("请选择出口"):r("没有可用出口")})}),s.jsx(ht,{children:f.map(A=>s.jsx(qe,{value:String(A.uid),children:yR(A)},String(A.uid)))})]}),s.jsx(se,{variant:"outline",size:"sm",onClick:()=>{WA({force:!0}).then(()=>Le(r("✅ 已重新读取 Clash Verge 配置"))).catch(A=>Le(r("读取失败:{error}",{error:ut(A)}),"err"))},children:r("重新读取")})]}),s.jsx("div",{className:"detail mt-1.5",children:d===null?r("正在读取 Clash Verge 配置…"):d.available===!1?d.error?r("不可用:{error}",{error:d.error}):r("未检测到 Clash Verge 配置"):f.length?r("读取自 {dir};端口由 Clash Verge 管理,这里实时同步",{dir:d.dir||"Clash Verge"}):r("Clash Verge 里还没有配置混合监听器或节点端口")}),s.jsxs("p",{className:"detail mt-1.5",children:[r("这是既有配置(直接引用 Clash 出口,不经过代理池)。推荐改用上面的"),s.jsx("b",{children:r("「已保存的代理」")}),r(":到「网络代理」页点「同步 Clash Verge」把出口导进池后即可选 —— 那样能集中测试、也能被多个账号共用。")]})]}):null,e.mode==="custom"?s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:`${a}-protocol`,children:r("协议")}),s.jsxs(ft,{value:e.protocol,onValueChange:A=>k({protocol:A}),children:[s.jsx(mt,{id:`${a}-protocol`,className:"min-w-[110px]",children:s.jsx(pt,{children:e.protocol==="socks5"?"SOCKS5":"HTTP"})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"http",children:"HTTP"}),s.jsx(qe,{value:"socks5",children:"SOCKS5"})]})]}),s.jsx("label",{htmlFor:`${a}-host`,className:"ml-2",children:r("主机")}),s.jsx($e,{id:`${a}-host`,className:"min-w-[140px]",placeholder:"127.0.0.1",value:e.host,onChange:A=>k({host:A.currentTarget.value})}),s.jsx("label",{htmlFor:`${a}-port`,children:r("端口")}),s.jsx($e,{id:`${a}-port`,type:"number",min:1,max:65535,className:"max-w-[110px]",placeholder:"7890",value:e.port,onChange:A=>k({port:A.currentTarget.value})})]}),s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:`${a}-user`,children:r("用户名")}),s.jsx($e,{id:`${a}-user`,placeholder:r("可选"),autoComplete:"off",value:e.username,onChange:A=>k({username:A.currentTarget.value})}),s.jsx("label",{htmlFor:`${a}-pass`,children:r("密码")}),s.jsx($e,{id:`${a}-pass`,type:"password",placeholder:r("可选"),autoComplete:"new-password",value:e.password,onChange:A=>k({password:A.currentTarget.value})})]})]}):null,s.jsxs("div",{className:"field-row mt-3",children:[s.jsx(se,{variant:"outline",size:"sm",disabled:g,onClick:()=>{C()},children:r(g?"测试中…":"测试出口")}),s.jsx("span",{className:"detail",children:y})]})]})}function l8({plan:e,hasJwt:t,onChange:a}){const o=QF(e),[c,d]=x.useState(null);return x.useEffect(()=>{if(e!==jo)return()=>{};let f=!0;const p=()=>{Promise.resolve(Pe().workbuddyDesktop?.zcodeCaptchaStats?.()).then(v=>{f&&v&&d({ready:Number(v.ready)||0,target:Number(v.target)||0})}).catch(()=>{})};p();const g=window.setInterval(p,5e3);return()=>{f=!1,window.clearInterval(g)}},[e]),s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:"account-plan-channel",children:r("使用套餐")}),s.jsxs(ft,{value:e,onValueChange:f=>a(String(f)),children:[s.jsx(mt,{id:"account-plan-channel",className:"min-w-[220px]",children:s.jsx(pt,{children:o})}),s.jsxs(ht,{children:[s.jsx(qe,{value:EA,children:r("编码套餐(Coding Plan)— 走开放平台端点,用自己订阅的额度")}),s.jsx(qe,{value:jo,children:r("活动套餐(Start Plan)— 走官方活动端点,用活动里领到的额度")})]})]}),e===jo&&!t?s.jsx("span",{className:"detail text-destructive",children:r("该账号没有套餐登录态(jwt),活动套餐会失败:请重新登录该账号")}):null,e===jo?s.jsxs("span",{className:"detail",title:r("活动套餐的推理端点要求每条请求带一个阿里云验证码令牌;令牌由本应用在后台静默铸造,界面关闭时无法铸造"),children:[r("验证码令牌:{counts}",{counts:c?`${c.ready} / ${c.target||3}`:r("读取中…")}),c&&c.ready===0?r("(库存为空,正在补;补不上时转发会失败)"):""]}):null]})}function o8({configured:e,value:t,onChange:a,onClear:o,clearBusy:c}){return s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:"account-balance-token-input",children:r("余额查询凭证")}),s.jsx($e,{id:"account-balance-token-input",className:"min-w-[220px]",placeholder:r(e?"已配置,留空则不修改":"一般不用填"),title:r("积分查询已复用转发用的登录凭证,这里通常留空即可。只有旧版本填过、或从旧代理导入过凭证时才有值"),value:t,onChange:d=>a(d.currentTarget.value)}),e?s.jsx(se,{variant:"outline",size:"sm",disabled:c,onClick:o,title:r("清除已配置的余额查询凭证"),children:r("清除")}):null]})}function i8({hasApiKey:e,noAuth:t,value:a,onValue:o,onToggleNoAuth:c,onClear:d,clearBusy:f}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:"account-api-key-input",children:r("API Key")}),s.jsx($e,{id:"account-api-key-input",type:"password",autoComplete:"new-password",className:"min-w-[220px]",disabled:t,placeholder:e?r("已配置,留空则不修改"):"sk-…",title:r("上游的 API Key。留空 = 不修改(改凭证不会换账号 id);要清掉已配的凭证用右边的「清除」"),value:a,onChange:p=>o(p.currentTarget.value)}),e&&!t?s.jsx(se,{variant:"outline",size:"sm",disabled:f,onClick:d,title:r("清除已配置的 API Key(转发时会因缺少凭证被跳过)"),children:r("清除")}):null]}),s.jsx("div",{className:"field-row mt-2.5",children:s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2.5 font-normal",children:[s.jsx(Or,{checked:t,"aria-label":r("该上游无需鉴权"),onCheckedChange:p=>c(p===!0)}),s.jsx("span",{className:"text-xs text-subtle",children:r("该上游无需鉴权(转发与拉取模型都不发送鉴权头)")})]})}),s.jsxs("p",{className:"detail",children:[r("上游本来不要凭证时(本地 Ollama、OpenCode Zen 的免费档)勾上这一项:账号会被正常选路;只把 Key 留空"),s.jsx("strong",{children:r("又不勾")}),r("会被当成「未配置凭证」而跳过。")]})]})}function c8({provider:e,name:t,protocol:a,baseUrl:o,count:c,emulation:d,onName:f,onProtocol:p,onBaseUrl:g,onEmulation:v,onRemove:y}){const b=Pe().wbProviders?.PROTOCOL_OPTIONS||[{value:"openai",label:r("OpenAI 兼容")},{value:"anthropic",label:"Anthropic"}],j=b.find(w=>w.value===a)?.label||a;return s.jsxs(Vn,{children:[s.jsx("h3",{children:r("提供商")}),s.jsxs("p",{children:[r("这一栏改的是"),s.jsx("strong",{children:r("「{name}」本身",{name:e.name||e.id})}),r("(名下 {count} 个账号共用)",{count:c}),r("改协议 / Base URL 会改变它们的转发方式,正在进行的请求可能失败;模型清单与映射在「模型管理」页。")]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:"account-provider-name",children:r("名称")}),s.jsx($e,{id:"account-provider-name",maxLength:xR,className:"min-w-[220px]",placeholder:r("提供商显示名,1~{max} 个字符",{max:xR}),value:t,onChange:w=>f(w.currentTarget.value)})]}),s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:"account-provider-protocol",children:r("协议")}),s.jsxs(ft,{value:a,onValueChange:w=>p(String(w)),children:[s.jsx(mt,{id:"account-provider-protocol",className:"min-w-[180px]",children:s.jsx(pt,{children:j})}),s.jsx(ht,{children:b.map(w=>s.jsx(qe,{value:w.value,children:w.label},w.value))})]})]}),s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:"account-provider-baseurl",children:r("Base URL")}),s.jsx($e,{id:"account-provider-baseurl",className:"min-w-[260px]",placeholder:r("OpenAI 兼容填到 /v1;Anthropic 填根地址"),value:o,onChange:w=>g(w.currentTarget.value)})]}),s.jsx("div",{className:"field-row mt-2.5",children:s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2.5 font-normal",children:[s.jsx(Or,{checked:d==="opencode","aria-label":r("伪装 OpenCode 官方客户端"),onCheckedChange:w=>v(w===!0?"opencode":"")}),s.jsx("span",{className:"text-xs text-subtle",children:r("伪装 OpenCode 官方客户端(OpenCode Zen 免费档要它才放行)")})]})}),s.jsxs("p",{className:"detail",children:[r("开启后,网关按 OpenCode 官方 CLI 的形状发请求:没填 Key 的账号用匿名凭证"),s.jsx("code",{children:"public"}),r("、补官方会话头、请求体补两个占位工具(上游免费档的三道校验)。"),s.jsx("strong",{children:r("它会改写请求体")}),r(",只对 OpenCode Zen 这类上游有意义,别的家请关掉。")]}),s.jsxs("div",{className:"field-row mt-3",children:[s.jsx(se,{variant:"destructive",onClick:y,children:r("删除提供商")}),s.jsx("span",{className:"detail",children:r("级联删除名下全部账号,不可恢复")})]})]})}function u8({id:e,onClose:t}){const a=Ea(e),[o,c]=x.useState(a?.enabled!==!1),[d,f]=x.useState(a?.name||""),[p,g]=x.useState(()=>vR(a?.proxy)),[v,y]=x.useState(""),[b,j]=x.useState(()=>aj(a)),[w,S]=x.useState(!1),[N,k]=x.useState(""),[E,D]=x.useState(null),[C,A]=x.useState(""),[R,I]=x.useState("chat_completions"),[P,O]=x.useState(""),[_,L]=x.useState(""),[H,B]=x.useState(""),[z,Q]=x.useState(a?.noAuth===!0),[K,X]=x.useState(()=>X$(a)),[q,$]=x.useState(()=>t8(a?.balanceQuery)),[Y,F]=x.useState(()=>G$(a)),[G,W]=x.useState("basic"),[le,M]=x.useState(()=>String(Number(a?.maxConcurrent)||0));if(x.useEffect(()=>{let he=!0;D(null);const ye=Ea(e);return ye?(Promise.resolve(Pe().wbCustomProvidersUi?.find?.(kn(ye))).then(we=>{!he||!we||(D(we),A(we.name||""),I(we.protocol||"chat_completions"),O(we.baseUrl||""),L(typeof we.clientEmulation=="string"?we.clientEmulation:""))}).catch(()=>{}),()=>{he=!1}):()=>{he=!1}},[e]),!a)return s.jsx(Qt,{open:!0,onOpenChange:he=>{he||t()},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("账号设置")})}),s.jsx(Bt,{children:s.jsx("p",{className:"detail",children:r("账号不存在,请刷新后重试。")})}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("关闭")})]})]})});const U=a,Z=a8(U,El()),ae=kn(U)==="catpaw",ce=kn(U).startsWith("custom-"),J=mA(E,U.baseUrl)||p.mode==="rotate",ie=Nf(U.balanceQuery?.scheme),ge={};for(const he of ie?.fields??[])ge[he.key]=J$(U.balanceQuery,he);const ee=!!(ie&&ie.fields.length)&&!e8(U.balanceQuery);async function fe(){if(!w){S(!0);try{await Pe().workbuddyDesktop?.updateAccount?.(e,{balanceToken:null}),y(""),Le(r("✅ 已清除余额查询凭证")),await Pe().wbApp?.refresh?.()}catch(he){Le(r("清除失败:{error}",{error:ut(he)}),"err")}finally{S(!1)}}}async function te(){if(!w){S(!0);try{await Pe().workbuddyDesktop?.updateAccount?.(e,{apiKey:null}),B(""),Le(r("✅ 已清除 API Key(该账号现在没有凭证,转发会被跳过)")),await Pe().wbApp?.refresh?.()}catch(he){Le(r("清除失败:{error}",{error:ut(he)}),"err")}finally{S(!1)}}}async function Ce(he){if(!w){S(!0);try{await Pe().workbuddyDesktop?.updateAccount?.(e,{balanceQuery:{[he]:null}}),$(ye=>({...ye,[he]:""})),Le(r("✅ 已清除查询凭证")),await Pe().wbApp?.refresh?.()}catch(ye){Le(r("清除失败:{error}",{error:ut(ye)}),"err")}finally{S(!1)}}}function re(){if(!ce)return null;const he=H.trim(),ye={};return he?ye.apiKey=he:z!==(U.noAuth===!0)&&(ye.noAuth=z),Object.keys(ye).length?ye:null}function de(){if(!E)return null;const he=C.trim(),ye=P.trim();if(!he)return{error:r("请填写提供商名称")};if(!ye)return{error:r("请填写提供商的 Base URL")};const we=typeof E.clientEmulation=="string"?E.clientEmulation:"";return E.name===he&&E.protocol===R&&E.baseUrl===ye&&we===_?null:{id:E.id,name:he,protocol:R,baseUrl:ye,clientEmulation:_}}async function ke(){if(w)return;let he;try{he=xj(p)}catch(Ct){Le(ut(Ct),"err");return}const ye=de();if(ye&&"error"in ye){k(s.jsx("span",{className:"text-destructive",children:ye.error}));return}const we=Ta(U)?Q$(U,K):null;if(we&&"error"in we){k(s.jsx("span",{className:"text-destructive",children:we.error}));return}const xe=q$(U,Y),Te=n8(U.balanceQuery?.scheme,q),Oe=re()||{},Ne=Number(le);if(!Number.isFinite(Ne)||Ne<0){Le(r("并发上限必须是 0~{max} 的整数",{max:Rl}),"err");return}const _e=Math.min(Rl,Math.round(Ne)),Ye=Number(U.maxConcurrent)||0,kt=_e!==Ye?{maxConcurrent:_e}:{};S(!0);try{const Ct=ae&&v.trim()?{balanceToken:v.trim()}:{},Rt=Fh(U)&&b!==aj(U)?{zcodePlan:b}:{};if(await Pe().workbuddyDesktop?.updateAccount?.(e,{name:d.trim()||U.name,enabled:o,proxy:he,...Ct,...Rt,...Oe,...kt,...Te?{balanceQuery:Te}:{},...we&&"patch"in we?we.patch:{},...xe&&"patch"in xe?xe.patch:{}}),ye)try{await Pe().wbCustomProvidersUi?.update?.(ye)}catch(ot){k(s.jsx("span",{className:"text-destructive",children:r("账号已保存,但提供商未更新:{error}",{error:ut(ot)})})),await Pe().wbApp?.refresh?.(),S(!1);return}t(),Le(r("✅ 账号设置已保存"));try{await Pe().wbApp?.refresh?.()}catch{}}catch(Ct){k(s.jsx("span",{className:"text-destructive",children:ut(Ct)})),Le(r("保存失败:{error}",{error:ut(Ct)}),"err")}finally{S(!1)}}const Ee=Number(ir(kn(U)).concurrencyDefault)||0,ve=ae||ce||Fh(U);return s.jsx(Qt,{open:!0,onOpenChange:he=>{he||w||t()},children:s.jsxs(Zt,{className:"w-[min(900px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("账号设置 · {name}",{name:eg(a)})})}),s.jsx(Bt,{className:"p-0",children:s.jsxs("div",{className:"acct-dlg",children:[s.jsx("aside",{className:"prov-rail acct-dlg-rail","aria-label":r("账号设置分组"),children:s.jsxs("div",{className:"rail-scroll",children:[s.jsx("div",{className:"rail-label",children:r("账号设置")}),[["basic",r("基本")],...ve?[["credential",r("凭证与套餐")]]:[],...Ta(U)?[["query",r("查询设置")],["limiter",r("限制器")]]:[],["network",r("网络")]].map(([he,ye])=>s.jsx(au,{active:G===he,title:ye,className:"shadow-none",onClick:()=>W(he),children:ye},he))]})}),s.jsxs("div",{className:"acct-dlg-main",children:[G==="basic"?s.jsxs("div",{children:[s.jsxs("div",{className:"acct-dlg-pane-head",children:[s.jsx("h3",{children:r("基本")}),s.jsx("p",{children:r("这条账号是谁、排第几、能不能接请求。")})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("启用")}),s.jsx(ms,{checked:o,onCheckedChange:c,"aria-label":r("启用该账号")}),s.jsx("span",{className:"detail",children:r("关闭则不参与转发(余额查询照常,见「查询设置」)")})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:"account-name-input",children:r("备注名")}),s.jsx($e,{id:"account-name-input",maxLength:100,placeholder:r("账号显示名称"),className:"max-w-[280px]",value:d,onChange:he=>f(he.currentTarget.value)})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("转发顺序")}),s.jsx("span",{className:"detail",children:r("在列表里拖:拖分组带调整整组顺位,拖行首把手调整组内先后(顺序由拖拽表达,不再填数字)")})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:"account-conc-input",children:r("并发上限")}),s.jsx($e,{id:"account-conc-input",type:"number",min:0,max:Rl,step:1,className:"max-w-[110px]",value:le,onChange:he=>M(he.currentTarget.value)}),s.jsx("span",{className:"detail",children:Ee>0?r("0 = 按本家默认 {default}",{default:Ee}):r("0 = 不限")})]}),s.jsx("p",{className:"detail acct-dlg-hint",children:Ee>0?r("并发上限 受上游硬顶约束,达到上限的账号跳过、请求转给其他账号(原列表 ⋯ 菜单的「并发上限」入口已并入这里)"):r("并发上限 0~{max};达到上限的账号跳过、请求转给其他账号(原列表 ⋯ 菜单的「并发上限」入口已并入这里)",{max:Rl})})]}):null,G==="credential"&&ve?s.jsxs("div",{children:[s.jsxs("div",{className:"acct-dlg-pane-head",children:[s.jsx("h3",{children:r("凭证与套餐")}),s.jsx("p",{children:r("这一段按提供商出现:有什么配什么。")})]}),ae?s.jsx(o8,{configured:a.hasBalanceToken===!0,value:v,onChange:y,clearBusy:w,onClear:()=>{fe()}}):null,ce?s.jsx(i8,{hasApiKey:U.hasApiKey===!0,noAuth:z,value:H,onValue:B,onToggleNoAuth:Q,onClear:()=>{te()},clearBusy:w}):null,Fh(U)?s.jsx(l8,{plan:b,hasJwt:a.canClaim===!0,onChange:j}):null,E?s.jsx(c8,{provider:E,count:Z.length+1,name:C,protocol:R,baseUrl:P,emulation:_,onName:A,onProtocol:I,onBaseUrl:O,onEmulation:L,onRemove:()=>{w||Promise.resolve(Pe().wbCustomProvidersUi?.remove?.(E.id)).then(he=>{he&&t()})}}):null]}):null,G==="query"&&Ta(U)?s.jsxs("div",{children:[s.jsxs("div",{className:"acct-dlg-pane-head",children:[s.jsx("h3",{children:r("查询设置")}),s.jsx("p",{children:r("余额列读数的自动刷新;也是「限制器」余额规则的数据来源。")})]}),ie?s.jsx(r8,{spec:ie,values:q,configured:ge,onValue:(he,ye)=>$(we=>({...we,[he]:ye})),onClear:he=>{Ce(he)},clearBusy:w,idPrefix:"account-balance-query"}):null,ee?s.jsx("p",{className:"detail mt-2.5 text-subtle",children:r("查询凭证还没配齐:填好后余额列才有读数,在此之前会显示「未配置」。")}):null,s.jsx(Z$,{account:U,draft:K,onChange:X})]}):null,G==="limiter"&&Ta(U)?s.jsxs("div",{children:[s.jsxs("div",{className:"acct-dlg-pane-head",children:[s.jsx("h3",{children:r("限制器")}),s.jsx("p",{children:r("按规则限制该账号参与转发:没有规则(或全部停用)= 不限制;跳过档自动恢复,禁用档需手动启用。")})]}),s.jsx($$,{account:U,draft:Y,onChange:F})]}):null,G==="network"?s.jsxs("div",{children:[s.jsxs("div",{className:"acct-dlg-pane-head",children:[s.jsx("h3",{children:r("网络")}),s.jsx("p",{children:r("这条账号访问上游走哪条线路。")})]}),s.jsx(jR,{draft:p,onChange:g,idPrefix:"account-proxy",allowRotate:J}),a.proxy?.error?s.jsx("p",{className:"detail text-destructive",children:r("当前代理不可用:{error}(转发时会回退直连)",{error:a.proxy.error})}):null]}):null]})]})}),s.jsxs(nn,{children:[s.jsx("div",{className:"detail mr-auto",style:{minHeight:18},children:N}),s.jsx(se,{variant:"outline",disabled:w,onClick:t,children:r("取消")}),s.jsx(se,{variant:"default",disabled:w,onClick:()=>{ke()},children:r(w?"保存中…":"保存")})]})]})})}const d8=[{value:"enable",label:r("启用")},{value:"disable",label:r("禁用")},{value:"proxy",label:r("修改代理")},{value:"concurrency",label:r("设置并发上限")},{value:"remove",label:r("删除")}];function f8({ids:e,action:t,onClose:a}){const[o,c]=x.useState(t),[d,f]=x.useState(()=>vR(null)),[p,g]=x.useState(""),[v,y]=x.useState(!1),[b,j]=x.useState(""),w=e.map(C=>Ea(C)).filter(C=>C!==null),S=w.reduce((C,A)=>Math.max(C,Number(ir(kn(A)).concurrencyDefault)||0),0),N=w.length>0&&w.every(C=>BF(C));function k(C){return Promise.resolve(Pe().wbConfirm?.ask?.({title:r("删除选中的账号"),html:r("确定删除选中的 {count} 个账号?此操作不可恢复,账号的登录态会一并移除。",{count:C}),okText:r("删除"),okClass:"danger"})??!1)}async function E(){if(v)return;if(!e.length){Le(r("没有选中的账号"),"err");return}let C;if(o==="proxy")try{C=xj(d)}catch(R){Le(ut(R),"err");return}let A;if(o==="concurrency"){const R=Number(p.trim());if(!p.trim()||!Number.isFinite(R)||R<0){Le(r("并发上限必须是 0~{max} 的整数",{max:Rl}),"err");return}A=Math.min(Rl,Math.round(R))}if(!(o==="remove"&&!await k(e.length))){if(o==="disable"||o==="remove"){const R=new Set(e);if(!El().filter(P=>P.enabled!==!1&&!R.has(P.id)).length){const P=r(o==="remove"?"删除":"禁用");if(!await Promise.resolve(Pe().wbConfirm?.ask?.({title:r("全部启用中的账号将被{what}",{what:P}),html:r("这会{what}所有启用中的账号,转发将不可用。确定继续?",{what:P}),okText:P,okClass:o==="remove"?"danger":"primary"})??!1))return}}y(!0),j("");try{const R={action:o,ids:e};o==="proxy"&&(R.proxy=C),o==="concurrency"&&(R.maxConcurrent=A);const I=await Pe().workbuddyDesktop?.batchAccounts?.(R),P=(I?.ok||[]).filter(B=>B.changes?.length).length,O=(I?.removed||[]).length,_=I?.failed||[],L=o==="remove"?O:P,H={enable:r("启用"),disable:r("禁用"),proxy:r("修改代理"),concurrency:r("设置并发上限"),remove:r("删除")}[o]||o;if(_.length){const B=_.slice(0,3).map(z=>eg(Ea(String(z.id)))||z.id).join(r("、"));Le(r("{verb}完成:成功 {ok} 个,失败 {fail} 个({detail}{more})",{verb:H,ok:L,fail:_.length,detail:B,more:_.length>3?r(" 等"):""}),"err"),j(s.jsxs("span",{className:"text-destructive",children:[r("失败 {count} 个:",{count:_.length}),_.map(z=>`${eg(Ea(String(z.id)))||z.id}(${z.error})`).join(r(";"))]}))}else Le(r("✅ {verb}完成:共 {count} 个账号",{verb:H,count:L})),a();await Pe().wbApp?.refresh?.()}catch(R){j(s.jsx("span",{className:"text-destructive",children:ut(R)})),Le(r("批量操作失败:{error}",{error:ut(R)}),"err")}finally{y(!1)}}}const D={enable:r("启用"),disable:r("禁用"),proxy:r("修改代理"),concurrency:r("设置并发上限"),remove:r("删除")}[o]||o;return s.jsx(Qt,{open:!0,onOpenChange:C=>{C||v||a()},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("批量操作 · 已选 {count} 个账号",{count:e.length})})}),s.jsxs(Bt,{children:[s.jsxs(Vn,{children:[s.jsx("h3",{children:r("将作用于以下账号")}),s.jsx("p",{style:{maxHeight:84,overflowY:"auto"},children:w.map(C=>eg(C)).join(r("、"))})]}),s.jsxs(Vn,{children:[s.jsx("h3",{children:r("操作")}),s.jsx(kh,{value:o,onValueChange:c,className:"flex-row flex-wrap items-center gap-5","aria-label":r("批量动作"),children:d8.map(C=>s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(bo,{value:C.value}),C.label]},C.value))}),o==="proxy"?s.jsx("div",{className:"mt-2.5",children:s.jsx(jR,{draft:d,onChange:f,idPrefix:"batch-proxy",allowRotate:N})}):null,o==="concurrency"?s.jsxs("div",{className:"mt-2.5",children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:"batch-conc-input",children:r("并发上限")}),s.jsx($e,{id:"batch-conc-input",type:"number",min:0,max:Rl,step:1,className:"max-w-[110px]",placeholder:r("不限"),value:p,onChange:C=>g(C.currentTarget.value)}),s.jsx("span",{className:"detail",children:r("0 = 不限")})]}),s.jsx("p",{className:"detail acct-dlg-hint",children:S>0?r("并发上限 0~{max};有上游硬顶的家(如 CodeArts)以它的硬顶为准;达到上限的账号会被跳过、请求转给其他账号",{max:Rl}):r("并发上限 0~{max};达到上限的账号会被跳过、请求转给其他账号",{max:Rl})})]}):null]}),s.jsx("div",{className:"detail",style:{minHeight:18},children:b})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:v,onClick:a,children:r("取消")}),s.jsx(se,{variant:o==="remove"?"destructive":"default",disabled:v,onClick:()=>{E()},children:v?r("执行中…"):r("执行({action})",{action:D})})]})]})})}function p8(){const e=Zs();return e.dialog?e.dialog.kind==="settings"?s.jsx(u8,{id:e.dialog.id,onClose:Zh},e.dialog.id):s.jsx(f8,{ids:e.dialog.ids,action:e.dialog.action,onClose:Zh},e.dialog.ids.join(",")):null}var bj={exports:{}},kf={},vj={exports:{}},yj={};var wR;function m8(){return wR||(wR=1,(function(e){function t(X,q){var $=X.length;X.push(q);e:for(;0<$;){var Y=$-1>>>1,F=X[Y];if(0>>1;Yc(le,$))Mc(U,le)?(X[Y]=U,X[M]=$,Y=M):(X[Y]=le,X[W]=$,Y=W);else if(Mc(U,$))X[Y]=U,X[M]=$,Y=M;else break e}}return q}function c(X,q){var $=X.sortIndex-q.sortIndex;return $!==0?$:X.id-q.id}if(e.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var d=performance;e.unstable_now=function(){return d.now()}}else{var f=Date,p=f.now();e.unstable_now=function(){return f.now()-p}}var g=[],v=[],y=1,b=null,j=3,w=!1,S=!1,N=!1,k=!1,E=typeof setTimeout=="function"?setTimeout:null,D=typeof clearTimeout=="function"?clearTimeout:null,C=typeof setImmediate<"u"?setImmediate:null;function A(X){for(var q=a(v);q!==null;){if(q.callback===null)o(v);else if(q.startTime<=X)o(v),q.sortIndex=q.expirationTime,t(g,q);else break;q=a(v)}}function R(X){if(N=!1,A(X),!S)if(a(g)!==null)S=!0,I||(I=!0,B());else{var q=a(v);q!==null&&K(R,q.startTime-X)}}var I=!1,P=-1,O=5,_=-1;function L(){return k?!0:!(e.unstable_now()-_X&&L());){var Y=b.callback;if(typeof Y=="function"){b.callback=null,j=b.priorityLevel;var F=Y(b.expirationTime<=X);if(X=e.unstable_now(),typeof F=="function"){b.callback=F,A(X),q=!0;break t}b===a(g)&&o(g),A(X)}else o(g);b=a(g)}if(b!==null)q=!0;else{var G=a(v);G!==null&&K(R,G.startTime-X),q=!1}}break e}finally{b=null,j=$,w=!1}q=void 0}}finally{q?B():I=!1}}}var B;if(typeof C=="function")B=function(){C(H)};else if(typeof MessageChannel<"u"){var z=new MessageChannel,Q=z.port2;z.port1.onmessage=H,B=function(){Q.postMessage(null)}}else B=function(){E(H,0)};function K(X,q){P=E(function(){X(e.unstable_now())},q)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(X){X.callback=null},e.unstable_forceFrameRate=function(X){0>X||125Y?(X.sortIndex=$,t(v,X),a(g)===null&&X===a(v)&&(N?(D(P),P=-1):N=!0,K(R,$-Y))):(X.sortIndex=F,t(g,X),S||w||(S=!0,I||(I=!0,B()))),X},e.unstable_shouldYield=L,e.unstable_wrapCallback=function(X){var q=j;return function(){var $=j;j=q;try{return X.apply(this,arguments)}finally{j=$}}}})(yj)),yj}var SR;function h8(){return SR||(SR=1,vj.exports=m8()),vj.exports}var NR;function g8(){if(NR)return kf;NR=1;var e=h8(),t=Ud(),a=g1();function o(n){var l="https://react.dev/errors/"+n;if(1Ce||(n.current=te[Ce],te[Ce]=null,Ce--)}function ke(n,l){Ce++,te[Ce]=n.current,n.current=l}var Ee=re(null),ve=re(null),he=re(null),ye=re(null);function we(n,l){switch(ke(he,l),ke(ve,n),ke(Ee,null),l.nodeType){case 9:case 11:n=(n=l.documentElement)&&(n=n.namespaceURI)?V3(n):0;break;default:if(n=l.tagName,l=l.namespaceURI)l=V3(l),n=F3(l,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}de(Ee),ke(Ee,n)}function xe(){de(Ee),de(ve),de(he)}function Te(n){var l=n.memoizedState;l!==null&&(Ld._currentValue=l.memoizedState,ke(ye,n)),l=Ee.current;var i=F3(l,n.type);l!==i&&(ke(ve,n),ke(Ee,i))}function Oe(n){ve.current===n&&(de(Ee),de(ve)),ye.current===n&&(de(ye),Ld._currentValue=fe)}var Ne,_e;function Ye(n){if(Ne===void 0)try{throw Error()}catch(i){var l=i.stack.trim().match(/\n( *(at )?)/);Ne=l&&l[1]||"",_e=-1)":-1m||ne[u]!==me[m]){var Se=` `+ne[u].replace(" at new "," at ");return n.displayName&&Se.includes("")&&(Se=Se.replace("",n.displayName)),Se}while(1<=u&&0<=m);break}}}finally{kt=!1,Error.prepareStackTrace=i}return(i=n?n.displayName||n.name:"")?Ye(i):""}function Rt(n,l){switch(n.tag){case 26:case 27:case 5:return Ye(n.type);case 16:return Ye("Lazy");case 13:return n.child!==l&&l!==null?Ye("Suspense Fallback"):Ye("Suspense");case 19:return Ye("SuspenseList");case 0:case 15:return Ct(n.type,!1);case 11:return Ct(n.type.render,!1);case 1:return Ct(n.type,!0);case 31:return Ye("Activity");case 30:return Ye("ViewTransition");default:return""}}function ot(n){try{var l="",i=null;do l+=Rt(n,i),i=n,n=n.return;while(n);return l}catch(u){return` Error generating stack: `+u.message+` -`+u.stack}}var qn=Object.prototype.hasOwnProperty,ds=e.unstable_scheduleCallback,Gn=e.unstable_cancelCallback,xs=e.unstable_shouldYield,it=e.unstable_requestPaint,Vt=e.unstable_now,Bn=e.unstable_getCurrentPriorityLevel,tn=e.unstable_ImmediatePriority,nt=e.unstable_UserBlockingPriority,Ot=e.unstable_NormalPriority,Ft=e.unstable_LowPriority,Zn=e.unstable_IdlePriority,Hn=e.log,Un=e.unstable_setDisableYieldValue,Rn=null,Jt=null;function as(n){if(typeof Hn=="function"&&Un(n),Jt&&typeof Jt.setStrictMode=="function")try{Jt.setStrictMode(Rn,n)}catch{}}var Tt=Math.clz32?Math.clz32:wt,gt=Math.log,jt=Math.LN2;function wt(n){return n>>>=0,n===0?32:31-(gt(n)/jt|0)|0}var Sr=256,rr=262144,Hr=4194304;function jn(n){var l=n&42;if(l!==0)return l;switch(n&-n){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return n&-n;case 262144:case 524288:case 1048576:case 2097152:return n&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return n&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return n}}function rl(n,l,i){var u=n.pendingLanes;if(u===0)return 0;var m=0,h=n.suspendedLanes,T=n.pingedLanes;n=n.warmLanes;var V=u&134217727;return V!==0?(u=V&~h,u!==0?m=jn(u):(T&=V,T!==0?m=jn(T):i||(i=V&~n,i!==0&&(m=jn(i))))):(V=u&~h,V!==0?m=jn(V):T!==0?m=jn(T):i||(i=u&~n,i!==0&&(m=jn(i)))),m===0?0:l!==0&&l!==m&&(l&h)===0&&(h=m&-m,i=l&-l,h>=i||h===32&&(i&4194048)!==0)?l:m}function rn(n,l){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&l)===0}function ic(n,l){(l&8)!==0&&(l|=l&32);var i=n.entangledLanes;if(i!==0)for(n=n.entanglements,i&=l;0i;i++)l.push(n);return l}function Ho(n,l){n.pendingLanes|=l,l!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function Uo(n,l,i,u,m,h){var T=n.pendingLanes;n.pendingLanes=i,n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0,n.expiredLanes&=i,n.entangledLanes&=i,n.errorRecoveryDisabledLanes&=i,n.shellSuspendCounter=0;var V=n.entanglements,ne=n.expirationTimes,me=n.hiddenUpdates;for(i=T&~i;0"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Yt=!1;if(lt)try{var On={};Object.defineProperty(On,"passive",{get:function(){Yt=!0}}),window.addEventListener("test",On,On),window.removeEventListener("test",On,On)}catch{Yt=!1}var mn=null,Mn=null,fs=null;function Nr(){if(fs)return fs;var n,l=Mn,i=l.length,u,m="value"in mn?mn.value:mn.textContent,h=m.length;for(n=0;n=qp),$P=" ",qP=!1;function GP(n,l){switch(n){case"keyup":return wte.indexOf(l.keyCode)!==-1;case"keydown":return l.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function KP(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var rd=!1;function Nte(n,l){switch(n){case"compositionend":return KP(l);case"keypress":return l.which!==32?null:(qP=!0,$P);case"textInput":return n=l.data,n===$P&&qP?null:n;default:return null}}function kte(n,l){if(rd)return n==="compositionend"||!FS&&GP(n,l)?(n=Nr(),fs=Mn=mn=null,rd=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(l.ctrlKey||l.altKey||l.metaKey)||l.ctrlKey&&l.altKey){if(l.char&&1"u")return null;try{return n.activeElement||n.body}catch{return n.body}}function t_(n){for(;n&&n.firstChild;)n=n.firstChild;return n}function n_(n,l){var i=t_(n);n=0;for(var u;i;){if(i.nodeType===3){if(u=n+i.textContent.length,n<=l&&u>=l)return{node:i,offset:l-n};n=u}e:{for(;i;){if(i.nextSibling){i=i.nextSibling;break e}i=i.parentNode}i=void 0}i=t_(i)}}function s_(n,l){return n&&l?n===l?!0:n&&n.nodeType===3?!1:l&&l.nodeType===3?s_(n,l.parentNode):"contains"in n?n.contains(l):n.compareDocumentPosition?!!(n.compareDocumentPosition(l)&16):!1:!1}function r_(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var l=GS(n.document);l instanceof n.HTMLIFrameElement;){try{var i=typeof l.contentWindow.location.href=="string"}catch{i=!1}if(i)n=l.contentWindow;else break;l=GS(n.document)}return l}function KS(n){var l=n&&n.nodeName&&n.nodeName.toLowerCase();return l&&(l==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||l==="textarea"||n.contentEditable==="true")}var Dte=lt&&"documentMode"in document&&11>=document.documentMode,ad=null,YS=null,Xp=null,XS=!1;function a_(n,l,i){var u=i.window===i?i.document:i.nodeType===9?i:i.ownerDocument;XS||ad==null||ad!==GS(u)||(u=ad,"selectionStart"in u&&KS(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),Xp&&Yp(Xp,u)||(Xp=u,u=av(YS,"onSelect"),0>=T,m-=T,ll=1<<32-Tt(l)+m|i<rt?(ws=st,st=null):ws=st.sibling;var Xt=ue(pe,st,be[rt],Ae);if(Xt===null){st===null&&(st=ws);break}n&&st&&Xt.alternate===null&&l(pe,st),oe=h(Xt,oe,rt),zt===null?Ge=Xt:zt.sibling=Xt,zt=Xt,st=ws}if(rt===be.length)return i(pe,st),Et&&Gl(pe,rt),Ge;if(st===null){for(;rtrt?(ws=st,st=null):ws=st.sibling;var gi=ue(pe,st,Xt.value,Ae);if(gi===null){st===null&&(st=ws);break}n&&st&&gi.alternate===null&&l(pe,st),oe=h(gi,oe,rt),zt===null?Ge=gi:zt.sibling=gi,zt=gi,st=ws}if(Xt.done)return i(pe,st),Et&&Gl(pe,rt),Ge;if(st===null){for(;!Xt.done;rt++,Xt=be.next())Xt=Re(pe,Xt.value,Ae),Xt!==null&&(oe=h(Xt,oe,rt),zt===null?Ge=Xt:zt.sibling=Xt,zt=Xt);return Et&&Gl(pe,rt),Ge}for(st=u(st);!Xt.done;rt++,Xt=be.next())Xt=je(st,pe,rt,Xt.value,Ae),Xt!==null&&(n&&(ws=Xt.alternate,ws!==null&&st.delete(ws.key===null?rt:ws.key)),oe=h(Xt,oe,rt),zt===null?Ge=Xt:zt.sibling=Xt,zt=Xt);return n&&st.forEach(function(Nse){return l(pe,Nse)}),Et&&Gl(pe,rt),Ge}function bt(pe,oe,be,Ae){if(typeof be=="object"&&be!==null&&be.type===H&&be.key===null&&be.props.ref===void 0&&(be=be.props.children),typeof be=="object"&&be!==null){switch(be.$$typeof){case _:e:{for(var Ge=be.key;oe!==null;){if(oe.key===Ge){if(Ge=be.type,Ge===H){if(oe.tag===7){i(pe,oe.sibling),Ae=m(oe,be.props.children),Zo(Ae,be),Ae.return=pe,pe=Ae;break e}}else if(oe.elementType===Ge||typeof Ge=="object"&&Ge!==null&&Ge.$$typeof===F&&Ac(Ge)===oe.type){i(pe,oe.sibling),Ae=m(oe,be.props),Zo(Ae,be),Ae.return=pe,pe=Ae;break e}i(pe,oe);break}else l(pe,oe);oe=oe.sibling}be.type===H?(Ae=wc(be.props.children,pe.mode,Ae,be.key),Zo(Ae,be),Ae.return=pe,pe=Ae):(Ae=ub(be.type,be.key,be.props,null,pe.mode,Ae),Zo(Ae,be),Ae.return=pe,pe=Ae)}return T(pe);case L:e:{for(Ge=be.key;oe!==null;){if(oe.key===Ge)if(oe.tag===4&&oe.stateNode.containerInfo===be.containerInfo&&oe.stateNode.implementation===be.implementation){i(pe,oe.sibling),Ae=m(oe,be.children||[]),Ae.return=pe,pe=Ae;break e}else{i(pe,oe);break}else l(pe,oe);oe=oe.sibling}Ae=nN(be,pe.mode,Ae),Ae.return=pe,pe=Ae}return T(pe);case F:return be=Ac(be),bt(pe,oe,be,Ae)}if(ie(be))return He(pe,oe,be,Ae);if(ae(be)){if(Ge=ae(be),typeof Ge!="function")throw Error(o(150));return be=Ge.call(be),We(pe,oe,be,Ae)}if(typeof be.then=="function")return bt(pe,oe,yb(be),Ae);if(be.$$typeof===K)return bt(pe,oe,gb(pe,be),Ae);jb(pe,be)}return typeof be=="string"&&be!==""||typeof be=="number"||typeof be=="bigint"?(be=""+be,oe!==null&&oe.tag===6?(i(pe,oe.sibling),Ae=m(oe,be),Ae.return=pe,pe=Ae):(i(pe,oe),Ae=tN(be,pe.mode,Ae),Ae.return=pe,pe=Ae),T(pe)):i(pe,oe)}return function(pe,oe,be,Ae){try{tm=0;var Ge=bt(pe,oe,be,Ae);return md=null,Ge}catch(st){if(st===pd||st===bb)throw st;var zt=kr(29,st,null,pe.mode);return zt.lanes=Ae,zt.return=pe,zt}}}var Oc=A_(!0),R_=A_(!1),Wo=!1;function fN(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function pN(n,l){n=n.updateQueue,l.updateQueue===n&&(l.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function Jo(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function ei(n,l,i){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(an&2)!==0){var m=u.pending;return m===null?l.next=l:(l.next=m.next,m.next=l),u.pending=l,l=cb(n),p_(n,null,i),l}return ib(n,u,l,i),cb(n)}function nm(n,l,i){if(l=l.updateQueue,l!==null&&(l=l.shared,(i&4194048)!==0)){var u=l.lanes;u&=n.pendingLanes,i|=u,l.lanes=i,cc(n,i)}}function mN(n,l){var i=n.updateQueue,u=n.alternate;if(u!==null&&(u=u.updateQueue,i===u)){var m=null,h=null;if(i=i.firstBaseUpdate,i!==null){do{var T={lane:i.lane,tag:i.tag,payload:i.payload,callback:null,next:null};h===null?m=h=T:h=h.next=T,i=i.next}while(i!==null);h===null?m=h=l:h=h.next=l}else m=h=l;i={baseState:u.baseState,firstBaseUpdate:m,lastBaseUpdate:h,shared:u.shared,callbacks:u.callbacks},n.updateQueue=i;return}n=i.lastBaseUpdate,n===null?i.firstBaseUpdate=l:n.next=l,i.lastBaseUpdate=l}var hN=!1;function sm(){if(hN){var n=fd;if(n!==null)throw n}}function rm(n,l,i,u){hN=!1;var m=n.updateQueue;Wo=!1;var h=m.firstBaseUpdate,T=m.lastBaseUpdate,V=m.shared.pending;if(V!==null){m.shared.pending=null;var ne=V,me=ne.next;ne.next=null,T===null?h=me:T.next=me,T=ne;var Se=n.alternate;Se!==null&&(Se=Se.updateQueue,V=Se.lastBaseUpdate,V!==T&&(V===null?Se.firstBaseUpdate=me:V.next=me,Se.lastBaseUpdate=ne))}if(h!==null){var Re=m.baseState;T=0,Se=me=ne=null,V=h;do{var ue=V.lane&-536870913,je=ue!==V.lane;if(je?(Lt&ue)===ue:(u&ue)===ue){ue!==0&&ue===Tc&&(hN=!0),Se!==null&&(Se=Se.next={lane:0,tag:V.tag,payload:V.payload,callback:null,next:null});e:{var He=n,We=V;ue=l;var bt=i;switch(We.tag){case 1:if(He=We.payload,typeof He=="function"){Re=He.call(bt,Re,ue);break e}Re=He;break e;case 3:He.flags=He.flags&-65537|128;case 0:if(He=We.payload,ue=typeof He=="function"?He.call(bt,Re,ue):He,ue==null)break e;Re=P({},Re,ue);break e;case 2:Wo=!0}}ue=V.callback,ue!==null&&(n.flags|=64,je&&(n.flags|=8192),je=m.callbacks,je===null?m.callbacks=[ue]:je.push(ue))}else je={lane:ue,tag:V.tag,payload:V.payload,callback:V.callback,next:null},Se===null?(me=Se=je,ne=Re):Se=Se.next=je,T|=ue;if(V=V.next,V===null){if(V=m.shared.pending,V===null)break;je=V,V=je.next,je.next=null,m.lastBaseUpdate=je,m.shared.pending=null}}while(!0);Se===null&&(ne=Re),m.baseState=ne,m.firstBaseUpdate=me,m.lastBaseUpdate=Se,h===null&&(m.shared.lanes=0),oi|=T,n.lanes=T,n.memoizedState=Re}}function O_(n,l){if(typeof n!="function")throw Error(o(191,n));n.call(l)}function M_(n,l){var i=n.callbacks;if(i!==null)for(n.callbacks=null,n=0;nh?h:8;var T=ge.T,V={};V.types=T!==null?T.types:null,ge.T=V,PN(n,!1,l,i);try{var ne=m(),me=ge.S;if(me!==null&&me(V,ne),ne!==null&&typeof ne=="object"&&typeof ne.then=="function"){var Se=$te(ne,u);im(n,l,Se,Qr(n))}else im(n,l,u,Qr(n))}catch(Re){im(n,l,{then:function(){},status:"rejected",reason:Re},Qr())}finally{ee.p=h,T!==null&&V.types!==null&&(T.types=V.types),ge.T=T}}function Qte(){}function DN(n,l,i,u){if(n.tag!==5)throw Error(o(476));var m=uL(n).queue;cL(n,m,l,fe,i===null?Qte:function(){return dL(n),i(u)})}function uL(n){var l=n.memoizedState;if(l!==null)return l;l={memoizedState:fe,baseState:fe,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ql,lastRenderedState:fe},next:null};var i={};return l.next={memoizedState:i,baseState:i,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ql,lastRenderedState:i},next:null},n.memoizedState=l,n=n.alternate,n!==null&&(n.memoizedState=l),l}function dL(n){var l=uL(n);l.next===null&&(l=n.alternate.memoizedState),im(n,l.next.queue,{},Qr())}function IN(){return qs(_d)}function fL(){return ps().memoizedState}function pL(){return ps().memoizedState}function Zte(n){for(var l=n.return;l!==null;){switch(l.tag){case 24:case 3:var i=Qr();n=Jo(i);var u=ei(l,n,i);u!==null&&(Ar(u,l,i),nm(u,l,i)),l={cache:iN()},n.payload=l;return}l=l.return}}function Wte(n,l,i){var u=Qr();i={lane:u,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},Ob(n)?hL(l,i):(i=JS(n,l,i,u),i!==null&&(Ar(i,n,u),gL(i,l,u)))}function mL(n,l,i){var u=Qr();im(n,l,i,u)}function im(n,l,i,u){var m={lane:u,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null};if(Ob(n))hL(l,m);else{var h=n.alternate;if(n.lanes===0&&(h===null||h.lanes===0)&&(h=l.lastRenderedReducer,h!==null))try{var T=l.lastRenderedState,V=h(T,i);if(m.hasEagerState=!0,m.eagerState=V,qr(V,T))return ib(n,l,m,0),Dn===null&&ob(),!1}catch{}if(i=JS(n,l,m,u),i!==null)return Ar(i,n,u),gL(i,l,u),!0}return!1}function PN(n,l,i,u){if(u={lane:2,revertLane:kk(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Ob(n)){if(l)throw Error(o(479))}else l=JS(n,i,u,2),l!==null&&Ar(l,n,2)}function Ob(n){var l=n.alternate;return n===xt||l!==null&&l===xt}function hL(n,l){hd=Nb=!0;var i=n.pending;i===null?l.next=l:(l.next=i.next,i.next=l),n.pending=l}function gL(n,l,i){if((i&4194048)!==0){var u=l.lanes;u&=n.pendingLanes,i|=u,l.lanes=i,cc(n,i)}}var Mb={readContext:qs,use:Tb,useCallback:ls,useContext:ls,useEffect:ls,useImperativeHandle:ls,useLayoutEffect:ls,useInsertionEffect:ls,useMemo:ls,useReducer:ls,useRef:ls,useState:ls,useDebugValue:ls,useDeferredValue:ls,useTransition:ls,useSyncExternalStore:ls,useId:ls,useHostTransitionStatus:ls,useFormState:ls,useActionState:ls,useOptimistic:ls,useMemoCache:ls,useCacheRefresh:ls,useEffectEvent:ls},xL={readContext:qs,use:Tb,useCallback:function(n,l){return mr().memoizedState=[n,l===void 0?null:l],n},useContext:qs,useEffect:eL,useImperativeHandle:function(n,l,i){i=i!=null?i.concat([n]):null,Ab(4194308,4,rL.bind(null,l,n),i)},useLayoutEffect:function(n,l){return Ab(4194308,4,n,l)},useInsertionEffect:function(n,l){Ab(4,2,n,l)},useMemo:function(n,l){var i=mr();l=l===void 0?null:l;var u=n();if(Mc){as(!0);try{n()}finally{as(!1)}}return i.memoizedState=[u,l],u},useReducer:function(n,l,i){var u=mr();if(i!==void 0){var m=i(l);if(Mc){as(!0);try{i(l)}finally{as(!1)}}}else m=l;return u.memoizedState=u.baseState=m,n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:m},u.queue=n,n=n.dispatch=Wte.bind(null,xt,n),[u.memoizedState,n]},useRef:function(n){var l=mr();return n={current:n},l.memoizedState=n},useState:function(n){n=EN(n);var l=n.queue,i=mL.bind(null,xt,l);return l.dispatch=i,[n.memoizedState,i]},useDebugValue:ON,useDeferredValue:function(n,l){var i=mr();return MN(i,n,l)},useTransition:function(){var n=EN(!1);return n=cL.bind(null,xt,n.queue,!0,!1),mr().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,l,i){var u=xt,m=mr();if(Et){if(i===void 0)throw Error(o(407));i=i()}else{if(i=l(),Dn===null)throw Error(o(349));(Lt&127)!==0||z_(u,l,i)}m.memoizedState=i;var h={value:i,getSnapshot:l};return m.queue=h,eL(H_.bind(null,u,h,n),[n]),u.flags|=2048,xd(9,{destroy:void 0},B_.bind(null,u,h,i,l),null),i},useId:function(){var n=mr(),l=Dn.identifierPrefix;if(Et){var i=ol,u=ll;i=(u&~(1<<32-Tt(u)-1)).toString(32)+i,l="_"+l+"R_"+i,i=kb++,0<\/script>",h=h.removeChild(h.firstChild);break;case"select":h=typeof u.is=="string"?T.createElement("select",{is:u.is}):T.createElement("select"),u.multiple?h.multiple=!0:u.size&&(h.size=u.size);break;default:h=typeof u.is=="string"?T.createElement(m,{is:u.is}):T.createElement(m)}}h[As]=l,h[$s]=u;e:for(T=l.child;T!==null;){if(T.tag===5||T.tag===6)h.appendChild(T.stateNode);else if(T.tag!==4&&T.tag!==27&&T.child!==null){T.child.return=T,T=T.child;continue}if(T===l)break e;for(;T.sibling===null;){if(T.return===null||T.return===l)break e;T=T.return}T.sibling.return=T.return,T=T.sibling}l.stateNode=h;e:switch(Xs(h,m,u),m){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&Wl(l)}}return Ln(l),l.subtreeFlags&=-33554433,YN(l,l.type,n===null?null:n.memoizedProps,l.pendingProps,i),null;case 6:if(n&&l.stateNode!=null)n.memoizedProps!==u&&Wl(l);else{if(typeof u!="string"&&l.stateNode===null)throw Error(o(166));if(n=he.current,dd(l)){if(n=l.stateNode,i=l.memoizedProps,u=null,m=_s,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[As]=l,n=!!(n.nodeValue===i||u!==null&&u.suppressHydrationWarning===!0||H3(n.nodeValue,i)),n||Xo(l,!0)}else n=jm(n).createTextNode(u),n[As]=l,l.stateNode=n}return Ln(l),null;case 31:if(i=l.memoizedState,n===null||n.memoizedState!==null){if(u=dd(l),i!==null){if(n===null){if(!u)throw Error(o(318));if(n=l.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(o(557));n[As]=l}else Sc(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;Ln(l),n=!1}else i=aN(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=i),n=!0;if(!n)return l.flags&256?(Gr(l),l):(Gr(l),null);if((l.flags&128)!==0)throw Error(o(558))}return Ln(l),null;case 13:if(u=l.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=dd(l),u!==null&&u.dehydrated!==null){if(n===null){if(!m)throw Error(o(318));if(m=l.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(o(317));m[As]=l}else Sc(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;Ln(l),m=!1}else m=aN(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return l.flags&256?(Gr(l),l):(Gr(l),null)}return Gr(l),(l.flags&128)!==0?(l.lanes=i,l):(i=u!==null,n=n!==null&&n.memoizedState!==null,i&&(u=l.child,m=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(m=u.alternate.memoizedState.cachePool.pool),h=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(h=u.memoizedState.cachePool.pool),h!==m&&(u.flags|=2048)),i!==n&&i&&(l.child.flags|=8192),zb(l,l.updateQueue),Ln(l),null);case 4:return xe(),n===null&&Ak(l.stateNode.containerInfo),l.flags|=67108864,Ln(l),null;case 10:return Yl(l.type),Ln(l),null;case 19:if(vN(l),u=l.memoizedState,u===null)return Ln(l),null;if(m=(l.flags&128)!==0,h=u.rendering,h===null)if(m)um(u,!1);else{if(os!==0||n!==null&&(n.flags&128)!==0)for(n=l.child;n!==null;){if(h=Sb(n),h!==null){for(l.flags|=128,um(u,!1),n=h.updateQueue,l.updateQueue=n,zb(l,n),l.subtreeFlags=0,n=i,i=l.child;i!==null;)m_(i,n),i=i.sibling;return am(l,Ks.current&1|2),Et&&Gl(l,u.treeForkCount),l.child}n=n.sibling}u.tail!==null&&Vt()>Qb&&(l.flags|=128,m=!0,um(u,!1),l.lanes=4194304)}else{if(!m)if(n=Sb(h),n!==null){if(l.flags|=128,m=!0,n=n.updateQueue,l.updateQueue=n,zb(l,n),um(u,!0),u.tail===null&&u.tailMode!=="collapsed"&&u.tailMode!=="visible"&&!h.alternate&&!Et)return Ln(l),null}else 2*Vt()-u.renderingStartTime>Qb&&i!==536870912&&(l.flags|=128,m=!0,um(u,!1),l.lanes=4194304);u.isBackwards?(h.sibling=l.child,l.child=h):(n=u.last,n!==null?n.sibling=h:l.child=h,u.last=h)}if(u.tail!==null){n=u.tail;e:{for(i=n;i!==null;){if(i.alternate!==null){i=!1;break e}i=i.sibling}i=!0}return u.rendering=n,u.tail=n.sibling,u.renderingStartTime=Vt(),n.sibling=null,h=Ks.current,h=m?h&1|2:h&1,u.tailMode==="visible"||u.tailMode==="collapsed"||!i||Et?am(l,h):(i=h,ke(Gs,l),ke(Ks,i),lr===null&&(lr=l)),Et&&Gl(l,u.treeForkCount),n}return Ln(l),null;case 22:case 23:return Gr(l),xN(),u=l.memoizedState!==null,n!==null?n.memoizedState!==null!==u&&(l.flags|=8192):u&&(l.flags|=8192),u?(i&536870912)!==0&&(l.flags&128)===0&&(Ln(l),l.subtreeFlags&6&&(l.flags|=8192)):Ln(l),i=l.updateQueue,i!==null&&zb(l,i.retryQueue),i=null,n!==null&&n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(i=n.memoizedState.cachePool.pool),u=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(u=l.memoizedState.cachePool.pool),u!==i&&(l.flags|=2048),n!==null&&de(Ec),null;case 24:return i=null,n!==null&&(i=n.memoizedState.cache),l.memoizedState.cache!==i&&(l.flags|=2048),Yl(vs),Ln(l),null;case 25:return null;case 30:return l.flags|=33554432,Ln(l),null}throw Error(o(156,l.tag))}function ane(n,l){switch(sN(l),l.tag){case 1:return n=l.flags,n&65536?(l.flags=n&-65537|128,l):null;case 3:return Yl(vs),xe(),n=l.flags,(n&65536)!==0&&(n&128)===0?(l.flags=n&-65537|128,l):null;case 26:case 27:case 5:return Oe(l),null;case 31:if(l.memoizedState!==null){if(Gr(l),l.alternate===null)throw Error(o(340));Sc()}return n=l.flags,n&65536?(l.flags=n&-65537|128,l):null;case 13:if(Gr(l),n=l.memoizedState,n!==null&&n.dehydrated!==null){if(l.alternate===null)throw Error(o(340));Sc()}return n=l.flags,n&65536?(l.flags=n&-65537|128,l):null;case 19:return vN(l),n=l.flags,n&65536?(l.flags=n&-65537|128,n=l.memoizedState,n!==null&&(n.rendering=null,n.tail=null),l.flags|=4,l):null;case 4:return xe(),null;case 10:return Yl(l.type),null;case 22:case 23:return Gr(l),xN(),n!==null&&de(Ec),n=l.flags,n&65536?(l.flags=n&-65537|128,l):null;case 24:return Yl(vs),null;case 25:return null;default:return null}}function VL(n,l){switch(sN(l),l.tag){case 3:Yl(vs),xe();break;case 26:case 27:case 5:Oe(l);break;case 4:xe();break;case 31:l.memoizedState!==null&&Gr(l);break;case 13:Gr(l);break;case 19:vN(l);break;case 10:Yl(l.type);break;case 22:case 23:Gr(l),xN(),n!==null&&de(Ec);break;case 24:Yl(vs)}}function dm(n,l){try{var i=l.updateQueue,u=i!==null?i.lastEffect:null;if(u!==null){var m=u.next;i=m;do{if((i.tag&n)===n){u=void 0;var h=i.create,T=i.inst;u=h(),T.destroy=u}i=i.next}while(i!==m)}}catch(V){gn(l,l.return,V)}}function ri(n,l,i){try{var u=l.updateQueue,m=u!==null?u.lastEffect:null;if(m!==null){var h=m.next;u=h;do{if((u.tag&n)===n){var T=u.inst,V=T.destroy;if(V!==void 0){T.destroy=void 0,m=l;var ne=i,me=V;try{me()}catch(Se){gn(m,ne,Se)}}}u=u.next}while(u!==h)}}catch(Se){gn(l,l.return,Se)}}function FL(n){var l=n.updateQueue;if(l!==null){var i=n.stateNode;try{M_(l,i)}catch(u){gn(n,n.return,u)}}}function $L(n,l,i){i.props=Dc(n.type,n.memoizedProps),i.state=n.memoizedState;try{i.componentWillUnmount()}catch(u){gn(n,l,u)}}function il(n,l){try{var i=n.ref;if(i!==null){switch(n.tag){case 26:case 27:case 5:var u=n.stateNode;break;case 30:var m=n.stateNode,h=Fl(n.memoizedProps,m);(m.ref===null||m.ref.name!==h)&&(m.ref=Z3(h)),u=m.ref;break;case 7:if(n.stateNode===null){var T=new Zr(n);b(n.child,!1,Xne,T,void 0,void 0),n.stateNode=T}u=n.stateNode;break;default:u=n.stateNode}typeof i=="function"?n.refCleanup=i(u):i.current=u}}catch(V){gn(n,l,V)}}function Ys(n,l){var i=n.ref,u=n.refCleanup;if(i!==null)if(typeof u=="function")try{u()}catch(m){gn(n,l,m)}finally{n.refCleanup=null,n=n.alternate,n!=null&&(n.refCleanup=null)}else if(typeof i=="function")try{i(null)}catch(m){gn(n,l,m)}else i.current=null}function Bb(n,l){if((n.tag===5||n.tag===27||n.tag===6)&&n.alternate===null&&l!==null)for(var i=0;i title"))),Xs(u,l,i),u[As]=n,bs(u),l=u;break e;case"link":if(h=m5("link","href",m).get(l+(i.href||""))){for(T=0;Tbt&&(T=bt,bt=We,We=T);var pe=n_(V,We),oe=n_(V,bt);if(pe&&oe&&(je.rangeCount!==1||je.anchorNode!==pe.node||je.anchorOffset!==pe.offset||je.focusNode!==oe.node||je.focusOffset!==oe.offset)){var be=Re.createRange();be.setStart(pe.node,pe.offset),je.removeAllRanges(),We>bt?(je.addRange(be),je.extend(oe.node,oe.offset)):(be.setEnd(oe.node,oe.offset),je.addRange(be))}}}}for(Re=[],je=V;je=je.parentNode;)je.nodeType===1&&Re.push({element:je,left:je.scrollLeft,top:je.scrollTop});for(typeof V.focus=="function"&&V.focus(),V=0;Vi?32:i,ge.T=null,i=hk,hk=null;var h=Ua,T=ml;if(Wn=0,Lc=Ua=null,ml=0,(an&6)!==0)throw Error(o(331));var V=an;if(an|=4,p3(h.current),u3(h,h.current,T,i),an=V,bm(0,!1),Jt&&typeof Jt.onPostCommitFiberRoot=="function")try{Jt.onPostCommitFiberRoot(Rn,h)}catch{}return!0}finally{ee.p=m,ge.T=u,E3(n,l)}}function A3(n,l,i){l=ga(i,l),l=zN(n.stateNode,l,2),n=ei(n,l,2),n!==null&&(Ho(n,2),hl(n))}function gn(n,l,i){if(n.tag===3)A3(n,n,i);else for(;l!==null;){if(l.tag===3){A3(l,n,i);break}else if(l.tag===1){var u=l.stateNode;if(typeof l.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ii===null||!ii.has(u))){n=ga(i,n),i=kL(2),u=ei(l,i,2),u!==null&&(CL(i,u,l,n),Ho(u,2),hl(u));break}}l=l.return}}function wk(n,l,i){var u=n.pingCache;if(u===null){u=n.pingCache=new cne;var m=new Set;u.set(l,m)}else m=u.get(l),m===void 0&&(m=new Set,u.set(l,m));m.has(i)||(fk=!0,m.add(i),n=xne.bind(null,n,l,i),l.then(n,n))}function xne(n,l,i){var u=n.pingCache;u!==null&&u.delete(l),n.pingedLanes|=n.suspendedLanes&i,n.warmLanes&=~i,Dn===n&&(Lt&i)===i&&((os===4||os===3&&(Lt&62914560)===Lt&&300>Vt()-Xb)&&(an&2)===0?Ed(n,0):Yb|=i,Sd===Lt&&(Sd=0)),hl(n)}function R3(n,l){l===0&&(l=dr()),n=jc(n,l),n!==null&&(Ho(n,l),hl(n))}function bne(n){var l=n.memoizedState,i=0;l!==null&&(i=l.retryLane),R3(n,i)}function vne(n,l){var i=0;switch(n.tag){case 31:case 13:var u=n.stateNode,m=n.memoizedState;m!==null&&(i=m.retryLane);break;case 19:u=n.stateNode;break;case 22:u=n.stateNode._retryCache;break;default:throw Error(o(314))}u!==null&&u.delete(l),R3(n,i)}function yne(n,l){return ds(n,l)}var Rd=null,Od=null,Sk=!1,sv=!1,Nk=!1,ui=0;function hl(n){n!==Od&&n.next===null&&(Od===null?Rd=Od=n:Od=Od.next=n),sv=!0,Sk||(Sk=!0,wne())}function bm(n,l){if(!Nk&&sv){Nk=!0;do for(var i=!1,u=Rd;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var h=0;else{var T=u.suspendedLanes,V=u.pingedLanes;h=(1<<31-Tt(42|n)+1)-1,h&=m&~(T&~V),h=h&201326741?h&201326741|1:h?h|2:0}h!==0&&(i=!0,I3(u,h))}else h=Lt,h=rl(u,u===Dn?h:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(h&3)===0||rn(u,h)||(i=!0,I3(u,h));u=u.next}while(i);Nk=!1}}function jne(){O3()}function O3(){sv=Sk=!1;var n=0;ui!==0&&Dne()&&(n=ui);for(var l=Vt(),i=null,u=Rd;u!==null;){var m=u.next,h=M3(u,l);h===0?(u.next=null,i===null?Rd=m:i.next=m,m===null&&(Od=i)):(i=u,(n!==0||(h&3)!==0)&&(sv=!0)),u=m}Wn!==0&&Wn!==5||bm(n),ui!==0&&(ui=0)}function M3(n,l){for(var i=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,h=n.pendingLanes&-62914561;0V)break;var Se=ne.transferSize,Re=ne.initiatorType;Se&&U3(Re)&&(ne=ne.responseEnd,T+=Se*(neiv){We.length=He;break}be=new Promise(Bne.bind(be)),We.push(be)}}}if(0"u"?null:document;function u5(n,l,i){var u=Dd;if(u&&typeof l=="string"&&l){var m=pr(l);m='link[rel="'+n+'"][href="'+m+'"]',typeof i=="string"&&(m+='[crossorigin="'+i+'"]'),c5.has(m)||(c5.add(m),n={rel:n,crossOrigin:i,href:l},u.querySelector(m)===null&&(l=u.createElement("link"),Xs(l,"link",n),bs(l),u.head.appendChild(l)))}}function rse(n){eo.D(n),u5("dns-prefetch",n,null)}function ase(n,l){eo.C(n,l),u5("preconnect",n,l)}function lse(n,l,i){eo.L(n,l,i);var u=Dd;if(u&&n&&l){var m='link[rel="preload"][as="'+pr(l)+'"]';l==="image"&&i&&i.imageSrcSet?(m+='[imagesrcset="'+pr(i.imageSrcSet)+'"]',typeof i.imageSizes=="string"&&(m+='[imagesizes="'+pr(i.imageSizes)+'"]')):m+='[href="'+pr(n)+'"]';var h=m;switch(l){case"style":h=Id(n);break;case"script":h=Pd(n)}if(!(wa.has(h)||(n=P({rel:"preload",href:l==="image"&&i&&i.imageSrcSet?void 0:n,as:l},i),wa.set(h,n),u.querySelector(m)!==null||l==="style"&&u.querySelector(Sm(h))||l==="script"&&u.querySelector(Nm(h))))){var T=u.createElement("link");Xs(T,"link",n),l==="style"&&(T[Rs]=!0,T.onload=T.onerror=function(){Ip(T)}),bs(T),u.head.appendChild(T)}}}function ose(n,l){eo.m(n,l);var i=Dd;if(i&&n){var u=l&&typeof l.as=="string"?l.as:"script",m='link[rel="modulepreload"][as="'+pr(u)+'"][href="'+pr(n)+'"]',h=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":h=Pd(n)}if(!wa.has(h)&&(n=P({rel:"modulepreload",href:n},l),wa.set(h,n),i.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(i.querySelector(Nm(h)))return}u=i.createElement("link"),Xs(u,"link",n),bs(u),i.head.appendChild(u)}}}function ise(n,l,i){eo.S(n,l,i);var u=Dd;if(u&&n){var m=$o(u).hoistableStyles,h=Id(n);l=l||"default";var T=m.get(h);if(!T){var V={loading:0,preload:null};if(T=u.querySelector(Sm(h)))V.loading=5;else{n=P({rel:"stylesheet",href:n,"data-precedence":l},i),(i=wa.get(h))&&qk(n,i);var ne=T=u.createElement("link");bs(ne),Xs(ne,"link",n),ne._p=new Promise(function(me,Se){ne.onload=me,ne.onerror=Se}),ne.addEventListener("load",function(){V.loading|=1}),ne.addEventListener("error",function(){V.loading|=2}),V.loading|=4,lv(T,l,u)}T={type:"stylesheet",instance:T,count:1,state:V},m.set(h,T)}}}function cse(n,l){eo.X(n,l);var i=Dd;if(i&&n){var u=$o(i).hoistableScripts,m=Pd(n),h=u.get(m);h||(h=i.querySelector(Nm(m)),h||(n=P({src:n,async:!0},l),(l=wa.get(m))&&Gk(n,l),h=i.createElement("script"),bs(h),Xs(h,"link",n),i.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},u.set(m,h))}}function use(n,l){eo.M(n,l);var i=Dd;if(i&&n){var u=$o(i).hoistableScripts,m=Pd(n),h=u.get(m);h||(h=i.querySelector(Nm(m)),h||(n=P({src:n,async:!0,type:"module"},l),(l=wa.get(m))&&Gk(n,l),h=i.createElement("script"),bs(h),Xs(h,"link",n),i.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},u.set(m,h))}}function d5(n,l,i,u){var m=(m=he.current)?wm(m):null;if(!m)throw Error(o(446));switch(n){case"meta":case"title":return null;case"style":return typeof i.precedence=="string"&&typeof i.href=="string"?(i=Id(i.href),l=$o(m).hoistableStyles,u=l.get(i),u||(u={type:"style",instance:null,count:0,state:null},l.set(i,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(i.rel==="stylesheet"&&typeof i.href=="string"&&typeof i.precedence=="string"){n=Id(i.href);var h=$o(m).hoistableStyles,T=h.get(n);if(T||(m=m.ownerDocument||m,T={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},h.set(n,T),(h=m.querySelector(Sm(n)))?h._p||(T.instance=h,T.state.loading=5):(h=wa.get(n),h||(h={rel:"preload",as:"style",href:i.href,crossOrigin:i.crossOrigin,integrity:i.integrity,media:i.media,hrefLang:i.hrefLang,referrerPolicy:i.referrerPolicy},wa.set(n,h)),dse(m,n,h,T.state))),l&&u===null)throw Error(o(528,""));return T}if(l&&u!==null)throw Error(o(529,""));return null;case"script":return l=i.async,i=i.src,typeof i=="string"&&l&&typeof l!="function"&&typeof l!="symbol"?(i=Pd(i),l=$o(m).hoistableScripts,u=l.get(i),u||(u={type:"script",instance:null,count:0,state:null},l.set(i,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(o(444,n))}}function Id(n){return'href="'+pr(n)+'"'}function Sm(n){return'link[rel="stylesheet"]['+n+"]"}function f5(n){return P({},n,{"data-precedence":n.precedence,precedence:null})}function dse(n,l,i,u){if(l=n.querySelector('link[rel="preload"][as="style"]['+l+"]")){if(l[Rs]!==!0){u.loading=1;return}}else l=n.createElement("link"),l[Rs]=!0,l.onload=l.onerror=Ip.bind(null,l),Xs(l,"link",i),bs(l),n.head.appendChild(l);u.preload=l,l.addEventListener("load",function(){return u.loading|=1}),l.addEventListener("error",function(){return u.loading|=2})}function Pd(n){return'[src="'+pr(n)+'"]'}function Nm(n){return"script[async]"+n}function p5(n,l,i){if(l.count++,l.instance===null)switch(l.type){case"style":var u=n.querySelector('style[data-href~="'+pr(i.href)+'"]');if(u)return l.instance=u,bs(u),u;var m=P({},i,{"data-href":i.href,"data-precedence":i.precedence,href:null,precedence:null});return u=(n.ownerDocument||n).createElement("style"),bs(u),Xs(u,"style",m),lv(u,i.precedence,n),l.instance=u;case"stylesheet":m=Id(i.href);var h=n.querySelector(Sm(m));if(h)return l.state.loading|=4,l.instance=h,bs(h),h;u=f5(i),(m=wa.get(m))&&qk(u,m),h=(n.ownerDocument||n).createElement("link"),bs(h);var T=h;return T._p=new Promise(function(V,ne){T.onload=V,T.onerror=ne}),Xs(h,"link",u),l.state.loading|=4,lv(h,i.precedence,n),l.instance=h;case"script":return h=Pd(i.src),(m=n.querySelector(Nm(h)))?(l.instance=m,bs(m),m):(u=i,(m=wa.get(h))&&(u=P({},i),Gk(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),bs(m),Xs(m,"link",u),n.head.appendChild(m),l.instance=m);case"void":return null;default:throw Error(o(443,l.type))}else l.type==="stylesheet"&&(l.state.loading&4)===0&&(u=l.instance,l.state.loading|=4,lv(u,i.precedence,n));return l.instance}function lv(n,l,i){for(var u=i.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=u.length?u[u.length-1]:null,h=m,T=0;T title"):null)}function fse(n,l,i){if(i===1||l.itemProp!=null)return!1;switch(n){case"meta":case"title":return!0;case"style":if(typeof l.precedence!="string"||typeof l.href!="string"||l.href==="")break;return!0;case"link":if(typeof l.rel!="string"||typeof l.href!="string"||l.href===""||l.onLoad||l.onError)break;return l.rel==="stylesheet"?(n=l.disabled,typeof l.precedence=="string"&&n==null):!0;case"script":if(l.async&&typeof l.async!="function"&&typeof l.async!="symbol"&&!l.onLoad&&!l.onError&&l.src&&typeof l.src=="string")return!0}return!1}function h5(n,l){return n==="img"&&l.src!=null&&l.src!==""&&l.onLoad==null&&l.loading!=="lazy"}function g5(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function x5(n){return(n.width||100)*(n.height||100)*(typeof devicePixelRatio=="number"?devicePixelRatio:1)*.25}function b5(n,l){typeof l.decode=="function"&&(n.imgCount++,l.complete||(n.imgBytes+=x5(l),n.suspenseyImages.push(l)),n=hse.bind(n),l.decode().then(n,n))}function pse(n,l,i,u){if(i.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(i.state.loading&4)===0){if(i.instance===null){var m=Id(u.href),h=l.querySelector(Sm(m));if(h){l=h._p,l!==null&&typeof l=="object"&&typeof l.then=="function"&&(n.count++,n=km.bind(n),l.then(n,n)),i.state.loading|=4,i.instance=h,bs(h);return}h=l.ownerDocument||l,u=f5(u),(m=wa.get(m))&&qk(u,m),h=h.createElement("link"),bs(h);var T=h;T._p=new Promise(function(V,ne){T.onload=V,T.onerror=ne}),Xs(h,"link",u),i.instance=h}n.stylesheets===null&&(n.stylesheets=new Map),n.stylesheets.set(i,l),(l=i.state.preload)&&(i.state.loading&3)===0&&(n.count++,i=km.bind(n),l.addEventListener("load",i),l.addEventListener("error",i))}}var iv=0;function mse(n,l){return n.stylesheets&&n.count===0&&uv(n,n.stylesheets),0iv?50:800)+l);return n.unsuspend=i,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function v5(n){if(n.count===0&&(n.imgCount===0||!n.waitingForImages)){if(n.stylesheets)uv(n,n.stylesheets);else if(n.unsuspend){var l=n.unsuspend;n.unsuspend=null,l()}}}function km(){this.count--,v5(this)}function hse(){this.imgCount--,v5(this)}var cv=null;function uv(n,l){n.stylesheets=null,n.unsuspend!==null&&(n.count++,cv=new Map,l.forEach(gse,n),cv=null,km.call(n))}function gse(n,l){if(!(l.state.loading&4)){var i=cv.get(n);if(i)var u=i.get(null);else{i=new Map,cv.set(n,i);for(var m=n.querySelectorAll("link[data-precedence],style[data-precedence]"),h=0;h"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),bj.exports=g8(),bj.exports}var vn=x8();const tg=[20,50,100,200],ng=[20,50,100,200,"all"],du=50,CR="workbuddy-desktop-table-size:";function TR(e){return e==="all"?r("全部"):String(e)}function sg(e,t=ng,a=du){t.includes(a)||(a=t.includes(du)?du:t[0]);let o=null;try{o=localStorage.getItem(CR+e)}catch{return a}if(o===null||o.trim()==="")return a;if(o==="all")return t.includes("all")?"all":a;const c=Number(o);return Number.isFinite(c)&&t.includes(c)?c:a}function rg(e,t){try{localStorage.setItem(CR+e,String(t))}catch{}}function ag(e,t,a={}){const o=a.sizes??ng,c=a.defaultSize??du,[d,f]=x.useState(()=>sg(t,o,c)),[p,g]=x.useState(1),v=Math.max(1,d==="all"?1:Math.ceil(e/d)),y=Math.min(Math.max(1,p),v);x.useEffect(()=>{y!==p&&g(y)},[y,p]);const b=x.useCallback(k=>{f(k),rg(t,k),g(1)},[t]),j=x.useCallback(k=>{g(Math.min(Math.max(1,Math.round(k)||1),v))},[v]),w=d==="all"?0:(y-1)*d,S=d==="all"?e:Math.min(e,w+d),N=x.useCallback(k=>d==="all"?k.slice():k.slice(w,S),[d,w,S]);return{size:d,page:y,pageCount:v,rangeStart:e?w+1:0,rangeEnd:e?S:0,paged:d!=="all",setSize:b,goto:j,slice:N}}function Li({total:e,page:t,pageCount:a,size:o,sizes:c=ng,onSizeChange:d,onPageChange:f,range:p=null,disabled:g=!1,leading:v,className:y}){const[b,j]=x.useState(String(t));x.useEffect(()=>j(String(t)),[t]);const w=()=>{const k=b.trim();if(!k){j(String(t));return}const E=Number(k);if(!Number.isFinite(E)){j(String(t));return}const D=Math.min(Math.max(1,Math.round(E)),a);j(String(D)),D!==t&&f(D)},S=a<=1,N=e===0?r("共 0 条"):p?r("共 {total} 条 · 当前第 {start}–{end} 条",{total:e,start:p.start,end:p.end}):r("共 {total} 条(全部显示)",{total:e});return s.jsxs("div",{className:y?`panel-foot table-foot-bar ${y}`:"panel-foot table-foot-bar",children:[v,s.jsx("div",{className:"spacer"}),s.jsxs("div",{className:"table-foot-ctl",children:[s.jsx("span",{className:"table-foot-count",children:N}),s.jsxs("span",{className:"table-foot-size",children:[r("每页"),s.jsxs(ft,{value:String(o),onValueChange:k=>d(k==="all"?"all":Number(k)),children:[s.jsx(mt,{className:"h-[26px] w-[86px]",disabled:g,"aria-label":r("每页条数"),children:s.jsx(pt,{children:TR(o)})}),s.jsx(ht,{children:c.map(k=>s.jsx(qe,{value:String(k),children:TR(k)},String(k)))})]}),r("条")]}),s.jsxs("span",{className:"table-foot-jump",children:[r("跳至"),s.jsx($e,{className:"h-[26px] w-[52px] px-1 text-center",value:b,disabled:g||S,"aria-label":r("跳转到指定页"),title:S?r("当前只有一页"):r("跳转到第 1–{pageCount} 页",{pageCount:a}),inputMode:"numeric",onChange:k=>j(k.target.value),onKeyDown:k=>{k.key==="Enter"?(k.preventDefault(),w()):k.key==="Escape"&&j(String(t))},onBlur:w}),r("页")]}),s.jsx(AF,{page:t,pageCount:a,onPageChange:f,disabled:g})]})]})}const jj=[{key:"pick",label:r("选择"),align:"center",legacyAlign:"left"},{key:"order",label:r("顺序"),title:r("组内先后:按住左边的把手上下拖动即可调整;整组的先后拖分组带的把手"),align:"center",legacyAlign:"left"},{key:"account",label:r("账号"),align:"center",legacyAlign:"left"},{key:"proxy",label:r("代理"),title:r("该账号出网走的代理(Clash 出口 / 自定义 / 直连);点击可修改"),align:"center"},{key:"connections",label:r("连接数"),title:r("此刻正在使用这个账号的请求数(含还在下发内容的流式请求);为 0 时不显示"),align:"center"},{key:"status",label:r("状态"),align:"center",legacyAlign:"left"},{key:"limits",label:r("限流"),title:r("该账号当前限流中的模型;点徽章看明细"),align:"center",legacyAlign:"left"},{key:"expiry",label:r("有效期"),align:"center",legacyAlign:"left"},{key:"usage",label:r("余额"),align:"center",legacyAlign:"left"},{key:"actions",label:r("操作"),align:"right"}],ER="agent2api-accounts-col-widths",kf={pick:47,order:84,proxy:186,connections:56,status:80,limits:148,expiry:80,usage:132,actions:200},wj=new Set(["account"]),b8=300,Sj=56,v8=new Set([...Object.keys(kf),...wj]),fu=(()=>{try{const e=JSON.parse(localStorage.getItem(ER)||"{}"),t={};for(const[a,o]of Object.entries(e||{})){const c=Number(o);v8.has(a)&&Number.isFinite(c)&&c>=Sj&&(t[a]=Math.round(c))}return t}catch{return{}}})();function AR(){try{localStorage.setItem(ER,JSON.stringify(fu))}catch{}}function y8(){return{...kf,...fu}}function j8(e){let t=0;for(const a of e){const o=fu[a];o?t+=o:wj.has(a)?t+=b8:kf[a]?t+=kf[a]:t+=Sj}return Math.round(t)}function RR(e,t){const a=e?.querySelector(`thead th:nth-child(${t+1})`),o=a?.getAttribute("data-col")||a?.className.match(/cell-([a-z]+)/)?.[1];if(!o)return null;const c=e?.querySelector(`colgroup col[data-col="${CSS.escape(o)}"]`)||e?.querySelectorAll("colgroup col")[t];return c?{key:o,col:c}:null}function w8(e,t,a){const o=Math.max(Sj,Math.round(a));e.style.width=o+"px",wj.has(t)||o!==kf[t]?fu[t]=o:delete fu[t]}let Nj=()=>{};function S8(e,t){if(Nj=t,!e)return;let a=null;e.addEventListener("pointerdown",o=>{if(o.button!==0)return;const c=o.target?.closest?.(".col-grip");if(!c)return;o.preventDefault();const d=c.closest("th"),f=d?.closest("table")||null,p=d?.parentElement?[...d.parentElement.children].indexOf(d):-1,g=RR(f,p);if(!g)return;const v=o.clientX,y=g.col.getBoundingClientRect().width;c.classList.add("active"),document.body.classList.add("col-resizing");try{c.setPointerCapture(o.pointerId)}catch{}a={...g,startX:v,startWidth:y,grip:c,pointerId:o.pointerId},window.addEventListener("pointermove",b),window.addEventListener("pointerup",j),window.addEventListener("pointercancel",j),window.addEventListener("blur",j);function b(w){if(a){if(w.buttons===0){j();return}w8(a.col,a.key,a.startWidth+w.clientX-a.startX)}}function j(){if(!a)return;const{grip:w,pointerId:S}=a;a=null,w.classList.remove("active"),document.body.classList.remove("col-resizing");try{w.releasePointerCapture(S)}catch{}window.removeEventListener("pointermove",b),window.removeEventListener("pointerup",j),window.removeEventListener("pointercancel",j),window.removeEventListener("blur",j),AR(),Nj()}}),e.addEventListener("dblclick",o=>{const c=o.target?.closest?.(".col-grip");if(!c)return;const d=c.closest("th"),f=d?.closest("table")||null,p=d?.parentElement?[...d.parentElement.children].indexOf(d):-1,g=RR(f,p);g&&(delete fu[g.key],AR(),Nj())})}function yt(){return window}function Ws(e,t){yt().wbApp?.toast?.(e,t)}function lg(e){return e instanceof Error&&e.message?e.message:String(e??"").trim()||r("未知错误")}function kj(e){return(yt().wbApp?.getState?.()?.accounts?.accounts||[]).filter(a=>(a?.provider||"workbuddy")===e).length}function OR(e){const t=e?.name||"";if(t)return(yt().wbProviders?.customList?.()||[]).find(a=>(a.name||"")===t)}async function MR(e){const t=yt().__TAURI_INTERNALS__;if(!t||typeof t.invoke!="function")throw new Error(r("桌面运行时不可用(Tauri 未初始化)"));return t.invoke("api_request",{request:{method:"POST",path:"/api/accounts",body:e}})}function DR(e){return e?.name||e?.uid||e?.userId||""}function Cj(){yt().wbAddAccountModal?.close?.()}async function og(e,t){Cj(),await yt().wbApp?.refresh?.(),Ws(r("✅ {label}账号已添加{name}",{label:t,name:e?`:${e}`:""}))}const pu=new Map;function Za(e){return{defaultValue:pu.get(e)??"",onChange:t=>{const a=t.currentTarget.value;a?pu.set(e,a):pu.delete(e)}}}function So(e,t){t?pu.set(e,t):pu.delete(e);const a=document.getElementById(e);(a instanceof HTMLInputElement||a instanceof HTMLTextAreaElement)&&(a.value=t)}function Mr(e){const t=document.getElementById(e);return t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?t.value.trim():(pu.get(e)??"").trim()}function Tj(e){for(const t of e)So(t,"")}const zi={edition:"cn",loginMode:"embedded",socialRestore:!1},N8=100,k8=256,C8=e=>e.key==="name"?N8:k8,T8={provider:"raccoon",label:"小浣熊",addButton:r("添加小浣熊账号"),webLogin:{noteHtml:r("在内嵌窗口里完成官方登录,成功后自动加入账号列表。"),button:r("打开网页登录"),hint:r("内嵌窗口打开;完成后自动加入列表,关窗即取消等待"),busyText:r("等待小浣熊登录完成…")},manualTitle:r("粘贴 token / refreshToken"),manualNoteHtml:r('refreshToken 可选,填了到期可自动续期;两者都能从小浣熊客户端登录态文件里取到。'),fields:[{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用凭证里的账号名")},{key:"token",label:"token",rows:3,placeholder:r("粘贴 access_token(一长串 JWT)")},{key:"refreshToken",inputKey:"refresh",label:"refreshToken",rows:2,optional:!0,placeholder:r("可选")}],desktopNote:r("读本机客户端当前登录态,每次实时读取(删掉这条记录不影响客户端登录态)。客户端重新登录后点「刷新 Token」同步。")},E8={provider:"catpaw",label:"CatPaw",webLogin:{noteHtml:r("用 CatPaw 账号完成登录(美团 passport),成功后自动加入账号列表。"),button:r("打开 CatPaw 网页登录"),busyText:r("等待 CatPaw 登录完成…"),modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("内嵌窗口打开;完成后自动加入列表,关窗即取消等待")},{value:"external",label:r("系统浏览器"),hint:r("系统浏览器打开(复用已登录的美团账号);完成后自动加入列表")}]},manualNote:r("token 是登录态 Cookie;CatPaw 没有刷新机制,过期后需在客户端重新登录。"),fields:[{key:"token",label:"token",rows:3,placeholder:r("CatPaw 的 X-Passport-Token(登录态 Cookie)")},{key:"uid",label:"uid",placeholder:r("必填,CatPaw 账号标识")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用登录名或 uid")}],desktopNote:r("读本机客户端当前登录态,每次实时读取(删掉这条记录不影响客户端登录态)。客户端重新登录后重新导入即可。"),desktopHint:r("读取 ~/.meituan-catpaw/auth.json,需已在 CatPaw 客户端登录")},A8={provider:"autoclaw",label:r("AutoClaw 国内版"),manualNote:r("token 支持 enc: 前缀(Windows 上自动解密)。未填 refreshToken 无法自动续期。"),smsLogin:{noteHtml:r("用绑定的手机号登录:点「获取验证码」后填入即可。这是国内版官方唯一的登录方式。")},fields:[{key:"token",label:"token",rows:3,placeholder:r("明文 JWT 或 auth.json 里的 enc: 加密值(自动解密)")},{key:"refreshToken",label:"refreshToken",rows:2,optional:!0,placeholder:r("没有则无法自动续期")},{key:"deviceId",label:"deviceId",optional:!0,placeholder:r("可选,续期时带上")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用 userId")}],desktopNote:r("读本机客户端当前登录态,每次实时读取(删掉这条记录不影响客户端登录态)。"),desktopHint:r("读取 %APPDATA%/AutoClaw/auth.json 并解密,仅 Windows"),desktopWindowsOnly:!0},R8={provider:"autoclaw-intl",label:r("AutoClaw 国际版"),manualNote:r("国际版与国内版账号体系独立,请填国际版的凭证。未填 refreshToken 无法自动续期。"),oauthLogin:{title:r("网页登录(Zai / Google)"),noteHtml:r("点按钮后先过一次滑块验证(官方风控),随后打开登录页,登录完成即自动添加账号。
这是国际版官方唯一的登录方式;已在客户端登录过的,用「导入桌面端登录态」更快。"),modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("内嵌窗口打开;关窗即取消等待(Google 账号被拒时改用系统浏览器)")},{value:"external",label:r("系统浏览器"),hint:r("系统浏览器打开(复用已登录的 Zai / Google 账号);完成后自动加入列表")}]},fields:[{key:"token",label:"token",rows:3,placeholder:r("明文 JWT(国际版账号的 access token)")},{key:"refreshToken",label:"refreshToken",rows:2,optional:!0,placeholder:r("没有则无法自动续期")},{key:"deviceId",label:"deviceId",optional:!0,placeholder:r("可选,续期时带上")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用 userId")}],desktopNote:r("读本机客户端当前登录态,每次实时读取(删掉这条记录不影响客户端登录态)。用 Zai / Google 登录客户端的用户走这一条。"),desktopHint:r("读取 %APPDATA%/AutoClaw/auth.json 并解密,仅 Windows"),desktopWindowsOnly:!0};function IR(e){const{provider:t,label:a,siteNote:o}=e;return{provider:t,label:a,desktop:!1,webLogin:{noteHtml:r("打开官方授权页完成设备码授权,登录的是{label}({site})的账号。",{label:a,site:o}),button:r("打开 Qoder 网页登录"),busyText:r("等待 Qoder 授权完成…"),edition:t==="qoder"?"cn":"global",modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("内嵌窗口用全新环境,多账号互不影响;关窗即取消等待")},{value:"external",label:r("系统浏览器"),hint:r("系统浏览器打开(复用已登录账号);完成后自动加入列表")}]},manualTitle:r("使用个人访问令牌(PAT)"),manualNote:r("在{label}的 Qoder 账号设置 → Integrations 生成 PAT(别填 Google / GitHub 的令牌)。两个地区的账号与凭证不通用。",{label:a}),fields:[{key:"pat",label:"Qoder PAT",rows:3,placeholder:r("粘贴 Qoder 个人访问令牌(pt-…)")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空使用账号昵称或邮箱")}]}}const O8=IR({provider:"qoder",label:r("中国版"),siteNote:"qoder.com.cn"}),M8=IR({provider:"qoder-intl",label:r("国际版"),siteNote:"qoder.com"});function PR(e){const{provider:t,label:a,poolNote:o}=e;return{provider:t,label:a,desktop:!0,webLogin:{noteHtml:r("打开授权页完成确认,账号自动加入 {label}{note}",{label:a,note:o}),button:r("打开 Cline 授权页"),busyText:r("等待 Cline 授权确认…"),modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("内嵌窗口打开;完成后自动加入列表,关窗即取消等待")},{value:"external",label:r("系统浏览器"),hint:r("系统浏览器打开(复用已登录的 Cline 账号);完成后自动加入列表")}]},manualTitle:r("填写凭证"),manualNote:r("refreshToken 可选,填了可自动续期;两者都能从客户端登录态文件取到。同一个 Cline 账号两个池都能用,这里归入 {label}。",{label:a}),fields:[{key:"accessToken",label:"accessToken",rows:3,placeholder:r("粘贴 workos:… 开头的令牌(不带前缀也会自动补上)")},{key:"refreshToken",label:"refreshToken",rows:2,optional:!0,placeholder:r("可选,没有则无法自动续期")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空使用账号姓名、邮箱或令牌指纹")}],desktopNote:r("读本机客户端当前登录态,每次实时读取(删掉这条记录不影响客户端登录态)。这一条归入 {label}。",{label:a}),desktopHint:r("读取 ~/.cline/data/settings/providers.json,需已在 Cline 客户端登录")}}function _R(e){const{provider:t,label:a,site:o,siteNote:c}=e;return{provider:t,label:a,webLogin:{noteHtml:r("打开 Accio {label}的官方登录页({site})并用你的 Accio 账号登录:登录成功后官方页面会跳回本机;同机自动完成,Docker / 远程面板按提示粘贴回调地址即可(授权码只在本机传给网关,界面不显示明文 token)。",{label:a,site:o}),button:r("打开 Accio {label}登录页",{label:a}),busyText:r("等待 Accio {label}登录完成…",{label:a}),modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("将打开内嵌窗口;登录完成后自动加入账号列表。关掉窗口即取消等待")},{value:"external",label:r("系统浏览器"),hint:r("将用系统默认浏览器打开登录页(会复用浏览器里已登录的 Accio 账号);完成登录后自动加入账号列表,关掉弹窗即取消等待")}]},manualTitle:r("填写凭证"),manualNoteHtml:r("accessToken 是 Accio 的登录凭证(一长串不透明 token,不是 JWT);refreshToken 可选,填了之后到期能自动续期。请填写 {label}账号的凭证 —— {siteNote}(最容易拿到的办法:直接用上方的「网页登录」,不需要手工找 token。)",{label:a,siteNote:c}),fields:[{key:"accessToken",label:"accessToken",rows:3,placeholder:r("粘贴 Accio 的 accessToken")},{key:"refreshToken",label:"refreshToken",rows:2,optional:!0,placeholder:r("可选,没有则无法自动续期")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空使用账号昵称或邮箱")}]}}function LR(e){const{provider:t,label:a,site:o,planNote:c}=e;return{provider:t,label:a,desktop:!1,webLogin:{noteHtml:r("打开 ZCode {label}的官方授权页并用你的账号登录。授权结果由 ZCode 服务端记录,网关在后台自动取回凭证并加入账号列表。",{label:a}),button:r("打开 ZCode {label}授权页",{label:a}),busyText:r("等待 ZCode {label}授权完成…",{label:a}),modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("将打开内嵌窗口;授权完成后自动加入账号列表。关掉窗口即取消等待。授权页最后可能提示无法打开 zcode:// 链接,这是正常的 —— 结果已由服务端记下")},{value:"external",label:r("系统浏览器"),hint:r("将用系统默认浏览器打开授权页(会复用浏览器里已登录的 ZCode 账号);授权完成后自动加入账号列表。页面最后可能提示无法打开 zcode:// 链接,属正常现象")}]},manualTitle:r("填写凭证"),manualNoteHtml:r("本家有两个**互不替代**的凭证,按你要用的功能填,至少填一个:编码套餐 API Key 用于转发推理(打 {site})与查询窗口限额(每 N 小时 / 每周的剩余比例);jwt 用于领取套餐与查询余额(打 zcode.z.ai 的 billing 网关,官方叫 Coding Plan JWT,是一串三段点分的字符串)。余额两把都能查、但读到的东西不同:jwt 读到余额桶与套餐到期,API Key 读到窗口限额;而领取只认 jwt、转发只认 API Key。请填写 {label}账号的凭证 —— {plan}(最容易拿到的办法:直接用上方的「网页登录」—— 它会替你把这个 API Key 换好,两个凭证一起拿到。)",{site:o,label:a,plan:c}),fields:[{key:"accessToken",label:r("编码套餐 API Key"),rows:3,optional:!0,placeholder:r("用于转发;形如 apiKey.secret 两段点分(不填则这个账号不能转发)")},{key:"jwt",label:"Coding Plan JWT",inputKey:"jwt",rows:3,optional:!0,placeholder:r("用于领取套餐与查询余额;不填则这个账号不能领取与查余额")},{key:"userId",label:r("用户 ID"),optional:!0,placeholder:r("可选;用于生成账号 id 与展示名")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空自动生成")}]}}const D8={provider:"codearts",label:"CodeArts",desktop:!1,webLogin:{noteHtml:r("打开华为云 CodeArts 的官方授权页登录:登录完成后官方页面会把浏览器带回网关自己的 /oauth/callback,网关用一次性授权码换取临时凭据并加入账号列表。
网关跑在另一台机器上时,网页端会提示把地址栏中的最终回调地址直接粘贴回面板。"),button:r("打开 CodeArts 授权页"),busyText:r("等待 CodeArts 登录完成…"),modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("将打开内嵌窗口;登录完成后自动加入账号列表。关掉窗口即取消等待")},{value:"external",label:r("系统浏览器"),hint:r("将用系统默认浏览器打开授权页(会复用浏览器里已登录的华为云账号);浏览器与网关不在同一台机器时,按上方说明把最终回调地址粘贴回面板")}]},manualTitle:r("粘贴登录凭据"),manualNoteHtml:r('整份粘贴官方插件 / CLIProxyAPI 落盘的凭据 JSON(形如 {"codearts_provider_credential":{…}},铺平的也行)。
必填:access_key_id、secret_access_key、security_token。要能自动续期,必须连 refresh_token 与 oauth_context 一起粘 —— 临时凭据约一小时到期,缺这半块就续不回来,只能重新登录。'),fields:[{key:"credentialJson",label:r("凭据 JSON"),rows:8,jsonExpand:!0,placeholder:'{"codearts_provider_credential":{"access_key_id":"HSTA…","secret_access_key":"…","security_token":"…","expires_at":"2026-09-27T16:17:00.327Z","domain_id":"…","user_id":"…","user_name":"…","refresh_token":"eyJ…","oauth_context":{…}}}'},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空使用凭据里的 user_name")}]},I8={provider:"trae",label:"Trae",desktop:!1,webLogin:{noteHtml:r("打开 Trae SOLO 的官方授权页(trae.cn)并用你的 Trae 账号登录:授权完成后官方页面会跳回本机的一个临时端口;同机部署自动接收,Docker / 远程面板请按提示复制地址栏回调地址。"),button:r("打开 Trae 授权页"),busyText:r("等待 Trae 授权完成…"),modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("将打开内嵌窗口;授权完成后自动加入账号列表。远程面板可粘贴回调地址。关掉窗口即取消等待。链接 5 分钟内有效,超时或未点就会作废(可重新发起)")},{value:"external",label:r("系统浏览器"),hint:r("将用系统默认浏览器打开授权页(会复用浏览器里已登录的 Trae 账号);同机完成后自动加入,Docker / 远程面板按提示粘贴地址栏回调地址。")}]},manualTitle:r("填写凭证"),manualNoteHtml:r("accessToken 是 Trae 的 Cloud-IDE-JWT(三段点分),refreshToken 用于到期自动续期(本家 refreshToken 一次一换:换发一次旧的即作废,所以两份程序别同时刷同一个账号)。
手工粘贴时请连 machineId / deviceId 一起填:上游把它们与登录时上传的设备公钥绑在一起判设备,凭空换一对会撞 2xxxx 那族设备绑定拒绝。
没有这三样时的正路是用上方的「网页登录」;容器 / 远程部署形态按提示粘贴地址栏回调地址即可。"),fields:[{key:"accessToken",label:"accessToken",rows:3,placeholder:r("Cloud-IDE-JWT(三段点分)")},{key:"refreshToken",label:"refreshToken",rows:2,optional:!0,placeholder:r("可选;填了才能到期自动续期")},{key:"uid",label:r("用户 ID"),optional:!0,placeholder:r("可选;用于去重与展示名(留空时网关会问一次上游)")},{key:"machineId",label:"machineId",optional:!0,placeholder:r("可选;UUID 形态,与凭据同生共死")},{key:"deviceId",label:"deviceId",optional:!0,placeholder:r("可选;纯数字串(上游只收 8–24 位数字)")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空自动用昵称")}]},P8={provider:"loomy",label:"Loomy",smsLogin:{noteHtml:r("用 Loomy 账号绑定的手机号登录:点「获取验证码」后填入即可。这是本家最省事的入口。")},manualNote:r("粘贴的是登录 session(同时是模型网关的 token)。Loomy 没有续期接口,session 有效期约 14 天,过期后重新登录即可。"),fields:[{key:"session",label:"session",rows:3,placeholder:r("登录 session(一长串)")},{key:"userId",label:"userId",optional:!0,placeholder:r("可选,讯飞侧 userid")},{key:"phone",label:r("手机号"),optional:!0,placeholder:r("可选,展示用")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用脱敏手机号或 userId")}],desktop:!1},_8={provider:"kuku",label:"KukuAI",webLogin:{noteHtml:r("在打开的窗口里用百度账号登录 KukuAI 主站(手机验证码 / 扫码均可),登录成功后自动加入账号列表。网关会向百度换发 KukuAI 业务会话令牌(依赖本机已安装库库AI 客户端)。"),button:r("打开网页登录"),busyText:r("等待 KukuAI 登录完成…")},manualTitle:r("粘贴 Cookie"),manualNote:r("BDUSS 必填;请粘贴**完整 Cookie**(Cookie 编辑器一键导出即可)—— 其中 **PTOKEN 必须保留**,网关要用它向百度换发 KukuAI 业务会话令牌,缺了它模型刷新会报「未登录」。支持整段 Cookie 头、Cookie 编辑器导出的 JSON 数组,或 {BDUSS, STOKEN} 对象。KukuAI 没有刷新机制,登录态过期后重新粘贴即可。"),fields:[{key:"cookie",label:"Cookie",rows:3,placeholder:r("BDUSS=…; STOKEN=…(或 Cookie 编辑器导出的 JSON)")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用账号 uk")}],desktop:!0,desktopHint:r("读取本机 KukuAI 客户端登录态(%APPDATA%\\baidugenflowpro\\Network\\Cookies),需已在 KukuAI 客户端登录"),desktopNote:r("读本机客户端当前登录态(明文 Cookie,无需解密)。客户端运行时 Cookies 文件被独占占用,导入前请先关闭 KukuAI 客户端。")};function zR(e){const{provider:t,label:a,siteNote:o}=e;return{provider:t,label:a,desktop:!1,manualTitle:r("粘贴 session cookie"),manualNoteHtml:r("粘贴网页登录态 cookie monkeycode_ai_session 的值(在浏览器里复制整段 Cookie 直接粘贴也行,网关会自己剥出值)。
{siteNote}
MonkeyCode 没有续期接口:session 有效期约 30 天(硬限制),过期后重新登录网页、再粘贴一次即可。",{siteNote:o}),fields:[{key:"session",label:"session",rows:3,placeholder:r("monkeycode_ai_session 的值(也可直接粘贴整段 Cookie)")},{key:"imageId",label:r("任务镜像 id"),optional:!0,placeholder:r("可选:发起对话必需,留空则由网关从该账号已有任务里自动发现,发现不到时之后手动补")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用上游返回的账号名或账号 id")}]}}const L8=zR({provider:"monkeycode",label:r("MonkeyCode"),siteNote:r("这里填国内站(monkeycode-ai.com)的账号:请粘贴国内站的 session。国际站(monkeycode-ai.net)是另一家 provider、另一套账号,两边的凭证不通用。")}),z8=zR({provider:"monkeycode-intl",label:r("MonkeyCode 国际版"),siteNote:r("这里填国际站(monkeycode-ai.net)的账号:请粘贴国际站的 session。国内站(monkeycode-ai.com)是另一家 provider、另一套账号,两边的凭证不通用。")}),B8={provider:"commandcode",label:r("Command Code"),desktop:!1,manualTitle:r("粘贴 API Key"),manualNote:r("粘贴 Command Code 的 API Key(user_ 开头;从官方 CLI 的 ~/.commandcode/auth.json 或网页 studio 获取)。整行 / 带引号 / 带 Bearer 前缀地粘都行,网关会自己剥成裸 key。key 不过期、也没有续期接口,失效后重新获取即可;添加时网关会做一次轻量探活,失败不影响添加。"),fields:[{key:"apiKey",label:"apiKey",rows:3,placeholder:r("user_ 开头的 API Key(也可直接粘贴 Authorization: Bearer … 整行)")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用 key 尾号")}]},H8={provider:"antigravity",label:r("Antigravity"),desktop:!1,webLogin:{noteHtml:r("在打开的窗口里登录 Google 账号(Antigravity 的授权页),授权完成后自动加入账号列表。"),button:r("打开 Antigravity 网页登录"),busyText:r("等待 Google 授权完成…"),modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("内嵌窗口打开;完成后自动加入列表,关窗即取消等待")},{value:"external",label:r("系统浏览器"),hint:r("系统浏览器打开(复用已登录的 Google 账号);完成后自动加入列表")}]},manualTitle:r("粘贴 Google refresh token"),manualNoteHtml:r("粘贴 Antigravity 的 Google refresh token(以 1// 开头;直接粘贴含 refresh_token= 的整行也行)。
这是网页登录之外的手工入口(例如从已登录的官方 IDE 里导出)。refresh token 不会过期,access token 到期由网关自动续期;令牌丢了只能重新走 Google 授权,请妥善保存。"),fields:[{key:"refreshToken",label:"refreshToken",rows:2,placeholder:r("1// 开头的 Google refresh token(也可直接粘贴 refresh_token=… 整行)")},{key:"projectId",label:"projectId",optional:!0,placeholder:r("可选(cloudaicompanionProject):留空由网关自动发现")},{key:"email",label:"email",optional:!0,placeholder:r("可选:账号邮箱,用于展示与身份识别(换新令牌也能认回同一账号)")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用邮箱或令牌尾号")}]},U8={provider:"officeace",label:r("OfficeAce 果办"),desktop:!1,webLogin:{noteHtml:r("打开华为云授权页登录:登录完成后网关会自动轮询云端取回授权码并加入账号列表(不需要装 OfficeAce 桌面端,也无需手工回填回调地址)。"),button:r("打开授权页"),busyText:r("等待 OfficeAce 登录完成…")},manualTitle:r("粘贴网关凭据"),manualNoteHtml:r("从别的机器(或 OfficeAce 桌面端 models.json)取三项贴进来:模型网关基址(baseUrl,形如 https://modelgw-…/v2)与 modelAppKey / modelAppSecret。这三项就能转发(网关凭据不过期);控制面临时凭据(accessKeyId 等)可选,留空则额度/自动续期不可用,但不影响转发。"),fields:[{key:"baseUrl",label:r("模型网关基址"),placeholder:"https://modelgw-…huaweicloud-agentarts.com/v2"},{key:"modelAppKey",label:r("网关 Key"),placeholder:"model_app_key"},{key:"modelAppSecret",label:r("网关 Secret"),placeholder:"model_app_secret"},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空用「OfficeAce 果办」")}]},BR=[T8,E8,A8,R8,O8,M8,PR({provider:"cline-free",label:"Cline Free",poolNote:r("(免费额度池,模型名带 cline-free/ 前缀)。")}),PR({provider:"cline-pass",label:"Cline Pass",poolNote:r("(订阅池,模型名带 cline-pass/ 前缀,需要账号有对应订阅)。")}),_R({provider:"accio",label:r("国际版"),site:"www.accio.com",siteNote:r("国际版与国内版是**两套独立的账号**(同一账号体系的两个站点),凭证不通用。")}),_R({provider:"accio-cn",label:r("国内版"),site:"www.accio-ai.com",siteNote:r("国内版的登录站点是 www.accio-ai.com,与国际版不是同一站。")}),LR({provider:"zcode",label:r("国内版"),site:"open.bigmodel.cn",planNote:r("国内版与**国际版是两套独立的账号与套餐**,凭证与领取的套餐都不通用。")}),LR({provider:"zcode-intl",label:r("国际版"),site:"api.z.ai",planNote:r("国际版的推理站点是 api.z.ai,与国内版不是同一站;套餐也各自独立。")}),D8,I8,P8,_8,L8,z8,B8,H8,U8],Bi="workbuddy",mu="custom",Ej="WorkBuddy";function V8(e){return BR.find(t=>t.provider===e)}const HR=[{id:"oauth",label:r("网页登录(Zai / Google)")},{id:"sms",label:r("手机验证码登录")},{id:"web",label:r("网页登录")},{id:"manual",label:r("填写凭证")},{id:"desktop",label:r("导入桌面端登录态")}],UR=()=>yt().workbuddyDesktop?.platform||"";function VR(e){return!(e.desktop===!1||UR()==="web"||e.desktopWindowsOnly&&UR()==="macos")}function FR(e,t){return HR.filter(a=>a.id==="oauth"?!!e.oauthLogin:a.id==="sms"?!!e.smsLogin:a.id==="web"?!!e.webLogin&&(!e.webLogin?.region||t===e.webLogin.region):a.id==="desktop"?VR(e):!0).map(a=>a.id)}const F8=e=>e.manualTitle||r("填写凭证添加"),$8=e=>e.manualNoteHtml?{html:e.manualNoteHtml}:{text:e.manualNote||""},q8=e=>e.addButton||r("添加 {name} 账号",{name:e.label}),Aj=(e,t)=>`${e.provider}-${t.inputKey||t.key}-input`,Cf="max-w-full flex-wrap [&_[data-slot=segmented-item]]:h-7 [&_[data-slot=segmented-item]]:px-3 [&_[data-slot=segmented-item]]:text-[12.5px]",G8=r("登录态文件路径:~/.box-agent/config/auth.json(Windows:C:\\Users\\<你的用户名>\\.box-agent\\config\\auth.json)");let Rj=!1;async function $R(e,t){if(!Rj){Rj=!0,e(!0);try{await t()}finally{Rj=!1,e(!1)}}}function ig({html:e,text:t}){return e?s.jsx("p",{dangerouslySetInnerHTML:{__html:e}}):s.jsx("p",{children:t||""})}function K8(e,t,a){let o;try{o=JSON.parse(t)}catch(c){return Ws(r("{name} 不是合法 JSON:{reason}",{name:e.label,reason:lg(c)}),"err"),!1}return!o||typeof o!="object"||Array.isArray(o)?(Ws(r("{name}要粘一个 JSON 对象(形如 {sample})",{name:e.label,sample:'{"codearts_provider_credential":{…}}'}),"err"),!1):(Object.assign(a,o),!0)}function Y8({config:e,region:t,visible:a}){const o=e.provider,[c,d]=x.useState(!1),[f,p]=x.useState(""),g=$8(e),v=e.fields.map(b=>Aj(e,b));async function y(){const b={provider:e.provider};e.regionOptions?.length&&(b.mode=t);for(const j of e.fields){const w=Mr(Aj(e,j));if(!j.optional&&!w){Ws(r("请填写 {label}",{label:j.label}),"err");return}if(w){if(j.jsonExpand){if(!K8(j,w,b))return;continue}b[j.key]=w}}await $R(d,async()=>{try{const j=await MR(b);Tj(v),p(""),await og(DR(j?.account),e.label)}catch(j){Ws(r("添加失败:{reason}",{reason:lg(j)}),"err")}})}return s.jsxs(Vn,{hidden:!a,onClick:b=>{b.target.closest("[data-raccoon-hint]")&&(b.preventDefault(),p(G8))},children:[s.jsx("h3",{children:F8(e)}),s.jsx(ig,{...g}),e.fields.map(b=>{const j=Aj(e,b),w=b.optional?"":r("(必填)");return s.jsxs("div",{className:`field-row${b.rows?" stack":""}`,children:[s.jsxs("label",{htmlFor:j,children:[b.label,w]}),b.rows?s.jsx(Qc,{id:j,rows:b.rows,placeholder:b.placeholder,...Za(j)}):s.jsx($e,{id:j,type:"text",maxLength:C8(b),placeholder:b.placeholder,...Za(j)})]},j)}),s.jsxs("div",{className:"field-row",children:[s.jsx(se,{id:`${o}-add-button`,onClick:()=>{y()},disabled:c,children:c?r("添加中…"):q8(e)}),s.jsx("span",{className:"detail",id:`${o}-add-hint`,children:f})]})]})}function X8({config:e,visible:t}){const a=e.provider,[o,c]=x.useState(!1);if(!VR(e)||!e.desktopNote)return null;async function d(){await $R(c,async()=>{try{const f=await MR({provider:e.provider,importDesktop:!0});await og(f?.account?.name||"",e.label)}catch(f){Ws(r("导入失败:{reason}",{reason:lg(f)}),"err")}})}return s.jsxs(Vn,{hidden:!t,children:[s.jsx("h3",{children:r("从本机导入桌面端登录态")}),s.jsx("p",{children:e.desktopNote}),s.jsx("div",{className:"field-row",children:s.jsx(se,{id:`${a}-desktop-button`,title:e.desktopHint,onClick:()=>{d()},disabled:o,children:r(o?"导入中…":"从本机导入桌面端登录态")})})]})}function Q8({config:e,mode:t,onModeChange:a,region:o,visible:c}){const d=e.webLogin,f=e.provider,p=x.useRef(t),g=x.useRef(o),v=x.useRef(null);return p.current=t,g.current=o,x.useEffect(()=>{const y=yt().wbWebLogin;if(!y||!d)return;const b=d.modes;v.current=y.create({provider:f,buttonId:`${f}-web-button`,cancelId:`${f}-web-cancel`,hintId:`${f}-web-hint`,busyText:d.busyText,texts:()=>{const j=b?.find(w=>w.value===p.current);return{button:d.button,hint:j?.hint||d.hint||""}},start:()=>yt().workbuddyDesktop?.startLogin(d.edition||g.current||"cn",p.current||"embedded",f),onSuccess:async j=>{Cj(),await yt().wbApp?.refresh?.();const w=j?.payload?.warning;w?Ws(r("账号已添加,但请留意:{warning}",{warning:w}),"err"):Ws(r("✅ {label}账号已添加",{label:e.label}))}})??null},[]),x.useEffect(()=>{v.current?.syncTexts()},[t]),d?s.jsxs(Vn,{hidden:!c,children:[s.jsx("h3",{children:r("网页登录")}),s.jsx(ig,{html:d.noteHtml}),d.modes?.length?s.jsxs("div",{className:"flex flex-col gap-2.5 border-l-2 border-border pl-[11px]",children:[s.jsx("span",{className:"text-[12.5px] text-subtle",children:r("打开方式")}),s.jsx(In,{"aria-label":r("{label} 网页登录的打开方式",{label:e.label}),options:d.modes,value:t,onValueChange:a})]}):null,s.jsxs("div",{className:"field-row",children:[s.jsx(se,{id:`${f}-web-button`,onClick:()=>v.current?.start(),children:d.button}),s.jsx(se,{id:`${f}-web-cancel`,variant:"outline",hidden:!0,onClick:()=>v.current?.cancel(),children:r("取消等待")}),s.jsx("span",{className:"detail",id:`${f}-web-hint`,children:d.hint||d.modes?.[0]?.hint||""})]})]}):null}function Z8({config:e,visible:t}){const a=e.smsLogin,o=e.provider;return x.useEffect(()=>{a&&yt().wbSmsLogin?.create({provider:o,onSuccess:c=>og(DR(c?.account),e.label)})},[]),a?s.jsxs(Vn,{hidden:!t,children:[s.jsx("h3",{children:r("手机验证码登录")}),s.jsx(ig,{html:a.noteHtml,text:r("用 AutoClaw 账号绑定的手机号登录:点击「获取验证码」,收到短信后填入下方并登录。验证码由本机直接提交给官方接口,界面不显示 token。")}),s.jsxs("div",{className:"sms-form",children:[s.jsxs("div",{className:"sms-field",children:[s.jsxs("label",{className:"lb",htmlFor:`${o}-sms-phone`,children:[r("手机号"),s.jsx("i",{className:"req",children:"*"})]}),s.jsxs(Ci,{children:[s.jsx(Ei,{id:`${o}-sms-phone`,type:"text",maxLength:11,placeholder:r("11 位大陆手机号"),...Za(`${o}-sms-phone`)}),s.jsx(Ti,{align:"inline-end",children:s.jsx(pB,{id:`${o}-sms-send`,className:"text-primary-fg",children:r("获取验证码")})})]})]}),s.jsxs("div",{className:"sms-field",children:[s.jsxs("label",{className:"lb",htmlFor:`${o}-sms-code`,children:[r("验证码"),s.jsx("i",{className:"req",children:"*"})]}),s.jsxs("div",{className:"sms-pair",children:[s.jsx($e,{id:`${o}-sms-code`,className:"sms-code",type:"text",maxLength:6,placeholder:r("6 位数字")}),s.jsx("label",{className:"lb-inline",htmlFor:`${o}-sms-name`,children:r("备注名")}),s.jsx($e,{id:`${o}-sms-name`,className:"sms-name",type:"text",placeholder:r("可选,留空则用脱敏手机号"),...Za(`${o}-sms-name`)})]})]}),s.jsxs("div",{className:"sms-foot",children:[s.jsx(se,{id:`${o}-sms-submit`,children:r("登录并添加")}),s.jsx("span",{className:"detail sms-hint",id:`${o}-sms-hint`})]})]})]}):null}function W8({config:e,mode:t,onModeChange:a,visible:o}){const c=e.oauthLogin,d=e.provider,f=x.useRef(t),p=x.useRef(null);f.current=t;const g=()=>c?.modes?.find(v=>v.value===f.current)?.hint||c?.hint||"";return x.useEffect(()=>{const v=yt().wbAutoclawOauth;!v||!c||(p.current=v.create({provider:d,mode:()=>f.current||"embedded",hint:g,cancelId:`${d}-oauth-cancel`,onSuccess:()=>og("",e.label)})??null)},[]),x.useEffect(()=>{p.current?.syncTexts()},[t]),c?s.jsxs(Vn,{hidden:!o,children:[s.jsx("h3",{children:c.title||r("网页登录")}),s.jsx(ig,{html:c.noteHtml}),c.modes?.length?s.jsxs("div",{className:"flex flex-col gap-2.5 border-l-2 border-border pl-[11px]",children:[s.jsx("span",{className:"text-[12.5px] text-subtle",children:r("打开方式")}),s.jsx(In,{"aria-label":r("{label} 网页登录的打开方式",{label:e.label}),options:c.modes,value:t,onValueChange:a})]}):null,s.jsxs("div",{className:"field-row",children:[s.jsx(se,{id:`${d}-oauth-zai`,children:r("使用 Zai 账号登录")}),s.jsx(se,{id:`${d}-oauth-google`,variant:"outline",children:r("使用 Google 账号登录")}),s.jsx(se,{id:`${d}-oauth-cancel`,variant:"outline",hidden:!0,children:r("取消")})]}),s.jsx("div",{className:"field-row",children:s.jsx("span",{className:"detail",id:`${d}-oauth-hint`,children:c.modes?.[0]?.hint||c.hint||""})})]}):null}function J8({config:e,active:t}){const a=e.regionOptions?.[0]?.value??"",[o,c]=x.useState(a),[d,f]=x.useState(()=>FR(e,a)[0]),[p,g]=x.useState(e.webLogin?.modes?.[0]?.value??""),[v,y]=x.useState(e.oauthLogin?.modes?.[0]?.value??""),b=FR(e,o),j=b.includes(d)?d:b[0],w=x.useMemo(()=>HR.filter(S=>b.includes(S.id)).map(S=>({value:S.id,label:S.label})),[b.join(",")]);return s.jsxs("div",{className:"add-provider-block",hidden:!t,children:[e.regionOptions?.length?s.jsxs(Vn,{children:[s.jsx("h3",{children:r("地区")}),s.jsx(In,{"aria-label":r("{label} 账号地区",{label:e.label}),className:Cf,options:e.regionOptions,value:o,onValueChange:c})]}):null,s.jsxs(Vn,{children:[s.jsx("h3",{children:r("添加方式")}),s.jsx(In,{"aria-label":r("{label} 账号的添加方式",{label:e.label}),className:Cf,options:w,value:j,onValueChange:S=>f(S)})]}),s.jsx(W8,{config:e,mode:v,onModeChange:y,visible:j==="oauth"}),s.jsx(Z8,{config:e,visible:j==="sms"}),s.jsx(Q8,{config:e,mode:p,onModeChange:g,region:o,visible:j==="web"}),s.jsx(Y8,{config:e,region:o,visible:j==="manual"}),s.jsx(X8,{config:e,visible:j==="desktop"})]})}function qR(e){return e==="intl"?"workbuddy-intl":"workbuddy"}function eq({active:e}){const[t,a]=x.useState(zi.edition),[o,c]=x.useState(zi.loginMode),[d,f]=x.useState(zi.socialRestore),p=x.useRef(t),g=x.useRef(o),v=x.useRef(d),y=x.useRef(null);p.current=t,g.current=o,v.current=d,x.useEffect(()=>{const E=yt().wbWebLogin;E&&(y.current=E.create({get provider(){return qR(p.current)},buttonId:"web-login-button",cancelId:"web-login-cancel",hintId:"web-login-hint",busyText:r("等待网页登录…"),texts:()=>{const D=g.current==="external";return{button:r(D?"在浏览器中打开登录页":"打开网页登录"),hint:r(D?"系统浏览器打开(复用已登录账号);完成后自动加入列表":"内嵌窗口打开;完成后自动加入列表,关窗即取消等待")}},start:()=>yt().workbuddyDesktop?.startLogin(p.current,g.current,qR(p.current),v.current),onSuccess:async()=>{const D=p.current==="intl"?r("国际版"):r("国内版");Cj(),await yt().wbApp?.refresh?.(),Ws(r("✅ 登录成功,{edition}账号已加入列表",{edition:D}))}})??null)},[]),x.useEffect(()=>{y.current?.syncTexts()},[t,o]);function b(E){const D=E==="intl"?"external":"embedded";a(E),zi.edition=E,c(D),zi.loginMode=D}function j(E){const D=E==="external"?"external":"embedded";c(D),zi.loginMode=D}const w=t==="intl",N=w&&o==="embedded",k=r(N?"国际版登录页默认只显示邮箱登录,勾选后恢复 Google / GitHub / X 入口":w?"只有「内嵌窗口」能恢复第三方入口:系统浏览器里我们无法改动登录页":"国内版登录页没有 Google / GitHub 入口(它用微信 / 手机号 / 邮箱登录)");return s.jsxs("div",{className:"add-provider-block",hidden:!e,children:[s.jsxs(Vn,{children:[s.jsx("h3",{children:r("账号版本")}),s.jsx("p",{children:r("两版账号可同时保存,各自一份模型清单(国内版与国际版是两家提供商,可分别启用与映射)。")}),s.jsx(In,{"aria-label":r("账号版本"),className:Cf,options:[{value:"cn",label:r("国内版(WorkBuddy)")},{value:"intl",label:r("国际版(WorkBuddy AI)")}],value:t,onValueChange:E=>b(E)})]}),s.jsxs(Vn,{children:[s.jsx("h3",{children:r("网页登录")}),s.jsx("p",{children:r("完成登录后自动加入账号列表,昵称取自上游。")}),s.jsxs("div",{className:"field-row",children:[s.jsx("span",{className:"text-[12.5px] whitespace-nowrap text-subtle",children:r("打开方式")}),s.jsx(In,{"aria-label":r("网页登录的打开方式"),className:Cf,options:[{value:"embedded",label:r("内嵌窗口")},{value:"external",label:r("系统默认浏览器")}],value:o,onValueChange:j}),s.jsxs("label",{className:"flex items-center gap-2",title:k,children:[s.jsx(ms,{checked:d,disabled:!N,onCheckedChange:E=>{f(E),zi.socialRestore=E}}),s.jsx("span",{className:"text-[12.5px] text-subtle",children:r("恢复 Google / GitHub 入口")})]})]}),s.jsx("p",{children:r("系统浏览器可复用已有登录态(国际版推荐);内嵌窗口更干净。")}),s.jsxs("div",{className:"field-row",children:[s.jsx(se,{id:"web-login-button",onClick:()=>y.current?.start(),children:r("打开网页登录")}),s.jsx(se,{id:"web-login-cancel",variant:"outline",hidden:!0,onClick:()=>y.current?.cancel(),children:r("取消等待")}),s.jsx("span",{className:"detail",id:"web-login-hint",children:r("内嵌窗口打开;完成后自动加入列表,关窗即取消等待")})]})]})]})}const Oj="proxy",Mj="preset",cg="custom",tq="import",Tf="preset:",Dj="__new__";function nq(e){return e===Mj||e===cg?e:Oj}const ug={workbuddy:"assets/providers/workbuddy.png","workbuddy-intl":"assets/providers/workbuddy.png",raccoon:"assets/providers/raccoon.png",catpaw:"assets/providers/catpaw.png",autoclaw:"assets/providers/autoclaw.png","autoclaw-intl":"assets/providers/autoclaw.png",qoder:"assets/providers/qoder.png","qoder-intl":"assets/providers/qoder.png","cline-free":"assets/providers/cline.png","cline-pass":"assets/providers/cline.png",accio:"assets/providers/accio.png","accio-cn":"assets/providers/accio.png",zcode:"assets/providers/zcode.png","zcode-intl":"assets/providers/zcode.png",codearts:"assets/providers/codearts.png",trae:"assets/providers/trae.png",loomy:"assets/providers/loomy.png",kuku:"assets/providers/kuku.png",monkeycode:"assets/providers/monkeycode.png","monkeycode-intl":"assets/providers/monkeycode.png",commandcode:"assets/providers/commandcode.png",antigravity:"assets/providers/antigravity.png",officeace:"assets/providers/officeace.png"},sq=new Set(["monkeycode","monkeycode-intl","commandcode","antigravity"]);function rq(e){const t=yt().wbProviders;if(e===Mj)return(yt().wbPresetProviders?.list||[]).map(g=>{const v=OR(g);return{id:Tf+g.key,label:g.name,count:v?kj(v.id):0,preset:!0,builtId:v?.id||""}});if(e===cg)return(t?.customList?.()||[]).map(g=>({id:g.id,label:g.name||g.id,count:kj(g.id),custom:!0}));const a=t?.all?.()||[],o=(g,v)=>g===Bi?Ej:yt().wbProviders?.labelOf?.(g)||v,d=(a.length?a.map(g=>{const v=String(g.id||"");return{id:v,label:o(v,String(g.label||g.id||"")),count:Number(g.count)||0,beta:sq.has(v)}}):[{id:Bi,label:Ej,count:kj(Bi)}]).filter(g=>g.id!=="workbuddy-intl"),f=d.findIndex(g=>g.id==="autoclaw-intl"),p=d.findIndex(g=>g.id==="autoclaw");return p>=0&&f>p&&d.splice(p+1,0,d.splice(f,1)[0]),d}function aq({item:e}){const t=e.id.startsWith(Tf)?yt().wbPresetProviders?.iconOf?.(e.id.slice(Tf.length))||"":ug[e.id];if(t)return s.jsx("span",{className:"add-provider-logo has-icon",children:s.jsx("img",{src:t,alt:"",loading:"lazy"})});const a=String(e.label||"?").trim().slice(0,1).toUpperCase()||"?";return s.jsx("span",{className:"add-provider-logo",children:a})}function lq(e){return e.preset?e.builtId?e.count?r("已建过 · {n} 个账号,点击继续添加",{n:e.count}):r("已建过,点击继续添加账号"):r("点开即预填,填 Key 接入"):e.custom?e.count?r("{n} 个账号,点击添加",{n:e.count}):r("点击添加账号"):e.count?r("{n} 个账号",{n:e.count}):r("还没有账号")}function oq({item:e,onPick:t}){return s.jsxs("button",{type:"button",className:"add-provider-card","data-provider":e.id,role:"option",onClick:()=>t(e.id),children:[s.jsx(aq,{item:e}),s.jsxs("span",{className:"add-provider-info",children:[s.jsxs("span",{className:"add-provider-name",children:[e.label,e.beta?s.jsx("span",{className:"add-provider-beta",children:"(beta)"}):null]}),s.jsx("span",{className:"add-provider-meta",children:lq(e)})]}),s.jsx("span",{className:"add-provider-go",children:"›"})]})}function iq({onPick:e}){return s.jsxs("button",{type:"button",className:"add-provider-card is-new","data-provider":Dj,role:"option",onClick:()=>e(Dj),children:[s.jsx("span",{className:"add-provider-logo is-new",children:"+"}),s.jsxs("span",{className:"add-provider-info",children:[s.jsx("span",{className:"add-provider-name",children:r("新建自定义提供商")}),s.jsx("span",{className:"add-provider-meta",children:r("接入一个兼容上游")})]}),s.jsx("span",{className:"add-provider-go",children:"›"})]})}function cq({accountType:e,onAccountTypeChange:t,search:a,onSearchChange:o,onPick:c,version:d,importing:f,importPanel:p}){const g=x.useMemo(()=>rq(e),[e,d]),v=a.trim().toLowerCase(),y=g.filter(j=>!v||j.label.toLowerCase().includes(v)),b=e===cg&&!v;return s.jsxs(Vn,{children:[s.jsx("h3",{children:r("选择提供商")}),s.jsxs("div",{className:"add-pick-row",style:f?{display:"none"}:void 0,children:[s.jsx(In,{"aria-label":r("账号类型"),className:Cf,options:[{value:Oj,label:"Agent"},{value:Mj,label:r("预置 API")},{value:cg,label:r("自定义")}],value:e,onValueChange:j=>t(nq(j))}),s.jsx("span",{id:"add-search-wrap",className:"add-provider-search ml-auto max-w-[340px] min-w-0 flex-[1_1_200px]",children:s.jsxs(Ci,{children:[s.jsx(Ti,{children:"⌕"}),s.jsx(Ei,{id:"add-provider-search",type:"search",placeholder:r("搜索提供商…"),autoComplete:"off","aria-label":r("搜索提供商"),value:a,onChange:j=>o(j.currentTarget.value)})]})})]}),p,s.jsxs("div",{className:"add-provider-grid",id:"add-provider-grid",role:"listbox","aria-label":r("选择要添加账号的提供商"),style:f?{display:"none"}:void 0,children:[b?s.jsx(iq,{onPick:c}):null,y.map(j=>s.jsx(oq,{item:j,onPick:c},j.id)),!y.length&&v?s.jsx("div",{className:"add-provider-empty",children:r("没有匹配「{keyword}」的提供商",{keyword:a.trim()})}):null]})]})}function dg(e,t){return Pe().wbIcons?.icon?.(e,t)||""}function uq({account:e,rank:t}){const a=r("组内第 {rank} 位",{rank:t});return s.jsxs("div",{className:"order-cell",children:[s.jsx("span",{className:"order-grip",role:"button",tabIndex:-1,"aria-label":r("拖动调整组内顺序"),title:r("按住拖动,调整这个账号在本组内的顺序"),dangerouslySetInnerHTML:{__html:dg("gripVertical",14)}}),s.jsx("span",{className:"order-rank",title:a,children:`#${t}`})]})}function dq({group:e,ids:t,collapsed:a}){const[o,c]=x.useState(!1),d="w-full justify-start px-2 font-normal";return s.jsxs(pf,{open:o,onOpenChange:c,children:[s.jsx(Lh,{render:s.jsx("button",{type:"button",className:"grp-iconbtn",title:r("本组操作")}),children:"⋯"}),s.jsx(mf,{align:"end",sideOffset:4,className:"w-[196px] p-1.5",children:s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsx(se,{variant:"ghost",size:"sm",className:d,title:r("启用这一组里的全部账号(含被筛选隐藏的)"),onClick:()=>{c(!1),fR(t,!0)},children:r("全部启用({n})",{n:t.length})}),s.jsx(se,{variant:"ghost",size:"sm",className:d,title:r("禁用这一组里的全部账号(含被筛选隐藏的)"),onClick:()=>{c(!1),fR(t,!1)},children:r("全部禁用({n})",{n:t.length})}),s.jsx(se,{variant:"ghost",size:"sm",className:d,title:r("打开批量操作弹窗,并预选这一组的账号(改代理等动作在弹窗里挑参数)"),onClick:()=>{c(!1),hj(t,"proxy")},children:r("批量操作本组")}),s.jsx("div",{className:"my-1 h-px bg-hairline"}),s.jsx(se,{variant:"ghost",size:"sm",className:d,onClick:()=>{c(!1),GA(e.provider)},children:r(a?"展开这一组":"折叠这一组")})]})})]})}function fq({group:e,collapsed:t,colSpan:a}){const o=ug[e.provider];return s.jsx("tr",{className:"grp-band","data-provider":e.provider,children:s.jsx("td",{colSpan:a,children:s.jsxs("div",{className:"grp-band-inner",children:[s.jsx("span",{className:"queue-grip",role:"button",tabIndex:-1,"aria-label":r("拖动调整整组顺序"),title:r("按住拖动,调整这一家的组顺位(整组一起动)"),dangerouslySetInnerHTML:{__html:dg("gripVertical",14)}}),s.jsx("span",{className:"grp-rank",title:r("组顺位:越小越先用(拖动分组带调整)"),children:r("第 {rank} 顺位",{rank:e.rank})}),s.jsx("span",{className:"grp-logo",children:o?s.jsx("img",{src:o,alt:"",loading:"lazy"}):s.jsx("span",{className:"grp-logo-txt",children:String(e.label||"?").trim().slice(0,1).toUpperCase()})}),s.jsx("span",{className:"grp-name",children:e.label}),s.jsx("span",{className:"grp-stat",children:r("{total} 个账号 · 启用 {enabled} · 禁用 {disabled}{limited}",{total:e.members.length,enabled:e.enabled,disabled:e.disabled,limited:e.limited>0?r(" · 限流 {n}",{n:e.limited}):""})}),s.jsx("span",{className:"grp-spacer"}),s.jsx("button",{type:"button",className:"grp-iconbtn grp-fold","aria-expanded":!t,title:r(t?"展开这一组":"折叠这一组"),onClick:()=>GA(e.provider),dangerouslySetInnerHTML:{__html:dg("chevronDown",14)}}),s.jsx(dq,{group:e,ids:e.accounts.map(c=>c.id),collapsed:t})]})})})}function pq({account:e}){const t=cr(e),a=r$(e);!t&&KF(e,Al(e))&&a.push({text:r("Token 限额 · 已禁用"),kind:"bad",title:r("本周期 Token 消耗达到限制器的上限,账号已被自动禁用(窗口重置也不恢复,需手动启用)")});const o=cu(e)||e.id;return s.jsxs(s.Fragment,{children:[s.jsx(ms,{checked:t,"aria-label":r("{action}{who}",{action:r(t?"禁用":"启用"),who:o}),title:r(t?"已启用,点击禁用(不参与转发)":"已禁用,点击启用"),onCheckedChange:c=>{uR(e.id,c)}}),a.length?s.jsx("div",{className:"status-tags",children:a.map(c=>s.jsx(ze,{shape:"tag",variant:c.kind==="bad"?"destructive":"secondary",title:c.title,children:c.text},c.text))}):null]})}function mq({account:e,open:t}){const a=ij(e);if(!a.length)return Hh(e,Qa(e))?s.jsx(ze,{variant:"warning",shape:"tag",title:r("余额低于限制器的阈值,转发时会跳过该账号(余额回升自动恢复)"),children:r("余额不足")}):sj(e,Al(e))?s.jsx(ze,{variant:"warning",shape:"tag",title:r("本周期 Token 消耗达到限制器的上限,转发时会跳过该账号(窗口重置自动恢复)"),children:r("Token 限额")}):s.jsxs(ze,{variant:"success",shape:"tag",title:r("当前没有任何模型处于限流中"),children:[s.jsx(ay,{}),r("正常")]});const o=dj(a[0].resetAt);return s.jsxs(s.Fragment,{children:[s.jsx(ze,{variant:"warning",shape:"tag",render:s.jsx("button",{type:"button"}),className:t?"ring-2 ring-warning-soft":void 0,title:r("点击{action}各模型的限流明细",{action:r(t?"收起":"查看")}),onClick:()=>XA(e.id,"limits",!t),children:r("{n} 个模型 ▾",{n:a.length})}),s.jsx("span",{className:"lim-sub",title:r("最早恢复"),children:r("最早 {soonest} 恢复",{soonest:o===uj?r("待定"):o})})]})}function hq({account:e}){const t=ir(kn(e)),a=gA(t.edition?e.expiresAt:e[t.expiry]);if(!a)return s.jsx("span",{className:"muted",title:r("记录里没有过期时间"),children:"—"});const o=a-Date.now();if(o<=0)return s.jsx(ze,{variant:"destructive",shape:"tag",title:r("凭证已过期,转发时会先刷新"),children:r("已过期")});const c=o<36e5?r("{n} 分钟后",{n:Math.max(1,Math.round(o/6e4))}):o<48*36e5?r("{n} 小时后",{n:(o/36e5).toFixed(1)}):r("{n} 天后",{n:Math.floor(o/24/36e5)}),d=Vs(a);return s.jsx("span",{title:d?r("{text}过期({full})",{text:c,full:d}):r("{text}过期",{text:c}),children:c})}function gq({account:e}){const t=tR(e.id);return t<=0?null:s.jsx("span",{className:"conn-count",title:r("{n} 个请求正在使用该账号(含还在下发内容的流式请求)",{n:t}),children:t})}function vr(e){if(e==null||e==="")return"—";const t=Number(e);return Number.isFinite(t)?String(t):String(e)}function xq(e){return!e||typeof e!="object"||Array.isArray(e)?"":GR(e.subscription)}function GR(e){if(!e||typeof e!="object")return"";const t=e,a=[];t.planName&&a.push(r("套餐 {name}",{name:String(t.planName)})),t.status&&a.push(r("状态 {status}",{status:String(t.status)})),t.state&&String(t.state)!=="active"&&a.push(AA(t.state));const o=t.expireAt;if(o!=null&&o!==""){const c=Number(o),d=Number.isFinite(c)&&c>1e11?Vs(c):String(o);d&&a.push(r("到期 {time}",{time:d}))}return Number.isFinite(Number(t.remainQuota))&&a.push(r("余量 {value}",{value:vr(t.remainQuota)})),Number.isFinite(Number(t.totalQuota))&&a.push(r("总量 {value}",{value:vr(t.totalQuota)})),a.join(" ")}function bq(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=e.plans;return Array.isArray(t)?t.filter(a=>a&&typeof a=="object"&&String(a.state||"")==="pending"):[]}function vq(e){const t=e.map(a=>{const o=String(a.name||a.planId||r("套餐")),c=Number(a.pendingUntil??a.startsAt);return Number.isFinite(c)&&c>0?r("{name}({time} 起生效)",{name:o,time:Vs(c*1e3)}):o});return r(`已领到、还没到生效时间的套餐(生效后余额列会按它显示): +`+u.stack}}var qn=Object.prototype.hasOwnProperty,ds=e.unstable_scheduleCallback,Gn=e.unstable_cancelCallback,xs=e.unstable_shouldYield,it=e.unstable_requestPaint,Vt=e.unstable_now,Bn=e.unstable_getCurrentPriorityLevel,tn=e.unstable_ImmediatePriority,nt=e.unstable_UserBlockingPriority,Ot=e.unstable_NormalPriority,Ft=e.unstable_LowPriority,Zn=e.unstable_IdlePriority,Hn=e.log,Un=e.unstable_setDisableYieldValue,Rn=null,Jt=null;function as(n){if(typeof Hn=="function"&&Un(n),Jt&&typeof Jt.setStrictMode=="function")try{Jt.setStrictMode(Rn,n)}catch{}}var Tt=Math.clz32?Math.clz32:wt,gt=Math.log,jt=Math.LN2;function wt(n){return n>>>=0,n===0?32:31-(gt(n)/jt|0)|0}var Sr=256,rr=262144,Hr=4194304;function jn(n){var l=n&42;if(l!==0)return l;switch(n&-n){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return n&-n;case 262144:case 524288:case 1048576:case 2097152:return n&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return n&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return n}}function rl(n,l,i){var u=n.pendingLanes;if(u===0)return 0;var m=0,h=n.suspendedLanes,T=n.pingedLanes;n=n.warmLanes;var V=u&134217727;return V!==0?(u=V&~h,u!==0?m=jn(u):(T&=V,T!==0?m=jn(T):i||(i=V&~n,i!==0&&(m=jn(i))))):(V=u&~h,V!==0?m=jn(V):T!==0?m=jn(T):i||(i=u&~n,i!==0&&(m=jn(i)))),m===0?0:l!==0&&l!==m&&(l&h)===0&&(h=m&-m,i=l&-l,h>=i||h===32&&(i&4194048)!==0)?l:m}function rn(n,l){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&l)===0}function cc(n,l){(l&8)!==0&&(l|=l&32);var i=n.entangledLanes;if(i!==0)for(n=n.entanglements,i&=l;0i;i++)l.push(n);return l}function Ho(n,l){n.pendingLanes|=l,l!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function Uo(n,l,i,u,m,h){var T=n.pendingLanes;n.pendingLanes=i,n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0,n.expiredLanes&=i,n.entangledLanes&=i,n.errorRecoveryDisabledLanes&=i,n.shellSuspendCounter=0;var V=n.entanglements,ne=n.expirationTimes,me=n.hiddenUpdates;for(i=T&~i;0"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Yt=!1;if(lt)try{var On={};Object.defineProperty(On,"passive",{get:function(){Yt=!0}}),window.addEventListener("test",On,On),window.removeEventListener("test",On,On)}catch{Yt=!1}var mn=null,Mn=null,fs=null;function Nr(){if(fs)return fs;var n,l=Mn,i=l.length,u,m="value"in mn?mn.value:mn.textContent,h=m.length;for(n=0;n=qp),$P=" ",qP=!1;function GP(n,l){switch(n){case"keyup":return wte.indexOf(l.keyCode)!==-1;case"keydown":return l.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function KP(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var ad=!1;function Nte(n,l){switch(n){case"compositionend":return KP(l);case"keypress":return l.which!==32?null:(qP=!0,$P);case"textInput":return n=l.data,n===$P&&qP?null:n;default:return null}}function kte(n,l){if(ad)return n==="compositionend"||!FS&&GP(n,l)?(n=Nr(),fs=Mn=mn=null,ad=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(l.ctrlKey||l.altKey||l.metaKey)||l.ctrlKey&&l.altKey){if(l.char&&1"u")return null;try{return n.activeElement||n.body}catch{return n.body}}function t_(n){for(;n&&n.firstChild;)n=n.firstChild;return n}function n_(n,l){var i=t_(n);n=0;for(var u;i;){if(i.nodeType===3){if(u=n+i.textContent.length,n<=l&&u>=l)return{node:i,offset:l-n};n=u}e:{for(;i;){if(i.nextSibling){i=i.nextSibling;break e}i=i.parentNode}i=void 0}i=t_(i)}}function s_(n,l){return n&&l?n===l?!0:n&&n.nodeType===3?!1:l&&l.nodeType===3?s_(n,l.parentNode):"contains"in n?n.contains(l):n.compareDocumentPosition?!!(n.compareDocumentPosition(l)&16):!1:!1}function r_(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var l=GS(n.document);l instanceof n.HTMLIFrameElement;){try{var i=typeof l.contentWindow.location.href=="string"}catch{i=!1}if(i)n=l.contentWindow;else break;l=GS(n.document)}return l}function KS(n){var l=n&&n.nodeName&&n.nodeName.toLowerCase();return l&&(l==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||l==="textarea"||n.contentEditable==="true")}var Dte=lt&&"documentMode"in document&&11>=document.documentMode,ld=null,YS=null,Xp=null,XS=!1;function a_(n,l,i){var u=i.window===i?i.document:i.nodeType===9?i:i.ownerDocument;XS||ld==null||ld!==GS(u)||(u=ld,"selectionStart"in u&&KS(u)?u={start:u.selectionStart,end:u.selectionEnd}:(u=(u.ownerDocument&&u.ownerDocument.defaultView||window).getSelection(),u={anchorNode:u.anchorNode,anchorOffset:u.anchorOffset,focusNode:u.focusNode,focusOffset:u.focusOffset}),Xp&&Yp(Xp,u)||(Xp=u,u=av(YS,"onSelect"),0>=T,m-=T,ll=1<<32-Tt(l)+m|i<rt?(ws=st,st=null):ws=st.sibling;var Xt=ue(pe,st,be[rt],Ae);if(Xt===null){st===null&&(st=ws);break}n&&st&&Xt.alternate===null&&l(pe,st),oe=h(Xt,oe,rt),zt===null?Ge=Xt:zt.sibling=Xt,zt=Xt,st=ws}if(rt===be.length)return i(pe,st),Et&&Gl(pe,rt),Ge;if(st===null){for(;rtrt?(ws=st,st=null):ws=st.sibling;var gi=ue(pe,st,Xt.value,Ae);if(gi===null){st===null&&(st=ws);break}n&&st&&gi.alternate===null&&l(pe,st),oe=h(gi,oe,rt),zt===null?Ge=gi:zt.sibling=gi,zt=gi,st=ws}if(Xt.done)return i(pe,st),Et&&Gl(pe,rt),Ge;if(st===null){for(;!Xt.done;rt++,Xt=be.next())Xt=Re(pe,Xt.value,Ae),Xt!==null&&(oe=h(Xt,oe,rt),zt===null?Ge=Xt:zt.sibling=Xt,zt=Xt);return Et&&Gl(pe,rt),Ge}for(st=u(st);!Xt.done;rt++,Xt=be.next())Xt=je(st,pe,rt,Xt.value,Ae),Xt!==null&&(n&&(ws=Xt.alternate,ws!==null&&st.delete(ws.key===null?rt:ws.key)),oe=h(Xt,oe,rt),zt===null?Ge=Xt:zt.sibling=Xt,zt=Xt);return n&&st.forEach(function(Nse){return l(pe,Nse)}),Et&&Gl(pe,rt),Ge}function bt(pe,oe,be,Ae){if(typeof be=="object"&&be!==null&&be.type===H&&be.key===null&&be.props.ref===void 0&&(be=be.props.children),typeof be=="object"&&be!==null){switch(be.$$typeof){case _:e:{for(var Ge=be.key;oe!==null;){if(oe.key===Ge){if(Ge=be.type,Ge===H){if(oe.tag===7){i(pe,oe.sibling),Ae=m(oe,be.props.children),Zo(Ae,be),Ae.return=pe,pe=Ae;break e}}else if(oe.elementType===Ge||typeof Ge=="object"&&Ge!==null&&Ge.$$typeof===F&&Rc(Ge)===oe.type){i(pe,oe.sibling),Ae=m(oe,be.props),Zo(Ae,be),Ae.return=pe,pe=Ae;break e}i(pe,oe);break}else l(pe,oe);oe=oe.sibling}be.type===H?(Ae=Sc(be.props.children,pe.mode,Ae,be.key),Zo(Ae,be),Ae.return=pe,pe=Ae):(Ae=ub(be.type,be.key,be.props,null,pe.mode,Ae),Zo(Ae,be),Ae.return=pe,pe=Ae)}return T(pe);case L:e:{for(Ge=be.key;oe!==null;){if(oe.key===Ge)if(oe.tag===4&&oe.stateNode.containerInfo===be.containerInfo&&oe.stateNode.implementation===be.implementation){i(pe,oe.sibling),Ae=m(oe,be.children||[]),Ae.return=pe,pe=Ae;break e}else{i(pe,oe);break}else l(pe,oe);oe=oe.sibling}Ae=nN(be,pe.mode,Ae),Ae.return=pe,pe=Ae}return T(pe);case F:return be=Rc(be),bt(pe,oe,be,Ae)}if(ie(be))return He(pe,oe,be,Ae);if(ae(be)){if(Ge=ae(be),typeof Ge!="function")throw Error(o(150));return be=Ge.call(be),We(pe,oe,be,Ae)}if(typeof be.then=="function")return bt(pe,oe,yb(be),Ae);if(be.$$typeof===K)return bt(pe,oe,gb(pe,be),Ae);jb(pe,be)}return typeof be=="string"&&be!==""||typeof be=="number"||typeof be=="bigint"?(be=""+be,oe!==null&&oe.tag===6?(i(pe,oe.sibling),Ae=m(oe,be),Ae.return=pe,pe=Ae):(i(pe,oe),Ae=tN(be,pe.mode,Ae),Ae.return=pe,pe=Ae),T(pe)):i(pe,oe)}return function(pe,oe,be,Ae){try{tm=0;var Ge=bt(pe,oe,be,Ae);return hd=null,Ge}catch(st){if(st===md||st===bb)throw st;var zt=kr(29,st,null,pe.mode);return zt.lanes=Ae,zt.return=pe,zt}}}var Mc=A_(!0),R_=A_(!1),Wo=!1;function fN(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function pN(n,l){n=n.updateQueue,l.updateQueue===n&&(l.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function Jo(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function ei(n,l,i){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(an&2)!==0){var m=u.pending;return m===null?l.next=l:(l.next=m.next,m.next=l),u.pending=l,l=cb(n),p_(n,null,i),l}return ib(n,u,l,i),cb(n)}function nm(n,l,i){if(l=l.updateQueue,l!==null&&(l=l.shared,(i&4194048)!==0)){var u=l.lanes;u&=n.pendingLanes,i|=u,l.lanes=i,uc(n,i)}}function mN(n,l){var i=n.updateQueue,u=n.alternate;if(u!==null&&(u=u.updateQueue,i===u)){var m=null,h=null;if(i=i.firstBaseUpdate,i!==null){do{var T={lane:i.lane,tag:i.tag,payload:i.payload,callback:null,next:null};h===null?m=h=T:h=h.next=T,i=i.next}while(i!==null);h===null?m=h=l:h=h.next=l}else m=h=l;i={baseState:u.baseState,firstBaseUpdate:m,lastBaseUpdate:h,shared:u.shared,callbacks:u.callbacks},n.updateQueue=i;return}n=i.lastBaseUpdate,n===null?i.firstBaseUpdate=l:n.next=l,i.lastBaseUpdate=l}var hN=!1;function sm(){if(hN){var n=pd;if(n!==null)throw n}}function rm(n,l,i,u){hN=!1;var m=n.updateQueue;Wo=!1;var h=m.firstBaseUpdate,T=m.lastBaseUpdate,V=m.shared.pending;if(V!==null){m.shared.pending=null;var ne=V,me=ne.next;ne.next=null,T===null?h=me:T.next=me,T=ne;var Se=n.alternate;Se!==null&&(Se=Se.updateQueue,V=Se.lastBaseUpdate,V!==T&&(V===null?Se.firstBaseUpdate=me:V.next=me,Se.lastBaseUpdate=ne))}if(h!==null){var Re=m.baseState;T=0,Se=me=ne=null,V=h;do{var ue=V.lane&-536870913,je=ue!==V.lane;if(je?(Lt&ue)===ue:(u&ue)===ue){ue!==0&&ue===Ec&&(hN=!0),Se!==null&&(Se=Se.next={lane:0,tag:V.tag,payload:V.payload,callback:null,next:null});e:{var He=n,We=V;ue=l;var bt=i;switch(We.tag){case 1:if(He=We.payload,typeof He=="function"){Re=He.call(bt,Re,ue);break e}Re=He;break e;case 3:He.flags=He.flags&-65537|128;case 0:if(He=We.payload,ue=typeof He=="function"?He.call(bt,Re,ue):He,ue==null)break e;Re=P({},Re,ue);break e;case 2:Wo=!0}}ue=V.callback,ue!==null&&(n.flags|=64,je&&(n.flags|=8192),je=m.callbacks,je===null?m.callbacks=[ue]:je.push(ue))}else je={lane:ue,tag:V.tag,payload:V.payload,callback:V.callback,next:null},Se===null?(me=Se=je,ne=Re):Se=Se.next=je,T|=ue;if(V=V.next,V===null){if(V=m.shared.pending,V===null)break;je=V,V=je.next,je.next=null,m.lastBaseUpdate=je,m.shared.pending=null}}while(!0);Se===null&&(ne=Re),m.baseState=ne,m.firstBaseUpdate=me,m.lastBaseUpdate=Se,h===null&&(m.shared.lanes=0),oi|=T,n.lanes=T,n.memoizedState=Re}}function O_(n,l){if(typeof n!="function")throw Error(o(191,n));n.call(l)}function M_(n,l){var i=n.callbacks;if(i!==null)for(n.callbacks=null,n=0;nh?h:8;var T=ge.T,V={};V.types=T!==null?T.types:null,ge.T=V,PN(n,!1,l,i);try{var ne=m(),me=ge.S;if(me!==null&&me(V,ne),ne!==null&&typeof ne=="object"&&typeof ne.then=="function"){var Se=$te(ne,u);im(n,l,Se,Qr(n))}else im(n,l,u,Qr(n))}catch(Re){im(n,l,{then:function(){},status:"rejected",reason:Re},Qr())}finally{ee.p=h,T!==null&&V.types!==null&&(T.types=V.types),ge.T=T}}function Qte(){}function DN(n,l,i,u){if(n.tag!==5)throw Error(o(476));var m=uL(n).queue;cL(n,m,l,fe,i===null?Qte:function(){return dL(n),i(u)})}function uL(n){var l=n.memoizedState;if(l!==null)return l;l={memoizedState:fe,baseState:fe,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ql,lastRenderedState:fe},next:null};var i={};return l.next={memoizedState:i,baseState:i,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Ql,lastRenderedState:i},next:null},n.memoizedState=l,n=n.alternate,n!==null&&(n.memoizedState=l),l}function dL(n){var l=uL(n);l.next===null&&(l=n.alternate.memoizedState),im(n,l.next.queue,{},Qr())}function IN(){return qs(Ld)}function fL(){return ps().memoizedState}function pL(){return ps().memoizedState}function Zte(n){for(var l=n.return;l!==null;){switch(l.tag){case 24:case 3:var i=Qr();n=Jo(i);var u=ei(l,n,i);u!==null&&(Ar(u,l,i),nm(u,l,i)),l={cache:iN()},n.payload=l;return}l=l.return}}function Wte(n,l,i){var u=Qr();i={lane:u,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},Ob(n)?hL(l,i):(i=JS(n,l,i,u),i!==null&&(Ar(i,n,u),gL(i,l,u)))}function mL(n,l,i){var u=Qr();im(n,l,i,u)}function im(n,l,i,u){var m={lane:u,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null};if(Ob(n))hL(l,m);else{var h=n.alternate;if(n.lanes===0&&(h===null||h.lanes===0)&&(h=l.lastRenderedReducer,h!==null))try{var T=l.lastRenderedState,V=h(T,i);if(m.hasEagerState=!0,m.eagerState=V,qr(V,T))return ib(n,l,m,0),Dn===null&&ob(),!1}catch{}if(i=JS(n,l,m,u),i!==null)return Ar(i,n,u),gL(i,l,u),!0}return!1}function PN(n,l,i,u){if(u={lane:2,revertLane:kk(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Ob(n)){if(l)throw Error(o(479))}else l=JS(n,i,u,2),l!==null&&Ar(l,n,2)}function Ob(n){var l=n.alternate;return n===xt||l!==null&&l===xt}function hL(n,l){gd=Nb=!0;var i=n.pending;i===null?l.next=l:(l.next=i.next,i.next=l),n.pending=l}function gL(n,l,i){if((i&4194048)!==0){var u=l.lanes;u&=n.pendingLanes,i|=u,l.lanes=i,uc(n,i)}}var Mb={readContext:qs,use:Tb,useCallback:ls,useContext:ls,useEffect:ls,useImperativeHandle:ls,useLayoutEffect:ls,useInsertionEffect:ls,useMemo:ls,useReducer:ls,useRef:ls,useState:ls,useDebugValue:ls,useDeferredValue:ls,useTransition:ls,useSyncExternalStore:ls,useId:ls,useHostTransitionStatus:ls,useFormState:ls,useActionState:ls,useOptimistic:ls,useMemoCache:ls,useCacheRefresh:ls,useEffectEvent:ls},xL={readContext:qs,use:Tb,useCallback:function(n,l){return mr().memoizedState=[n,l===void 0?null:l],n},useContext:qs,useEffect:eL,useImperativeHandle:function(n,l,i){i=i!=null?i.concat([n]):null,Ab(4194308,4,rL.bind(null,l,n),i)},useLayoutEffect:function(n,l){return Ab(4194308,4,n,l)},useInsertionEffect:function(n,l){Ab(4,2,n,l)},useMemo:function(n,l){var i=mr();l=l===void 0?null:l;var u=n();if(Dc){as(!0);try{n()}finally{as(!1)}}return i.memoizedState=[u,l],u},useReducer:function(n,l,i){var u=mr();if(i!==void 0){var m=i(l);if(Dc){as(!0);try{i(l)}finally{as(!1)}}}else m=l;return u.memoizedState=u.baseState=m,n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:m},u.queue=n,n=n.dispatch=Wte.bind(null,xt,n),[u.memoizedState,n]},useRef:function(n){var l=mr();return n={current:n},l.memoizedState=n},useState:function(n){n=EN(n);var l=n.queue,i=mL.bind(null,xt,l);return l.dispatch=i,[n.memoizedState,i]},useDebugValue:ON,useDeferredValue:function(n,l){var i=mr();return MN(i,n,l)},useTransition:function(){var n=EN(!1);return n=cL.bind(null,xt,n.queue,!0,!1),mr().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,l,i){var u=xt,m=mr();if(Et){if(i===void 0)throw Error(o(407));i=i()}else{if(i=l(),Dn===null)throw Error(o(349));(Lt&127)!==0||z_(u,l,i)}m.memoizedState=i;var h={value:i,getSnapshot:l};return m.queue=h,eL(H_.bind(null,u,h,n),[n]),u.flags|=2048,bd(9,{destroy:void 0},B_.bind(null,u,h,i,l),null),i},useId:function(){var n=mr(),l=Dn.identifierPrefix;if(Et){var i=ol,u=ll;i=(u&~(1<<32-Tt(u)-1)).toString(32)+i,l="_"+l+"R_"+i,i=kb++,0<\/script>",h=h.removeChild(h.firstChild);break;case"select":h=typeof u.is=="string"?T.createElement("select",{is:u.is}):T.createElement("select"),u.multiple?h.multiple=!0:u.size&&(h.size=u.size);break;default:h=typeof u.is=="string"?T.createElement(m,{is:u.is}):T.createElement(m)}}h[As]=l,h[$s]=u;e:for(T=l.child;T!==null;){if(T.tag===5||T.tag===6)h.appendChild(T.stateNode);else if(T.tag!==4&&T.tag!==27&&T.child!==null){T.child.return=T,T=T.child;continue}if(T===l)break e;for(;T.sibling===null;){if(T.return===null||T.return===l)break e;T=T.return}T.sibling.return=T.return,T=T.sibling}l.stateNode=h;e:switch(Xs(h,m,u),m){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&Wl(l)}}return Ln(l),l.subtreeFlags&=-33554433,YN(l,l.type,n===null?null:n.memoizedProps,l.pendingProps,i),null;case 6:if(n&&l.stateNode!=null)n.memoizedProps!==u&&Wl(l);else{if(typeof u!="string"&&l.stateNode===null)throw Error(o(166));if(n=he.current,fd(l)){if(n=l.stateNode,i=l.memoizedProps,u=null,m=_s,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[As]=l,n=!!(n.nodeValue===i||u!==null&&u.suppressHydrationWarning===!0||H3(n.nodeValue,i)),n||Xo(l,!0)}else n=jm(n).createTextNode(u),n[As]=l,l.stateNode=n}return Ln(l),null;case 31:if(i=l.memoizedState,n===null||n.memoizedState!==null){if(u=fd(l),i!==null){if(n===null){if(!u)throw Error(o(318));if(n=l.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(o(557));n[As]=l}else Nc(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;Ln(l),n=!1}else i=aN(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=i),n=!0;if(!n)return l.flags&256?(Gr(l),l):(Gr(l),null);if((l.flags&128)!==0)throw Error(o(558))}return Ln(l),null;case 13:if(u=l.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=fd(l),u!==null&&u.dehydrated!==null){if(n===null){if(!m)throw Error(o(318));if(m=l.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(o(317));m[As]=l}else Nc(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;Ln(l),m=!1}else m=aN(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return l.flags&256?(Gr(l),l):(Gr(l),null)}return Gr(l),(l.flags&128)!==0?(l.lanes=i,l):(i=u!==null,n=n!==null&&n.memoizedState!==null,i&&(u=l.child,m=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(m=u.alternate.memoizedState.cachePool.pool),h=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(h=u.memoizedState.cachePool.pool),h!==m&&(u.flags|=2048)),i!==n&&i&&(l.child.flags|=8192),zb(l,l.updateQueue),Ln(l),null);case 4:return xe(),n===null&&Ak(l.stateNode.containerInfo),l.flags|=67108864,Ln(l),null;case 10:return Yl(l.type),Ln(l),null;case 19:if(vN(l),u=l.memoizedState,u===null)return Ln(l),null;if(m=(l.flags&128)!==0,h=u.rendering,h===null)if(m)um(u,!1);else{if(os!==0||n!==null&&(n.flags&128)!==0)for(n=l.child;n!==null;){if(h=Sb(n),h!==null){for(l.flags|=128,um(u,!1),n=h.updateQueue,l.updateQueue=n,zb(l,n),l.subtreeFlags=0,n=i,i=l.child;i!==null;)m_(i,n),i=i.sibling;return am(l,Ks.current&1|2),Et&&Gl(l,u.treeForkCount),l.child}n=n.sibling}u.tail!==null&&Vt()>Qb&&(l.flags|=128,m=!0,um(u,!1),l.lanes=4194304)}else{if(!m)if(n=Sb(h),n!==null){if(l.flags|=128,m=!0,n=n.updateQueue,l.updateQueue=n,zb(l,n),um(u,!0),u.tail===null&&u.tailMode!=="collapsed"&&u.tailMode!=="visible"&&!h.alternate&&!Et)return Ln(l),null}else 2*Vt()-u.renderingStartTime>Qb&&i!==536870912&&(l.flags|=128,m=!0,um(u,!1),l.lanes=4194304);u.isBackwards?(h.sibling=l.child,l.child=h):(n=u.last,n!==null?n.sibling=h:l.child=h,u.last=h)}if(u.tail!==null){n=u.tail;e:{for(i=n;i!==null;){if(i.alternate!==null){i=!1;break e}i=i.sibling}i=!0}return u.rendering=n,u.tail=n.sibling,u.renderingStartTime=Vt(),n.sibling=null,h=Ks.current,h=m?h&1|2:h&1,u.tailMode==="visible"||u.tailMode==="collapsed"||!i||Et?am(l,h):(i=h,ke(Gs,l),ke(Ks,i),lr===null&&(lr=l)),Et&&Gl(l,u.treeForkCount),n}return Ln(l),null;case 22:case 23:return Gr(l),xN(),u=l.memoizedState!==null,n!==null?n.memoizedState!==null!==u&&(l.flags|=8192):u&&(l.flags|=8192),u?(i&536870912)!==0&&(l.flags&128)===0&&(Ln(l),l.subtreeFlags&6&&(l.flags|=8192)):Ln(l),i=l.updateQueue,i!==null&&zb(l,i.retryQueue),i=null,n!==null&&n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(i=n.memoizedState.cachePool.pool),u=null,l.memoizedState!==null&&l.memoizedState.cachePool!==null&&(u=l.memoizedState.cachePool.pool),u!==i&&(l.flags|=2048),n!==null&&de(Ac),null;case 24:return i=null,n!==null&&(i=n.memoizedState.cache),l.memoizedState.cache!==i&&(l.flags|=2048),Yl(vs),Ln(l),null;case 25:return null;case 30:return l.flags|=33554432,Ln(l),null}throw Error(o(156,l.tag))}function ane(n,l){switch(sN(l),l.tag){case 1:return n=l.flags,n&65536?(l.flags=n&-65537|128,l):null;case 3:return Yl(vs),xe(),n=l.flags,(n&65536)!==0&&(n&128)===0?(l.flags=n&-65537|128,l):null;case 26:case 27:case 5:return Oe(l),null;case 31:if(l.memoizedState!==null){if(Gr(l),l.alternate===null)throw Error(o(340));Nc()}return n=l.flags,n&65536?(l.flags=n&-65537|128,l):null;case 13:if(Gr(l),n=l.memoizedState,n!==null&&n.dehydrated!==null){if(l.alternate===null)throw Error(o(340));Nc()}return n=l.flags,n&65536?(l.flags=n&-65537|128,l):null;case 19:return vN(l),n=l.flags,n&65536?(l.flags=n&-65537|128,n=l.memoizedState,n!==null&&(n.rendering=null,n.tail=null),l.flags|=4,l):null;case 4:return xe(),null;case 10:return Yl(l.type),null;case 22:case 23:return Gr(l),xN(),n!==null&&de(Ac),n=l.flags,n&65536?(l.flags=n&-65537|128,l):null;case 24:return Yl(vs),null;case 25:return null;default:return null}}function VL(n,l){switch(sN(l),l.tag){case 3:Yl(vs),xe();break;case 26:case 27:case 5:Oe(l);break;case 4:xe();break;case 31:l.memoizedState!==null&&Gr(l);break;case 13:Gr(l);break;case 19:vN(l);break;case 10:Yl(l.type);break;case 22:case 23:Gr(l),xN(),n!==null&&de(Ac);break;case 24:Yl(vs)}}function dm(n,l){try{var i=l.updateQueue,u=i!==null?i.lastEffect:null;if(u!==null){var m=u.next;i=m;do{if((i.tag&n)===n){u=void 0;var h=i.create,T=i.inst;u=h(),T.destroy=u}i=i.next}while(i!==m)}}catch(V){gn(l,l.return,V)}}function ri(n,l,i){try{var u=l.updateQueue,m=u!==null?u.lastEffect:null;if(m!==null){var h=m.next;u=h;do{if((u.tag&n)===n){var T=u.inst,V=T.destroy;if(V!==void 0){T.destroy=void 0,m=l;var ne=i,me=V;try{me()}catch(Se){gn(m,ne,Se)}}}u=u.next}while(u!==h)}}catch(Se){gn(l,l.return,Se)}}function FL(n){var l=n.updateQueue;if(l!==null){var i=n.stateNode;try{M_(l,i)}catch(u){gn(n,n.return,u)}}}function $L(n,l,i){i.props=Ic(n.type,n.memoizedProps),i.state=n.memoizedState;try{i.componentWillUnmount()}catch(u){gn(n,l,u)}}function il(n,l){try{var i=n.ref;if(i!==null){switch(n.tag){case 26:case 27:case 5:var u=n.stateNode;break;case 30:var m=n.stateNode,h=Fl(n.memoizedProps,m);(m.ref===null||m.ref.name!==h)&&(m.ref=Z3(h)),u=m.ref;break;case 7:if(n.stateNode===null){var T=new Zr(n);b(n.child,!1,Xne,T,void 0,void 0),n.stateNode=T}u=n.stateNode;break;default:u=n.stateNode}typeof i=="function"?n.refCleanup=i(u):i.current=u}}catch(V){gn(n,l,V)}}function Ys(n,l){var i=n.ref,u=n.refCleanup;if(i!==null)if(typeof u=="function")try{u()}catch(m){gn(n,l,m)}finally{n.refCleanup=null,n=n.alternate,n!=null&&(n.refCleanup=null)}else if(typeof i=="function")try{i(null)}catch(m){gn(n,l,m)}else i.current=null}function Bb(n,l){if((n.tag===5||n.tag===27||n.tag===6)&&n.alternate===null&&l!==null)for(var i=0;i title"))),Xs(u,l,i),u[As]=n,bs(u),l=u;break e;case"link":if(h=m5("link","href",m).get(l+(i.href||""))){for(T=0;Tbt&&(T=bt,bt=We,We=T);var pe=n_(V,We),oe=n_(V,bt);if(pe&&oe&&(je.rangeCount!==1||je.anchorNode!==pe.node||je.anchorOffset!==pe.offset||je.focusNode!==oe.node||je.focusOffset!==oe.offset)){var be=Re.createRange();be.setStart(pe.node,pe.offset),je.removeAllRanges(),We>bt?(je.addRange(be),je.extend(oe.node,oe.offset)):(be.setEnd(oe.node,oe.offset),je.addRange(be))}}}}for(Re=[],je=V;je=je.parentNode;)je.nodeType===1&&Re.push({element:je,left:je.scrollLeft,top:je.scrollTop});for(typeof V.focus=="function"&&V.focus(),V=0;Vi?32:i,ge.T=null,i=hk,hk=null;var h=Ua,T=ml;if(Wn=0,zc=Ua=null,ml=0,(an&6)!==0)throw Error(o(331));var V=an;if(an|=4,p3(h.current),u3(h,h.current,T,i),an=V,bm(0,!1),Jt&&typeof Jt.onPostCommitFiberRoot=="function")try{Jt.onPostCommitFiberRoot(Rn,h)}catch{}return!0}finally{ee.p=m,ge.T=u,E3(n,l)}}function A3(n,l,i){l=ga(i,l),l=zN(n.stateNode,l,2),n=ei(n,l,2),n!==null&&(Ho(n,2),hl(n))}function gn(n,l,i){if(n.tag===3)A3(n,n,i);else for(;l!==null;){if(l.tag===3){A3(l,n,i);break}else if(l.tag===1){var u=l.stateNode;if(typeof l.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ii===null||!ii.has(u))){n=ga(i,n),i=kL(2),u=ei(l,i,2),u!==null&&(CL(i,u,l,n),Ho(u,2),hl(u));break}}l=l.return}}function wk(n,l,i){var u=n.pingCache;if(u===null){u=n.pingCache=new cne;var m=new Set;u.set(l,m)}else m=u.get(l),m===void 0&&(m=new Set,u.set(l,m));m.has(i)||(fk=!0,m.add(i),n=xne.bind(null,n,l,i),l.then(n,n))}function xne(n,l,i){var u=n.pingCache;u!==null&&u.delete(l),n.pingedLanes|=n.suspendedLanes&i,n.warmLanes&=~i,Dn===n&&(Lt&i)===i&&((os===4||os===3&&(Lt&62914560)===Lt&&300>Vt()-Xb)&&(an&2)===0?Ad(n,0):Yb|=i,Nd===Lt&&(Nd=0)),hl(n)}function R3(n,l){l===0&&(l=dr()),n=wc(n,l),n!==null&&(Ho(n,l),hl(n))}function bne(n){var l=n.memoizedState,i=0;l!==null&&(i=l.retryLane),R3(n,i)}function vne(n,l){var i=0;switch(n.tag){case 31:case 13:var u=n.stateNode,m=n.memoizedState;m!==null&&(i=m.retryLane);break;case 19:u=n.stateNode;break;case 22:u=n.stateNode._retryCache;break;default:throw Error(o(314))}u!==null&&u.delete(l),R3(n,i)}function yne(n,l){return ds(n,l)}var Od=null,Md=null,Sk=!1,sv=!1,Nk=!1,ui=0;function hl(n){n!==Md&&n.next===null&&(Md===null?Od=Md=n:Md=Md.next=n),sv=!0,Sk||(Sk=!0,wne())}function bm(n,l){if(!Nk&&sv){Nk=!0;do for(var i=!1,u=Od;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var h=0;else{var T=u.suspendedLanes,V=u.pingedLanes;h=(1<<31-Tt(42|n)+1)-1,h&=m&~(T&~V),h=h&201326741?h&201326741|1:h?h|2:0}h!==0&&(i=!0,I3(u,h))}else h=Lt,h=rl(u,u===Dn?h:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(h&3)===0||rn(u,h)||(i=!0,I3(u,h));u=u.next}while(i);Nk=!1}}function jne(){O3()}function O3(){sv=Sk=!1;var n=0;ui!==0&&Dne()&&(n=ui);for(var l=Vt(),i=null,u=Od;u!==null;){var m=u.next,h=M3(u,l);h===0?(u.next=null,i===null?Od=m:i.next=m,m===null&&(Md=i)):(i=u,(n!==0||(h&3)!==0)&&(sv=!0)),u=m}Wn!==0&&Wn!==5||bm(n),ui!==0&&(ui=0)}function M3(n,l){for(var i=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,h=n.pendingLanes&-62914561;0V)break;var Se=ne.transferSize,Re=ne.initiatorType;Se&&U3(Re)&&(ne=ne.responseEnd,T+=Se*(neiv){We.length=He;break}be=new Promise(Bne.bind(be)),We.push(be)}}}if(0"u"?null:document;function u5(n,l,i){var u=Id;if(u&&typeof l=="string"&&l){var m=pr(l);m='link[rel="'+n+'"][href="'+m+'"]',typeof i=="string"&&(m+='[crossorigin="'+i+'"]'),c5.has(m)||(c5.add(m),n={rel:n,crossOrigin:i,href:l},u.querySelector(m)===null&&(l=u.createElement("link"),Xs(l,"link",n),bs(l),u.head.appendChild(l)))}}function rse(n){eo.D(n),u5("dns-prefetch",n,null)}function ase(n,l){eo.C(n,l),u5("preconnect",n,l)}function lse(n,l,i){eo.L(n,l,i);var u=Id;if(u&&n&&l){var m='link[rel="preload"][as="'+pr(l)+'"]';l==="image"&&i&&i.imageSrcSet?(m+='[imagesrcset="'+pr(i.imageSrcSet)+'"]',typeof i.imageSizes=="string"&&(m+='[imagesizes="'+pr(i.imageSizes)+'"]')):m+='[href="'+pr(n)+'"]';var h=m;switch(l){case"style":h=Pd(n);break;case"script":h=_d(n)}if(!(wa.has(h)||(n=P({rel:"preload",href:l==="image"&&i&&i.imageSrcSet?void 0:n,as:l},i),wa.set(h,n),u.querySelector(m)!==null||l==="style"&&u.querySelector(Sm(h))||l==="script"&&u.querySelector(Nm(h))))){var T=u.createElement("link");Xs(T,"link",n),l==="style"&&(T[Rs]=!0,T.onload=T.onerror=function(){Ip(T)}),bs(T),u.head.appendChild(T)}}}function ose(n,l){eo.m(n,l);var i=Id;if(i&&n){var u=l&&typeof l.as=="string"?l.as:"script",m='link[rel="modulepreload"][as="'+pr(u)+'"][href="'+pr(n)+'"]',h=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":h=_d(n)}if(!wa.has(h)&&(n=P({rel:"modulepreload",href:n},l),wa.set(h,n),i.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(i.querySelector(Nm(h)))return}u=i.createElement("link"),Xs(u,"link",n),bs(u),i.head.appendChild(u)}}}function ise(n,l,i){eo.S(n,l,i);var u=Id;if(u&&n){var m=$o(u).hoistableStyles,h=Pd(n);l=l||"default";var T=m.get(h);if(!T){var V={loading:0,preload:null};if(T=u.querySelector(Sm(h)))V.loading=5;else{n=P({rel:"stylesheet",href:n,"data-precedence":l},i),(i=wa.get(h))&&qk(n,i);var ne=T=u.createElement("link");bs(ne),Xs(ne,"link",n),ne._p=new Promise(function(me,Se){ne.onload=me,ne.onerror=Se}),ne.addEventListener("load",function(){V.loading|=1}),ne.addEventListener("error",function(){V.loading|=2}),V.loading|=4,lv(T,l,u)}T={type:"stylesheet",instance:T,count:1,state:V},m.set(h,T)}}}function cse(n,l){eo.X(n,l);var i=Id;if(i&&n){var u=$o(i).hoistableScripts,m=_d(n),h=u.get(m);h||(h=i.querySelector(Nm(m)),h||(n=P({src:n,async:!0},l),(l=wa.get(m))&&Gk(n,l),h=i.createElement("script"),bs(h),Xs(h,"link",n),i.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},u.set(m,h))}}function use(n,l){eo.M(n,l);var i=Id;if(i&&n){var u=$o(i).hoistableScripts,m=_d(n),h=u.get(m);h||(h=i.querySelector(Nm(m)),h||(n=P({src:n,async:!0,type:"module"},l),(l=wa.get(m))&&Gk(n,l),h=i.createElement("script"),bs(h),Xs(h,"link",n),i.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},u.set(m,h))}}function d5(n,l,i,u){var m=(m=he.current)?wm(m):null;if(!m)throw Error(o(446));switch(n){case"meta":case"title":return null;case"style":return typeof i.precedence=="string"&&typeof i.href=="string"?(i=Pd(i.href),l=$o(m).hoistableStyles,u=l.get(i),u||(u={type:"style",instance:null,count:0,state:null},l.set(i,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(i.rel==="stylesheet"&&typeof i.href=="string"&&typeof i.precedence=="string"){n=Pd(i.href);var h=$o(m).hoistableStyles,T=h.get(n);if(T||(m=m.ownerDocument||m,T={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},h.set(n,T),(h=m.querySelector(Sm(n)))?h._p||(T.instance=h,T.state.loading=5):(h=wa.get(n),h||(h={rel:"preload",as:"style",href:i.href,crossOrigin:i.crossOrigin,integrity:i.integrity,media:i.media,hrefLang:i.hrefLang,referrerPolicy:i.referrerPolicy},wa.set(n,h)),dse(m,n,h,T.state))),l&&u===null)throw Error(o(528,""));return T}if(l&&u!==null)throw Error(o(529,""));return null;case"script":return l=i.async,i=i.src,typeof i=="string"&&l&&typeof l!="function"&&typeof l!="symbol"?(i=_d(i),l=$o(m).hoistableScripts,u=l.get(i),u||(u={type:"script",instance:null,count:0,state:null},l.set(i,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(o(444,n))}}function Pd(n){return'href="'+pr(n)+'"'}function Sm(n){return'link[rel="stylesheet"]['+n+"]"}function f5(n){return P({},n,{"data-precedence":n.precedence,precedence:null})}function dse(n,l,i,u){if(l=n.querySelector('link[rel="preload"][as="style"]['+l+"]")){if(l[Rs]!==!0){u.loading=1;return}}else l=n.createElement("link"),l[Rs]=!0,l.onload=l.onerror=Ip.bind(null,l),Xs(l,"link",i),bs(l),n.head.appendChild(l);u.preload=l,l.addEventListener("load",function(){return u.loading|=1}),l.addEventListener("error",function(){return u.loading|=2})}function _d(n){return'[src="'+pr(n)+'"]'}function Nm(n){return"script[async]"+n}function p5(n,l,i){if(l.count++,l.instance===null)switch(l.type){case"style":var u=n.querySelector('style[data-href~="'+pr(i.href)+'"]');if(u)return l.instance=u,bs(u),u;var m=P({},i,{"data-href":i.href,"data-precedence":i.precedence,href:null,precedence:null});return u=(n.ownerDocument||n).createElement("style"),bs(u),Xs(u,"style",m),lv(u,i.precedence,n),l.instance=u;case"stylesheet":m=Pd(i.href);var h=n.querySelector(Sm(m));if(h)return l.state.loading|=4,l.instance=h,bs(h),h;u=f5(i),(m=wa.get(m))&&qk(u,m),h=(n.ownerDocument||n).createElement("link"),bs(h);var T=h;return T._p=new Promise(function(V,ne){T.onload=V,T.onerror=ne}),Xs(h,"link",u),l.state.loading|=4,lv(h,i.precedence,n),l.instance=h;case"script":return h=_d(i.src),(m=n.querySelector(Nm(h)))?(l.instance=m,bs(m),m):(u=i,(m=wa.get(h))&&(u=P({},i),Gk(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),bs(m),Xs(m,"link",u),n.head.appendChild(m),l.instance=m);case"void":return null;default:throw Error(o(443,l.type))}else l.type==="stylesheet"&&(l.state.loading&4)===0&&(u=l.instance,l.state.loading|=4,lv(u,i.precedence,n));return l.instance}function lv(n,l,i){for(var u=i.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),m=u.length?u[u.length-1]:null,h=m,T=0;T title"):null)}function fse(n,l,i){if(i===1||l.itemProp!=null)return!1;switch(n){case"meta":case"title":return!0;case"style":if(typeof l.precedence!="string"||typeof l.href!="string"||l.href==="")break;return!0;case"link":if(typeof l.rel!="string"||typeof l.href!="string"||l.href===""||l.onLoad||l.onError)break;return l.rel==="stylesheet"?(n=l.disabled,typeof l.precedence=="string"&&n==null):!0;case"script":if(l.async&&typeof l.async!="function"&&typeof l.async!="symbol"&&!l.onLoad&&!l.onError&&l.src&&typeof l.src=="string")return!0}return!1}function h5(n,l){return n==="img"&&l.src!=null&&l.src!==""&&l.onLoad==null&&l.loading!=="lazy"}function g5(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function x5(n){return(n.width||100)*(n.height||100)*(typeof devicePixelRatio=="number"?devicePixelRatio:1)*.25}function b5(n,l){typeof l.decode=="function"&&(n.imgCount++,l.complete||(n.imgBytes+=x5(l),n.suspenseyImages.push(l)),n=hse.bind(n),l.decode().then(n,n))}function pse(n,l,i,u){if(i.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(i.state.loading&4)===0){if(i.instance===null){var m=Pd(u.href),h=l.querySelector(Sm(m));if(h){l=h._p,l!==null&&typeof l=="object"&&typeof l.then=="function"&&(n.count++,n=km.bind(n),l.then(n,n)),i.state.loading|=4,i.instance=h,bs(h);return}h=l.ownerDocument||l,u=f5(u),(m=wa.get(m))&&qk(u,m),h=h.createElement("link"),bs(h);var T=h;T._p=new Promise(function(V,ne){T.onload=V,T.onerror=ne}),Xs(h,"link",u),i.instance=h}n.stylesheets===null&&(n.stylesheets=new Map),n.stylesheets.set(i,l),(l=i.state.preload)&&(i.state.loading&3)===0&&(n.count++,i=km.bind(n),l.addEventListener("load",i),l.addEventListener("error",i))}}var iv=0;function mse(n,l){return n.stylesheets&&n.count===0&&uv(n,n.stylesheets),0iv?50:800)+l);return n.unsuspend=i,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function v5(n){if(n.count===0&&(n.imgCount===0||!n.waitingForImages)){if(n.stylesheets)uv(n,n.stylesheets);else if(n.unsuspend){var l=n.unsuspend;n.unsuspend=null,l()}}}function km(){this.count--,v5(this)}function hse(){this.imgCount--,v5(this)}var cv=null;function uv(n,l){n.stylesheets=null,n.unsuspend!==null&&(n.count++,cv=new Map,l.forEach(gse,n),cv=null,km.call(n))}function gse(n,l){if(!(l.state.loading&4)){var i=cv.get(n);if(i)var u=i.get(null);else{i=new Map,cv.set(n,i);for(var m=n.querySelectorAll("link[data-precedence],style[data-precedence]"),h=0;h"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),bj.exports=g8(),bj.exports}var vn=x8();const tg=[20,50,100,200],ng=[20,50,100,200,"all"],fu=50,CR="workbuddy-desktop-table-size:";function TR(e){return e==="all"?r("全部"):String(e)}function sg(e,t=ng,a=fu){t.includes(a)||(a=t.includes(fu)?fu:t[0]);let o=null;try{o=localStorage.getItem(CR+e)}catch{return a}if(o===null||o.trim()==="")return a;if(o==="all")return t.includes("all")?"all":a;const c=Number(o);return Number.isFinite(c)&&t.includes(c)?c:a}function rg(e,t){try{localStorage.setItem(CR+e,String(t))}catch{}}function ag(e,t,a={}){const o=a.sizes??ng,c=a.defaultSize??fu,[d,f]=x.useState(()=>sg(t,o,c)),[p,g]=x.useState(1),v=Math.max(1,d==="all"?1:Math.ceil(e/d)),y=Math.min(Math.max(1,p),v);x.useEffect(()=>{y!==p&&g(y)},[y,p]);const b=x.useCallback(k=>{f(k),rg(t,k),g(1)},[t]),j=x.useCallback(k=>{g(Math.min(Math.max(1,Math.round(k)||1),v))},[v]),w=d==="all"?0:(y-1)*d,S=d==="all"?e:Math.min(e,w+d),N=x.useCallback(k=>d==="all"?k.slice():k.slice(w,S),[d,w,S]);return{size:d,page:y,pageCount:v,rangeStart:e?w+1:0,rangeEnd:e?S:0,paged:d!=="all",setSize:b,goto:j,slice:N}}function Li({total:e,page:t,pageCount:a,size:o,sizes:c=ng,onSizeChange:d,onPageChange:f,range:p=null,disabled:g=!1,leading:v,className:y}){const[b,j]=x.useState(String(t));x.useEffect(()=>j(String(t)),[t]);const w=()=>{const k=b.trim();if(!k){j(String(t));return}const E=Number(k);if(!Number.isFinite(E)){j(String(t));return}const D=Math.min(Math.max(1,Math.round(E)),a);j(String(D)),D!==t&&f(D)},S=a<=1,N=e===0?r("共 0 条"):p?r("共 {total} 条 · 当前第 {start}–{end} 条",{total:e,start:p.start,end:p.end}):r("共 {total} 条(全部显示)",{total:e});return s.jsxs("div",{className:y?`panel-foot table-foot-bar ${y}`:"panel-foot table-foot-bar",children:[v,s.jsx("div",{className:"spacer"}),s.jsxs("div",{className:"table-foot-ctl",children:[s.jsx("span",{className:"table-foot-count",children:N}),s.jsxs("span",{className:"table-foot-size",children:[r("每页"),s.jsxs(ft,{value:String(o),onValueChange:k=>d(k==="all"?"all":Number(k)),children:[s.jsx(mt,{className:"h-[26px] w-[86px]",disabled:g,"aria-label":r("每页条数"),children:s.jsx(pt,{children:TR(o)})}),s.jsx(ht,{children:c.map(k=>s.jsx(qe,{value:String(k),children:TR(k)},String(k)))})]}),r("条")]}),s.jsxs("span",{className:"table-foot-jump",children:[r("跳至"),s.jsx($e,{className:"h-[26px] w-[52px] px-1 text-center",value:b,disabled:g||S,"aria-label":r("跳转到指定页"),title:S?r("当前只有一页"):r("跳转到第 1–{pageCount} 页",{pageCount:a}),inputMode:"numeric",onChange:k=>j(k.target.value),onKeyDown:k=>{k.key==="Enter"?(k.preventDefault(),w()):k.key==="Escape"&&j(String(t))},onBlur:w}),r("页")]}),s.jsx(AF,{page:t,pageCount:a,onPageChange:f,disabled:g})]})]})}const jj=[{key:"pick",label:r("选择"),align:"center",legacyAlign:"left"},{key:"order",label:r("顺序"),title:r("组内先后:按住左边的把手上下拖动即可调整;整组的先后拖分组带的把手"),align:"center",legacyAlign:"left"},{key:"account",label:r("账号"),align:"center",legacyAlign:"left"},{key:"proxy",label:r("代理"),title:r("该账号出网走的代理(Clash 出口 / 自定义 / 直连);点击可修改"),align:"center"},{key:"connections",label:r("连接数"),title:r("此刻正在使用这个账号的请求数(含还在下发内容的流式请求);为 0 时不显示"),align:"center"},{key:"status",label:r("状态"),align:"center",legacyAlign:"left"},{key:"limits",label:r("限流"),title:r("该账号当前限流中的模型;点徽章看明细"),align:"center",legacyAlign:"left"},{key:"expiry",label:r("有效期"),align:"center",legacyAlign:"left"},{key:"usage",label:r("余额"),align:"center",legacyAlign:"left"},{key:"actions",label:r("操作"),align:"right"}],ER="agent2api-accounts-col-widths",Cf={pick:47,order:84,proxy:186,connections:56,status:80,limits:148,expiry:80,usage:132,actions:200},wj=new Set(["account"]),b8=300,Sj=56,v8=new Set([...Object.keys(Cf),...wj]),pu=(()=>{try{const e=JSON.parse(localStorage.getItem(ER)||"{}"),t={};for(const[a,o]of Object.entries(e||{})){const c=Number(o);v8.has(a)&&Number.isFinite(c)&&c>=Sj&&(t[a]=Math.round(c))}return t}catch{return{}}})();function AR(){try{localStorage.setItem(ER,JSON.stringify(pu))}catch{}}function y8(){return{...Cf,...pu}}function j8(e){let t=0;for(const a of e){const o=pu[a];o?t+=o:wj.has(a)?t+=b8:Cf[a]?t+=Cf[a]:t+=Sj}return Math.round(t)}function RR(e,t){const a=e?.querySelector(`thead th:nth-child(${t+1})`),o=a?.getAttribute("data-col")||a?.className.match(/cell-([a-z]+)/)?.[1];if(!o)return null;const c=e?.querySelector(`colgroup col[data-col="${CSS.escape(o)}"]`)||e?.querySelectorAll("colgroup col")[t];return c?{key:o,col:c}:null}function w8(e,t,a){const o=Math.max(Sj,Math.round(a));e.style.width=o+"px",wj.has(t)||o!==Cf[t]?pu[t]=o:delete pu[t]}let Nj=()=>{};function S8(e,t){if(Nj=t,!e)return;let a=null;e.addEventListener("pointerdown",o=>{if(o.button!==0)return;const c=o.target?.closest?.(".col-grip");if(!c)return;o.preventDefault();const d=c.closest("th"),f=d?.closest("table")||null,p=d?.parentElement?[...d.parentElement.children].indexOf(d):-1,g=RR(f,p);if(!g)return;const v=o.clientX,y=g.col.getBoundingClientRect().width;c.classList.add("active"),document.body.classList.add("col-resizing");try{c.setPointerCapture(o.pointerId)}catch{}a={...g,startX:v,startWidth:y,grip:c,pointerId:o.pointerId},window.addEventListener("pointermove",b),window.addEventListener("pointerup",j),window.addEventListener("pointercancel",j),window.addEventListener("blur",j);function b(w){if(a){if(w.buttons===0){j();return}w8(a.col,a.key,a.startWidth+w.clientX-a.startX)}}function j(){if(!a)return;const{grip:w,pointerId:S}=a;a=null,w.classList.remove("active"),document.body.classList.remove("col-resizing");try{w.releasePointerCapture(S)}catch{}window.removeEventListener("pointermove",b),window.removeEventListener("pointerup",j),window.removeEventListener("pointercancel",j),window.removeEventListener("blur",j),AR(),Nj()}}),e.addEventListener("dblclick",o=>{const c=o.target?.closest?.(".col-grip");if(!c)return;const d=c.closest("th"),f=d?.closest("table")||null,p=d?.parentElement?[...d.parentElement.children].indexOf(d):-1,g=RR(f,p);g&&(delete pu[g.key],AR(),Nj())})}function yt(){return window}function Ws(e,t){yt().wbApp?.toast?.(e,t)}function lg(e){return e instanceof Error&&e.message?e.message:String(e??"").trim()||r("未知错误")}function kj(e){return(yt().wbApp?.getState?.()?.accounts?.accounts||[]).filter(a=>(a?.provider||"workbuddy")===e).length}function OR(e){const t=e?.name||"";if(t)return(yt().wbProviders?.customList?.()||[]).find(a=>(a.name||"")===t)}async function MR(e){const t=yt().__TAURI_INTERNALS__;if(!t||typeof t.invoke!="function")throw new Error(r("桌面运行时不可用(Tauri 未初始化)"));return t.invoke("api_request",{request:{method:"POST",path:"/api/accounts",body:e}})}function DR(e){return e?.name||e?.uid||e?.userId||""}function Cj(){yt().wbAddAccountModal?.close?.()}async function og(e,t){Cj(),await yt().wbApp?.refresh?.(),Ws(r("✅ {label}账号已添加{name}",{label:t,name:e?`:${e}`:""}))}const mu=new Map;function Za(e){return{defaultValue:mu.get(e)??"",onChange:t=>{const a=t.currentTarget.value;a?mu.set(e,a):mu.delete(e)}}}function So(e,t){t?mu.set(e,t):mu.delete(e);const a=document.getElementById(e);(a instanceof HTMLInputElement||a instanceof HTMLTextAreaElement)&&(a.value=t)}function Mr(e){const t=document.getElementById(e);return t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?t.value.trim():(mu.get(e)??"").trim()}function Tj(e){for(const t of e)So(t,"")}const zi={edition:"cn",loginMode:"embedded",socialRestore:!1},N8=100,k8=256,C8=e=>e.key==="name"?N8:k8,T8={provider:"raccoon",label:"小浣熊",addButton:r("添加小浣熊账号"),webLogin:{noteHtml:r("在内嵌窗口里完成官方登录,成功后自动加入账号列表。"),button:r("打开网页登录"),hint:r("内嵌窗口打开;完成后自动加入列表,关窗即取消等待"),busyText:r("等待小浣熊登录完成…")},manualTitle:r("粘贴 token / refreshToken"),manualNoteHtml:r('refreshToken 可选,填了到期可自动续期;两者都能从小浣熊客户端登录态文件里取到。'),fields:[{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用凭证里的账号名")},{key:"token",label:"token",rows:3,placeholder:r("粘贴 access_token(一长串 JWT)")},{key:"refreshToken",inputKey:"refresh",label:"refreshToken",rows:2,optional:!0,placeholder:r("可选")}],desktopNote:r("读本机客户端当前登录态,每次实时读取(删掉这条记录不影响客户端登录态)。客户端重新登录后点「刷新 Token」同步。")},E8={provider:"catpaw",label:"CatPaw",webLogin:{noteHtml:r("用 CatPaw 账号完成登录(美团 passport),成功后自动加入账号列表。"),button:r("打开 CatPaw 网页登录"),busyText:r("等待 CatPaw 登录完成…"),modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("内嵌窗口打开;完成后自动加入列表,关窗即取消等待")},{value:"external",label:r("系统浏览器"),hint:r("系统浏览器打开(复用已登录的美团账号);完成后自动加入列表")}]},manualNote:r("token 是登录态 Cookie;CatPaw 没有刷新机制,过期后需在客户端重新登录。"),fields:[{key:"token",label:"token",rows:3,placeholder:r("CatPaw 的 X-Passport-Token(登录态 Cookie)")},{key:"uid",label:"uid",placeholder:r("必填,CatPaw 账号标识")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用登录名或 uid")}],desktopNote:r("读本机客户端当前登录态,每次实时读取(删掉这条记录不影响客户端登录态)。客户端重新登录后重新导入即可。"),desktopHint:r("读取 ~/.meituan-catpaw/auth.json,需已在 CatPaw 客户端登录")},A8={provider:"autoclaw",label:r("AutoClaw 国内版"),manualNote:r("token 支持 enc: 前缀(Windows 上自动解密)。未填 refreshToken 无法自动续期。"),smsLogin:{noteHtml:r("用绑定的手机号登录:点「获取验证码」后填入即可。这是国内版官方唯一的登录方式。")},fields:[{key:"token",label:"token",rows:3,placeholder:r("明文 JWT 或 auth.json 里的 enc: 加密值(自动解密)")},{key:"refreshToken",label:"refreshToken",rows:2,optional:!0,placeholder:r("没有则无法自动续期")},{key:"deviceId",label:"deviceId",optional:!0,placeholder:r("可选,续期时带上")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用 userId")}],desktopNote:r("读本机客户端当前登录态,每次实时读取(删掉这条记录不影响客户端登录态)。"),desktopHint:r("读取 %APPDATA%/AutoClaw/auth.json 并解密,仅 Windows"),desktopWindowsOnly:!0},R8={provider:"autoclaw-intl",label:r("AutoClaw 国际版"),manualNote:r("国际版与国内版账号体系独立,请填国际版的凭证。未填 refreshToken 无法自动续期。"),oauthLogin:{title:r("网页登录(Zai / Google)"),noteHtml:r("点按钮后先过一次滑块验证(官方风控),随后打开登录页,登录完成即自动添加账号。
这是国际版官方唯一的登录方式;已在客户端登录过的,用「导入桌面端登录态」更快。"),modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("内嵌窗口打开;关窗即取消等待(Google 账号被拒时改用系统浏览器)")},{value:"external",label:r("系统浏览器"),hint:r("系统浏览器打开(复用已登录的 Zai / Google 账号);完成后自动加入列表")}]},fields:[{key:"token",label:"token",rows:3,placeholder:r("明文 JWT(国际版账号的 access token)")},{key:"refreshToken",label:"refreshToken",rows:2,optional:!0,placeholder:r("没有则无法自动续期")},{key:"deviceId",label:"deviceId",optional:!0,placeholder:r("可选,续期时带上")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用 userId")}],desktopNote:r("读本机客户端当前登录态,每次实时读取(删掉这条记录不影响客户端登录态)。用 Zai / Google 登录客户端的用户走这一条。"),desktopHint:r("读取 %APPDATA%/AutoClaw/auth.json 并解密,仅 Windows"),desktopWindowsOnly:!0};function IR(e){const{provider:t,label:a,siteNote:o}=e;return{provider:t,label:a,desktop:!1,webLogin:{noteHtml:r("打开官方授权页完成设备码授权,登录的是{label}({site})的账号。",{label:a,site:o}),button:r("打开 Qoder 网页登录"),busyText:r("等待 Qoder 授权完成…"),edition:t==="qoder"?"cn":"global",modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("内嵌窗口用全新环境,多账号互不影响;关窗即取消等待")},{value:"external",label:r("系统浏览器"),hint:r("系统浏览器打开(复用已登录账号);完成后自动加入列表")}]},manualTitle:r("使用个人访问令牌(PAT)"),manualNote:r("在{label}的 Qoder 账号设置 → Integrations 生成 PAT(别填 Google / GitHub 的令牌)。两个地区的账号与凭证不通用。",{label:a}),fields:[{key:"pat",label:"Qoder PAT",rows:3,placeholder:r("粘贴 Qoder 个人访问令牌(pt-…)")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空使用账号昵称或邮箱")}]}}const O8=IR({provider:"qoder",label:r("中国版"),siteNote:"qoder.com.cn"}),M8=IR({provider:"qoder-intl",label:r("国际版"),siteNote:"qoder.com"});function PR(e){const{provider:t,label:a,poolNote:o}=e;return{provider:t,label:a,desktop:!0,webLogin:{noteHtml:r("打开授权页完成确认,账号自动加入 {label}{note}",{label:a,note:o}),button:r("打开 Cline 授权页"),busyText:r("等待 Cline 授权确认…"),modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("内嵌窗口打开;完成后自动加入列表,关窗即取消等待")},{value:"external",label:r("系统浏览器"),hint:r("系统浏览器打开(复用已登录的 Cline 账号);完成后自动加入列表")}]},manualTitle:r("填写凭证"),manualNote:r("refreshToken 可选,填了可自动续期;两者都能从客户端登录态文件取到。同一个 Cline 账号两个池都能用,这里归入 {label}。",{label:a}),fields:[{key:"accessToken",label:"accessToken",rows:3,placeholder:r("粘贴 workos:… 开头的令牌(不带前缀也会自动补上)")},{key:"refreshToken",label:"refreshToken",rows:2,optional:!0,placeholder:r("可选,没有则无法自动续期")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空使用账号姓名、邮箱或令牌指纹")}],desktopNote:r("读本机客户端当前登录态,每次实时读取(删掉这条记录不影响客户端登录态)。这一条归入 {label}。",{label:a}),desktopHint:r("读取 ~/.cline/data/settings/providers.json,需已在 Cline 客户端登录")}}function _R(e){const{provider:t,label:a,site:o,siteNote:c}=e;return{provider:t,label:a,webLogin:{noteHtml:r("打开 Accio {label}的官方登录页({site})并用你的 Accio 账号登录:登录成功后官方页面会跳回本机;同机自动完成,Docker / 远程面板按提示粘贴回调地址即可(授权码只在本机传给网关,界面不显示明文 token)。",{label:a,site:o}),button:r("打开 Accio {label}登录页",{label:a}),busyText:r("等待 Accio {label}登录完成…",{label:a}),modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("将打开内嵌窗口;登录完成后自动加入账号列表。关掉窗口即取消等待")},{value:"external",label:r("系统浏览器"),hint:r("将用系统默认浏览器打开登录页(会复用浏览器里已登录的 Accio 账号);完成登录后自动加入账号列表,关掉弹窗即取消等待")}]},manualTitle:r("填写凭证"),manualNoteHtml:r("accessToken 是 Accio 的登录凭证(一长串不透明 token,不是 JWT);refreshToken 可选,填了之后到期能自动续期。请填写 {label}账号的凭证 —— {siteNote}(最容易拿到的办法:直接用上方的「网页登录」,不需要手工找 token。)",{label:a,siteNote:c}),fields:[{key:"accessToken",label:"accessToken",rows:3,placeholder:r("粘贴 Accio 的 accessToken")},{key:"refreshToken",label:"refreshToken",rows:2,optional:!0,placeholder:r("可选,没有则无法自动续期")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空使用账号昵称或邮箱")}]}}function LR(e){const{provider:t,label:a,site:o,planNote:c}=e;return{provider:t,label:a,desktop:!1,webLogin:{noteHtml:r("打开 ZCode {label}的官方授权页并用你的账号登录。授权结果由 ZCode 服务端记录,网关在后台自动取回凭证并加入账号列表。",{label:a}),button:r("打开 ZCode {label}授权页",{label:a}),busyText:r("等待 ZCode {label}授权完成…",{label:a}),modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("将打开内嵌窗口;授权完成后自动加入账号列表。关掉窗口即取消等待。授权页最后可能提示无法打开 zcode:// 链接,这是正常的 —— 结果已由服务端记下")},{value:"external",label:r("系统浏览器"),hint:r("将用系统默认浏览器打开授权页(会复用浏览器里已登录的 ZCode 账号);授权完成后自动加入账号列表。页面最后可能提示无法打开 zcode:// 链接,属正常现象")}]},manualTitle:r("填写凭证"),manualNoteHtml:r("本家有两个**互不替代**的凭证,按你要用的功能填,至少填一个:编码套餐 API Key 用于转发推理(打 {site})与查询窗口限额(每 N 小时 / 每周的剩余比例);jwt 用于领取套餐与查询余额(打 zcode.z.ai 的 billing 网关,官方叫 Coding Plan JWT,是一串三段点分的字符串)。余额两把都能查、但读到的东西不同:jwt 读到余额桶与套餐到期,API Key 读到窗口限额;而领取只认 jwt、转发只认 API Key。请填写 {label}账号的凭证 —— {plan}(最容易拿到的办法:直接用上方的「网页登录」—— 它会替你把这个 API Key 换好,两个凭证一起拿到。)",{site:o,label:a,plan:c}),fields:[{key:"accessToken",label:r("编码套餐 API Key"),rows:3,optional:!0,placeholder:r("用于转发;形如 apiKey.secret 两段点分(不填则这个账号不能转发)")},{key:"jwt",label:"Coding Plan JWT",inputKey:"jwt",rows:3,optional:!0,placeholder:r("用于领取套餐与查询余额;不填则这个账号不能领取与查余额")},{key:"userId",label:r("用户 ID"),optional:!0,placeholder:r("可选;用于生成账号 id 与展示名")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空自动生成")}]}}const D8={provider:"codearts",label:"CodeArts",desktop:!1,webLogin:{noteHtml:r("打开华为云 CodeArts 的官方授权页登录:登录完成后官方页面会把浏览器带回网关自己的 /oauth/callback,网关用一次性授权码换取临时凭据并加入账号列表。
网关跑在另一台机器上时,网页端会提示把地址栏中的最终回调地址直接粘贴回面板。"),button:r("打开 CodeArts 授权页"),busyText:r("等待 CodeArts 登录完成…"),modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("将打开内嵌窗口;登录完成后自动加入账号列表。关掉窗口即取消等待")},{value:"external",label:r("系统浏览器"),hint:r("将用系统默认浏览器打开授权页(会复用浏览器里已登录的华为云账号);浏览器与网关不在同一台机器时,按上方说明把最终回调地址粘贴回面板")}]},manualTitle:r("粘贴登录凭据"),manualNoteHtml:r('整份粘贴官方插件 / CLIProxyAPI 落盘的凭据 JSON(形如 {"codearts_provider_credential":{…}},铺平的也行)。
必填:access_key_id、secret_access_key、security_token。要能自动续期,必须连 refresh_token 与 oauth_context 一起粘 —— 临时凭据约一小时到期,缺这半块就续不回来,只能重新登录。'),fields:[{key:"credentialJson",label:r("凭据 JSON"),rows:8,jsonExpand:!0,placeholder:'{"codearts_provider_credential":{"access_key_id":"HSTA…","secret_access_key":"…","security_token":"…","expires_at":"2026-09-27T16:17:00.327Z","domain_id":"…","user_id":"…","user_name":"…","refresh_token":"eyJ…","oauth_context":{…}}}'},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空使用凭据里的 user_name")}]},I8={provider:"trae",label:"Trae",desktop:!1,webLogin:{noteHtml:r("打开 Trae SOLO 的官方授权页(trae.cn)并用你的 Trae 账号登录:授权完成后官方页面会跳回本机的一个临时端口;同机部署自动接收,Docker / 远程面板请按提示复制地址栏回调地址。"),button:r("打开 Trae 授权页"),busyText:r("等待 Trae 授权完成…"),modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("将打开内嵌窗口;授权完成后自动加入账号列表。远程面板可粘贴回调地址。关掉窗口即取消等待。链接 5 分钟内有效,超时或未点就会作废(可重新发起)")},{value:"external",label:r("系统浏览器"),hint:r("将用系统默认浏览器打开授权页(会复用浏览器里已登录的 Trae 账号);同机完成后自动加入,Docker / 远程面板按提示粘贴地址栏回调地址。")}]},manualTitle:r("填写凭证"),manualNoteHtml:r("accessToken 是 Trae 的 Cloud-IDE-JWT(三段点分),refreshToken 用于到期自动续期(本家 refreshToken 一次一换:换发一次旧的即作废,所以两份程序别同时刷同一个账号)。
手工粘贴时请连 machineId / deviceId 一起填:上游把它们与登录时上传的设备公钥绑在一起判设备,凭空换一对会撞 2xxxx 那族设备绑定拒绝。
没有这三样时的正路是用上方的「网页登录」;容器 / 远程部署形态按提示粘贴地址栏回调地址即可。"),fields:[{key:"accessToken",label:"accessToken",rows:3,placeholder:r("Cloud-IDE-JWT(三段点分)")},{key:"refreshToken",label:"refreshToken",rows:2,optional:!0,placeholder:r("可选;填了才能到期自动续期")},{key:"uid",label:r("用户 ID"),optional:!0,placeholder:r("可选;用于去重与展示名(留空时网关会问一次上游)")},{key:"machineId",label:"machineId",optional:!0,placeholder:r("可选;UUID 形态,与凭据同生共死")},{key:"deviceId",label:"deviceId",optional:!0,placeholder:r("可选;纯数字串(上游只收 8–24 位数字)")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空自动用昵称")}]},P8={provider:"loomy",label:"Loomy",smsLogin:{noteHtml:r("用 Loomy 账号绑定的手机号登录:点「获取验证码」后填入即可。这是本家最省事的入口。")},manualNote:r("粘贴的是登录 session(同时是模型网关的 token)。Loomy 没有续期接口,session 有效期约 14 天,过期后重新登录即可。"),fields:[{key:"session",label:"session",rows:3,placeholder:r("登录 session(一长串)")},{key:"userId",label:"userId",optional:!0,placeholder:r("可选,讯飞侧 userid")},{key:"phone",label:r("手机号"),optional:!0,placeholder:r("可选,展示用")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用脱敏手机号或 userId")}],desktop:!1},_8={provider:"kuku",label:"KukuAI",webLogin:{noteHtml:r("在打开的窗口里用百度账号登录 KukuAI 主站(手机验证码 / 扫码均可),登录成功后自动加入账号列表。网关会向百度换发 KukuAI 业务会话令牌(依赖本机已安装库库AI 客户端)。"),button:r("打开网页登录"),busyText:r("等待 KukuAI 登录完成…")},manualTitle:r("粘贴 Cookie"),manualNote:r("BDUSS 必填;请粘贴**完整 Cookie**(Cookie 编辑器一键导出即可)—— 其中 **PTOKEN 必须保留**,网关要用它向百度换发 KukuAI 业务会话令牌,缺了它模型刷新会报「未登录」。支持整段 Cookie 头、Cookie 编辑器导出的 JSON 数组,或 {BDUSS, STOKEN} 对象。KukuAI 没有刷新机制,登录态过期后重新粘贴即可。"),fields:[{key:"cookie",label:"Cookie",rows:3,placeholder:r("BDUSS=…; STOKEN=…(或 Cookie 编辑器导出的 JSON)")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用账号 uk")}],desktop:!0,desktopHint:r("读取本机 KukuAI 客户端登录态(%APPDATA%\\baidugenflowpro\\Network\\Cookies),需已在 KukuAI 客户端登录"),desktopNote:r("读本机客户端当前登录态(明文 Cookie,无需解密)。客户端运行时 Cookies 文件被独占占用,导入前请先关闭 KukuAI 客户端。")};function zR(e){const{provider:t,label:a,siteNote:o}=e;return{provider:t,label:a,desktop:!1,manualTitle:r("粘贴 session cookie"),manualNoteHtml:r("粘贴网页登录态 cookie monkeycode_ai_session 的值(在浏览器里复制整段 Cookie 直接粘贴也行,网关会自己剥出值)。
{siteNote}
MonkeyCode 没有续期接口:session 有效期约 30 天(硬限制),过期后重新登录网页、再粘贴一次即可。",{siteNote:o}),fields:[{key:"session",label:"session",rows:3,placeholder:r("monkeycode_ai_session 的值(也可直接粘贴整段 Cookie)")},{key:"imageId",label:r("任务镜像 id"),optional:!0,placeholder:r("可选:发起对话必需,留空则由网关从该账号已有任务里自动发现,发现不到时之后手动补")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用上游返回的账号名或账号 id")}]}}const L8=zR({provider:"monkeycode",label:r("MonkeyCode"),siteNote:r("这里填国内站(monkeycode-ai.com)的账号:请粘贴国内站的 session。国际站(monkeycode-ai.net)是另一家 provider、另一套账号,两边的凭证不通用。")}),z8=zR({provider:"monkeycode-intl",label:r("MonkeyCode 国际版"),siteNote:r("这里填国际站(monkeycode-ai.net)的账号:请粘贴国际站的 session。国内站(monkeycode-ai.com)是另一家 provider、另一套账号,两边的凭证不通用。")}),B8={provider:"commandcode",label:r("Command Code"),desktop:!1,manualTitle:r("粘贴 API Key"),manualNote:r("粘贴 Command Code 的 API Key(user_ 开头;从官方 CLI 的 ~/.commandcode/auth.json 或网页 studio 获取)。整行 / 带引号 / 带 Bearer 前缀地粘都行,网关会自己剥成裸 key。key 不过期、也没有续期接口,失效后重新获取即可;添加时网关会做一次轻量探活,失败不影响添加。"),fields:[{key:"apiKey",label:"apiKey",rows:3,placeholder:r("user_ 开头的 API Key(也可直接粘贴 Authorization: Bearer … 整行)")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用 key 尾号")}]},H8={provider:"antigravity",label:r("Antigravity"),desktop:!1,webLogin:{noteHtml:r("在打开的窗口里登录 Google 账号(Antigravity 的授权页),授权完成后自动加入账号列表。"),button:r("打开 Antigravity 网页登录"),busyText:r("等待 Google 授权完成…"),modes:[{value:"embedded",label:r("内嵌窗口(推荐)"),hint:r("内嵌窗口打开;完成后自动加入列表,关窗即取消等待")},{value:"external",label:r("系统浏览器"),hint:r("系统浏览器打开(复用已登录的 Google 账号);完成后自动加入列表")}]},manualTitle:r("粘贴 Google refresh token"),manualNoteHtml:r("粘贴 Antigravity 的 Google refresh token(以 1// 开头;直接粘贴含 refresh_token= 的整行也行)。
这是网页登录之外的手工入口(例如从已登录的官方 IDE 里导出)。refresh token 不会过期,access token 到期由网关自动续期;令牌丢了只能重新走 Google 授权,请妥善保存。"),fields:[{key:"refreshToken",label:"refreshToken",rows:2,placeholder:r("1// 开头的 Google refresh token(也可直接粘贴 refresh_token=… 整行)")},{key:"projectId",label:"projectId",optional:!0,placeholder:r("可选(cloudaicompanionProject):留空由网关自动发现")},{key:"email",label:"email",optional:!0,placeholder:r("可选:账号邮箱,用于展示与身份识别(换新令牌也能认回同一账号)")},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空则用邮箱或令牌尾号")}]},U8={provider:"officeace",label:r("OfficeAce 果办"),desktop:!1,webLogin:{noteHtml:r("打开华为云授权页登录:登录完成后网关会自动轮询云端取回授权码并加入账号列表(不需要装 OfficeAce 桌面端,也无需手工回填回调地址)。"),button:r("打开授权页"),busyText:r("等待 OfficeAce 登录完成…")},manualTitle:r("粘贴网关凭据"),manualNoteHtml:r("从别的机器(或 OfficeAce 桌面端 models.json)取三项贴进来:模型网关基址(baseUrl,形如 https://modelgw-…/v2)与 modelAppKey / modelAppSecret。这三项就能转发(网关凭据不过期);控制面临时凭据(accessKeyId 等)可选,留空则额度/自动续期不可用,但不影响转发。"),fields:[{key:"baseUrl",label:r("模型网关基址"),placeholder:"https://modelgw-…huaweicloud-agentarts.com/v2"},{key:"modelAppKey",label:r("网关 Key"),placeholder:"model_app_key"},{key:"modelAppSecret",label:r("网关 Secret"),placeholder:"model_app_secret"},{key:"name",label:r("备注名"),optional:!0,placeholder:r("可选,留空用「OfficeAce 果办」")}]},BR=[T8,E8,A8,R8,O8,M8,PR({provider:"cline-free",label:"Cline Free",poolNote:r("(免费额度池,模型名带 cline-free/ 前缀)。")}),PR({provider:"cline-pass",label:"Cline Pass",poolNote:r("(订阅池,模型名带 cline-pass/ 前缀,需要账号有对应订阅)。")}),_R({provider:"accio",label:r("国际版"),site:"www.accio.com",siteNote:r("国际版与国内版是**两套独立的账号**(同一账号体系的两个站点),凭证不通用。")}),_R({provider:"accio-cn",label:r("国内版"),site:"www.accio-ai.com",siteNote:r("国内版的登录站点是 www.accio-ai.com,与国际版不是同一站。")}),LR({provider:"zcode",label:r("国内版"),site:"open.bigmodel.cn",planNote:r("国内版与**国际版是两套独立的账号与套餐**,凭证与领取的套餐都不通用。")}),LR({provider:"zcode-intl",label:r("国际版"),site:"api.z.ai",planNote:r("国际版的推理站点是 api.z.ai,与国内版不是同一站;套餐也各自独立。")}),D8,I8,P8,_8,L8,z8,B8,H8,U8],Bi="workbuddy",hu="custom",Ej="WorkBuddy";function V8(e){return BR.find(t=>t.provider===e)}const HR=[{id:"oauth",label:r("网页登录(Zai / Google)")},{id:"sms",label:r("手机验证码登录")},{id:"web",label:r("网页登录")},{id:"manual",label:r("填写凭证")},{id:"desktop",label:r("导入桌面端登录态")}],UR=()=>yt().workbuddyDesktop?.platform||"";function VR(e){return!(e.desktop===!1||UR()==="web"||e.desktopWindowsOnly&&UR()==="macos")}function FR(e,t){return HR.filter(a=>a.id==="oauth"?!!e.oauthLogin:a.id==="sms"?!!e.smsLogin:a.id==="web"?!!e.webLogin&&(!e.webLogin?.region||t===e.webLogin.region):a.id==="desktop"?VR(e):!0).map(a=>a.id)}const F8=e=>e.manualTitle||r("填写凭证添加"),$8=e=>e.manualNoteHtml?{html:e.manualNoteHtml}:{text:e.manualNote||""},q8=e=>e.addButton||r("添加 {name} 账号",{name:e.label}),Aj=(e,t)=>`${e.provider}-${t.inputKey||t.key}-input`,Tf="max-w-full flex-wrap [&_[data-slot=segmented-item]]:h-7 [&_[data-slot=segmented-item]]:px-3 [&_[data-slot=segmented-item]]:text-[12.5px]",G8=r("登录态文件路径:~/.box-agent/config/auth.json(Windows:C:\\Users\\<你的用户名>\\.box-agent\\config\\auth.json)");let Rj=!1;async function $R(e,t){if(!Rj){Rj=!0,e(!0);try{await t()}finally{Rj=!1,e(!1)}}}function ig({html:e,text:t}){return e?s.jsx("p",{dangerouslySetInnerHTML:{__html:e}}):s.jsx("p",{children:t||""})}function K8(e,t,a){let o;try{o=JSON.parse(t)}catch(c){return Ws(r("{name} 不是合法 JSON:{reason}",{name:e.label,reason:lg(c)}),"err"),!1}return!o||typeof o!="object"||Array.isArray(o)?(Ws(r("{name}要粘一个 JSON 对象(形如 {sample})",{name:e.label,sample:'{"codearts_provider_credential":{…}}'}),"err"),!1):(Object.assign(a,o),!0)}function Y8({config:e,region:t,visible:a}){const o=e.provider,[c,d]=x.useState(!1),[f,p]=x.useState(""),g=$8(e),v=e.fields.map(b=>Aj(e,b));async function y(){const b={provider:e.provider};e.regionOptions?.length&&(b.mode=t);for(const j of e.fields){const w=Mr(Aj(e,j));if(!j.optional&&!w){Ws(r("请填写 {label}",{label:j.label}),"err");return}if(w){if(j.jsonExpand){if(!K8(j,w,b))return;continue}b[j.key]=w}}await $R(d,async()=>{try{const j=await MR(b);Tj(v),p(""),await og(DR(j?.account),e.label)}catch(j){Ws(r("添加失败:{reason}",{reason:lg(j)}),"err")}})}return s.jsxs(Vn,{hidden:!a,onClick:b=>{b.target.closest("[data-raccoon-hint]")&&(b.preventDefault(),p(G8))},children:[s.jsx("h3",{children:F8(e)}),s.jsx(ig,{...g}),e.fields.map(b=>{const j=Aj(e,b),w=b.optional?"":r("(必填)");return s.jsxs("div",{className:`field-row${b.rows?" stack":""}`,children:[s.jsxs("label",{htmlFor:j,children:[b.label,w]}),b.rows?s.jsx(Zc,{id:j,rows:b.rows,placeholder:b.placeholder,...Za(j)}):s.jsx($e,{id:j,type:"text",maxLength:C8(b),placeholder:b.placeholder,...Za(j)})]},j)}),s.jsxs("div",{className:"field-row",children:[s.jsx(se,{id:`${o}-add-button`,onClick:()=>{y()},disabled:c,children:c?r("添加中…"):q8(e)}),s.jsx("span",{className:"detail",id:`${o}-add-hint`,children:f})]})]})}function X8({config:e,visible:t}){const a=e.provider,[o,c]=x.useState(!1);if(!VR(e)||!e.desktopNote)return null;async function d(){await $R(c,async()=>{try{const f=await MR({provider:e.provider,importDesktop:!0});await og(f?.account?.name||"",e.label)}catch(f){Ws(r("导入失败:{reason}",{reason:lg(f)}),"err")}})}return s.jsxs(Vn,{hidden:!t,children:[s.jsx("h3",{children:r("从本机导入桌面端登录态")}),s.jsx("p",{children:e.desktopNote}),s.jsx("div",{className:"field-row",children:s.jsx(se,{id:`${a}-desktop-button`,title:e.desktopHint,onClick:()=>{d()},disabled:o,children:r(o?"导入中…":"从本机导入桌面端登录态")})})]})}function Q8({config:e,mode:t,onModeChange:a,region:o,visible:c}){const d=e.webLogin,f=e.provider,p=x.useRef(t),g=x.useRef(o),v=x.useRef(null);return p.current=t,g.current=o,x.useEffect(()=>{const y=yt().wbWebLogin;if(!y||!d)return;const b=d.modes;v.current=y.create({provider:f,buttonId:`${f}-web-button`,cancelId:`${f}-web-cancel`,hintId:`${f}-web-hint`,busyText:d.busyText,texts:()=>{const j=b?.find(w=>w.value===p.current);return{button:d.button,hint:j?.hint||d.hint||""}},start:()=>yt().workbuddyDesktop?.startLogin(d.edition||g.current||"cn",p.current||"embedded",f),onSuccess:async j=>{Cj(),await yt().wbApp?.refresh?.();const w=j?.payload?.warning;w?Ws(r("账号已添加,但请留意:{warning}",{warning:w}),"err"):Ws(r("✅ {label}账号已添加",{label:e.label}))}})??null},[]),x.useEffect(()=>{v.current?.syncTexts()},[t]),d?s.jsxs(Vn,{hidden:!c,children:[s.jsx("h3",{children:r("网页登录")}),s.jsx(ig,{html:d.noteHtml}),d.modes?.length?s.jsxs("div",{className:"flex flex-col gap-2.5 border-l-2 border-border pl-[11px]",children:[s.jsx("span",{className:"text-[12.5px] text-subtle",children:r("打开方式")}),s.jsx(In,{"aria-label":r("{label} 网页登录的打开方式",{label:e.label}),options:d.modes,value:t,onValueChange:a})]}):null,s.jsxs("div",{className:"field-row",children:[s.jsx(se,{id:`${f}-web-button`,onClick:()=>v.current?.start(),children:d.button}),s.jsx(se,{id:`${f}-web-cancel`,variant:"outline",hidden:!0,onClick:()=>v.current?.cancel(),children:r("取消等待")}),s.jsx("span",{className:"detail",id:`${f}-web-hint`,children:d.hint||d.modes?.[0]?.hint||""})]})]}):null}function Z8({config:e,visible:t}){const a=e.smsLogin,o=e.provider;return x.useEffect(()=>{a&&yt().wbSmsLogin?.create({provider:o,onSuccess:c=>og(DR(c?.account),e.label)})},[]),a?s.jsxs(Vn,{hidden:!t,children:[s.jsx("h3",{children:r("手机验证码登录")}),s.jsx(ig,{html:a.noteHtml,text:r("用 AutoClaw 账号绑定的手机号登录:点击「获取验证码」,收到短信后填入下方并登录。验证码由本机直接提交给官方接口,界面不显示 token。")}),s.jsxs("div",{className:"sms-form",children:[s.jsxs("div",{className:"sms-field",children:[s.jsxs("label",{className:"lb",htmlFor:`${o}-sms-phone`,children:[r("手机号"),s.jsx("i",{className:"req",children:"*"})]}),s.jsxs(Ci,{children:[s.jsx(Ei,{id:`${o}-sms-phone`,type:"text",maxLength:11,placeholder:r("11 位大陆手机号"),...Za(`${o}-sms-phone`)}),s.jsx(Ti,{align:"inline-end",children:s.jsx(pB,{id:`${o}-sms-send`,className:"text-primary-fg",children:r("获取验证码")})})]})]}),s.jsxs("div",{className:"sms-field",children:[s.jsxs("label",{className:"lb",htmlFor:`${o}-sms-code`,children:[r("验证码"),s.jsx("i",{className:"req",children:"*"})]}),s.jsxs("div",{className:"sms-pair",children:[s.jsx($e,{id:`${o}-sms-code`,className:"sms-code",type:"text",maxLength:6,placeholder:r("6 位数字")}),s.jsx("label",{className:"lb-inline",htmlFor:`${o}-sms-name`,children:r("备注名")}),s.jsx($e,{id:`${o}-sms-name`,className:"sms-name",type:"text",placeholder:r("可选,留空则用脱敏手机号"),...Za(`${o}-sms-name`)})]})]}),s.jsxs("div",{className:"sms-foot",children:[s.jsx(se,{id:`${o}-sms-submit`,children:r("登录并添加")}),s.jsx("span",{className:"detail sms-hint",id:`${o}-sms-hint`})]})]})]}):null}function W8({config:e,mode:t,onModeChange:a,visible:o}){const c=e.oauthLogin,d=e.provider,f=x.useRef(t),p=x.useRef(null);f.current=t;const g=()=>c?.modes?.find(v=>v.value===f.current)?.hint||c?.hint||"";return x.useEffect(()=>{const v=yt().wbAutoclawOauth;!v||!c||(p.current=v.create({provider:d,mode:()=>f.current||"embedded",hint:g,cancelId:`${d}-oauth-cancel`,onSuccess:()=>og("",e.label)})??null)},[]),x.useEffect(()=>{p.current?.syncTexts()},[t]),c?s.jsxs(Vn,{hidden:!o,children:[s.jsx("h3",{children:c.title||r("网页登录")}),s.jsx(ig,{html:c.noteHtml}),c.modes?.length?s.jsxs("div",{className:"flex flex-col gap-2.5 border-l-2 border-border pl-[11px]",children:[s.jsx("span",{className:"text-[12.5px] text-subtle",children:r("打开方式")}),s.jsx(In,{"aria-label":r("{label} 网页登录的打开方式",{label:e.label}),options:c.modes,value:t,onValueChange:a})]}):null,s.jsxs("div",{className:"field-row",children:[s.jsx(se,{id:`${d}-oauth-zai`,children:r("使用 Zai 账号登录")}),s.jsx(se,{id:`${d}-oauth-google`,variant:"outline",children:r("使用 Google 账号登录")}),s.jsx(se,{id:`${d}-oauth-cancel`,variant:"outline",hidden:!0,children:r("取消")})]}),s.jsx("div",{className:"field-row",children:s.jsx("span",{className:"detail",id:`${d}-oauth-hint`,children:c.modes?.[0]?.hint||c.hint||""})})]}):null}function J8({config:e,active:t}){const a=e.regionOptions?.[0]?.value??"",[o,c]=x.useState(a),[d,f]=x.useState(()=>FR(e,a)[0]),[p,g]=x.useState(e.webLogin?.modes?.[0]?.value??""),[v,y]=x.useState(e.oauthLogin?.modes?.[0]?.value??""),b=FR(e,o),j=b.includes(d)?d:b[0],w=x.useMemo(()=>HR.filter(S=>b.includes(S.id)).map(S=>({value:S.id,label:S.label})),[b.join(",")]);return s.jsxs("div",{className:"add-provider-block",hidden:!t,children:[e.regionOptions?.length?s.jsxs(Vn,{children:[s.jsx("h3",{children:r("地区")}),s.jsx(In,{"aria-label":r("{label} 账号地区",{label:e.label}),className:Tf,options:e.regionOptions,value:o,onValueChange:c})]}):null,s.jsxs(Vn,{children:[s.jsx("h3",{children:r("添加方式")}),s.jsx(In,{"aria-label":r("{label} 账号的添加方式",{label:e.label}),className:Tf,options:w,value:j,onValueChange:S=>f(S)})]}),s.jsx(W8,{config:e,mode:v,onModeChange:y,visible:j==="oauth"}),s.jsx(Z8,{config:e,visible:j==="sms"}),s.jsx(Q8,{config:e,mode:p,onModeChange:g,region:o,visible:j==="web"}),s.jsx(Y8,{config:e,region:o,visible:j==="manual"}),s.jsx(X8,{config:e,visible:j==="desktop"})]})}function qR(e){return e==="intl"?"workbuddy-intl":"workbuddy"}function eq({active:e}){const[t,a]=x.useState(zi.edition),[o,c]=x.useState(zi.loginMode),[d,f]=x.useState(zi.socialRestore),p=x.useRef(t),g=x.useRef(o),v=x.useRef(d),y=x.useRef(null);p.current=t,g.current=o,v.current=d,x.useEffect(()=>{const E=yt().wbWebLogin;E&&(y.current=E.create({get provider(){return qR(p.current)},buttonId:"web-login-button",cancelId:"web-login-cancel",hintId:"web-login-hint",busyText:r("等待网页登录…"),texts:()=>{const D=g.current==="external";return{button:r(D?"在浏览器中打开登录页":"打开网页登录"),hint:r(D?"系统浏览器打开(复用已登录账号);完成后自动加入列表":"内嵌窗口打开;完成后自动加入列表,关窗即取消等待")}},start:()=>yt().workbuddyDesktop?.startLogin(p.current,g.current,qR(p.current),v.current),onSuccess:async()=>{const D=p.current==="intl"?r("国际版"):r("国内版");Cj(),await yt().wbApp?.refresh?.(),Ws(r("✅ 登录成功,{edition}账号已加入列表",{edition:D}))}})??null)},[]),x.useEffect(()=>{y.current?.syncTexts()},[t,o]);function b(E){const D=E==="intl"?"external":"embedded";a(E),zi.edition=E,c(D),zi.loginMode=D}function j(E){const D=E==="external"?"external":"embedded";c(D),zi.loginMode=D}const w=t==="intl",N=w&&o==="embedded",k=r(N?"国际版登录页默认只显示邮箱登录,勾选后恢复 Google / GitHub / X 入口":w?"只有「内嵌窗口」能恢复第三方入口:系统浏览器里我们无法改动登录页":"国内版登录页没有 Google / GitHub 入口(它用微信 / 手机号 / 邮箱登录)");return s.jsxs("div",{className:"add-provider-block",hidden:!e,children:[s.jsxs(Vn,{children:[s.jsx("h3",{children:r("账号版本")}),s.jsx("p",{children:r("两版账号可同时保存,各自一份模型清单(国内版与国际版是两家提供商,可分别启用与映射)。")}),s.jsx(In,{"aria-label":r("账号版本"),className:Tf,options:[{value:"cn",label:r("国内版(WorkBuddy)")},{value:"intl",label:r("国际版(WorkBuddy AI)")}],value:t,onValueChange:E=>b(E)})]}),s.jsxs(Vn,{children:[s.jsx("h3",{children:r("网页登录")}),s.jsx("p",{children:r("完成登录后自动加入账号列表,昵称取自上游。")}),s.jsxs("div",{className:"field-row",children:[s.jsx("span",{className:"text-[12.5px] whitespace-nowrap text-subtle",children:r("打开方式")}),s.jsx(In,{"aria-label":r("网页登录的打开方式"),className:Tf,options:[{value:"embedded",label:r("内嵌窗口")},{value:"external",label:r("系统默认浏览器")}],value:o,onValueChange:j}),s.jsxs("label",{className:"flex items-center gap-2",title:k,children:[s.jsx(ms,{checked:d,disabled:!N,onCheckedChange:E=>{f(E),zi.socialRestore=E}}),s.jsx("span",{className:"text-[12.5px] text-subtle",children:r("恢复 Google / GitHub 入口")})]})]}),s.jsx("p",{children:r("系统浏览器可复用已有登录态(国际版推荐);内嵌窗口更干净。")}),s.jsxs("div",{className:"field-row",children:[s.jsx(se,{id:"web-login-button",onClick:()=>y.current?.start(),children:r("打开网页登录")}),s.jsx(se,{id:"web-login-cancel",variant:"outline",hidden:!0,onClick:()=>y.current?.cancel(),children:r("取消等待")}),s.jsx("span",{className:"detail",id:"web-login-hint",children:r("内嵌窗口打开;完成后自动加入列表,关窗即取消等待")})]})]})]})}const Oj="proxy",Mj="preset",cg="custom",tq="import",Ef="preset:",Dj="__new__";function nq(e){return e===Mj||e===cg?e:Oj}const ug={workbuddy:"assets/providers/workbuddy.png","workbuddy-intl":"assets/providers/workbuddy.png",raccoon:"assets/providers/raccoon.png",catpaw:"assets/providers/catpaw.png",autoclaw:"assets/providers/autoclaw.png","autoclaw-intl":"assets/providers/autoclaw.png",qoder:"assets/providers/qoder.png","qoder-intl":"assets/providers/qoder.png","cline-free":"assets/providers/cline.png","cline-pass":"assets/providers/cline.png",accio:"assets/providers/accio.png","accio-cn":"assets/providers/accio.png",zcode:"assets/providers/zcode.png","zcode-intl":"assets/providers/zcode.png",codearts:"assets/providers/codearts.png",trae:"assets/providers/trae.png",loomy:"assets/providers/loomy.png",kuku:"assets/providers/kuku.png",monkeycode:"assets/providers/monkeycode.png","monkeycode-intl":"assets/providers/monkeycode.png",commandcode:"assets/providers/commandcode.png",antigravity:"assets/providers/antigravity.png",officeace:"assets/providers/officeace.png"},sq=new Set(["monkeycode","monkeycode-intl","commandcode","antigravity"]);function rq(e){const t=yt().wbProviders;if(e===Mj)return(yt().wbPresetProviders?.list||[]).map(g=>{const v=OR(g);return{id:Ef+g.key,label:g.name,count:v?kj(v.id):0,preset:!0,builtId:v?.id||""}});if(e===cg)return(t?.customList?.()||[]).map(g=>({id:g.id,label:g.name||g.id,count:kj(g.id),custom:!0}));const a=t?.all?.()||[],o=(g,v)=>g===Bi?Ej:yt().wbProviders?.labelOf?.(g)||v,d=(a.length?a.map(g=>{const v=String(g.id||"");return{id:v,label:o(v,String(g.label||g.id||"")),count:Number(g.count)||0,beta:sq.has(v)}}):[{id:Bi,label:Ej,count:kj(Bi)}]).filter(g=>g.id!=="workbuddy-intl"),f=d.findIndex(g=>g.id==="autoclaw-intl"),p=d.findIndex(g=>g.id==="autoclaw");return p>=0&&f>p&&d.splice(p+1,0,d.splice(f,1)[0]),d}function aq({item:e}){const t=e.id.startsWith(Ef)?yt().wbPresetProviders?.iconOf?.(e.id.slice(Ef.length))||"":ug[e.id];if(t)return s.jsx("span",{className:"add-provider-logo has-icon",children:s.jsx("img",{src:t,alt:"",loading:"lazy"})});const a=String(e.label||"?").trim().slice(0,1).toUpperCase()||"?";return s.jsx("span",{className:"add-provider-logo",children:a})}function lq(e){return e.preset?e.builtId?e.count?r("已建过 · {n} 个账号,点击继续添加",{n:e.count}):r("已建过,点击继续添加账号"):r("点开即预填,填 Key 接入"):e.custom?e.count?r("{n} 个账号,点击添加",{n:e.count}):r("点击添加账号"):e.count?r("{n} 个账号",{n:e.count}):r("还没有账号")}function oq({item:e,onPick:t}){return s.jsxs("button",{type:"button",className:"add-provider-card","data-provider":e.id,role:"option",onClick:()=>t(e.id),children:[s.jsx(aq,{item:e}),s.jsxs("span",{className:"add-provider-info",children:[s.jsxs("span",{className:"add-provider-name",children:[e.label,e.beta?s.jsx("span",{className:"add-provider-beta",children:"(beta)"}):null]}),s.jsx("span",{className:"add-provider-meta",children:lq(e)})]}),s.jsx("span",{className:"add-provider-go",children:"›"})]})}function iq({onPick:e}){return s.jsxs("button",{type:"button",className:"add-provider-card is-new","data-provider":Dj,role:"option",onClick:()=>e(Dj),children:[s.jsx("span",{className:"add-provider-logo is-new",children:"+"}),s.jsxs("span",{className:"add-provider-info",children:[s.jsx("span",{className:"add-provider-name",children:r("新建自定义提供商")}),s.jsx("span",{className:"add-provider-meta",children:r("接入一个兼容上游")})]}),s.jsx("span",{className:"add-provider-go",children:"›"})]})}function cq({accountType:e,onAccountTypeChange:t,search:a,onSearchChange:o,onPick:c,version:d,importing:f,importPanel:p}){const g=x.useMemo(()=>rq(e),[e,d]),v=a.trim().toLowerCase(),y=g.filter(j=>!v||j.label.toLowerCase().includes(v)),b=e===cg&&!v;return s.jsxs(Vn,{children:[s.jsx("h3",{children:r("选择提供商")}),s.jsxs("div",{className:"add-pick-row",style:f?{display:"none"}:void 0,children:[s.jsx(In,{"aria-label":r("账号类型"),className:Tf,options:[{value:Oj,label:"Agent"},{value:Mj,label:r("预置 API")},{value:cg,label:r("自定义")}],value:e,onValueChange:j=>t(nq(j))}),s.jsx("span",{id:"add-search-wrap",className:"add-provider-search ml-auto max-w-[340px] min-w-0 flex-[1_1_200px]",children:s.jsxs(Ci,{children:[s.jsx(Ti,{children:"⌕"}),s.jsx(Ei,{id:"add-provider-search",type:"search",placeholder:r("搜索提供商…"),autoComplete:"off","aria-label":r("搜索提供商"),value:a,onChange:j=>o(j.currentTarget.value)})]})})]}),p,s.jsxs("div",{className:"add-provider-grid",id:"add-provider-grid",role:"listbox","aria-label":r("选择要添加账号的提供商"),style:f?{display:"none"}:void 0,children:[b?s.jsx(iq,{onPick:c}):null,y.map(j=>s.jsx(oq,{item:j,onPick:c},j.id)),!y.length&&v?s.jsx("div",{className:"add-provider-empty",children:r("没有匹配「{keyword}」的提供商",{keyword:a.trim()})}):null]})]})}function dg(e,t){return Pe().wbIcons?.icon?.(e,t)||""}function uq({account:e,rank:t}){const a=r("组内第 {rank} 位",{rank:t});return s.jsxs("div",{className:"order-cell",children:[s.jsx("span",{className:"order-grip",role:"button",tabIndex:-1,"aria-label":r("拖动调整组内顺序"),title:r("按住拖动,调整这个账号在本组内的顺序"),dangerouslySetInnerHTML:{__html:dg("gripVertical",14)}}),s.jsx("span",{className:"order-rank",title:a,children:`#${t}`})]})}function dq({group:e,ids:t,collapsed:a}){const[o,c]=x.useState(!1),d="w-full justify-start px-2 font-normal";return s.jsxs(mf,{open:o,onOpenChange:c,children:[s.jsx(Lh,{render:s.jsx("button",{type:"button",className:"grp-iconbtn",title:r("本组操作")}),children:"⋯"}),s.jsx(hf,{align:"end",sideOffset:4,className:"w-[196px] p-1.5",children:s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsx(se,{variant:"ghost",size:"sm",className:d,title:r("启用这一组里的全部账号(含被筛选隐藏的)"),onClick:()=>{c(!1),fR(t,!0)},children:r("全部启用({n})",{n:t.length})}),s.jsx(se,{variant:"ghost",size:"sm",className:d,title:r("禁用这一组里的全部账号(含被筛选隐藏的)"),onClick:()=>{c(!1),fR(t,!1)},children:r("全部禁用({n})",{n:t.length})}),s.jsx(se,{variant:"ghost",size:"sm",className:d,title:r("打开批量操作弹窗,并预选这一组的账号(改代理等动作在弹窗里挑参数)"),onClick:()=>{c(!1),hj(t,"proxy")},children:r("批量操作本组")}),s.jsx("div",{className:"my-1 h-px bg-hairline"}),s.jsx(se,{variant:"ghost",size:"sm",className:d,onClick:()=>{c(!1),GA(e.provider)},children:r(a?"展开这一组":"折叠这一组")})]})})]})}function fq({group:e,collapsed:t,colSpan:a}){const o=ug[e.provider];return s.jsx("tr",{className:"grp-band","data-provider":e.provider,children:s.jsx("td",{colSpan:a,children:s.jsxs("div",{className:"grp-band-inner",children:[s.jsx("span",{className:"queue-grip",role:"button",tabIndex:-1,"aria-label":r("拖动调整整组顺序"),title:r("按住拖动,调整这一家的组顺位(整组一起动)"),dangerouslySetInnerHTML:{__html:dg("gripVertical",14)}}),s.jsx("span",{className:"grp-rank",title:r("组顺位:越小越先用(拖动分组带调整)"),children:r("第 {rank} 顺位",{rank:e.rank})}),s.jsx("span",{className:"grp-logo",children:o?s.jsx("img",{src:o,alt:"",loading:"lazy"}):s.jsx("span",{className:"grp-logo-txt",children:String(e.label||"?").trim().slice(0,1).toUpperCase()})}),s.jsx("span",{className:"grp-name",children:e.label}),s.jsx("span",{className:"grp-stat",children:r("{total} 个账号 · 启用 {enabled} · 禁用 {disabled}{limited}",{total:e.members.length,enabled:e.enabled,disabled:e.disabled,limited:e.limited>0?r(" · 限流 {n}",{n:e.limited}):""})}),s.jsx("span",{className:"grp-spacer"}),s.jsx("button",{type:"button",className:"grp-iconbtn grp-fold","aria-expanded":!t,title:r(t?"展开这一组":"折叠这一组"),onClick:()=>GA(e.provider),dangerouslySetInnerHTML:{__html:dg("chevronDown",14)}}),s.jsx(dq,{group:e,ids:e.accounts.map(c=>c.id),collapsed:t})]})})})}function pq({account:e}){const t=cr(e),a=r$(e);!t&&KF(e,Al(e))&&a.push({text:r("Token 限额 · 已禁用"),kind:"bad",title:r("本周期 Token 消耗达到限制器的上限,账号已被自动禁用(窗口重置也不恢复,需手动启用)")});const o=uu(e)||e.id;return s.jsxs(s.Fragment,{children:[s.jsx(ms,{checked:t,"aria-label":r("{action}{who}",{action:r(t?"禁用":"启用"),who:o}),title:r(t?"已启用,点击禁用(不参与转发)":"已禁用,点击启用"),onCheckedChange:c=>{uR(e.id,c)}}),a.length?s.jsx("div",{className:"status-tags",children:a.map(c=>s.jsx(ze,{shape:"tag",variant:c.kind==="bad"?"destructive":"secondary",title:c.title,children:c.text},c.text))}):null]})}function mq({account:e,open:t}){const a=ij(e);if(!a.length)return Hh(e,Qa(e))?s.jsx(ze,{variant:"warning",shape:"tag",title:r("余额低于限制器的阈值,转发时会跳过该账号(余额回升自动恢复)"),children:r("余额不足")}):sj(e,Al(e))?s.jsx(ze,{variant:"warning",shape:"tag",title:r("本周期 Token 消耗达到限制器的上限,转发时会跳过该账号(窗口重置自动恢复)"),children:r("Token 限额")}):s.jsxs(ze,{variant:"success",shape:"tag",title:r("当前没有任何模型处于限流中"),children:[s.jsx(ay,{}),r("正常")]});const o=dj(a[0].resetAt);return s.jsxs(s.Fragment,{children:[s.jsx(ze,{variant:"warning",shape:"tag",render:s.jsx("button",{type:"button"}),className:t?"ring-2 ring-warning-soft":void 0,title:r("点击{action}各模型的限流明细",{action:r(t?"收起":"查看")}),onClick:()=>XA(e.id,"limits",!t),children:r("{n} 个模型 ▾",{n:a.length})}),s.jsx("span",{className:"lim-sub",title:r("最早恢复"),children:r("最早 {soonest} 恢复",{soonest:o===uj?r("待定"):o})})]})}function hq({account:e}){const t=ir(kn(e)),a=gA(t.edition?e.expiresAt:e[t.expiry]);if(!a)return s.jsx("span",{className:"muted",title:r("记录里没有过期时间"),children:"—"});const o=a-Date.now();if(o<=0)return s.jsx(ze,{variant:"destructive",shape:"tag",title:r("凭证已过期,转发时会先刷新"),children:r("已过期")});const c=o<36e5?r("{n} 分钟后",{n:Math.max(1,Math.round(o/6e4))}):o<48*36e5?r("{n} 小时后",{n:(o/36e5).toFixed(1)}):r("{n} 天后",{n:Math.floor(o/24/36e5)}),d=Vs(a);return s.jsx("span",{title:d?r("{text}过期({full})",{text:c,full:d}):r("{text}过期",{text:c}),children:c})}function gq({account:e}){const t=tR(e.id);return t<=0?null:s.jsx("span",{className:"conn-count",title:r("{n} 个请求正在使用该账号(含还在下发内容的流式请求)",{n:t}),children:t})}function vr(e){if(e==null||e==="")return"—";const t=Number(e);return Number.isFinite(t)?String(t):String(e)}function xq(e){return!e||typeof e!="object"||Array.isArray(e)?"":GR(e.subscription)}function GR(e){if(!e||typeof e!="object")return"";const t=e,a=[];t.planName&&a.push(r("套餐 {name}",{name:String(t.planName)})),t.status&&a.push(r("状态 {status}",{status:String(t.status)})),t.state&&String(t.state)!=="active"&&a.push(AA(t.state));const o=t.expireAt;if(o!=null&&o!==""){const c=Number(o),d=Number.isFinite(c)&&c>1e11?Vs(c):String(o);d&&a.push(r("到期 {time}",{time:d}))}return Number.isFinite(Number(t.remainQuota))&&a.push(r("余量 {value}",{value:vr(t.remainQuota)})),Number.isFinite(Number(t.totalQuota))&&a.push(r("总量 {value}",{value:vr(t.totalQuota)})),a.join(" ")}function bq(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=e.plans;return Array.isArray(t)?t.filter(a=>a&&typeof a=="object"&&String(a.state||"")==="pending"):[]}function vq(e){const t=e.map(a=>{const o=String(a.name||a.planId||r("套餐")),c=Number(a.pendingUntil??a.startsAt);return Number.isFinite(c)&&c>0?r("{name}({time} 起生效)",{name:o,time:Vs(c*1e3)}):o});return r(`已领到、还没到生效时间的套餐(生效后余额列会按它显示): {lines}`,{lines:t.join(` -`)})}function yq(e){if(e===void 0)return{text:r("未查询"),kind:"muted",title:r("尚未查询该账号的余额")};if(e===null)return{text:r("查询中…"),kind:"muted",title:r("正在查询")};const t=uu(e);if(t)return t.notConfigured?{text:r("未配置"),kind:"muted",title:r("{message}(去该账号的「设置」里填上查询凭证即可)",{message:t.message})}:{text:r("查询失败"),kind:"bad",title:t.message};if(typeof e!="object"||e===null)return{text:r("无数据"),kind:"muted",title:String(e)};const a=e;if(Object.prototype.hasOwnProperty.call(a,"totalLeft")){const o=a.unlimited?"∞":vr(a.totalLeft);return{text:r("可用 {total}",{total:o}),kind:"ok",title:r("总剩余 {total} · 套餐 {plan} · 奖励 {bonus}",{total:o,plan:vr(a.planLeft),bonus:vr(a.bonusLeft)})}}if(Object.prototype.hasOwnProperty.call(a,"available")||Array.isArray(a.wallets)){const o=String(a.unit||r("积分")),c=Array.isArray(a.wallets)?a.wallets:[],d=c.map(j=>`${j?.displayName||j?.type||r("明细")} ${j?.balanceView?String(j.balanceView):vr(j?.balance)}`).join(" · "),f=GR(a.subscription),p=[];if(c.length===0&&Array.isArray(a.plans)&&a.plans.length>0){const j=KR(a);p.push(j&&YR(j)?r("读数里没有额度桶,这里按套餐权益里的已用 / 总量显示(上游给的数)"):r("上游的余额读数里没有这个套餐的额度桶,剩余量读不到;余额列显示的是套餐发放的权益额度,不是剩余量"))}String(a.walletsFrom||"")==="monitor"&&p.push(r("额度窗口读数来自开放平台监控通道(套餐 JWT 那条通道没有额度桶):读的是每 N 小时 / 每周窗口的剩余比例"));const g=a.available==null?c.find(j=>j?.balance!=null):void 0,v=a.availableView?String(a.availableView):g?r("可用 {value} {unit}",{value:vr(g.balance),unit:String(g.unit||o)}):r("可用 {value} {unit}",{value:vr(a.available),unit:o}),y=[a.statisticsError?r("订阅统计未读到:{error}",{error:String(a.statisticsError)}):"",a.benefitError?r("福利网关未读到:{error}",{error:String(a.benefitError)}):""].filter(Boolean),b=a.benefitAbsent?[r("该账号没有福利模型额度(福利按活动下发,不是每个账号都有)")]:[];return{text:v+(y.length?" ⚠":""),kind:y.length?"warn":"ok",title:[v,d,f,...p,...b,...y].filter(Boolean).join(" · ")}}return{text:r("无数据"),kind:"muted",title:r("未返回可识别的余额数据")}}function KR(e){const t=Array.isArray(e.plans)?e.plans:[],a=o=>String(o?.state||"");return t.find(o=>a(o)==="active")||t.find(o=>a(o)==="pending")||t[0]||null}function jq(e){const t=Array.isArray(e.entitlements)?e.entitlements:[];let a=null;for(const o of t){const c=Number(o?.grantUnits);if(!Number.isFinite(c)||c<=0)continue;const d=String(o?.unitType||"").trim();(!a||c>a.units)&&(a={units:c,unit:d})}return a}function YR(e){const t=Array.isArray(e.entitlements)?e.entitlements:[];for(const a of t){const o=Dr(a?.totalUnits);if(o===null||o<=0)continue;const c=Dr(a?.usedUnits),d=Dr(a?.remainingUnits),f=c===null?d===null?null:Math.max(0,o-d):c;if(f!==null)return{used:f,total:o,unit:String(a?.unitType||"").trim()}}return null}function wq(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,a=Array.isArray(t.wallets)?t.wallets:[];let o=null;for(const p of a){const g=Number(p?.total);!Number.isFinite(g)||g<=0||(!o||g>Number(o.total))&&(o=p)}const c=t.subscription&&typeof t.subscription=="object"?t.subscription:{};if(!o){let p=null;for(const j of a){const w=Dr(j?.remainingPercent);w!==null&&(!p||w0,N=S?Math.max(0,Math.min(100,y/b*100)):null;c.push({name:v,view:S?r("剩 {remaining} / {total}",{remaining:vr(y),total:vr(b)}):r("剩 {remaining}",{remaining:vr(y)}),tone:y<=0?"muted":N!==null&&N<20?"warn":"ok",percent:N,over:!1,title:S?void 0:r("上游未给总量,画不出剩余比例")});continue}if(w!==null||Dr(g.allowanceTokens)!==null){const S=Dr(g.usedTokens)??0,N=Dr(g.allowanceTokens),k=N!==null&&N>1,E=k&&S>N,D=g.unlimited===!0,C=k?Math.max(0,Math.min(100,(1-S/N)*100)):null,A=D?r("无上限 · 已用 {used}",{used:No(S)}):k?r("剩 {remaining} / {total}",{remaining:No(Math.max(0,N-S)),total:No(N)}):S>0?r("已用 {used}",{used:No(S)}):r("未使用");d.push({name:Nq(v),view:A,tone:E?"bad":!k&&!D?"muted":C!==null&&C<20?"warn":"ok",percent:C,over:E,title:[j,D?r("无上限按日计(上游到达上限后仍继续计数,超额如实显示)"):null].filter(Boolean).join(" · ")});continue}d.push({name:v,view:j,tone:"muted",percent:null,over:!1,title:j})}const f=t.subscription&&typeof t.subscription=="object"?t.subscription:{},p=[t.statisticsError?r("订阅统计未读到:{error}",{error:String(t.statisticsError)}):"",t.benefitError?r("福利网关未读到:{error}",{error:String(t.benefitError)}):""].filter(Boolean);return{credit:c,token:d,total:Dr(t.available),unit:o,plan:e$(f.planName),free:OA(f.planName),resetDate:String(f.resetDate||""),missing:p,benefitAbsent:t.benefitAbsent===!0}}function Cq(e){const t=Al(e);let a=null;for(const b of qF(e)){if(b.enabled===!1)continue;const j=hf(b,t);if(!j)continue;const w=b.threshold>0?j.used/b.threshold:0;if(w>=1){a={rule:b,reading:j,ratio:w};break}(!a||w>a.ratio)&&(a={rule:b,reading:j,ratio:w})}if(!a)return null;const{rule:o,reading:c}=a,d=c.used>=o.threshold,f=rj(o),p=d?"":` · ${Uh(f.remainingMs,f.daily)}`,g=f.daily?r("今日已用"):r("周期 Token"),v=o.reset==="daily"?r("今天(本地 0 点重置)"):r("{period}窗口",{period:NA(o.period??0)}),y=r("限制器:{window}已用 {used} / {threshold} Token",{window:v,used:Math.round(c.used).toLocaleString("en-US"),threshold:Math.round(o.threshold).toLocaleString("en-US")})+(d?r(",已达到上限"):r(",{countdown}重置",{countdown:Uh(f.remainingMs,f.daily)}));return s.jsxs("span",{className:"usage-token-sub",title:y,children:[g," ",s.jsx("span",{className:d?"hit":void 0,children:Tl(c.used)})," ","/ ",Tl(o.threshold),p]})}function Tq({account:e}){if(!Ta(e))return s.jsx("span",{className:"muted",title:r("该提供商没有余额查询"),children:"—"});const t=Qa(e),a=yq(t),o=Hh(e,t)?s.jsx(ze,{variant:"warning",shape:"tag",title:r("余额低于限制器的阈值,转发时会跳过该账号(余额回升自动恢复)"),children:r("余额不足 · 已跳过")}):sj(e,Al(e))?s.jsx(ze,{variant:"warning",shape:"tag",title:r("本周期 Token 消耗达到限制器的上限,转发时会跳过该账号(窗口重置自动恢复)"),children:r("Token 限额 · 已跳过")}):null,c=Cq(e),d=a.kind==="ok"||a.kind==="warn"?bq(t):[],f=d.length?s.jsx(ze,{variant:"warning",shape:"tag",title:vq(d),children:r("待生效 {n} 份",{n:d.length})}):null,p=a.kind==="ok"||a.kind==="warn"?MF(t):[],g=RA(e)&&p.length?{rows:p,subscriptionLine:xq(t),kind:a.kind,title:a.title}:null,v=a.kind==="ok"||a.kind==="warn"?Sq(t):[];if(v.length)return s.jsxs("span",{className:"usage-cell",title:a.title,children:[v.map(j=>s.jsx(XR,{row:j},j.name)),o,f,c]});if(JF(e)){const w=a.kind==="ok"||a.kind==="warn"?kq(t):null;return w?s.jsx(Eq,{summary:a,detail:w,blockedBadge:o,tokenSub:c}):s.jsxs("span",{className:"usage-sum-wrap",children:[s.jsx("span",{className:`usage-sum ${a.kind}`,title:a.title,children:a.text}),o,f,c]})}const y=a.kind==="ok"||a.kind==="warn"?wq(t):null;if(!y)return s.jsxs("span",{className:"usage-sum-wrap",children:[g?s.jsx(pA,{variant:"sum",...g,children:a.text}):s.jsx("span",{className:`usage-sum ${a.kind}`,title:a.title,children:a.text}),o,f,c]});const b=s.jsxs(s.Fragment,{children:[y.percent!==null?s.jsx(Jd,{value:y.percent,className:"usage-pool-bar"}):null,s.jsx("span",{className:`usage-pool-view ${a.kind}`,children:y.text})]});return s.jsxs("span",{className:"usage-pool",title:a.title,children:[y.planName?s.jsx("span",{className:"usage-pool-name",children:y.planName}):null,g?s.jsx(pA,{variant:"pool",...g,children:b}):s.jsx("span",{className:"usage-pool-line",children:b}),o,f,c]})}function Eq({summary:e,detail:t,blockedBadge:a,tokenSub:o}){const[c,d]=x.useState(!1),f=e.kind==="ok"||e.kind==="warn";return s.jsxs("span",{className:c?"usage-cell open":"usage-cell",children:[s.jsxs("span",{className:"usage-plan",children:[t.plan?s.jsx("span",{className:`plan-chip${t.free?" free":""}`,children:t.plan}):null,t.resetDate?s.jsx("span",{className:"plan-sub",title:r("套餐积分的重置日期"),children:r("重置 {date}",{date:t.resetDate})}):null]}),s.jsxs(pf,{open:c,onOpenChange:d,children:[s.jsxs(Lh,{render:s.jsx("button",{type:"button",className:`usage-toggle ${e.kind}`,title:e.title,"aria-label":r("积分明细")}),children:[s.jsx("span",{className:"val",children:e.text}),s.jsx("span",{className:"caret","aria-hidden":!0,children:"▾"})]}),s.jsxs(mf,{align:"end",sideOffset:6,className:"usage-pop w-[288px]",children:[f&&t.missing.length?t.missing.map(p=>s.jsx("div",{className:"usage-pop-missing",title:p,children:p},p)):null,t.credit.length?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"usage-pop-group",children:r("积分")}),t.credit.map(p=>s.jsx(Aq,{row:p},p.name))]}):null,t.total!==null?s.jsxs("div",{className:"usage-pop-total",children:[s.jsx("span",{className:"k",children:r("可用合计")}),s.jsxs("span",{className:"v",children:[vr(t.total)," ",s.jsx("small",{children:t.unit})]})]}):null,!t.credit.length&&t.total===null?s.jsx("div",{className:"usage-pop-empty",title:r("该账号的额度只有福利 token 池(见余额格那两行),订阅统计没有积分类计量表"),children:r("该账号没有积分类读数(额度只有福利 token 池)")}):null]})]}),t.token.map(p=>s.jsx(XR,{row:p},p.name)),t.benefitAbsent?s.jsxs("span",{className:"usage-flat-line",title:r("福利按限时活动下发,不是每个账号都有 —— 正常状态,不是查询失败"),children:[s.jsx("span",{className:"usage-flat-name",children:r("福利日额度")}),s.jsx("span",{className:"usage-flat-view muted",children:r("无福利额度")})]}):null,a,o]})}function Aq({row:e}){return s.jsxs("div",{className:"usage-pop-row",title:e.title,children:[s.jsxs("div",{className:"usage-pop-line",children:[s.jsx("span",{className:"usage-pop-name",children:e.name}),s.jsx("span",{className:`usage-pop-view ${e.tone}`,children:e.view})]}),e.percent!==null?s.jsx("span",{className:`usage-pop-track${e.over?" over":""}`,children:s.jsx("i",{style:{width:`${e.percent}%`},"aria-label":r("剩余 {percent}%",{percent:Math.round(e.percent)})})}):null]})}function Rq({account:e,namesHidden:t}){const a=Bh(e),o=ir(kn(e)),c=cu(e)||r("未命名账号"),d=String(e.email||"").trim(),f=String(e.nickname||"").trim(),p=String(e.name||"").trim(),g=w=>t?y$(w):w,v=[d&&d!==c?r("邮箱 {email}",{email:g(d)}):"",a?`${o.identifier} ${a}`:"",!e.nameCustom&&p&&p!==d&&p!==f?r("备注名 {name}",{name:g(p)}):"",f&&f!==c&&f!==d?r("昵称 {name}",{name:g(f)}):"",gf(e)?r("桌面端实时登录态(凭证每次从客户端登录态文件读取)"):"",e.updatedAt?r("更新于 {time}",{time:Vs(e.updatedAt)}):"",e.source?r("来源 {source}",{source:e.source==="imported"?r("旧数据导入"):r("手动添加")}):""].filter(Boolean),y=d&&d!==c,b=e.proxy?.error,j=v.length?s.jsx(KU,{delay:0,children:s.jsxs(Ii,{children:[s.jsx(Pi,{render:s.jsx("div",{className:"acct-name"}),children:s.jsx("span",{className:"name",children:g(c)})}),s.jsxs(_i,{children:[s.jsx(YU,{}),v.map((w,S)=>s.jsx("div",{children:w},S))]})]})}):s.jsx("div",{className:"acct-name",children:s.jsx("span",{className:"name",children:g(c)})});return s.jsxs(s.Fragment,{children:[j,y?s.jsx("div",{className:"acct-sub",children:s.jsx("span",{className:"acct-email",title:r("账号邮箱"),children:g(d)})}):null,b?s.jsx("div",{className:"acct-note bad",title:r("代理不可用:{error}",{error:b}),children:r("代理不可用:{error}",{error:b})}):null]})}function Oq({account:e}){const t=e.proxy,a=t?.config?.source||t?.source,o=t?.label||r(a==="custom"?"自定义代理":"已设置"),c=t?.error,d=S$(),f=Array.isArray(d)?d:[];let p="";a==="pool"&&t?.config?.proxyId?p=`${Ya}${t.config.proxyId}`:t&&(p=Jh);const g=[{value:"",label:r("直连")}];for(const b of f)g.push({value:`${Ya}${b.id}`,label:au(b)});if(d===null?g.push({value:"__hint_pool__",label:r("正在读取代理列表…"),disabled:!0}):f.length||g.push({value:"__hint_pool__",label:N$()?r("代理列表读取失败(重试中)"):r("还没有代理(去「网络代理」页添加)"),disabled:!0}),p===Jh){const b=a==="clash"?r("Clash 出口:"):a==="custom"?r("自定义:"):"";g.push({value:Jh,label:`${b}${o}${c?r("(不可用)"):""}`})}else a==="pool"&&!f.some(b=>`${Ya}${b.id}`===p)&&g.push({value:p,label:`${o}${c?r("(不可用)"):""}`});g.push({value:pR,label:r("自定义代理…")});const v=c?r("代理不可用:{error}(转发时会回退直连);选「自定义代理…」去修改",{error:c}):a==="rotate"?r("当前:{label}(每条请求换一个出口);「自定义代理…」打开完整设置",{label:o}):a==="clash"||a==="custom"?r("当前:{label}(未经过代理池 —— 可在「网络代理」页把出口同步进池后来这里改选)",{label:o}):r("当前:{label};选项来自「网络代理」页;「自定义代理…」打开完整设置",{label:t?o:r("直连")}),y=g.find(b=>b.value===p);return s.jsxs(ft,{value:p,onValueChange:b=>{I$(e.id,String(b),p)},children:[s.jsx(mt,{className:Ue("w-full",c&&"border-destructive-bd"),title:v,"aria-label":r("出网代理"),children:s.jsx(pt,{children:y?.label||r("直连")})}),s.jsx(ht,{children:g.map(b=>s.jsx(qe,{value:b.value,disabled:b.disabled,children:b.label},b.value))})]})}function Mq({account:e,atFront:t}){const[a,o]=x.useState(!1),c=Ta(e),d=TA(e);return s.jsxs("div",{className:"acct-actions",children:[d?s.jsx(se,{variant:"outline",size:"xs",title:ZF(e)?WF(e):r("查看可领取的套餐与名下已有的套餐(每天一期,领取需过一次人机验证)"),onClick:()=>mR(e.id),children:r("领套餐")}):null,c?s.jsx(se,{variant:"outline",size:"xs",disabled:a,title:r("查询该账号剩余余额(读数显示在余额列)"),onClick:()=>{o(!0),M$(e.id).finally(()=>o(!1))},children:r("余额")}):null,s.jsx(se,{variant:"outline",size:"xs",title:r("备注名 / 启用 / 代理"),onClick:()=>Qh(e.id),children:r("设置")}),s.jsx(Dq,{account:e,atFront:t})]})}function Dq({account:e,atFront:t}){const[a,o]=x.useState(!1),c=cr(e),d=Number(e.maxConcurrent)||0,f="w-full justify-start px-2 font-normal",p=`${f} text-destructive hover:text-destructive`;return s.jsxs(pf,{open:a,onOpenChange:o,children:[s.jsx(Lh,{render:s.jsx(se,{variant:"outline",size:"xs",title:r("更多操作")}),children:"⋯"}),s.jsx(mf,{align:"end",sideOffset:4,className:"w-[172px] p-1.5",children:s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsx(se,{variant:"ghost",size:"sm",className:p,onClick:()=>{o(!1),uR(e.id,!c)},children:r(c?"禁用":"启用")}),s.jsx(se,{variant:"ghost",size:"sm",className:f,disabled:t,title:r(t?"已在全局队列第一位":"仅将优先级调整到全局第一位,不改变启用状态"),onClick:()=>{o(!1),Pe().wbApp?.runAccountAction?.("switch",e.id)},children:r("设为首选")}),s.jsx(se,{variant:"ghost",size:"sm",className:f,title:r("在账号设置的「基本」分组里设置该账号同时最多处理的请求数"),onClick:()=>{o(!1),Qh(e.id)},children:r("并发上限:{value}",{value:d>0?d:r("不限")})}),e.hasRefreshToken?s.jsx(se,{variant:"ghost",size:"sm",className:f,onClick:()=>{o(!1),Pe().wbApp?.runAccountAction?.("refresh",e.id)},children:r("刷新 Token")}):null,s.jsx("div",{className:"my-1 h-px bg-hairline"}),s.jsx(se,{variant:"ghost",size:"sm",className:p,title:gf(e)?r("删除这条账号记录(不会影响客户端自己的登录态;之后可再点「导入桌面端登录态」加回来)"):void 0,onClick:()=>{o(!1),Pe().wbApp?.runAccountAction?.("remove",e.id)},children:r("删除账号")})]})})]})}function Iq({account:e,onClose:t,onClear:a}){const o=ij(e),c=s.jsx(se,{variant:"ghost",size:"icon-xs",className:"panel-close",title:r("收起"),onClick:t,children:"✕"});return o.length?s.jsxs("div",{className:"row-panel limit-panel",children:[c,s.jsxs("div",{className:"lp-head",children:[s.jsx("b",{children:cu(e)}),s.jsx("span",{className:"muted",children:r("{n} 个模型限流中 · 记录来自上游 429 / 限额码,到恢复时间自动解除",{n:o.length})}),s.jsx(se,{variant:"outline",size:"xs",title:r("清掉该账号全部模型的限流标记"),onClick:()=>a(""),children:r("全部清除")})]}),o.map(d=>{const f=dj(d.resetAt),p=d.message||(d.status?r("上游返回 {status}",{status:d.status}):"");return s.jsxs("div",{className:"lp-row",children:[s.jsx("span",{className:"lp-model",title:d.model,children:d.model}),s.jsx(ze,{variant:"warning",shape:"tag",children:r("限流中")}),s.jsx("span",{className:"lp-reset",title:r("到恢复时间后自动解除,无需手动操作"),children:f===uj?r("恢复时间未知"):r("{time} 恢复",{time:f})}),s.jsx("span",{className:"lp-reason",title:p,children:p}),s.jsx(se,{variant:"outline",size:"2xs",title:r("清掉本机的限流标记,立刻重新尝试该模型(上游若仍在限流会再次被标记)"),onClick:()=>a(d.model),children:r("清除标记")})]},d.model)})]}):s.jsxs("div",{className:"row-panel limit-panel",children:[r("当前没有限流中的模型。"),c]})}function Pq({account:e,colSpan:t,limitsOpen:a,onClear:o}){return a?s.jsx("tr",{className:"acct-panels","data-panels-for":e.id,children:s.jsx("td",{colSpan:t,children:s.jsx(Iq,{account:e,onClose:()=>XA(e.id,"limits",!1),onClear:c=>o(e.id,c)})})}):null}function _q({namesHidden:e,allPicked:t,somePicked:a,disabled:o,onToggleAll:c}){const d=s.jsx("span",{className:"col-grip",title:r("拖动调整列宽(双击还原)")});return s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{className:"cell-pick","data-col":"pick",children:s.jsx(Or,{id:"acct-select-all",checked:t,indeterminate:!t&&a,disabled:o,"aria-label":r("全选当前筛选结果"),title:r("全选 / 取消全选当前筛选结果(与批量栏同一个选择)"),onCheckedChange:f=>c(f)})}),s.jsxs("th",{className:"cell-order","data-col":"order",children:[s.jsx("span",{className:"th-label",title:r("组内先后:按住左边的把手上下拖动即可调整;整组的先后拖分组带的把手"),children:r("顺序")}),d]}),s.jsxs("th",{className:"cell-account","data-col":"account",children:[s.jsxs("span",{className:"th-label",children:[r("账号"),s.jsx(Lq,{hidden:e})]}),d]}),s.jsxs("th",{className:"cell-proxy","data-col":"proxy",children:[s.jsx("span",{className:"th-label",title:r("该账号出网走的代理(Clash 出口 / 自定义 / 直连);点击可修改"),children:r("代理")}),d]}),s.jsxs("th",{className:"cell-connections","data-col":"connections",children:[s.jsx("span",{className:"th-label",title:r("此刻正在使用这个账号的请求数(含还在下发内容的流式请求);为 0 时不显示"),children:r("连接数")}),d]}),s.jsxs("th",{className:"cell-status","data-col":"status",children:[s.jsx("span",{className:"th-label",children:r("状态")}),d]}),s.jsxs("th",{className:"cell-limits","data-col":"limits",children:[s.jsx("span",{className:"th-label",title:r("该账号当前限流中的模型;点徽章看明细"),children:r("限流")}),d]}),s.jsxs("th",{className:"cell-expiry","data-col":"expiry",children:[s.jsx("span",{className:"th-label",children:r("有效期")}),d]}),s.jsxs("th",{className:"cell-usage","data-col":"usage",children:[s.jsx("span",{className:"th-label",children:r("余额")}),d]}),s.jsx("th",{className:"cell-actions","data-col":"actions",children:s.jsx("span",{className:"th-label",children:r("操作")})})]})})}function Lq({hidden:e}){const t=r(e?"显示账号名":"隐藏账号名(名字显示为星号)");return s.jsx("button",{type:"button",className:`name-eye${e?" on":""}`,title:t,"aria-label":t,"aria-pressed":e,onClick:()=>v$(),dangerouslySetInnerHTML:{__html:dg(e?"eyeOff":"eye",13)}})}const QR="dragging",Ef=["drop-before","drop-after"];let Wa=null;function ZR(e){e.querySelectorAll(`.${Ef[0]}, .${Ef[1]}`).forEach(t=>{t.classList.remove(...Ef)})}function zq(e,t){if(t==="group"){const o=e.parentElement;return o?[...o.children].filter(c=>c.classList.contains("acct-group")):[]}const a=e.parentElement;return a?[...a.children].filter(o=>o.classList.contains("acct-row")):[]}function WR(e,t){for(let a=0;aa!==e.item);ZR(e.container),t.length&&(e.index>=t.length?t[t.length-1].classList.add(Ef[1]):t[e.index].classList.add(Ef[0]))}function JR(e){if(!Wa)return;if(e.buttons===0){fg(!1);return}const t=Wa.items.filter(o=>o!==Wa.item),a=WR(t,e.clientY);a!==Wa.index&&(Wa.index=a,Bq(Wa))}function fg(e){const t=Wa;t&&(Wa=null,window.removeEventListener("pointermove",JR),window.removeEventListener("pointerup",eO),window.removeEventListener("pointercancel",tO),window.removeEventListener("keydown",nO),document.body.classList.remove("queue-dragging"),t.item.classList.remove(QR),ZR(t.container),e&&(t.kind==="group"?Ij?.onDrop({kind:"group",provider:t.provider,index:t.index}):Ij?.onDrop({kind:"row",provider:t.provider,accountId:t.accountId,index:t.index})))}function eO(){fg(!0)}function tO(){fg(!1)}function nO(e){e.key==="Escape"&&fg(!1)}let Ij=null;function Hq(e,t){Ij=t,e&&e.dataset.queueDragBound!=="1"&&(e.dataset.queueDragBound="1",e.addEventListener("pointerdown",a=>{if(a.button!==0||Wa)return;const o=a.target,c=o?.closest?.(".queue-grip"),d=o?.closest?.(".order-grip");if(!c&&!d)return;if(a.preventDefault(),c&&t.isLocked()){t.onLockedAttempt();return}const f=(c??d).closest("tbody.acct-group, tr.acct-row");if(!f)return;const p=c?"group":"row",g=f.dataset.provider||f.closest("tbody.acct-group")?.dataset.provider||"",v=f.dataset.id||"";if(p==="row"&&!v)return;const y=zq(f,p);if(y.length<2)return;const b=y.filter(j=>j!==f);Wa={kind:p,provider:g,accountId:v,item:f,container:f.parentElement||e,items:y,index:WR(b,a.clientY)},f.classList.add(QR),document.body.classList.add("queue-dragging"),window.addEventListener("pointermove",JR),window.addEventListener("pointerup",eO),window.addEventListener("pointercancel",tO),window.addEventListener("keydown",nO)}))}let pg=null,sO=!1,Pj=0,mg=null,rO="";function aO(){return pg?pg.apply(jj):jj}function lO(){window.wbAccountsView?.render?.()}function Uq(){const e=aO(),t=`${mg?"T":"F"}|${e.map(o=>`${o.key}:${o.align}`).join("|")}`;if(t===rO)return;rO=t,Pe().wbColSettings?.syncStaticHead("accounts",mg);const a=[...mg?.querySelectorAll("thead th")||[]];a.forEach((o,c)=>{const d=o.querySelector(".col-grip");d&&(d.style.display=c===a.length-1?"none":"")})}function Vq(){const e=x.useSyncExternalStore(UA,Zs),t=x.useRef(null),[,a]=x.useReducer(B=>B+1,0),o=!!pj(),c=El(),{groups:d,allGroups:f}=i$(Qa,Al),p=c$(Qa,Al),g=[{value:"all",label:r("全部({n})",{n:c.length})}].concat(VA().map(B=>({value:B.id,label:r("{label}({count})",{label:B.label,count:B.count})}))),v=d.flatMap(B=>B.accounts),y=u$(),b=aO(),j=ag(v.length,"accounts",{defaultSize:"all"}),w=j.paged?j.slice(v):v,S=Gh()||j.paged,N=Gh()?r("清除筛选"):r("把每页调回「全部」");x.useEffect(()=>{k$()}),x.useEffect(()=>{p$()},[e.version]),x.useLayoutEffect(()=>{if(!sO){if(!Pe().wbColSettings?.register){window.clearTimeout(Pj),Pj=window.setTimeout(()=>k(B=>B+1),50);return}sO=!0,pg=Pe().wbColSettings?.register({id:"accounts",label:r("账号表"),columns:jj.map(B=>({key:B.key,label:B.label,align:B.align,legacyAlign:B.legacyAlign})),mount:()=>document.querySelector("#batch-bar .batch-actions"),onChange:lO})||null,pg&&a();return}Uq()});const[,k]=x.useState(0);x.useEffect(()=>()=>window.clearTimeout(Pj),[]),x.useEffect(()=>{S8(t.current,lO)},[]);const E=v.map(B=>B.id),D=E.length>0&&E.every(B=>e.selected.has(B)),C=E.some(B=>e.selected.has(B)),A=[...e.selected].filter(B=>!E.includes(B)).length,R=e.selected.size>0,I=f.length>0&&f.every(B=>e.collapsed.has(B.provider)),P=new Map;for(const B of d)P.set(B.provider,w.filter(z=>kn(z)===B.provider).map(z=>z.id));const O=x.useRef({displayed:d,all:f,renderedRows:P});x.useEffect(()=>{O.current={displayed:d,all:f,renderedRows:P}});const _=x.useRef({locked:!1,lockReason:"",onDrop:B=>{}}),L=x.useCallback(B=>{const{displayed:z,all:Q}=O.current;if(B.kind==="group"){const Z=Q.findIndex(te=>te.provider===B.provider);if(Z<0)return;const ae=Q[Z],ce=Q.filter((te,Ce)=>Ce!==Z),J=B.indexte.provider===J),ge=J===null||ie<0?ce.length:ie;if(ge===Z)return;const fe=[...ce.slice(0,ge),ae,...ce.slice(ge)].flatMap(te=>te.members.map(Ce=>Ce.id));dR(fe,r("{name} 移到第 {rank} 顺位",{name:ae.label,rank:ge+1}));return}const K=Q.find(Z=>Z.provider===B.provider);if(!K)return;const X=K.members.findIndex(Z=>Z.id===B.accountId);if(X<0)return;const q=K.members[X],$=K.members.filter((Z,ae)=>ae!==X),Y=O.current.renderedRows.get(B.provider)||[],F=B.indexZ.id===F),W=F===null||G<0?$.length:G;if(W===X)return;const le=[...$.slice(0,W),q,...$.slice(W)],U=Q.map(Z=>Z.provider===B.provider?{...Z,members:le}:Z).flatMap(Z=>Z.members.map(ae=>ae.id));dR(U,r("{name} 移到 {group} 组内第 {rank} 位",{name:String(q.name||q.id),group:K.label,rank:W+1}))},[]);x.useEffect(()=>{_.current={locked:S,lockReason:N,onDrop:L}}),x.useEffect(()=>{Hq(t.current,{isLocked:()=>_.current.locked,onLockedAttempt:()=>Le(r("当前视图不能调整组顺位:{reason} 之后再拖动",{reason:_.current.lockReason}),"err"),onDrop:B=>_.current.onDrop(B)})},[]);function H(B,z,Q){switch(B){case"pick":return s.jsx(Or,{checked:Q.picked,"data-pick":z.id,title:r("勾选后可批量操作"),"aria-label":r("勾选后可批量操作"),onCheckedChange:K=>g$(z.id,K)});case"order":return s.jsx(uq,{account:z,rank:Q.rank});case"account":return s.jsx(Rq,{account:z,namesHidden:e.namesHidden});case"proxy":return s.jsx(Oq,{account:z});case"connections":return s.jsx(gq,{account:z});case"status":return s.jsx(pq,{account:z});case"limits":return s.jsx(mq,{account:z,open:Q.limitsOpen});case"expiry":return s.jsx(hq,{account:z});case"usage":return s.jsx(Tq,{account:z});case"actions":return s.jsx(Mq,{account:z,atFront:Q.seat.position<=1});default:return null}}return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel account-table",children:[s.jsxs("div",{className:"toolbar",children:[s.jsxs("div",{className:"group","data-provider-group":"1",children:[s.jsx("span",{className:"label",children:r("提供商")}),s.jsxs(ft,{value:e.filter.provider,onValueChange:B=>f$(String(B)),children:[s.jsx(mt,{className:"max-w-none min-w-0 w-full min-[768px]:max-w-[200px] min-[768px]:min-w-[130px] min-[768px]:w-auto","aria-label":r("按提供商筛选账号"),children:s.jsx(pt,{children:g.find(B=>B.value===e.filter.provider)?.label||r("全部")})}),s.jsx(ht,{children:g.map(B=>s.jsx(qe,{value:B.value,children:B.label},B.value))})]})]}),s.jsx("div",{className:"divider","data-provider-divider":"1"}),s.jsxs("div",{className:"group",children:[s.jsx("span",{className:"label",children:r("搜索")}),s.jsx($e,{className:"acct-search",type:"search",value:e.filter.q,placeholder:r("账号名 / 邮箱 / 备注"),"aria-label":r("搜索账号"),onChange:B=>d$(B.currentTarget.value)})]}),s.jsx("div",{className:"divider"}),s.jsxs("div",{className:"group",children:[s.jsx("span",{className:"label",children:r("状态")}),s.jsx(In,{options:[{value:"all",label:r("全部"),count:p.enabledAll??0},{value:"enabled",label:r("启用"),count:p.enabled??0},{value:"disabled",label:r("禁用"),count:p.disabled??0}],value:e.filter.enabled,onValueChange:B=>FA("enabled",B),"aria-label":r("启用状态")})]}),s.jsxs("div",{className:"group",children:[s.jsx("span",{className:"label",children:r("限额")}),s.jsx(In,{options:[{value:"all",label:r("全部"),count:p.limitAll??0},{value:"normal",label:r("正常"),count:p.normal??0,disabled:e.filter.enabled==="disabled"},{value:"limited",label:r("已限流"),count:p.limited??0,disabled:e.filter.enabled==="disabled"}],value:e.filter.limit,onValueChange:B=>FA("limit",B),"aria-label":r("限额状态")})]}),s.jsxs("div",{className:"actions",children:[s.jsx(se,{id:"btn-fold-groups",variant:"outline",disabled:!f.length,title:r(I?"展开全部分组":"折叠全部分组(只留组头)"),onClick:()=>m$(f.map(B=>B.provider),!I),children:r(I?"展开全部":"折叠全部")}),s.jsx(se,{id:"btn-add-account-2",variant:"default",title:r("登录 / 导入一个新账号"),onClick:()=>{Pe().wbAddAccountModal?.open?.(),Pe().wbAccountAddForms?.syncAddProvider?.()},children:r("添加账号")}),s.jsx(se,{id:"btn-query-usage",variant:"outline",disabled:e.usageBusy||!c.some(Ta),title:r("查询全部账号的余额(含已禁用账号 —— 禁用只表示不参与转发)"),onClick:()=>{iR()},children:e.usageBusy?r("查询中…"):r("查询余额")})]})]}),s.jsxs("div",{className:Ue("batch-bar",R&&"active"),id:"batch-bar",children:[s.jsxs("label",{className:"batch-select-all",children:[s.jsx(Or,{id:"batch-select-all",checked:D,indeterminate:!D&&C,disabled:!E.length,"aria-label":r("全选当前筛选结果"),onCheckedChange:B=>KA(E,B)}),s.jsx("span",{id:"batch-select-label",children:E.length?r("全选当前筛选结果({n} 个)",{n:E.length}):r("没有可全选的账号")})]}),s.jsxs("span",{className:"batch-count",children:[r("已选")," ",s.jsx("b",{id:"batch-count",children:e.selected.size})," ",r("个 · 共")," ",s.jsx("b",{id:"accounts-count",children:c.length})," ",r("个")]}),s.jsx("span",{className:"batch-summary",id:"accounts-group-summary",children:d.length?r("{groups} 家 · 显示 {rows} 行",{groups:d.length,rows:E.length}):""}),S?s.jsx("span",{className:"batch-hidden",title:r("筛选 / 搜索 / 分页生效时组顺位不可拖动(别家的组整组不可见,落点没法定位)"),children:r("组顺位已锁定")}):null,Gh()?s.jsx(se,{id:"btn-clear-filter",variant:"ghost",size:"xs",title:r("清空搜索与三个筛选档位,回到全部账号"),onClick:()=>$A(),children:r("清除筛选")}):null,A?s.jsx("span",{className:"batch-hidden",id:"batch-hidden-hint",children:r("另有 {n} 个已勾选账号被当前筛选隐藏,仍会参与操作",{n:A})}):null,s.jsxs("div",{className:"batch-actions",children:[s.jsx(se,{id:"btn-batch-open",variant:"outline",disabled:!R,onClick:()=>hj([...e.selected],"enable"),children:r("批量操作")}),s.jsx(se,{id:"btn-batch-clear",variant:"outline",disabled:!R,onClick:()=>x$(),children:r("取消选择")})]})]}),s.jsx("div",{className:"acct-scroll",id:"account-list",ref:t,children:o?c.length?v.length?s.jsxs("table",{className:"acct-table",ref:Fq,style:{minWidth:`${j8(b.map(B=>B.key))}px`},children:[s.jsx($q,{}),s.jsx(_q,{namesHidden:e.namesHidden,allPicked:D,somePicked:C,disabled:!E.length,onToggleAll:B=>KA(E,B)}),d.map(B=>{const z=e.collapsed.has(B.provider),Q=w.filter(K=>kn(K)===B.provider);return s.jsxs("tbody",{className:"acct-group","data-provider":B.provider,children:[s.jsx(fq,{group:B,collapsed:z,colSpan:b.length}),z?null:Q.map(K=>{const X=B.members.findIndex($=>$.id===K.id)+1,q=P$(K,y,X>0?X:1);return s.jsxs(x.Fragment,{children:[s.jsx("tr",{className:Ue("acct-row",!cr(K)&&"disabled",q.picked&&"selected"),"data-id":K.id,"data-provider":B.provider,"data-desktop":gf(K)?"1":void 0,children:b.map($=>s.jsx("td",{className:`cell-${$.key} ta-${$.align}`,children:H($.key,K,q)},$.key))}),s.jsx(Pq,{account:K,colSpan:b.length,limitsOpen:YA(K.id,"limits"),onClear:($,Y)=>{D$($,Y)}})]},K.id)})]},B.provider)})]}):s.jsxs("div",{className:"empty",children:[r("当前筛选条件下没有账号"),Gh()?s.jsx("button",{type:"button",className:"link-btn",onClick:()=>$A(),children:r("清除筛选")}):null]}):s.jsx("div",{className:"empty",children:r("暂无账号,请点击右上角「添加账号」")}):s.jsxs("div",{className:"empty",children:[s.jsx("span",{className:"spinner"}),r("正在加载…")]})}),s.jsx(Li,{total:v.length,range:j.paged?{start:j.rangeStart,end:j.rangeEnd}:null,page:j.page,pageCount:j.pageCount,size:j.size,onSizeChange:j.setSize,onPageChange:j.goto})]}),s.jsx(p8,{})]})}function Fq(e){mg=e}function $q(){const e=y8(),t=a=>s.jsx("col",{"data-col":a,style:e[a]?{width:`${e[a]}px`}:void 0},a);return s.jsxs("colgroup",{children:[t("pick"),t("order"),t("account"),t("proxy"),t("connections"),t("status"),t("limits"),t("expiry"),t("usage"),t("actions")]})}const oO='.page[data-page="accounts"]';let _j=null;function iO(){if(_j)return;const e=document.querySelector(oO);e&&(e.replaceChildren(),_j=vn.createRoot(e),ks.flushSync(()=>{_j.render(s.jsx(Vq,{}))}))}L$(),E$(),document.querySelector(oO)?iO():document.addEventListener("DOMContentLoaded",iO,{once:!0});const qq=64,Gq=100,Kq=r("OpenAI 兼容填到 /v1;Anthropic 填根地址"),Yq=r("Anthropic 协议填根地址,不要带 /v1"),Xq="https://open.bigmodel.cn/api/paas/v4",Qq="https://api.anthropic.com",Zq=[{value:"chat_completions",label:"OpenAI - Chat Completions"},{value:"responses",label:"OpenAI - Responses"},{value:"anthropic",label:"Anthropic - Messages"}],hu="custom-protocol-select",gu="custom-name-input",xu="custom-baseurl-input",Af="custom-apikey-input",Rf="custom-noauth-check",bu="custom-existing-select",Of="custom-existing-apikey-input",Mf="custom-existing-noauth-check",Df="custom-existing-name-input",Wq="custom-create-button",Jq="custom-existing-button",eG="custom-existing-remove";let Lj=!1;const cO=()=>yt().wbProviders?.PROTOCOL_OPTIONS||Zq,zj=()=>yt().wbProviders?.customList?.()||[],Bj="custom-balance",Hj="custom-existing-balance",If=(e,t)=>`${e}-${t}-input`;function uO(e){if(!e)return"";const t=yt().wbPresetProviders?.presetOf?.(e);return String(t?.balance?.scheme||"")}function dO(e,t){const a=Sf(e);if(!a||!a.fields.length)return null;const o={};for(const c of a.fields){const d=Mr(If(t,c.key));d&&(o[c.key]=d)}return Object.keys(o).length?o:null}function fO(e,t){const a=Sf(e);if(a)for(const o of a.fields)So(If(t,o.key),"")}function pO({scheme:e,prefix:t}){const a=Sf(e);return a?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"add-field",children:[s.jsx(Je,{children:r("余额查询")}),s.jsxs("div",{className:"col-start-2 row-start-1 flex h-[30px] items-center",children:[s.jsx("span",{className:"text-xs text-subtle",children:r("方案:{label}",{label:a.label})}),s.jsx("span",{className:"ml-1.5 text-xs text-subtle",children:a.endpoint})]}),s.jsx("span",{className:"hint",children:a.note})]}),a.fields.map(o=>s.jsxs("div",{className:"add-field",children:[s.jsx(Je,{htmlFor:If(t,o.key),children:o.label}),s.jsx($e,{id:If(t,o.key),type:o.secret?"password":"text",autoComplete:o.secret?"new-password":"off",placeholder:o.placeholder,...Za(If(t,o.key))}),s.jsx("span",{className:"hint",children:o.hint})]},o.key))]}):null}async function Uj(e,t){if(!Lj){Lj=!0,e(!0);try{await t()}finally{Lj=!1,e(!1)}}}async function mO(e){yt().wbAddAccountModal?.close?.(),yt().wbProviders?.refreshCustom?.(),await yt().wbApp?.refresh?.(),Ws(e)}function Pf(e,t){So(e,t?"1":"")}function hg(e){return Mr(e)==="1"}function hO({checked:e,note:t,onChange:a}){return s.jsxs("div",{className:"add-field",children:[s.jsx(Je,{children:r("鉴权")}),s.jsx("div",{className:"col-start-2 row-start-1 flex h-[30px] items-center",children:s.jsxs("label",{className:"inline-flex cursor-pointer items-center gap-2.5",children:[s.jsx(Or,{checked:e,"aria-label":r("该上游无需鉴权"),onCheckedChange:o=>a(o===!0)}),s.jsx("span",{className:"text-xs text-subtle",children:r("该上游无需鉴权(不发送鉴权头)")})]})}),s.jsx("span",{className:"hint",children:t})]})}function tG({mode:e,providerHint:t,presetKey:a,showToken:o,version:c}){const d=cO(),[f,p]=x.useState(()=>Mr(hu)||d[0].value),[g,v]=x.useState(""),[y,b]=x.useState(""),[j,w]=x.useState(()=>Mr(bu)),[S,N]=x.useState(()=>hg(Rf)),[k,E]=x.useState(()=>hg(Mf)),D=x.useMemo(()=>zj(),[c]),A=(t&&D.some(B=>B.id===t)?t:"")||(D.some(B=>B.id===j)?j:D[0]?.id||""),R=D.find(B=>B.id===A)?.name||r("该提供商");x.useEffect(()=>{So(bu,A)},[A]),x.useEffect(()=>{if(!a)return;const B=yt().wbPresetProviders?.presetOf?.(a);if(!B)return;const z=B.account?.noAuth===!0;if(e!=="create"){E(z),Pf(Mf,z);return}So(gu,B.name||""),So(xu,B.baseUrl||""),B.protocol&&(p(B.protocol),So(hu,B.protocol)),N(z),Pf(Rf,z),v(B.hint||""),b(B.placeholder||"")},[e,a,t,o]);const I=f==="anthropic",P=g||(I?Yq:Kq),O=y||(I?Qq:Xq),_=e==="create"?uO(a):"",L=e==="existing"?String(D.find(B=>B.id===A)?.balanceScheme||""):"",H=(B,z)=>Q=>{z(Q),Pf(B,Q)};return s.jsxs(s.Fragment,{children:[s.jsxs(Vn,{hidden:e!=="create",children:[s.jsxs("div",{className:"add-panel-head",children:[s.jsx("h3",{children:r("上游信息")}),s.jsx("span",{children:r("创建这个提供商,并同时建立它的第一个账号。")})]}),s.jsxs("div",{className:"add-form",children:[s.jsxs("div",{className:"add-field",children:[s.jsxs(Je,{htmlFor:gu,children:[r("名称"),s.jsx("i",{className:"req","aria-hidden":"true",children:"*"})]}),s.jsx($e,{id:gu,type:"text",maxLength:qq,"aria-required":"true",placeholder:r("如:智谱 GLM"),...Za(gu)}),s.jsx("span",{className:"hint",children:r("1~64 个字符,账号列表里按它分组显示")})]}),s.jsxs("div",{className:"add-field",children:[s.jsx(Je,{htmlFor:hu,children:r("协议")}),s.jsxs(ft,{value:f,onValueChange:B=>{const z=String(B);p(z),So(hu,z),v("")},children:[s.jsx(mt,{id:hu,className:"col-start-2 row-start-1 w-full",children:s.jsx(pt,{children:d.find(B=>B.value===f)?.label||f})}),s.jsx(ht,{children:d.map(B=>s.jsx(qe,{value:B.value,children:B.label},B.value))})]})]}),s.jsxs("div",{className:"add-field",children:[s.jsxs(Je,{htmlFor:xu,children:["Base URL",s.jsx("i",{className:"req","aria-hidden":"true",children:"*"})]}),s.jsx($e,{id:xu,type:"text","aria-required":"true",placeholder:O,...Za(xu)}),s.jsx("span",{className:"hint",id:"custom-baseurl-hint",children:P})]}),s.jsxs("div",{className:"add-field",children:[s.jsx(Je,{htmlFor:Af,children:"API Key"}),s.jsx($e,{id:Af,type:"password",autoComplete:"new-password",placeholder:"sk-…",disabled:S,...Za(Af)}),s.jsx("span",{className:"hint",children:r(S?"不需要 Key:转发与拉取模型都不发送鉴权头":"上游不要鉴权时留空,并勾选下面一项(留空又不勾会被当成未配置凭证)")})]}),s.jsx(hO,{checked:S,note:r(S?"已声明无需鉴权:账号会被正常选路,出网时不带任何鉴权头":"本地 Ollama、OpenCode Zen 免费档这类上游要勾上,否则账号不可用"),onChange:H(Rf,N)}),s.jsx(pO,{scheme:_,prefix:Bj})]})]}),s.jsxs(Vn,{hidden:e!=="existing",children:[s.jsxs("div",{className:"add-panel-head",children:[s.jsx("h3",{children:r("账号信息")}),s.jsxs("span",{children:[r("添加到 "),s.jsx("b",{children:R}),r(" 同一家可以放多把 key,按优先级轮换。")]})]}),s.jsxs("div",{className:"add-form",children:[s.jsxs("div",{className:"add-field",children:[s.jsx(Je,{htmlFor:bu,children:r("提供商")}),s.jsxs(ft,{value:A,onValueChange:B=>w(String(B)),children:[s.jsx(mt,{id:bu,className:"col-start-2 row-start-1 w-full",children:s.jsx(pt,{children:R})}),s.jsx(ht,{children:D.map(B=>s.jsx(qe,{value:B.id,children:B.name||B.id},B.id))})]})]}),s.jsxs("div",{className:"add-field",children:[s.jsx(Je,{htmlFor:Of,children:"API Key"}),s.jsx($e,{id:Of,type:"password",autoComplete:"new-password",placeholder:"sk-…",disabled:k,...Za(Of)}),s.jsx("span",{className:"hint",children:r(k?"不需要 Key:转发与拉取模型都不发送鉴权头":"上游不要鉴权时留空,并勾选下面一项(留空又不勾会被当成未配置凭证)")})]}),s.jsx(hO,{checked:k,note:r(k?"已声明无需鉴权:账号会被正常选路,出网时不带任何鉴权头":"同一家可以混着放:有 Key 的账号与无鉴权账号各按各的规则走"),onChange:H(Mf,E)}),s.jsx(pO,{scheme:L,prefix:Hj}),s.jsxs("div",{className:"add-field",children:[s.jsx(Je,{htmlFor:Df,children:r("备注名")}),s.jsx($e,{id:Df,type:"text",maxLength:Gq,placeholder:r("可选"),...Za(Df)}),s.jsx("span",{className:"hint",children:r("留空则用提供商名称")})]})]})]})]})}function gO(e,t){const a=lg(t);Ws(r("添加失败:{reason}",{reason:a}),"err"),e.setHint(a)}async function nG(e){const t=Mr(gu),a=Mr(hu)||cO()[0].value,o=Mr(xu),c=Mr(Af),d=hg(Rf);if(!t){Ws(r("请填写名称"),"err");return}if(!o){Ws(r("请填写 Base URL"),"err");return}await Uj(e.setBusy,async()=>{const f={name:t,protocol:a,baseUrl:o},p=e.presetKey?yt().wbPresetProviders?.presetOf?.(e.presetKey):null,g=p?.quirks||{};g.urlSuffix&&(f.urlSuffix=g.urlSuffix),g.headers&&Object.keys(g.headers).length&&(f.headers={...g.headers}),g.anthropicToolType&&(f.anthropicToolType=g.anthropicToolType),p?.clientEmulation&&(f.clientEmulation=p.clientEmulation);const v=uO(e.presetKey);v&&(f.balanceScheme=v);const y=dO(v,Bj);y&&(f.balanceQuery=y),d?f.noAuth=!0:c&&(f.apiKey=c),e.setHint("");try{const b=await yt().wbProviders?.customRequest?.("POST","/api/custom-providers",f);Tj([gu,xu,Af]),fO(v,Bj),Pf(Rf,!1);const j=b?.provider?.name||t;await mO(r("✅ 已创建自定义提供商「{name}」并添加账号",{name:j}))}catch(b){gO(e,b)}})}async function sG(e){const t=Mr(bu);if(!t){Ws(r("请先选择一个自定义提供商"),"err");return}const a=Mr(Of),o=hg(Mf),c=Mr(Df),d=String(zj().find(f=>f.id===t)?.balanceScheme||"");await Uj(e.setBusy,async()=>{const f={provider:t};o?f.noAuth=!0:a&&(f.apiKey=a),c&&(f.name=c);const p=dO(d,Hj);p&&(f.balanceQuery=p),e.setHint("");try{const g=await yt().wbProviders?.customRequest?.("POST","/api/accounts",f);Tj([Of,Df]),fO(d,Hj),Pf(Mf,!1);const v=g?.account?.name||zj().find(y=>y.id===t)?.name||"";await mO(r("✅ {label}账号已添加{name}",{label:"",name:v?`:${v}`:""}))}catch(g){gO(e,g)}})}async function rG(){const e=Mr(bu);if(!e){Ws(r("请先选择一个自定义提供商"),"err");return}const t=yt().wbCustomProvidersUi?.remove;if(typeof t!="function"){Ws(r("删除功能不可用(脚本未就绪)"),"err");return}await Uj(()=>{},async()=>{await t(e)&&yt().wbAddAccountModal?.close?.()})}function aG({mode:e,presetKey:t}){const[a,o]=x.useState(!1),[c,d]=x.useState(""),f={presetKey:t,setBusy:o,setHint:d};return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`add-foot-hint${c?" err":""}`,id:"add-form-foot-hint",children:c}),s.jsxs("span",{className:"add-foot-actions",id:"add-form-foot-actions",children:[e==="existing"?s.jsx(se,{id:eG,variant:"destructive",title:r("级联删除名下全部账号,不可恢复"),onClick:()=>{rG()},children:r("删除此提供商")}):null,s.jsx(se,{id:Wq,hidden:e!=="create",disabled:a,onClick:()=>{nG(f)},children:r(a&&e==="create"?"提交中…":"创建并添加账号")}),s.jsx(se,{id:Jq,hidden:e!=="existing",disabled:a,onClick:()=>{sG(f)},children:r(a&&e==="existing"?"提交中…":"添加账号")})]})]})}const Vj={step:"pick",accountType:Oj,search:"",provider:Bi,providerHint:"",presetKey:"",showToken:0},xO=()=>yt().wbProviders?.customList?.()||[];function lG({onClose:e,onReady:t}){const[a,o]=x.useState(Vj),[c,d]=x.useState(0),f=x.useCallback(()=>d(C=>C+1),[]),p=x.useCallback(()=>{o(Vj);const C=yt().wbProviders;(C?.all?.()||[]).length||C?.load?.().then(f),C?.refreshCustom?.().then(f)},[f]),g=x.useCallback(()=>{p(),o({...Vj,step:"form",provider:mu})},[p]);x.useEffect(()=>(t({reset:p,openNewCustomForm:g}),()=>t(null)),[t,p,g]),x.useEffect(()=>{yt().wbWebLogin?.refresh?.()},[]),x.useEffect(()=>{yt().wbProviders?.refreshCustom?.().then(f)},[f]),x.useEffect(()=>{a.step!=="form"||a.provider!==mu||yt().wbProviders?.refreshCustom?.().then(f)},[a.step,a.provider,a.showToken,f]);const v=V8(a.provider),y=a.provider===mu,b=a.provider===Bi||y||!!v,j=a.providerHint?"existing":"create",w=a.providerHint?xO().find(C=>C.id===a.providerHint)?.name||"":a.presetKey&&yt().wbPresetProviders?.presetOf?.(a.presetKey)?.name||"",S=a.provider===Bi?Ej:yt().wbProviders?.labelOf?.(a.provider)||a.provider,N=y?a.providerHint||a.presetKey?r("登录 / 添加 {name} 账号",{name:w||r("自定义提供商")}):r("新建自定义提供商"):r("登录 / 添加 {name} 账号",{name:S});function k(C){if(!C)return;const A={step:"form",showToken:a.showToken+1};if(C===Dj)o(R=>({...R,...A,provider:mu,providerHint:"",presetKey:""}));else if(C.startsWith(Tf)){const R=C.slice(Tf.length),I=OR(yt().wbPresetProviders?.presetOf?.(R));o(P=>({...P,...A,provider:mu,providerHint:I?.id||"",presetKey:R}))}else xO().some(R=>R.id===C)?o(R=>({...R,...A,provider:mu,providerHint:C,presetKey:""})):o(R=>({...R,...A,provider:C,providerHint:"",presetKey:""}))}const E=()=>o(C=>({...C,step:"pick"})),D=a.accountType===tq;return s.jsx(Qt,{open:!0,onOpenChange:C=>{C||e()},children:s.jsxs(Zt,{className:"w-[min(1100px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("添加账号")})}),s.jsx(Bt,{children:s.jsx(cq,{accountType:a.accountType,onAccountTypeChange:C=>o(A=>({...A,accountType:C})),search:a.search,onSearchChange:C=>o(A=>({...A,search:C})),onPick:k,version:c,importing:D,importPanel:void 0})}),null,s.jsx(Qt,{open:a.step==="form",onOpenChange:C=>{C||E()},children:s.jsxs(Zt,{keepMounted:!0,overlayForceRender:!0,className:"w-[min(620px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:N})}),s.jsxs(Bt,{children:[s.jsx(eq,{active:a.provider===Bi}),BR.map(C=>s.jsx(J8,{config:C,active:a.provider===C.provider},C.provider)),s.jsx("div",{className:"add-provider-block",style:y?void 0:{display:"none"},children:s.jsx(tG,{mode:j,providerHint:a.providerHint,presetKey:a.presetKey,showToken:a.showToken,version:c})}),b?null:s.jsx("div",{className:"add-provider-block",children:s.jsxs(Vn,{children:[s.jsx("h3",{children:r("该提供商账号添加功能即将上线")}),s.jsx("p",{children:r("「{name}」的账号添加功能还在开发中,敬请期待。",{name:S})})]})})]}),y?s.jsx(nn,{children:s.jsx(aG,{mode:j,presetKey:a.presetKey})}):null]})})]})})}let ko=null,vu=null,Hi=null,gg=null;function oG(){ko&&(ko.unmount(),ko=null),vu&&(vu.remove(),vu=null),Hi=null}function bO(){vu=document.createElement("div"),document.body.append(vu),ko=vn.createRoot(vu),ko.render(s.jsx(lG,{onClose:vO,onReady:e=>{if(Hi=e,!e)return;const t=gg;gg=null,t?.()}}))}function vO(){yt().wbWebLogin?.cancelIfActive?.(""),yt().wbAutoclawOauth?.cancel?.(),oG()}function Fj(){if(ko){Hi?.reset();return}gg=()=>Hi?.reset(),bO()}function iG(){if(ko){Hi?.openNewCustomForm();return}gg=()=>Hi?.openNewCustomForm(),bO()}for(const e of["btn-add-account","btn-add-account-2"])document.getElementById(e)?.addEventListener("click",Fj);const yO=window;yO.wbAddAccountModal={open:Fj,close:vO},yO.wbAccountAddForms={syncAddProvider:()=>{ko?Hi?.reset():Fj()},openNewCustomForm:iG};const cG=3065;let yu=null;function uG(){return window.workbuddyDesktop}const jO="same-origin";async function $j(e=!1){if(yu&&!e)return yu;const t=uG();if(t?.platform==="web"){const o=typeof window>"u"?"":window.location?.origin;if(o&&o!=="null")return yu=o,yu}let a=0;try{const o=await t?.getBackendStatus?.(),c=Number(o?.port);Number.isFinite(c)&&c>0&&(a=c)}catch{}return a>0?(yu=`http://127.0.0.1:${a}`,yu):`http://127.0.0.1:${cG}`}async function dG(){const t=await window.workbuddyDesktop?.getModelManage?.(),a=Array.isArray(t?.models)?t.models:[],o=Array.isArray(t?.mappings)?t.mappings:[],c=new Set,d=[],f=new Set;for(const p of a){if(p.enabled!==!0)continue;const g=String(p.provider??""),v=String(p.id??"");!g||!v||(c.add(`${g}${v}`),f.has(v)||(f.add(v),d.push(v)))}for(const p of o){if(p.enabled!==!0||p.isDefault===!0)continue;const g=String(p.provider??""),v=String(p.target??""),y=String(p.alias??"");(!y||!f.has(y)&&c.has(`${g}${v}`))&&(f.add(y),d.push(y))}return d}function wO(e,t){if(typeof e=="string"&&e.trim())return e.trim();if(e&&typeof e=="object"){const a=e.message;if(typeof a=="string"&&a.trim())return a.trim();try{return JSON.stringify(e)}catch{}}return`HTTP ${t}`}function SO(e,t){const a=e instanceof Error?e.message:String(e);return new Error(`连接网关失败(${t}):${a}`)}async function NO(e,t,a){const o=await $j();let c;try{c=await fetch(o+t,{method:e,headers:a===void 0?void 0:{"Content-Type":"application/json"},body:a===void 0?void 0:JSON.stringify(a),credentials:jO})}catch(v){throw SO(v,o)}const d=await c.text();let f=null;try{f=d?JSON.parse(d):null}catch{f=null}const p=f;if(!c.ok||p?.success===!1){const v=p?.error??f?.error,y=wO(v,c.status);throw c.status===404?new Error(`这一版网关还没有 AI 助手接口(HTTP 404):后端还是旧的,重新编译 / 重启客户端后再试。${y}`):new Error(y)}return p&&typeof p=="object"&&"data"in p?p.data:f}async function fG(){const t=(await NO("GET","/api/assistant/config"))?.config;if(!t||typeof t!="object")throw new Error("配置响应不完整");const a=typeof t.model=="string"?t.model:t.model?.id;return{model:typeof a=="string"&&a.trim()?a:null,systemPromptEnabled:t.systemPromptEnabled!==!1,systemPrompt:typeof t.systemPrompt=="string"?t.systemPrompt:"",tools:t.tools&&typeof t.tools=="object"?t.tools:{}}}async function pG(e){const t=await NO("PUT","/api/assistant/config",{config:e});return t?.config&&typeof t.config=="object"?t.config:e}function mG(e){return e.map(t=>{if(t.role==="tool")return{role:"tool",tool_call_id:t.toolCallId,content:t.content};if(t.role==="assistant"){const a={role:"assistant",content:t.content||""};return t.toolCalls?.length&&(a.tool_calls=t.toolCalls.map(o=>({id:o.id,type:"function",function:{name:o.name,arguments:o.arguments}}))),a}return{role:"user",content:t.content}})}async function hG(e){const t=await $j(),a={messages:mG(e.messages)};e.tools.length&&(a.tools=e.tools);let o;try{o=await fetch(t+"/api/assistant/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:e.signal,credentials:jO})}catch(b){throw e.signal?.aborted?b:SO(b,t)}if(!o.ok||!o.body){const b=await o.text().catch(()=>"");let j=null;try{j=b?JSON.parse(b):null}catch{}const w=j?.error,S=wO(w,o.status);throw o.status===404?new Error(`这一版网关还没有 AI 助手接口(HTTP 404):后端还是旧的,重新编译 / 重启客户端后再试。${S}`):new Error(S)}const c=o.body.getReader(),d=new TextDecoder;let f="";const p=new Map;let g="";const v=b=>{for(const j of b.split(` +`)})}function yq(e){if(e===void 0)return{text:r("未查询"),kind:"muted",title:r("尚未查询该账号的余额")};if(e===null)return{text:r("查询中…"),kind:"muted",title:r("正在查询")};const t=du(e);if(t)return t.notConfigured?{text:r("未配置"),kind:"muted",title:r("{message}(去该账号的「设置」里填上查询凭证即可)",{message:t.message})}:{text:r("查询失败"),kind:"bad",title:t.message};if(typeof e!="object"||e===null)return{text:r("无数据"),kind:"muted",title:String(e)};const a=e;if(Object.prototype.hasOwnProperty.call(a,"totalLeft")){const o=a.unlimited?"∞":vr(a.totalLeft);return{text:r("可用 {total}",{total:o}),kind:"ok",title:r("总剩余 {total} · 套餐 {plan} · 奖励 {bonus}",{total:o,plan:vr(a.planLeft),bonus:vr(a.bonusLeft)})}}if(Object.prototype.hasOwnProperty.call(a,"available")||Array.isArray(a.wallets)){const o=String(a.unit||r("积分")),c=Array.isArray(a.wallets)?a.wallets:[],d=c.map(j=>`${j?.displayName||j?.type||r("明细")} ${j?.balanceView?String(j.balanceView):vr(j?.balance)}`).join(" · "),f=GR(a.subscription),p=[];if(c.length===0&&Array.isArray(a.plans)&&a.plans.length>0){const j=KR(a);p.push(j&&YR(j)?r("读数里没有额度桶,这里按套餐权益里的已用 / 总量显示(上游给的数)"):r("上游的余额读数里没有这个套餐的额度桶,剩余量读不到;余额列显示的是套餐发放的权益额度,不是剩余量"))}String(a.walletsFrom||"")==="monitor"&&p.push(r("额度窗口读数来自开放平台监控通道(套餐 JWT 那条通道没有额度桶):读的是每 N 小时 / 每周窗口的剩余比例"));const g=a.available==null?c.find(j=>j?.balance!=null):void 0,v=a.availableView?String(a.availableView):g?r("可用 {value} {unit}",{value:vr(g.balance),unit:String(g.unit||o)}):r("可用 {value} {unit}",{value:vr(a.available),unit:o}),y=[a.statisticsError?r("订阅统计未读到:{error}",{error:String(a.statisticsError)}):"",a.benefitError?r("福利网关未读到:{error}",{error:String(a.benefitError)}):""].filter(Boolean),b=a.benefitAbsent?[r("该账号没有福利模型额度(福利按活动下发,不是每个账号都有)")]:[];return{text:v+(y.length?" ⚠":""),kind:y.length?"warn":"ok",title:[v,d,f,...p,...b,...y].filter(Boolean).join(" · ")}}return{text:r("无数据"),kind:"muted",title:r("未返回可识别的余额数据")}}function KR(e){const t=Array.isArray(e.plans)?e.plans:[],a=o=>String(o?.state||"");return t.find(o=>a(o)==="active")||t.find(o=>a(o)==="pending")||t[0]||null}function jq(e){const t=Array.isArray(e.entitlements)?e.entitlements:[];let a=null;for(const o of t){const c=Number(o?.grantUnits);if(!Number.isFinite(c)||c<=0)continue;const d=String(o?.unitType||"").trim();(!a||c>a.units)&&(a={units:c,unit:d})}return a}function YR(e){const t=Array.isArray(e.entitlements)?e.entitlements:[];for(const a of t){const o=Dr(a?.totalUnits);if(o===null||o<=0)continue;const c=Dr(a?.usedUnits),d=Dr(a?.remainingUnits),f=c===null?d===null?null:Math.max(0,o-d):c;if(f!==null)return{used:f,total:o,unit:String(a?.unitType||"").trim()}}return null}function wq(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,a=Array.isArray(t.wallets)?t.wallets:[];let o=null;for(const p of a){const g=Number(p?.total);!Number.isFinite(g)||g<=0||(!o||g>Number(o.total))&&(o=p)}const c=t.subscription&&typeof t.subscription=="object"?t.subscription:{};if(!o){let p=null;for(const j of a){const w=Dr(j?.remainingPercent);w!==null&&(!p||w0,N=S?Math.max(0,Math.min(100,y/b*100)):null;c.push({name:v,view:S?r("剩 {remaining} / {total}",{remaining:vr(y),total:vr(b)}):r("剩 {remaining}",{remaining:vr(y)}),tone:y<=0?"muted":N!==null&&N<20?"warn":"ok",percent:N,over:!1,title:S?void 0:r("上游未给总量,画不出剩余比例")});continue}if(w!==null||Dr(g.allowanceTokens)!==null){const S=Dr(g.usedTokens)??0,N=Dr(g.allowanceTokens),k=N!==null&&N>1,E=k&&S>N,D=g.unlimited===!0,C=k?Math.max(0,Math.min(100,(1-S/N)*100)):null,A=D?r("无上限 · 已用 {used}",{used:No(S)}):k?r("剩 {remaining} / {total}",{remaining:No(Math.max(0,N-S)),total:No(N)}):S>0?r("已用 {used}",{used:No(S)}):r("未使用");d.push({name:Nq(v),view:A,tone:E?"bad":!k&&!D?"muted":C!==null&&C<20?"warn":"ok",percent:C,over:E,title:[j,D?r("无上限按日计(上游到达上限后仍继续计数,超额如实显示)"):null].filter(Boolean).join(" · ")});continue}d.push({name:v,view:j,tone:"muted",percent:null,over:!1,title:j})}const f=t.subscription&&typeof t.subscription=="object"?t.subscription:{},p=[t.statisticsError?r("订阅统计未读到:{error}",{error:String(t.statisticsError)}):"",t.benefitError?r("福利网关未读到:{error}",{error:String(t.benefitError)}):""].filter(Boolean);return{credit:c,token:d,total:Dr(t.available),unit:o,plan:e$(f.planName),free:OA(f.planName),resetDate:String(f.resetDate||""),missing:p,benefitAbsent:t.benefitAbsent===!0}}function Cq(e){const t=Al(e);let a=null;for(const b of qF(e)){if(b.enabled===!1)continue;const j=gf(b,t);if(!j)continue;const w=b.threshold>0?j.used/b.threshold:0;if(w>=1){a={rule:b,reading:j,ratio:w};break}(!a||w>a.ratio)&&(a={rule:b,reading:j,ratio:w})}if(!a)return null;const{rule:o,reading:c}=a,d=c.used>=o.threshold,f=rj(o),p=d?"":` · ${Uh(f.remainingMs,f.daily)}`,g=f.daily?r("今日已用"):r("周期 Token"),v=o.reset==="daily"?r("今天(本地 0 点重置)"):r("{period}窗口",{period:NA(o.period??0)}),y=r("限制器:{window}已用 {used} / {threshold} Token",{window:v,used:Math.round(c.used).toLocaleString("en-US"),threshold:Math.round(o.threshold).toLocaleString("en-US")})+(d?r(",已达到上限"):r(",{countdown}重置",{countdown:Uh(f.remainingMs,f.daily)}));return s.jsxs("span",{className:"usage-token-sub",title:y,children:[g," ",s.jsx("span",{className:d?"hit":void 0,children:Tl(c.used)})," ","/ ",Tl(o.threshold),p]})}function Tq({account:e}){if(!Ta(e))return s.jsx("span",{className:"muted",title:r("该提供商没有余额查询"),children:"—"});const t=Qa(e),a=yq(t),o=Hh(e,t)?s.jsx(ze,{variant:"warning",shape:"tag",title:r("余额低于限制器的阈值,转发时会跳过该账号(余额回升自动恢复)"),children:r("余额不足 · 已跳过")}):sj(e,Al(e))?s.jsx(ze,{variant:"warning",shape:"tag",title:r("本周期 Token 消耗达到限制器的上限,转发时会跳过该账号(窗口重置自动恢复)"),children:r("Token 限额 · 已跳过")}):null,c=Cq(e),d=a.kind==="ok"||a.kind==="warn"?bq(t):[],f=d.length?s.jsx(ze,{variant:"warning",shape:"tag",title:vq(d),children:r("待生效 {n} 份",{n:d.length})}):null,p=a.kind==="ok"||a.kind==="warn"?MF(t):[],g=RA(e)&&p.length?{rows:p,subscriptionLine:xq(t),kind:a.kind,title:a.title}:null,v=a.kind==="ok"||a.kind==="warn"?Sq(t):[];if(v.length)return s.jsxs("span",{className:"usage-cell",title:a.title,children:[v.map(j=>s.jsx(XR,{row:j},j.name)),o,f,c]});if(JF(e)){const w=a.kind==="ok"||a.kind==="warn"?kq(t):null;return w?s.jsx(Eq,{summary:a,detail:w,blockedBadge:o,tokenSub:c}):s.jsxs("span",{className:"usage-sum-wrap",children:[s.jsx("span",{className:`usage-sum ${a.kind}`,title:a.title,children:a.text}),o,f,c]})}const y=a.kind==="ok"||a.kind==="warn"?wq(t):null;if(!y)return s.jsxs("span",{className:"usage-sum-wrap",children:[g?s.jsx(pA,{variant:"sum",...g,children:a.text}):s.jsx("span",{className:`usage-sum ${a.kind}`,title:a.title,children:a.text}),o,f,c]});const b=s.jsxs(s.Fragment,{children:[y.percent!==null?s.jsx(ef,{value:y.percent,className:"usage-pool-bar"}):null,s.jsx("span",{className:`usage-pool-view ${a.kind}`,children:y.text})]});return s.jsxs("span",{className:"usage-pool",title:a.title,children:[y.planName?s.jsx("span",{className:"usage-pool-name",children:y.planName}):null,g?s.jsx(pA,{variant:"pool",...g,children:b}):s.jsx("span",{className:"usage-pool-line",children:b}),o,f,c]})}function Eq({summary:e,detail:t,blockedBadge:a,tokenSub:o}){const[c,d]=x.useState(!1),f=e.kind==="ok"||e.kind==="warn";return s.jsxs("span",{className:c?"usage-cell open":"usage-cell",children:[s.jsxs("span",{className:"usage-plan",children:[t.plan?s.jsx("span",{className:`plan-chip${t.free?" free":""}`,children:t.plan}):null,t.resetDate?s.jsx("span",{className:"plan-sub",title:r("套餐积分的重置日期"),children:r("重置 {date}",{date:t.resetDate})}):null]}),s.jsxs(mf,{open:c,onOpenChange:d,children:[s.jsxs(Lh,{render:s.jsx("button",{type:"button",className:`usage-toggle ${e.kind}`,title:e.title,"aria-label":r("积分明细")}),children:[s.jsx("span",{className:"val",children:e.text}),s.jsx("span",{className:"caret","aria-hidden":!0,children:"▾"})]}),s.jsxs(hf,{align:"end",sideOffset:6,className:"usage-pop w-[288px]",children:[f&&t.missing.length?t.missing.map(p=>s.jsx("div",{className:"usage-pop-missing",title:p,children:p},p)):null,t.credit.length?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"usage-pop-group",children:r("积分")}),t.credit.map(p=>s.jsx(Aq,{row:p},p.name))]}):null,t.total!==null?s.jsxs("div",{className:"usage-pop-total",children:[s.jsx("span",{className:"k",children:r("可用合计")}),s.jsxs("span",{className:"v",children:[vr(t.total)," ",s.jsx("small",{children:t.unit})]})]}):null,!t.credit.length&&t.total===null?s.jsx("div",{className:"usage-pop-empty",title:r("该账号的额度只有福利 token 池(见余额格那两行),订阅统计没有积分类计量表"),children:r("该账号没有积分类读数(额度只有福利 token 池)")}):null]})]}),t.token.map(p=>s.jsx(XR,{row:p},p.name)),t.benefitAbsent?s.jsxs("span",{className:"usage-flat-line",title:r("福利按限时活动下发,不是每个账号都有 —— 正常状态,不是查询失败"),children:[s.jsx("span",{className:"usage-flat-name",children:r("福利日额度")}),s.jsx("span",{className:"usage-flat-view muted",children:r("无福利额度")})]}):null,a,o]})}function Aq({row:e}){return s.jsxs("div",{className:"usage-pop-row",title:e.title,children:[s.jsxs("div",{className:"usage-pop-line",children:[s.jsx("span",{className:"usage-pop-name",children:e.name}),s.jsx("span",{className:`usage-pop-view ${e.tone}`,children:e.view})]}),e.percent!==null?s.jsx("span",{className:`usage-pop-track${e.over?" over":""}`,children:s.jsx("i",{style:{width:`${e.percent}%`},"aria-label":r("剩余 {percent}%",{percent:Math.round(e.percent)})})}):null]})}function Rq({account:e,namesHidden:t}){const a=Bh(e),o=ir(kn(e)),c=uu(e)||r("未命名账号"),d=String(e.email||"").trim(),f=String(e.nickname||"").trim(),p=String(e.name||"").trim(),g=w=>t?y$(w):w,v=[d&&d!==c?r("邮箱 {email}",{email:g(d)}):"",a?`${o.identifier} ${a}`:"",!e.nameCustom&&p&&p!==d&&p!==f?r("备注名 {name}",{name:g(p)}):"",f&&f!==c&&f!==d?r("昵称 {name}",{name:g(f)}):"",xf(e)?r("桌面端实时登录态(凭证每次从客户端登录态文件读取)"):"",e.updatedAt?r("更新于 {time}",{time:Vs(e.updatedAt)}):"",e.source?r("来源 {source}",{source:e.source==="imported"?r("旧数据导入"):r("手动添加")}):""].filter(Boolean),y=d&&d!==c,b=e.proxy?.error,j=v.length?s.jsx(KU,{delay:0,children:s.jsxs(Ii,{children:[s.jsx(Pi,{render:s.jsx("div",{className:"acct-name"}),children:s.jsx("span",{className:"name",children:g(c)})}),s.jsxs(_i,{children:[s.jsx(YU,{}),v.map((w,S)=>s.jsx("div",{children:w},S))]})]})}):s.jsx("div",{className:"acct-name",children:s.jsx("span",{className:"name",children:g(c)})});return s.jsxs(s.Fragment,{children:[j,y?s.jsx("div",{className:"acct-sub",children:s.jsx("span",{className:"acct-email",title:r("账号邮箱"),children:g(d)})}):null,b?s.jsx("div",{className:"acct-note bad",title:r("代理不可用:{error}",{error:b}),children:r("代理不可用:{error}",{error:b})}):null]})}function Oq({account:e}){const t=e.proxy,a=t?.config?.source||t?.source,o=t?.label||r(a==="custom"?"自定义代理":"已设置"),c=t?.error,d=S$(),f=Array.isArray(d)?d:[];let p="";a==="pool"&&t?.config?.proxyId?p=`${Ya}${t.config.proxyId}`:t&&(p=Jh);const g=[{value:"",label:r("直连")}];for(const b of f)g.push({value:`${Ya}${b.id}`,label:lu(b)});if(d===null?g.push({value:"__hint_pool__",label:r("正在读取代理列表…"),disabled:!0}):f.length||g.push({value:"__hint_pool__",label:N$()?r("代理列表读取失败(重试中)"):r("还没有代理(去「网络代理」页添加)"),disabled:!0}),p===Jh){const b=a==="clash"?r("Clash 出口:"):a==="custom"?r("自定义:"):"";g.push({value:Jh,label:`${b}${o}${c?r("(不可用)"):""}`})}else a==="pool"&&!f.some(b=>`${Ya}${b.id}`===p)&&g.push({value:p,label:`${o}${c?r("(不可用)"):""}`});g.push({value:pR,label:r("自定义代理…")});const v=c?r("代理不可用:{error}(转发时会回退直连);选「自定义代理…」去修改",{error:c}):a==="rotate"?r("当前:{label}(每条请求换一个出口);「自定义代理…」打开完整设置",{label:o}):a==="clash"||a==="custom"?r("当前:{label}(未经过代理池 —— 可在「网络代理」页把出口同步进池后来这里改选)",{label:o}):r("当前:{label};选项来自「网络代理」页;「自定义代理…」打开完整设置",{label:t?o:r("直连")}),y=g.find(b=>b.value===p);return s.jsxs(ft,{value:p,onValueChange:b=>{I$(e.id,String(b),p)},children:[s.jsx(mt,{className:Ue("w-full",c&&"border-destructive-bd"),title:v,"aria-label":r("出网代理"),children:s.jsx(pt,{children:y?.label||r("直连")})}),s.jsx(ht,{children:g.map(b=>s.jsx(qe,{value:b.value,disabled:b.disabled,children:b.label},b.value))})]})}function Mq({account:e,atFront:t}){const[a,o]=x.useState(!1),c=Ta(e),d=TA(e);return s.jsxs("div",{className:"acct-actions",children:[d?s.jsx(se,{variant:"outline",size:"xs",title:ZF(e)?WF(e):r("查看可领取的套餐与名下已有的套餐(每天一期,领取需过一次人机验证)"),onClick:()=>mR(e.id),children:r("领套餐")}):null,c?s.jsx(se,{variant:"outline",size:"xs",disabled:a,title:r("查询该账号剩余余额(读数显示在余额列)"),onClick:()=>{o(!0),M$(e.id).finally(()=>o(!1))},children:r("余额")}):null,s.jsx(se,{variant:"outline",size:"xs",title:r("备注名 / 启用 / 代理"),onClick:()=>Qh(e.id),children:r("设置")}),s.jsx(Dq,{account:e,atFront:t})]})}function Dq({account:e,atFront:t}){const[a,o]=x.useState(!1),c=cr(e),d=Number(e.maxConcurrent)||0,f="w-full justify-start px-2 font-normal",p=`${f} text-destructive hover:text-destructive`;return s.jsxs(mf,{open:a,onOpenChange:o,children:[s.jsx(Lh,{render:s.jsx(se,{variant:"outline",size:"xs",title:r("更多操作")}),children:"⋯"}),s.jsx(hf,{align:"end",sideOffset:4,className:"w-[172px] p-1.5",children:s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsx(se,{variant:"ghost",size:"sm",className:p,onClick:()=>{o(!1),uR(e.id,!c)},children:r(c?"禁用":"启用")}),s.jsx(se,{variant:"ghost",size:"sm",className:f,disabled:t,title:r(t?"已在全局队列第一位":"仅将优先级调整到全局第一位,不改变启用状态"),onClick:()=>{o(!1),Pe().wbApp?.runAccountAction?.("switch",e.id)},children:r("设为首选")}),s.jsx(se,{variant:"ghost",size:"sm",className:f,title:r("在账号设置的「基本」分组里设置该账号同时最多处理的请求数"),onClick:()=>{o(!1),Qh(e.id)},children:r("并发上限:{value}",{value:d>0?d:r("不限")})}),e.hasRefreshToken?s.jsx(se,{variant:"ghost",size:"sm",className:f,onClick:()=>{o(!1),Pe().wbApp?.runAccountAction?.("refresh",e.id)},children:r("刷新 Token")}):null,s.jsx("div",{className:"my-1 h-px bg-hairline"}),s.jsx(se,{variant:"ghost",size:"sm",className:p,title:xf(e)?r("删除这条账号记录(不会影响客户端自己的登录态;之后可再点「导入桌面端登录态」加回来)"):void 0,onClick:()=>{o(!1),Pe().wbApp?.runAccountAction?.("remove",e.id)},children:r("删除账号")})]})})]})}function Iq({account:e,onClose:t,onClear:a}){const o=ij(e),c=s.jsx(se,{variant:"ghost",size:"icon-xs",className:"panel-close",title:r("收起"),onClick:t,children:"✕"});return o.length?s.jsxs("div",{className:"row-panel limit-panel",children:[c,s.jsxs("div",{className:"lp-head",children:[s.jsx("b",{children:uu(e)}),s.jsx("span",{className:"muted",children:r("{n} 个模型限流中 · 记录来自上游 429 / 限额码,到恢复时间自动解除",{n:o.length})}),s.jsx(se,{variant:"outline",size:"xs",title:r("清掉该账号全部模型的限流标记"),onClick:()=>a(""),children:r("全部清除")})]}),o.map(d=>{const f=dj(d.resetAt),p=d.message||(d.status?r("上游返回 {status}",{status:d.status}):"");return s.jsxs("div",{className:"lp-row",children:[s.jsx("span",{className:"lp-model",title:d.model,children:d.model}),s.jsx(ze,{variant:"warning",shape:"tag",children:r("限流中")}),s.jsx("span",{className:"lp-reset",title:r("到恢复时间后自动解除,无需手动操作"),children:f===uj?r("恢复时间未知"):r("{time} 恢复",{time:f})}),s.jsx("span",{className:"lp-reason",title:p,children:p}),s.jsx(se,{variant:"outline",size:"2xs",title:r("清掉本机的限流标记,立刻重新尝试该模型(上游若仍在限流会再次被标记)"),onClick:()=>a(d.model),children:r("清除标记")})]},d.model)})]}):s.jsxs("div",{className:"row-panel limit-panel",children:[r("当前没有限流中的模型。"),c]})}function Pq({account:e,colSpan:t,limitsOpen:a,onClear:o}){return a?s.jsx("tr",{className:"acct-panels","data-panels-for":e.id,children:s.jsx("td",{colSpan:t,children:s.jsx(Iq,{account:e,onClose:()=>XA(e.id,"limits",!1),onClear:c=>o(e.id,c)})})}):null}function _q({namesHidden:e,allPicked:t,somePicked:a,disabled:o,onToggleAll:c}){const d=s.jsx("span",{className:"col-grip",title:r("拖动调整列宽(双击还原)")});return s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{className:"cell-pick","data-col":"pick",children:s.jsx(Or,{id:"acct-select-all",checked:t,indeterminate:!t&&a,disabled:o,"aria-label":r("全选当前筛选结果"),title:r("全选 / 取消全选当前筛选结果(与批量栏同一个选择)"),onCheckedChange:f=>c(f)})}),s.jsxs("th",{className:"cell-order","data-col":"order",children:[s.jsx("span",{className:"th-label",title:r("组内先后:按住左边的把手上下拖动即可调整;整组的先后拖分组带的把手"),children:r("顺序")}),d]}),s.jsxs("th",{className:"cell-account","data-col":"account",children:[s.jsxs("span",{className:"th-label",children:[r("账号"),s.jsx(Lq,{hidden:e})]}),d]}),s.jsxs("th",{className:"cell-proxy","data-col":"proxy",children:[s.jsx("span",{className:"th-label",title:r("该账号出网走的代理(Clash 出口 / 自定义 / 直连);点击可修改"),children:r("代理")}),d]}),s.jsxs("th",{className:"cell-connections","data-col":"connections",children:[s.jsx("span",{className:"th-label",title:r("此刻正在使用这个账号的请求数(含还在下发内容的流式请求);为 0 时不显示"),children:r("连接数")}),d]}),s.jsxs("th",{className:"cell-status","data-col":"status",children:[s.jsx("span",{className:"th-label",children:r("状态")}),d]}),s.jsxs("th",{className:"cell-limits","data-col":"limits",children:[s.jsx("span",{className:"th-label",title:r("该账号当前限流中的模型;点徽章看明细"),children:r("限流")}),d]}),s.jsxs("th",{className:"cell-expiry","data-col":"expiry",children:[s.jsx("span",{className:"th-label",children:r("有效期")}),d]}),s.jsxs("th",{className:"cell-usage","data-col":"usage",children:[s.jsx("span",{className:"th-label",children:r("余额")}),d]}),s.jsx("th",{className:"cell-actions","data-col":"actions",children:s.jsx("span",{className:"th-label",children:r("操作")})})]})})}function Lq({hidden:e}){const t=r(e?"显示账号名":"隐藏账号名(名字显示为星号)");return s.jsx("button",{type:"button",className:`name-eye${e?" on":""}`,title:t,"aria-label":t,"aria-pressed":e,onClick:()=>v$(),dangerouslySetInnerHTML:{__html:dg(e?"eyeOff":"eye",13)}})}const QR="dragging",Af=["drop-before","drop-after"];let Wa=null;function ZR(e){e.querySelectorAll(`.${Af[0]}, .${Af[1]}`).forEach(t=>{t.classList.remove(...Af)})}function zq(e,t){if(t==="group"){const o=e.parentElement;return o?[...o.children].filter(c=>c.classList.contains("acct-group")):[]}const a=e.parentElement;return a?[...a.children].filter(o=>o.classList.contains("acct-row")):[]}function WR(e,t){for(let a=0;aa!==e.item);ZR(e.container),t.length&&(e.index>=t.length?t[t.length-1].classList.add(Af[1]):t[e.index].classList.add(Af[0]))}function JR(e){if(!Wa)return;if(e.buttons===0){fg(!1);return}const t=Wa.items.filter(o=>o!==Wa.item),a=WR(t,e.clientY);a!==Wa.index&&(Wa.index=a,Bq(Wa))}function fg(e){const t=Wa;t&&(Wa=null,window.removeEventListener("pointermove",JR),window.removeEventListener("pointerup",eO),window.removeEventListener("pointercancel",tO),window.removeEventListener("keydown",nO),document.body.classList.remove("queue-dragging"),t.item.classList.remove(QR),ZR(t.container),e&&(t.kind==="group"?Ij?.onDrop({kind:"group",provider:t.provider,index:t.index}):Ij?.onDrop({kind:"row",provider:t.provider,accountId:t.accountId,index:t.index})))}function eO(){fg(!0)}function tO(){fg(!1)}function nO(e){e.key==="Escape"&&fg(!1)}let Ij=null;function Hq(e,t){Ij=t,e&&e.dataset.queueDragBound!=="1"&&(e.dataset.queueDragBound="1",e.addEventListener("pointerdown",a=>{if(a.button!==0||Wa)return;const o=a.target,c=o?.closest?.(".queue-grip"),d=o?.closest?.(".order-grip");if(!c&&!d)return;if(a.preventDefault(),c&&t.isLocked()){t.onLockedAttempt();return}const f=(c??d).closest("tbody.acct-group, tr.acct-row");if(!f)return;const p=c?"group":"row",g=f.dataset.provider||f.closest("tbody.acct-group")?.dataset.provider||"",v=f.dataset.id||"";if(p==="row"&&!v)return;const y=zq(f,p);if(y.length<2)return;const b=y.filter(j=>j!==f);Wa={kind:p,provider:g,accountId:v,item:f,container:f.parentElement||e,items:y,index:WR(b,a.clientY)},f.classList.add(QR),document.body.classList.add("queue-dragging"),window.addEventListener("pointermove",JR),window.addEventListener("pointerup",eO),window.addEventListener("pointercancel",tO),window.addEventListener("keydown",nO)}))}let pg=null,sO=!1,Pj=0,mg=null,rO="";function aO(){return pg?pg.apply(jj):jj}function lO(){window.wbAccountsView?.render?.()}function Uq(){const e=aO(),t=`${mg?"T":"F"}|${e.map(o=>`${o.key}:${o.align}`).join("|")}`;if(t===rO)return;rO=t,Pe().wbColSettings?.syncStaticHead("accounts",mg);const a=[...mg?.querySelectorAll("thead th")||[]];a.forEach((o,c)=>{const d=o.querySelector(".col-grip");d&&(d.style.display=c===a.length-1?"none":"")})}function Vq(){const e=x.useSyncExternalStore(UA,Zs),t=x.useRef(null),[,a]=x.useReducer(B=>B+1,0),o=!!pj(),c=El(),{groups:d,allGroups:f}=i$(Qa,Al),p=c$(Qa,Al),g=[{value:"all",label:r("全部({n})",{n:c.length})}].concat(VA().map(B=>({value:B.id,label:r("{label}({count})",{label:B.label,count:B.count})}))),v=d.flatMap(B=>B.accounts),y=u$(),b=aO(),j=ag(v.length,"accounts",{defaultSize:"all"}),w=j.paged?j.slice(v):v,S=Gh()||j.paged,N=Gh()?r("清除筛选"):r("把每页调回「全部」");x.useEffect(()=>{k$()}),x.useEffect(()=>{p$()},[e.version]),x.useLayoutEffect(()=>{if(!sO){if(!Pe().wbColSettings?.register){window.clearTimeout(Pj),Pj=window.setTimeout(()=>k(B=>B+1),50);return}sO=!0,pg=Pe().wbColSettings?.register({id:"accounts",label:r("账号表"),columns:jj.map(B=>({key:B.key,label:B.label,align:B.align,legacyAlign:B.legacyAlign})),mount:()=>document.querySelector("#batch-bar .batch-actions"),onChange:lO})||null,pg&&a();return}Uq()});const[,k]=x.useState(0);x.useEffect(()=>()=>window.clearTimeout(Pj),[]),x.useEffect(()=>{S8(t.current,lO)},[]);const E=v.map(B=>B.id),D=E.length>0&&E.every(B=>e.selected.has(B)),C=E.some(B=>e.selected.has(B)),A=[...e.selected].filter(B=>!E.includes(B)).length,R=e.selected.size>0,I=f.length>0&&f.every(B=>e.collapsed.has(B.provider)),P=new Map;for(const B of d)P.set(B.provider,w.filter(z=>kn(z)===B.provider).map(z=>z.id));const O=x.useRef({displayed:d,all:f,renderedRows:P});x.useEffect(()=>{O.current={displayed:d,all:f,renderedRows:P}});const _=x.useRef({locked:!1,lockReason:"",onDrop:B=>{}}),L=x.useCallback(B=>{const{displayed:z,all:Q}=O.current;if(B.kind==="group"){const Z=Q.findIndex(te=>te.provider===B.provider);if(Z<0)return;const ae=Q[Z],ce=Q.filter((te,Ce)=>Ce!==Z),J=B.indexte.provider===J),ge=J===null||ie<0?ce.length:ie;if(ge===Z)return;const fe=[...ce.slice(0,ge),ae,...ce.slice(ge)].flatMap(te=>te.members.map(Ce=>Ce.id));dR(fe,r("{name} 移到第 {rank} 顺位",{name:ae.label,rank:ge+1}));return}const K=Q.find(Z=>Z.provider===B.provider);if(!K)return;const X=K.members.findIndex(Z=>Z.id===B.accountId);if(X<0)return;const q=K.members[X],$=K.members.filter((Z,ae)=>ae!==X),Y=O.current.renderedRows.get(B.provider)||[],F=B.indexZ.id===F),W=F===null||G<0?$.length:G;if(W===X)return;const le=[...$.slice(0,W),q,...$.slice(W)],U=Q.map(Z=>Z.provider===B.provider?{...Z,members:le}:Z).flatMap(Z=>Z.members.map(ae=>ae.id));dR(U,r("{name} 移到 {group} 组内第 {rank} 位",{name:String(q.name||q.id),group:K.label,rank:W+1}))},[]);x.useEffect(()=>{_.current={locked:S,lockReason:N,onDrop:L}}),x.useEffect(()=>{Hq(t.current,{isLocked:()=>_.current.locked,onLockedAttempt:()=>Le(r("当前视图不能调整组顺位:{reason} 之后再拖动",{reason:_.current.lockReason}),"err"),onDrop:B=>_.current.onDrop(B)})},[]);function H(B,z,Q){switch(B){case"pick":return s.jsx(Or,{checked:Q.picked,"data-pick":z.id,title:r("勾选后可批量操作"),"aria-label":r("勾选后可批量操作"),onCheckedChange:K=>g$(z.id,K)});case"order":return s.jsx(uq,{account:z,rank:Q.rank});case"account":return s.jsx(Rq,{account:z,namesHidden:e.namesHidden});case"proxy":return s.jsx(Oq,{account:z});case"connections":return s.jsx(gq,{account:z});case"status":return s.jsx(pq,{account:z});case"limits":return s.jsx(mq,{account:z,open:Q.limitsOpen});case"expiry":return s.jsx(hq,{account:z});case"usage":return s.jsx(Tq,{account:z});case"actions":return s.jsx(Mq,{account:z,atFront:Q.seat.position<=1});default:return null}}return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel account-table",children:[s.jsxs("div",{className:"toolbar",children:[s.jsxs("div",{className:"group","data-provider-group":"1",children:[s.jsx("span",{className:"label",children:r("提供商")}),s.jsxs(ft,{value:e.filter.provider,onValueChange:B=>f$(String(B)),children:[s.jsx(mt,{className:"max-w-none min-w-0 w-full min-[768px]:max-w-[200px] min-[768px]:min-w-[130px] min-[768px]:w-auto","aria-label":r("按提供商筛选账号"),children:s.jsx(pt,{children:g.find(B=>B.value===e.filter.provider)?.label||r("全部")})}),s.jsx(ht,{children:g.map(B=>s.jsx(qe,{value:B.value,children:B.label},B.value))})]})]}),s.jsx("div",{className:"divider","data-provider-divider":"1"}),s.jsxs("div",{className:"group",children:[s.jsx("span",{className:"label",children:r("搜索")}),s.jsx($e,{className:"acct-search",type:"search",value:e.filter.q,placeholder:r("账号名 / 邮箱 / 备注"),"aria-label":r("搜索账号"),onChange:B=>d$(B.currentTarget.value)})]}),s.jsx("div",{className:"divider"}),s.jsxs("div",{className:"group",children:[s.jsx("span",{className:"label",children:r("状态")}),s.jsx(In,{options:[{value:"all",label:r("全部"),count:p.enabledAll??0},{value:"enabled",label:r("启用"),count:p.enabled??0},{value:"disabled",label:r("禁用"),count:p.disabled??0}],value:e.filter.enabled,onValueChange:B=>FA("enabled",B),"aria-label":r("启用状态")})]}),s.jsxs("div",{className:"group",children:[s.jsx("span",{className:"label",children:r("限额")}),s.jsx(In,{options:[{value:"all",label:r("全部"),count:p.limitAll??0},{value:"normal",label:r("正常"),count:p.normal??0,disabled:e.filter.enabled==="disabled"},{value:"limited",label:r("已限流"),count:p.limited??0,disabled:e.filter.enabled==="disabled"}],value:e.filter.limit,onValueChange:B=>FA("limit",B),"aria-label":r("限额状态")})]}),s.jsxs("div",{className:"actions",children:[s.jsx(se,{id:"btn-fold-groups",variant:"outline",disabled:!f.length,title:r(I?"展开全部分组":"折叠全部分组(只留组头)"),onClick:()=>m$(f.map(B=>B.provider),!I),children:r(I?"展开全部":"折叠全部")}),s.jsx(se,{id:"btn-add-account-2",variant:"default",title:r("登录 / 导入一个新账号"),onClick:()=>{Pe().wbAddAccountModal?.open?.(),Pe().wbAccountAddForms?.syncAddProvider?.()},children:r("添加账号")}),s.jsx(se,{id:"btn-query-usage",variant:"outline",disabled:e.usageBusy||!c.some(Ta),title:r("查询全部账号的余额(含已禁用账号 —— 禁用只表示不参与转发)"),onClick:()=>{iR()},children:e.usageBusy?r("查询中…"):r("查询余额")})]})]}),s.jsxs("div",{className:Ue("batch-bar",R&&"active"),id:"batch-bar",children:[s.jsxs("label",{className:"batch-select-all",children:[s.jsx(Or,{id:"batch-select-all",checked:D,indeterminate:!D&&C,disabled:!E.length,"aria-label":r("全选当前筛选结果"),onCheckedChange:B=>KA(E,B)}),s.jsx("span",{id:"batch-select-label",children:E.length?r("全选当前筛选结果({n} 个)",{n:E.length}):r("没有可全选的账号")})]}),s.jsxs("span",{className:"batch-count",children:[r("已选")," ",s.jsx("b",{id:"batch-count",children:e.selected.size})," ",r("个 · 共")," ",s.jsx("b",{id:"accounts-count",children:c.length})," ",r("个")]}),s.jsx("span",{className:"batch-summary",id:"accounts-group-summary",children:d.length?r("{groups} 家 · 显示 {rows} 行",{groups:d.length,rows:E.length}):""}),S?s.jsx("span",{className:"batch-hidden",title:r("筛选 / 搜索 / 分页生效时组顺位不可拖动(别家的组整组不可见,落点没法定位)"),children:r("组顺位已锁定")}):null,Gh()?s.jsx(se,{id:"btn-clear-filter",variant:"ghost",size:"xs",title:r("清空搜索与三个筛选档位,回到全部账号"),onClick:()=>$A(),children:r("清除筛选")}):null,A?s.jsx("span",{className:"batch-hidden",id:"batch-hidden-hint",children:r("另有 {n} 个已勾选账号被当前筛选隐藏,仍会参与操作",{n:A})}):null,s.jsxs("div",{className:"batch-actions",children:[s.jsx(se,{id:"btn-batch-open",variant:"outline",disabled:!R,onClick:()=>hj([...e.selected],"enable"),children:r("批量操作")}),s.jsx(se,{id:"btn-batch-clear",variant:"outline",disabled:!R,onClick:()=>x$(),children:r("取消选择")})]})]}),s.jsx("div",{className:"acct-scroll",id:"account-list",ref:t,children:o?c.length?v.length?s.jsxs("table",{className:"acct-table",ref:Fq,style:{minWidth:`${j8(b.map(B=>B.key))}px`},children:[s.jsx($q,{}),s.jsx(_q,{namesHidden:e.namesHidden,allPicked:D,somePicked:C,disabled:!E.length,onToggleAll:B=>KA(E,B)}),d.map(B=>{const z=e.collapsed.has(B.provider),Q=w.filter(K=>kn(K)===B.provider);return s.jsxs("tbody",{className:"acct-group","data-provider":B.provider,children:[s.jsx(fq,{group:B,collapsed:z,colSpan:b.length}),z?null:Q.map(K=>{const X=B.members.findIndex($=>$.id===K.id)+1,q=P$(K,y,X>0?X:1);return s.jsxs(x.Fragment,{children:[s.jsx("tr",{className:Ue("acct-row",!cr(K)&&"disabled",q.picked&&"selected"),"data-id":K.id,"data-provider":B.provider,"data-desktop":xf(K)?"1":void 0,children:b.map($=>s.jsx("td",{className:`cell-${$.key} ta-${$.align}`,children:H($.key,K,q)},$.key))}),s.jsx(Pq,{account:K,colSpan:b.length,limitsOpen:YA(K.id,"limits"),onClear:($,Y)=>{D$($,Y)}})]},K.id)})]},B.provider)})]}):s.jsxs("div",{className:"empty",children:[r("当前筛选条件下没有账号"),Gh()?s.jsx("button",{type:"button",className:"link-btn",onClick:()=>$A(),children:r("清除筛选")}):null]}):s.jsx("div",{className:"empty",children:r("暂无账号,请点击右上角「添加账号」")}):s.jsxs("div",{className:"empty",children:[s.jsx("span",{className:"spinner"}),r("正在加载…")]})}),s.jsx(Li,{total:v.length,range:j.paged?{start:j.rangeStart,end:j.rangeEnd}:null,page:j.page,pageCount:j.pageCount,size:j.size,onSizeChange:j.setSize,onPageChange:j.goto})]}),s.jsx(p8,{})]})}function Fq(e){mg=e}function $q(){const e=y8(),t=a=>s.jsx("col",{"data-col":a,style:e[a]?{width:`${e[a]}px`}:void 0},a);return s.jsxs("colgroup",{children:[t("pick"),t("order"),t("account"),t("proxy"),t("connections"),t("status"),t("limits"),t("expiry"),t("usage"),t("actions")]})}const oO='.page[data-page="accounts"]';let _j=null;function iO(){if(_j)return;const e=document.querySelector(oO);e&&(e.replaceChildren(),_j=vn.createRoot(e),ks.flushSync(()=>{_j.render(s.jsx(Vq,{}))}))}L$(),E$(),document.querySelector(oO)?iO():document.addEventListener("DOMContentLoaded",iO,{once:!0});const qq=64,Gq=100,Kq=r("OpenAI 兼容填到 /v1;Anthropic 填根地址"),Yq=r("Anthropic 协议填根地址,不要带 /v1"),Xq="https://open.bigmodel.cn/api/paas/v4",Qq="https://api.anthropic.com",Zq=[{value:"chat_completions",label:"OpenAI - Chat Completions"},{value:"responses",label:"OpenAI - Responses"},{value:"anthropic",label:"Anthropic - Messages"}],gu="custom-protocol-select",xu="custom-name-input",bu="custom-baseurl-input",Rf="custom-apikey-input",Of="custom-noauth-check",vu="custom-existing-select",Mf="custom-existing-apikey-input",Df="custom-existing-noauth-check",If="custom-existing-name-input",Wq="custom-create-button",Jq="custom-existing-button",eG="custom-existing-remove";let Lj=!1;const cO=()=>yt().wbProviders?.PROTOCOL_OPTIONS||Zq,zj=()=>yt().wbProviders?.customList?.()||[],Bj="custom-balance",Hj="custom-existing-balance",Pf=(e,t)=>`${e}-${t}-input`;function uO(e){if(!e)return"";const t=yt().wbPresetProviders?.presetOf?.(e);return String(t?.balance?.scheme||"")}function dO(e,t){const a=Nf(e);if(!a||!a.fields.length)return null;const o={};for(const c of a.fields){const d=Mr(Pf(t,c.key));d&&(o[c.key]=d)}return Object.keys(o).length?o:null}function fO(e,t){const a=Nf(e);if(a)for(const o of a.fields)So(Pf(t,o.key),"")}function pO({scheme:e,prefix:t}){const a=Nf(e);return a?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"add-field",children:[s.jsx(Je,{children:r("余额查询")}),s.jsxs("div",{className:"col-start-2 row-start-1 flex h-[30px] items-center",children:[s.jsx("span",{className:"text-xs text-subtle",children:r("方案:{label}",{label:a.label})}),s.jsx("span",{className:"ml-1.5 text-xs text-subtle",children:a.endpoint})]}),s.jsx("span",{className:"hint",children:a.note})]}),a.fields.map(o=>s.jsxs("div",{className:"add-field",children:[s.jsx(Je,{htmlFor:Pf(t,o.key),children:o.label}),s.jsx($e,{id:Pf(t,o.key),type:o.secret?"password":"text",autoComplete:o.secret?"new-password":"off",placeholder:o.placeholder,...Za(Pf(t,o.key))}),s.jsx("span",{className:"hint",children:o.hint})]},o.key))]}):null}async function Uj(e,t){if(!Lj){Lj=!0,e(!0);try{await t()}finally{Lj=!1,e(!1)}}}async function mO(e){yt().wbAddAccountModal?.close?.(),yt().wbProviders?.refreshCustom?.(),await yt().wbApp?.refresh?.(),Ws(e)}function _f(e,t){So(e,t?"1":"")}function hg(e){return Mr(e)==="1"}function hO({checked:e,note:t,onChange:a}){return s.jsxs("div",{className:"add-field",children:[s.jsx(Je,{children:r("鉴权")}),s.jsx("div",{className:"col-start-2 row-start-1 flex h-[30px] items-center",children:s.jsxs("label",{className:"inline-flex cursor-pointer items-center gap-2.5",children:[s.jsx(Or,{checked:e,"aria-label":r("该上游无需鉴权"),onCheckedChange:o=>a(o===!0)}),s.jsx("span",{className:"text-xs text-subtle",children:r("该上游无需鉴权(不发送鉴权头)")})]})}),s.jsx("span",{className:"hint",children:t})]})}function tG({mode:e,providerHint:t,presetKey:a,showToken:o,version:c}){const d=cO(),[f,p]=x.useState(()=>Mr(gu)||d[0].value),[g,v]=x.useState(""),[y,b]=x.useState(""),[j,w]=x.useState(()=>Mr(vu)),[S,N]=x.useState(()=>hg(Of)),[k,E]=x.useState(()=>hg(Df)),D=x.useMemo(()=>zj(),[c]),A=(t&&D.some(B=>B.id===t)?t:"")||(D.some(B=>B.id===j)?j:D[0]?.id||""),R=D.find(B=>B.id===A)?.name||r("该提供商");x.useEffect(()=>{So(vu,A)},[A]),x.useEffect(()=>{if(!a)return;const B=yt().wbPresetProviders?.presetOf?.(a);if(!B)return;const z=B.account?.noAuth===!0;if(e!=="create"){E(z),_f(Df,z);return}So(xu,B.name||""),So(bu,B.baseUrl||""),B.protocol&&(p(B.protocol),So(gu,B.protocol)),N(z),_f(Of,z),v(B.hint||""),b(B.placeholder||"")},[e,a,t,o]);const I=f==="anthropic",P=g||(I?Yq:Kq),O=y||(I?Qq:Xq),_=e==="create"?uO(a):"",L=e==="existing"?String(D.find(B=>B.id===A)?.balanceScheme||""):"",H=(B,z)=>Q=>{z(Q),_f(B,Q)};return s.jsxs(s.Fragment,{children:[s.jsxs(Vn,{hidden:e!=="create",children:[s.jsxs("div",{className:"add-panel-head",children:[s.jsx("h3",{children:r("上游信息")}),s.jsx("span",{children:r("创建这个提供商,并同时建立它的第一个账号。")})]}),s.jsxs("div",{className:"add-form",children:[s.jsxs("div",{className:"add-field",children:[s.jsxs(Je,{htmlFor:xu,children:[r("名称"),s.jsx("i",{className:"req","aria-hidden":"true",children:"*"})]}),s.jsx($e,{id:xu,type:"text",maxLength:qq,"aria-required":"true",placeholder:r("如:智谱 GLM"),...Za(xu)}),s.jsx("span",{className:"hint",children:r("1~64 个字符,账号列表里按它分组显示")})]}),s.jsxs("div",{className:"add-field",children:[s.jsx(Je,{htmlFor:gu,children:r("协议")}),s.jsxs(ft,{value:f,onValueChange:B=>{const z=String(B);p(z),So(gu,z),v("")},children:[s.jsx(mt,{id:gu,className:"col-start-2 row-start-1 w-full",children:s.jsx(pt,{children:d.find(B=>B.value===f)?.label||f})}),s.jsx(ht,{children:d.map(B=>s.jsx(qe,{value:B.value,children:B.label},B.value))})]})]}),s.jsxs("div",{className:"add-field",children:[s.jsxs(Je,{htmlFor:bu,children:["Base URL",s.jsx("i",{className:"req","aria-hidden":"true",children:"*"})]}),s.jsx($e,{id:bu,type:"text","aria-required":"true",placeholder:O,...Za(bu)}),s.jsx("span",{className:"hint",id:"custom-baseurl-hint",children:P})]}),s.jsxs("div",{className:"add-field",children:[s.jsx(Je,{htmlFor:Rf,children:"API Key"}),s.jsx($e,{id:Rf,type:"password",autoComplete:"new-password",placeholder:"sk-…",disabled:S,...Za(Rf)}),s.jsx("span",{className:"hint",children:r(S?"不需要 Key:转发与拉取模型都不发送鉴权头":"上游不要鉴权时留空,并勾选下面一项(留空又不勾会被当成未配置凭证)")})]}),s.jsx(hO,{checked:S,note:r(S?"已声明无需鉴权:账号会被正常选路,出网时不带任何鉴权头":"本地 Ollama、OpenCode Zen 免费档这类上游要勾上,否则账号不可用"),onChange:H(Of,N)}),s.jsx(pO,{scheme:_,prefix:Bj})]})]}),s.jsxs(Vn,{hidden:e!=="existing",children:[s.jsxs("div",{className:"add-panel-head",children:[s.jsx("h3",{children:r("账号信息")}),s.jsxs("span",{children:[r("添加到 "),s.jsx("b",{children:R}),r(" 同一家可以放多把 key,按优先级轮换。")]})]}),s.jsxs("div",{className:"add-form",children:[s.jsxs("div",{className:"add-field",children:[s.jsx(Je,{htmlFor:vu,children:r("提供商")}),s.jsxs(ft,{value:A,onValueChange:B=>w(String(B)),children:[s.jsx(mt,{id:vu,className:"col-start-2 row-start-1 w-full",children:s.jsx(pt,{children:R})}),s.jsx(ht,{children:D.map(B=>s.jsx(qe,{value:B.id,children:B.name||B.id},B.id))})]})]}),s.jsxs("div",{className:"add-field",children:[s.jsx(Je,{htmlFor:Mf,children:"API Key"}),s.jsx($e,{id:Mf,type:"password",autoComplete:"new-password",placeholder:"sk-…",disabled:k,...Za(Mf)}),s.jsx("span",{className:"hint",children:r(k?"不需要 Key:转发与拉取模型都不发送鉴权头":"上游不要鉴权时留空,并勾选下面一项(留空又不勾会被当成未配置凭证)")})]}),s.jsx(hO,{checked:k,note:r(k?"已声明无需鉴权:账号会被正常选路,出网时不带任何鉴权头":"同一家可以混着放:有 Key 的账号与无鉴权账号各按各的规则走"),onChange:H(Df,E)}),s.jsx(pO,{scheme:L,prefix:Hj}),s.jsxs("div",{className:"add-field",children:[s.jsx(Je,{htmlFor:If,children:r("备注名")}),s.jsx($e,{id:If,type:"text",maxLength:Gq,placeholder:r("可选"),...Za(If)}),s.jsx("span",{className:"hint",children:r("留空则用提供商名称")})]})]})]})]})}function gO(e,t){const a=lg(t);Ws(r("添加失败:{reason}",{reason:a}),"err"),e.setHint(a)}async function nG(e){const t=Mr(xu),a=Mr(gu)||cO()[0].value,o=Mr(bu),c=Mr(Rf),d=hg(Of);if(!t){Ws(r("请填写名称"),"err");return}if(!o){Ws(r("请填写 Base URL"),"err");return}await Uj(e.setBusy,async()=>{const f={name:t,protocol:a,baseUrl:o},p=e.presetKey?yt().wbPresetProviders?.presetOf?.(e.presetKey):null,g=p?.quirks||{};g.urlSuffix&&(f.urlSuffix=g.urlSuffix),g.headers&&Object.keys(g.headers).length&&(f.headers={...g.headers}),g.anthropicToolType&&(f.anthropicToolType=g.anthropicToolType),p?.clientEmulation&&(f.clientEmulation=p.clientEmulation);const v=uO(e.presetKey);v&&(f.balanceScheme=v);const y=dO(v,Bj);y&&(f.balanceQuery=y),d?f.noAuth=!0:c&&(f.apiKey=c),e.setHint("");try{const b=await yt().wbProviders?.customRequest?.("POST","/api/custom-providers",f);Tj([xu,bu,Rf]),fO(v,Bj),_f(Of,!1);const j=b?.provider?.name||t;await mO(r("✅ 已创建自定义提供商「{name}」并添加账号",{name:j}))}catch(b){gO(e,b)}})}async function sG(e){const t=Mr(vu);if(!t){Ws(r("请先选择一个自定义提供商"),"err");return}const a=Mr(Mf),o=hg(Df),c=Mr(If),d=String(zj().find(f=>f.id===t)?.balanceScheme||"");await Uj(e.setBusy,async()=>{const f={provider:t};o?f.noAuth=!0:a&&(f.apiKey=a),c&&(f.name=c);const p=dO(d,Hj);p&&(f.balanceQuery=p),e.setHint("");try{const g=await yt().wbProviders?.customRequest?.("POST","/api/accounts",f);Tj([Mf,If]),fO(d,Hj),_f(Df,!1);const v=g?.account?.name||zj().find(y=>y.id===t)?.name||"";await mO(r("✅ {label}账号已添加{name}",{label:"",name:v?`:${v}`:""}))}catch(g){gO(e,g)}})}async function rG(){const e=Mr(vu);if(!e){Ws(r("请先选择一个自定义提供商"),"err");return}const t=yt().wbCustomProvidersUi?.remove;if(typeof t!="function"){Ws(r("删除功能不可用(脚本未就绪)"),"err");return}await Uj(()=>{},async()=>{await t(e)&&yt().wbAddAccountModal?.close?.()})}function aG({mode:e,presetKey:t}){const[a,o]=x.useState(!1),[c,d]=x.useState(""),f={presetKey:t,setBusy:o,setHint:d};return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:`add-foot-hint${c?" err":""}`,id:"add-form-foot-hint",children:c}),s.jsxs("span",{className:"add-foot-actions",id:"add-form-foot-actions",children:[e==="existing"?s.jsx(se,{id:eG,variant:"destructive",title:r("级联删除名下全部账号,不可恢复"),onClick:()=>{rG()},children:r("删除此提供商")}):null,s.jsx(se,{id:Wq,hidden:e!=="create",disabled:a,onClick:()=>{nG(f)},children:r(a&&e==="create"?"提交中…":"创建并添加账号")}),s.jsx(se,{id:Jq,hidden:e!=="existing",disabled:a,onClick:()=>{sG(f)},children:r(a&&e==="existing"?"提交中…":"添加账号")})]})]})}const Vj={step:"pick",accountType:Oj,search:"",provider:Bi,providerHint:"",presetKey:"",showToken:0},xO=()=>yt().wbProviders?.customList?.()||[];function lG({onClose:e,onReady:t}){const[a,o]=x.useState(Vj),[c,d]=x.useState(0),f=x.useCallback(()=>d(C=>C+1),[]),p=x.useCallback(()=>{o(Vj);const C=yt().wbProviders;(C?.all?.()||[]).length||C?.load?.().then(f),C?.refreshCustom?.().then(f)},[f]),g=x.useCallback(()=>{p(),o({...Vj,step:"form",provider:hu})},[p]);x.useEffect(()=>(t({reset:p,openNewCustomForm:g}),()=>t(null)),[t,p,g]),x.useEffect(()=>{yt().wbWebLogin?.refresh?.()},[]),x.useEffect(()=>{yt().wbProviders?.refreshCustom?.().then(f)},[f]),x.useEffect(()=>{a.step!=="form"||a.provider!==hu||yt().wbProviders?.refreshCustom?.().then(f)},[a.step,a.provider,a.showToken,f]);const v=V8(a.provider),y=a.provider===hu,b=a.provider===Bi||y||!!v,j=a.providerHint?"existing":"create",w=a.providerHint?xO().find(C=>C.id===a.providerHint)?.name||"":a.presetKey&&yt().wbPresetProviders?.presetOf?.(a.presetKey)?.name||"",S=a.provider===Bi?Ej:yt().wbProviders?.labelOf?.(a.provider)||a.provider,N=y?a.providerHint||a.presetKey?r("登录 / 添加 {name} 账号",{name:w||r("自定义提供商")}):r("新建自定义提供商"):r("登录 / 添加 {name} 账号",{name:S});function k(C){if(!C)return;const A={step:"form",showToken:a.showToken+1};if(C===Dj)o(R=>({...R,...A,provider:hu,providerHint:"",presetKey:""}));else if(C.startsWith(Ef)){const R=C.slice(Ef.length),I=OR(yt().wbPresetProviders?.presetOf?.(R));o(P=>({...P,...A,provider:hu,providerHint:I?.id||"",presetKey:R}))}else xO().some(R=>R.id===C)?o(R=>({...R,...A,provider:hu,providerHint:C,presetKey:""})):o(R=>({...R,...A,provider:C,providerHint:"",presetKey:""}))}const E=()=>o(C=>({...C,step:"pick"})),D=a.accountType===tq;return s.jsx(Qt,{open:!0,onOpenChange:C=>{C||e()},children:s.jsxs(Zt,{className:"w-[min(1100px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("添加账号")})}),s.jsx(Bt,{children:s.jsx(cq,{accountType:a.accountType,onAccountTypeChange:C=>o(A=>({...A,accountType:C})),search:a.search,onSearchChange:C=>o(A=>({...A,search:C})),onPick:k,version:c,importing:D,importPanel:void 0})}),null,s.jsx(Qt,{open:a.step==="form",onOpenChange:C=>{C||E()},children:s.jsxs(Zt,{keepMounted:!0,overlayForceRender:!0,className:"w-[min(620px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:N})}),s.jsxs(Bt,{children:[s.jsx(eq,{active:a.provider===Bi}),BR.map(C=>s.jsx(J8,{config:C,active:a.provider===C.provider},C.provider)),s.jsx("div",{className:"add-provider-block",style:y?void 0:{display:"none"},children:s.jsx(tG,{mode:j,providerHint:a.providerHint,presetKey:a.presetKey,showToken:a.showToken,version:c})}),b?null:s.jsx("div",{className:"add-provider-block",children:s.jsxs(Vn,{children:[s.jsx("h3",{children:r("该提供商账号添加功能即将上线")}),s.jsx("p",{children:r("「{name}」的账号添加功能还在开发中,敬请期待。",{name:S})})]})})]}),y?s.jsx(nn,{children:s.jsx(aG,{mode:j,presetKey:a.presetKey})}):null]})})]})})}let ko=null,yu=null,Hi=null,gg=null;function oG(){ko&&(ko.unmount(),ko=null),yu&&(yu.remove(),yu=null),Hi=null}function bO(){yu=document.createElement("div"),document.body.append(yu),ko=vn.createRoot(yu),ko.render(s.jsx(lG,{onClose:vO,onReady:e=>{if(Hi=e,!e)return;const t=gg;gg=null,t?.()}}))}function vO(){yt().wbWebLogin?.cancelIfActive?.(""),yt().wbAutoclawOauth?.cancel?.(),oG()}function Fj(){if(ko){Hi?.reset();return}gg=()=>Hi?.reset(),bO()}function iG(){if(ko){Hi?.openNewCustomForm();return}gg=()=>Hi?.openNewCustomForm(),bO()}for(const e of["btn-add-account","btn-add-account-2"])document.getElementById(e)?.addEventListener("click",Fj);const yO=window;yO.wbAddAccountModal={open:Fj,close:vO},yO.wbAccountAddForms={syncAddProvider:()=>{ko?Hi?.reset():Fj()},openNewCustomForm:iG};const cG=3065;let ju=null;function uG(){return window.workbuddyDesktop}const jO="same-origin";async function $j(e=!1){if(ju&&!e)return ju;const t=uG();if(t?.platform==="web"){const o=typeof window>"u"?"":window.location?.origin;if(o&&o!=="null")return ju=o,ju}let a=0;try{const o=await t?.getBackendStatus?.(),c=Number(o?.port);Number.isFinite(c)&&c>0&&(a=c)}catch{}return a>0?(ju=`http://127.0.0.1:${a}`,ju):`http://127.0.0.1:${cG}`}async function dG(){const t=await window.workbuddyDesktop?.getModelManage?.(),a=Array.isArray(t?.models)?t.models:[],o=Array.isArray(t?.mappings)?t.mappings:[],c=new Set,d=[],f=new Set;for(const p of a){if(p.enabled!==!0)continue;const g=String(p.provider??""),v=String(p.id??"");!g||!v||(c.add(`${g}${v}`),f.has(v)||(f.add(v),d.push(v)))}for(const p of o){if(p.enabled!==!0||p.isDefault===!0)continue;const g=String(p.provider??""),v=String(p.target??""),y=String(p.alias??"");(!y||!f.has(y)&&c.has(`${g}${v}`))&&(f.add(y),d.push(y))}return d}function wO(e,t){if(typeof e=="string"&&e.trim())return e.trim();if(e&&typeof e=="object"){const a=e.message;if(typeof a=="string"&&a.trim())return a.trim();try{return JSON.stringify(e)}catch{}}return`HTTP ${t}`}function SO(e,t){const a=e instanceof Error?e.message:String(e);return new Error(`连接网关失败(${t}):${a}`)}async function NO(e,t,a){const o=await $j();let c;try{c=await fetch(o+t,{method:e,headers:a===void 0?void 0:{"Content-Type":"application/json"},body:a===void 0?void 0:JSON.stringify(a),credentials:jO})}catch(v){throw SO(v,o)}const d=await c.text();let f=null;try{f=d?JSON.parse(d):null}catch{f=null}const p=f;if(!c.ok||p?.success===!1){const v=p?.error??f?.error,y=wO(v,c.status);throw c.status===404?new Error(`这一版网关还没有 AI 助手接口(HTTP 404):后端还是旧的,重新编译 / 重启客户端后再试。${y}`):new Error(y)}return p&&typeof p=="object"&&"data"in p?p.data:f}async function fG(){const t=(await NO("GET","/api/assistant/config"))?.config;if(!t||typeof t!="object")throw new Error("配置响应不完整");const a=typeof t.model=="string"?t.model:t.model?.id;return{model:typeof a=="string"&&a.trim()?a:null,systemPromptEnabled:t.systemPromptEnabled!==!1,systemPrompt:typeof t.systemPrompt=="string"?t.systemPrompt:"",tools:t.tools&&typeof t.tools=="object"?t.tools:{}}}async function pG(e){const t=await NO("PUT","/api/assistant/config",{config:e});return t?.config&&typeof t.config=="object"?t.config:e}function mG(e){return e.map(t=>{if(t.role==="tool")return{role:"tool",tool_call_id:t.toolCallId,content:t.content};if(t.role==="assistant"){const a={role:"assistant",content:t.content||""};return t.toolCalls?.length&&(a.tool_calls=t.toolCalls.map(o=>({id:o.id,type:"function",function:{name:o.name,arguments:o.arguments}}))),a}return{role:"user",content:t.content}})}async function hG(e){const t=await $j(),a={messages:mG(e.messages)};e.tools.length&&(a.tools=e.tools);let o;try{o=await fetch(t+"/api/assistant/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:e.signal,credentials:jO})}catch(b){throw e.signal?.aborted?b:SO(b,t)}if(!o.ok||!o.body){const b=await o.text().catch(()=>"");let j=null;try{j=b?JSON.parse(b):null}catch{}const w=j?.error,S=wO(w,o.status);throw o.status===404?new Error(`这一版网关还没有 AI 助手接口(HTTP 404):后端还是旧的,重新编译 / 重启客户端后再试。${S}`):new Error(S)}const c=o.body.getReader(),d=new TextDecoder;let f="";const p=new Map;let g="";const v=b=>{for(const j of b.split(` `)){const w=j.trimEnd();if(!w.startsWith("data:"))continue;const S=w.slice(5).trim();if(!S)continue;if(S==="[DONE]")return!0;let N;try{N=JSON.parse(S)}catch{continue}const k=Array.isArray(N.choices)?N.choices[0]:void 0,E=k?.delta||{},D=typeof E.content=="string"?E.content:"";if(D&&e.onEvent({type:"delta",text:D}),Array.isArray(E.tool_calls))for(const C of E.tool_calls){const A=Number(C.index??0),R=p.get(A)||{id:"",name:"",arguments:""};typeof C.id=="string"&&C.id&&(R.id=C.id);const I=C.function||{};typeof I.name=="string"&&I.name&&(R.name=I.name),typeof I.arguments=="string"&&(R.arguments+=I.arguments),p.set(A,R)}typeof k?.finish_reason=="string"&&(g=k.finish_reason)}return!1};for(;;){const{done:b,value:j}=await c.read();if(b)break;f+=d.decode(j,{stream:!0});let w=f.indexOf(` `);for(;w>=0;){const S=f.slice(0,w);if(f=f.slice(w+2),v(S)){await c.cancel().catch(()=>{}),f="",w=-1;break}w=f.indexOf(` -`)}}const y=[...p.entries()].sort((b,j)=>b[0]-j[0]).map(([,b])=>b);y.length&&e.onEvent({type:"toolCalls",calls:y}),e.onEvent({type:"done",finishReason:g})}function qj(e){const t=String(e||"").trim();if(!t)return{};try{const a=JSON.parse(t);return a&&typeof a=="object"&&!Array.isArray(a)?a:{}}catch{return{}}}function Ja(){const e=window.workbuddyDesktop;if(!e)throw new Error(r("桌面桥不可用(本页需要在 Agent2API 客户端里打开)"));return e}function ju(){window.wbApp?.refresh?.()}function at(e,t=256){return typeof e=="string"?e.trim().slice(0,t):""}function Ui(e){return typeof e=="boolean"?e:void 0}function _f(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function wu(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"):[]}function Su(e){return(e instanceof Error?e.message:String(e)).replace(/^Error:\s*/,"")}async function xg(){const e=await Ja().getState?.();return(Array.isArray(e?.accounts)?e.accounts:[]).slice().sort((a,o)=>Number(a.priority??0)-Number(o.priority??0))}function Lf(e){return at(e.name)||at(e.nickname)||at(e.id)||"(未命名账号)"}function Gj(e,t){const a=t.trim();if(!a)throw new Error(r("没给账号名"));const o=e.find(p=>at(p.id)===a);if(o)return o;const c=e.filter(p=>Lf(p)===a);if(c.length===1)return c[0];const d=e.filter(p=>Lf(p).includes(a));if(d.length===1)return d[0];const f=(c.length?c:d).map(Lf).slice(0,6);throw f.length?new Error(r("「{name}」匹配到多个账号:{list},请用完整账号名重试",{name:a,list:f.join("、")})):new Error(r("没有找到账号「{name}」",{name:a}))}const gG={id:"list_models",label:r("获取模型列表"),kind:"read",desc:"读取各提供商的模型清单(模型 ID、所属提供商、是否启用、已挂的映射名)以及全部映射。回答「有哪些模型」「哪些模型在多家重复」「某个名字挂在哪」这类问题之前先调用它。",params:{type:"object",properties:{provider:{type:"string",description:"只看某一家(提供商 id,如 codearts / workbuddy);不填 = 全部"},keyword:{type:"string",description:"按模型 ID 或映射名做子串过滤;不填 = 不过滤"},enabledOnly:{type:"boolean",description:"true = 只看已启用的模型"}}},run:async e=>{const t=at(e.provider,64).toLowerCase(),a=at(e.keyword,128).toLowerCase(),o=Ui(e.enabledOnly)===!0,c=await Ja().getModelManage?.(),f=(Array.isArray(c?.models)?c.models:[]).filter(p=>!(t&&at(p.provider).toLowerCase()!==t||o&&p.enabled!==!0||a&&![at(p.id),at(p.name),...Array.isArray(p.aliases)?p.aliases.map(v=>at(v)):[]].join(" ").toLowerCase().includes(a))).map(p=>({provider:at(p.provider),id:at(p.id),enabled:p.enabled===!0,aliases:Array.isArray(p.aliases)?p.aliases.map(g=>at(g)):[]}));return{text:JSON.stringify({total:f.length,models:f.slice(0,400)}),summary:r("{n} 个模型",{n:f.length})}}},xG={id:"list_account_balance",label:r("查询账号余额"),kind:"read",desc:"查询各账号的余额 / 剩余额度(会向各上游发起真实的余额查询)。回答「还剩多少」「哪个账号快用完了」这类问题之前先调用它。",params:{type:"object",properties:{account:{type:"string",description:"只查某个账号(账号名或 id);不填 = 全部账号"}}},run:async e=>{const t=at(e.account,128),a=t?at(Gj(await xg(),t).id):"",o=await Ja().getAllBalances?.(a||void 0),c=Array.isArray(o?.results)?o.results:o,d=Array.isArray(c)?c:[];return{text:JSON.stringify({accounts:d.slice(0,60)}).slice(0,12e3),summary:r("{n} 个账号",{n:d.length})}}},bG={id:"set_model_enabled",label:r("启用 / 禁用模型"),kind:"write",desc:"开启或关闭某几个模型在网关上的可用性(粒度是「提供商 × 模型」)。禁用后下游请求不再路由到它。一次可以改多个。",params:{type:"object",properties:{items:{type:"array",description:"要改的模型列表",items:{type:"object",properties:{provider:{type:"string",description:"提供商 id"},id:{type:"string",description:"模型 ID"},enabled:{type:"boolean",description:"true = 启用,false = 禁用"}},required:["provider","id","enabled"]}}},required:["items"]},plan:e=>{const t=wu(e.items);return{lead:r("将修改 {n} 个模型的启停状态:",{n:t.length}),table:{head:[r("提供商"),r("模型"),r("改成")],rows:t.map(a=>[at(a.provider),at(a.id),Ui(a.enabled)===!1?r("禁用"):r("启用")])},note:r("改动立即生效;禁用后指向它的请求会落到下一个候选。")}},run:async e=>{const t=Ja(),a=wu(e.items),o=[];for(const c of a){const d=at(c.provider),f=at(c.id),p=Ui(c.enabled);if(!d||!f||p===void 0)throw new Error(r("参数不完整(需要 provider / id / enabled)"));await t.setModelState?.({provider:d,id:f,enabled:p}),o.push(`${p?"启用":"禁用"} ${d}/${f}`)}return ju(),{text:JSON.stringify({ok:!0,changed:o}),summary:r("已修改 {n} 个模型",{n:o.length})}}},vG={id:"set_model_mapping",label:r("设置模型映射 ID"),kind:"write",desc:"给模型新增或删除映射名(对外名)。同一对外名可以在多个提供商各挂一条:下游用同一个名字请求,网关按账号优先级主备切换;也可以给不同家的同名模型各加前缀(如 ca/claude-sonnet-4.5)来精确指定某一家。一次可以改多条。删掉的映射名只是不再对外可用,不删任何模型。",params:{type:"object",properties:{items:{type:"array",description:"要改的映射列表",items:{type:"object",properties:{provider:{type:"string",description:"提供商 id"},id:{type:"string",description:"上游模型 ID"},alias:{type:"string",description:"要新增 / 删除的映射名(对外名)"},action:{type:"string",enum:["add","remove"],description:"add = 新增映射,remove = 删除映射"}},required:["provider","id","alias","action"]}}},required:["items"]},plan:e=>{const t=wu(e.items),a=t.filter(d=>at(d.action)!=="remove").length,o=t.length-a,c=[];return a&&c.push(r("新增 {n} 条",{n:a})),o&&c.push(r("删除 {n} 条",{n:o})),{lead:r("将改动 {n} 条映射({parts}):",{n:t.length,parts:c.join("、")}),table:{head:[r("提供商"),r("上游模型"),r("操作"),r("映射名")],rows:t.map(d=>[at(d.provider),at(d.id),at(d.action)==="remove"?r("删除"):r("新增"),at(d.alias)])},note:r("只改映射名,不动上游模型 ID;映射立即生效(新对话即可用)。")}},run:async e=>{const t=Ja(),a=wu(e.items),o=[];for(const c of a){const d=at(c.provider),f=at(c.id),p=at(c.alias,128);if(!d||!f||!p)throw new Error(r("参数不完整(需要 provider / id / alias)"));at(c.action)==="remove"?(await t.removeModelMapping?.(p,f,d),o.push(`删除 ${p} → ${d}/${f}`)):(await t.addModelMapping?.(p,f,d),o.push(`新增 ${p} → ${d}/${f}`))}return ju(),{text:JSON.stringify({ok:!0,changed:o}),summary:r("已改动 {n} 条映射",{n:o.length})}}},kO=["maxInputTokens","maxOutputTokens","supportsToolCall","supportsImages","supportsVideo","supportsReasoning"],Kj={maxInputTokens:"上下文窗口",maxOutputTokens:"最大输出 Token",supportsToolCall:"工具调用",supportsImages:"图片识别",supportsVideo:"视频识别",supportsReasoning:"深度推理"},yG={id:"set_model_capability",label:r("修改模型能力"),kind:"write",desc:"修改某个模型对下游声明的能力位:上下文窗口、最大输出 Token、工具调用 / 图片 / 视频 / 深度推理四个布尔位。只传要改的键;布尔位给 null 表示恢复上游原值。",params:{type:"object",properties:{provider:{type:"string",description:"提供商 id"},id:{type:"string",description:"模型 ID"},capabilities:{type:"object",description:"要改的能力位(只写要改的键)",properties:{maxInputTokens:{type:["number","null"],description:"上下文窗口(token 数)"},maxOutputTokens:{type:["number","null"],description:"最大输出 token 数"},supportsToolCall:{type:["boolean","null"],description:"是否支持工具调用;null = 恢复上游原值"},supportsImages:{type:["boolean","null"],description:"是否支持图片识别;null = 恢复上游原值"},supportsVideo:{type:["boolean","null"],description:"是否支持视频识别;null = 恢复上游原值"},supportsReasoning:{type:["boolean","null"],description:"是否支持深度推理;null = 恢复上游原值"}}}},required:["provider","id","capabilities"]},plan:e=>{const t=e.capabilities&&typeof e.capabilities=="object"?e.capabilities:{},a=kO.filter(o=>o in t);return{lead:r("将修改 {model} 的 {n} 项能力:",{model:`${at(e.provider)} / ${at(e.id)}`,n:a.length}),table:{head:[r("能力"),r("改成")],rows:a.map(o=>{const c=t[o],d=c===null?r("恢复上游原值"):typeof c=="boolean"?r(c?"支持":"不支持"):String(c);return[Kj[o]||o,d]})},note:r("能力位决定下游看到的声明(能不能贴图、能塞多少上下文),不改上游的真实行为。")}},run:async e=>{const t=at(e.provider),a=at(e.id),o=e.capabilities&&typeof e.capabilities=="object"?e.capabilities:{},c={};for(const d of kO){if(!(d in o))continue;const f=o[d];if(f===null){c[d]=null;continue}if(d==="maxInputTokens"||d==="maxOutputTokens"){const p=_f(f);if(p===void 0)throw new Error(r("{key} 需要数字",{key:Kj[d]}));c[d]=Math.round(p)}else{const p=Ui(f);if(p===void 0)throw new Error(r("{key} 需要 true / false / null",{key:Kj[d]}));c[d]=p}}if(!t||!a||!Object.keys(c).length)throw new Error(r("参数不完整(需要 provider / id / capabilities)"));return await Ja().setModelCapabilities?.(t,a,c),ju(),{text:JSON.stringify({ok:!0,provider:t,id:a,capabilities:c}),summary:r("已修改 {n} 项能力",{n:Object.keys(c).length})}}},jG={id:"test_model",label:r("发起模型测试"),kind:"run",desc:"对某个模型发一次真实的对话请求,回报连通性、耗时与首字延迟。会消耗该账号的额度。回答「这个模型通不通 / 快不快」时用它。",params:{type:"object",properties:{provider:{type:"string",description:"提供商 id"},id:{type:"string",description:"模型 ID"},prompt:{type:"string",description:"测试用的用户提示词;不填 = 默认一句问候(最小请求)"}},required:["provider","id"]},plan:e=>({lead:r("将对 {model} 发起一次真实请求:",{model:`${at(e.provider)} / ${at(e.id)}`}),table:{head:[r("项"),r("值")],rows:[[r("提示词"),at(e.prompt)||r("(默认问候)")],[r("代价"),r("消耗该账号额度")]]},note:r("这是真实的上游请求,与生产走同一条链路(会记账,报表排除)。")}),run:async e=>{const t={provider:at(e.provider),model:at(e.id)},a=at(e.prompt,4e3);a&&(t.prompt=a);const o=await Ja().testModel?.(t),c=String(o?.status??""),d=o?.success===!0,f={ok:d,status:c,error:o?.error??null,reply:String(o?.reply??"").slice(0,1500),duration_ms:o?.duration_ms??null,ttfb_ms:o?.ttfb_ms??null,account:o?.account_name??null};return{text:JSON.stringify(f).slice(0,6e3),summary:d?r("连通 · {ms}ms",{ms:String(f.duration_ms??"")}):r("失败 · {status}",{status:c||"—"})}}},wG={id:"set_provider_order",label:r("调整提供商顺位"),kind:"write",desc:"调整某个提供商在账号全局队列里的**整组顺位**(第几组),决定路由时先试哪一家。这一家的所有账号会作为一整块移动。位置从 1 开始数。",params:{type:"object",properties:{provider:{type:"string",description:"提供商 id"},position:{type:"number",description:"目标组顺位(1 = 最前)"}},required:["provider","position"]},plan:e=>({lead:r("将把「{provider}」整组移到第 {position} 顺位:",{provider:at(e.provider)||r("(未指定)"),position:String(_f(e.position)??"?")}),note:r("队列是一次性整表提交(后端按新顺序重编优先级),移动会连带调整其它组的相对次序。")}),run:async e=>{const t=at(e.provider).toLowerCase(),a=_f(e.position);if(!t||a===void 0)throw new Error(r("参数不完整(需要 provider / position)"));const o=await xg(),c=[];for(const g of o){const v=at(g.id),y=at(g.provider).toLowerCase();if(!v)continue;const b=c[c.length-1];b&&b.provider===y?b.ids.push(v):c.push({provider:y,ids:[v]})}const d=c.findIndex(g=>g.provider===t);if(d<0)throw new Error(r("没有找到提供商「{provider}」的账号",{provider:t}));const f=Math.max(0,Math.min(c.length-1,Math.round(a)-1)),[p]=c.splice(d,1);return c.splice(f,0,p),await Ja().reorderAccounts?.(c.flatMap(g=>g.ids)),ju(),{text:JSON.stringify({ok:!0,provider:t,from:d+1,to:f+1,moved:p.ids.length}),summary:r("已移到第 {n} 顺位",{n:f+1})}}},SG={id:"set_account_order",label:r("调整账号优先级"),kind:"write",desc:"把某个账号移动到账号全局队列的第 N 顺位(1 = 最前)。位置决定主备与切换顺序:越靠前越先被使用。",params:{type:"object",properties:{account:{type:"string",description:"账号名或账号 id"},position:{type:"number",description:"目标顺位(1 = 最前)"}},required:["account","position"]},plan:e=>({lead:r("将把账号「{account}」移到第 {position} 顺位:",{account:at(e.account)||r("(未指定)"),position:String(_f(e.position)??"?")}),note:r("队列是一次性整表提交;位置越靠前,路由时越先被选中。")}),run:async e=>{const t=at(e.account,128),a=_f(e.position);if(!t||a===void 0)throw new Error(r("参数不完整(需要 account / position)"));const o=await xg(),c=Gj(o,t),d=at(c.id),f=o.map(v=>at(v.id)).filter(Boolean),p=f.indexOf(d);if(p<0)throw new Error(r("账号不在当前队列里"));f.splice(p,1);const g=Math.max(0,Math.min(f.length,Math.round(a)-1));return f.splice(g,0,d),await Ja().reorderAccounts?.(f),ju(),{text:JSON.stringify({ok:!0,account:Lf(c),from:p+1,to:g+1}),summary:r("已移到第 {n} 顺位",{n:g+1})}}},NG={id:"set_account_enabled",label:r("启用 / 禁用账号"),kind:"write",desc:"开启或关闭某几个账号的转发资格。禁用只是把它移出队列(余额仍可查),但**如果某条线路只剩它**,禁用会直接断供。一次可以改多个。",params:{type:"object",properties:{items:{type:"array",description:"要改的账号列表",items:{type:"object",properties:{account:{type:"string",description:"账号名或账号 id"},enabled:{type:"boolean",description:"true = 启用,false = 禁用"}},required:["account","enabled"]}}},required:["items"]},plan:e=>{const t=wu(e.items),a=t.filter(o=>Ui(o.enabled)===!1).length;return{lead:r("将修改 {n} 个账号的启用状态(其中禁用 {k} 个):",{n:t.length,k:a}),table:{head:[r("账号"),r("改成")],rows:t.map(o=>[at(o.account),Ui(o.enabled)===!1?r("禁用"):r("启用")])},note:r("禁用会把账号移出转发队列;若这条线路没有别的可用账号,请求会直接失败。")}},run:async e=>{const t=Ja(),a=wu(e.items),o=await xg(),c=[];for(const d of a){const f=Ui(d.enabled);if(f===void 0)throw new Error(r("参数不完整(需要 account / enabled)"));const p=Gj(o,at(d.account,128));await t.updateAccount?.(at(p.id),{enabled:f}),c.push(`${f?"启用":"禁用"} ${Lf(p)}`)}return ju(),{text:JSON.stringify({ok:!0,changed:c}),summary:r("已修改 {n} 个账号",{n:c.length})}}},bg=[gG,xG,bG,vG,yG,jG,wG,SG,NG];function Yj(e){return bg.find(t=>t.id===e)}function kG(e){return bg.filter(t=>e[t.id]).map(t=>({type:"function",function:{name:t.id,description:t.desc,parameters:t.params}}))}r("获取模型列表"),r("读各提供商的模型清单、映射名与启用状态。"),r("查询账号余额"),r("读各账号的额度 / 剩余用量。"),r("启用 / 禁用模型"),r("开关模型的对外可用性,不改其它属性。"),r("设置模型映射 ID"),r("新增 / 删除映射名,支持批量加前缀与同名合并到多家。"),r("修改模型能力"),r("改上下文窗口 / 最大输出 Token / 工具调用等能力位。"),r("发起模型测试"),r("对指定模型发一次真实请求,回报连通性与耗时。"),r("调整提供商顺位"),r("改某一家的整组顺位(先试哪一家)。"),r("调整账号优先级"),r("改账号在全局队列里的名次,决定主备与切换顺序。"),r("启用 / 禁用账号"),r("禁用会把账号移出转发队列,线路可能因此断供。");const CO=12;function zf(e,t){return window.wbIcons?.icon?.(e,t)||""}function CG(e){const t=window.wbMarkdown;return t?.render?t.render(e):e.replace(/[&<>]/g,a=>({"&":"&","<":"<",">":">"})[a]||a)}function TG({tone:e}){return e==="plain"?s.jsx("span",{className:"asst-tc-ico",dangerouslySetInnerHTML:{__html:zf("spark",13)}}):s.jsx("span",{className:Ue("asst-tc-ico",e),children:e==="warn"?"!":"✕"})}function EG({item:e,onConfirm:t}){const a=Yj(e.call.name),o=a?.label||e.call.name,c=qj(e.call.arguments),d=Object.keys(c).length?JSON.stringify(c,null,2):"";return s.jsxs("div",{className:Ue("asst-tool-card",e.state==="confirm"&&"confirm",e.state==="confirm"&&a?.kind==="run"&&"danger",e.state==="failed"&&"failed",e.state==="running"&&"running"),children:[s.jsxs("div",{className:"asst-tc-head",children:[e.state==="running"?s.jsx("span",{className:"asst-tc-ico",children:s.jsx("span",{className:"spin"})}):s.jsx(TG,{tone:e.state==="failed"?"bad":e.state==="confirm"?"warn":"plain"}),s.jsx("span",{className:"asst-tc-name",children:o}),e.state==="confirm"&&s.jsx("span",{className:"badge tag warn",children:r("待确认")}),e.state==="done"&&s.jsxs("span",{className:"asst-tc-state",children:["✓ ",e.summary||r("完成")]}),e.state==="failed"&&s.jsx("span",{className:"asst-tc-state bad",children:r("失败")}),e.state==="cancelled"&&s.jsx("span",{className:"asst-tc-state plain",children:r("已取消")})]}),e.state==="confirm"&&e.plan&&s.jsxs("div",{className:"asst-tc-plan",children:[e.plan.lead,e.plan.table&&s.jsxs("table",{className:"asst-mini-table",children:[s.jsx("thead",{children:s.jsx("tr",{children:e.plan.table.head.map((f,p)=>s.jsx("th",{children:f},p))})}),s.jsx("tbody",{children:e.plan.table.rows.slice(0,20).map((f,p)=>s.jsx("tr",{children:f.map((g,v)=>s.jsx("td",{className:v===f.length-1?"mono hl":"",children:g},v))},p))})]}),e.plan.table&&e.plan.table.rows.length>20&&s.jsx("div",{className:"hint",children:r("(仅显示前 20 条,共 {n} 条)",{n:e.plan.table.rows.length})}),e.plan.note&&s.jsx("div",{className:"hint",children:e.plan.note})]}),e.state==="failed"&&e.error&&s.jsx("div",{className:"asst-tc-error",children:e.error}),e.state==="done"&&e.detail&&s.jsxs("details",{children:[s.jsx("summary",{className:"asst-tc-result",style:{cursor:"pointer"},children:r("查看结果")}),s.jsx("pre",{className:"asst-tc-json",children:e.detail})]}),e.state!=="confirm"&&d&&s.jsxs("details",{children:[s.jsx("summary",{className:"asst-tc-result",style:{cursor:"pointer"},children:r("查看参数")}),s.jsx("pre",{className:"asst-tc-json",children:d})]}),e.state==="confirm"&&s.jsxs("div",{className:"asst-tc-foot",children:[s.jsx("span",{className:Ue("hint",a?.kind==="run"&&"danger"),children:a?.kind==="run"?r("这会真实发起上游请求并消耗额度"):r("确认后立即生效")}),s.jsx(se,{size:"sm",variant:a?.kind==="run"?"destructive":"default",onClick:()=>t(!0),children:r("执行")}),s.jsx(se,{size:"sm",variant:"outline",onClick:()=>t(!1),children:r("取消")})]})]})}function AG(){const[e,t]=x.useState(null),[a,o]=x.useState([]),[c,d]=x.useState([]),[f,p]=x.useState(!1),[g,v]=x.useState(!1),[y,b]=x.useState(""),[j,w]=x.useState(""),[S,N]=x.useState(!1),k=x.useRef([]),E=x.useRef([]),D=x.useRef(null),C=x.useRef(null),A=x.useRef(null),R=x.useRef(!1),I=x.useRef(0),P=x.useRef(null),O=x.useRef(0),_=x.useCallback(()=>{d(k.current.slice())},[]);x.useEffect(()=>{const M=A.current;if(!M)return;M.scrollHeight-M.scrollTop-M.clientHeight<160&&(M.scrollTop=M.scrollHeight)},[c]);const L=x.useCallback(async()=>{if(!R.current){R.current=!0;try{const M=await fG();t(M),N(!1),I.current=0}catch(M){N(!0),w(r("加载助手设置失败:{message}",{message:Su(M)})),I.current<3&&(I.current+=1,R.current=!1,setTimeout(()=>{L()},4e3))}try{o(await dG())}catch(M){w(U=>U||r("读取模型清单失败:{message}",{message:Su(M)}))}}},[]);x.useEffect(()=>{const M=window;return M.wbAssistant={activate:()=>{L()}},L(),()=>{delete M.wbAssistant}},[L]);const H=x.useMemo(()=>{const M={};for(const U of bg)M[U.id]=e?.tools?.[U.id]??!1;return M},[e]),B=x.useMemo(()=>kG(H),[H]),z=Object.values(H).filter(Boolean).length,Q=e?.model??null,K=x.useCallback(async(M,U,Z)=>{for(let ae=U;ae{if(O.current>=CO){k.current.push({kind:"notice",text:r("这一轮来回已达 {n} 次上限,我先停下等你指示(可以换个说法,或拆成几步让我做)。",{n:CO}),bad:!0}),_();return}O.current+=1,p(!0),w("");const M=new AbortController;C.current=M;const U=k.current.push({kind:"bot",text:"",streaming:!0})-1;_();let Z=[],ae=!1;try{await hG({messages:E.current,tools:B,signal:M.signal,onEvent:ie=>{if(ie.type==="delta"){const ge=k.current[U];ge&&ge.kind==="bot"&&(k.current[U]={...ge,text:ge.text+ie.text},_())}ie.type==="toolCalls"&&(Z=ie.calls)}})}catch(ie){ae=!0;const ge=Su(ie),ee=k.current[U],fe=ee&&ee.kind==="bot"?ee.text:"";fe?k.current[U]={kind:"bot",text:fe}:k.current.splice(U,1);const te=M.signal.aborted;k.current.push({kind:"notice",text:te?r("已停止这次回答。"):r("请求失败:{message}",{message:ge}),bad:!te}),_()}finally{C.current=null}if(ae){p(!1);return}const ce=k.current[U];ce&&ce.kind==="bot"&&(k.current[U]={...ce,streaming:!1});const J=ce&&ce.kind==="bot"?ce.text:"";if(E.current.push({role:"assistant",content:J,toolCalls:Z.length?Z:void 0}),_(),!Z.length){p(!1);return}await K(Z,0,[])},[B,K,_]);P.current=X;const q=x.useCallback(async M=>{const U=D.current;if(!U)return;D.current=null,v(!1);const Z=U.calls[U.index],ae=Yj(Z.name),ce=qj(Z.arguments);if(!M||!ae)k.current[U.cardIndex]={kind:"tool",call:Z,state:"cancelled"},U.collected.push({toolCallId:Z.id,content:"用户取消了这次操作,没有做任何改动。"}),_();else{k.current[U.cardIndex]={kind:"tool",call:Z,state:"running"},p(!0),_();try{const J=await ae.run(ce);k.current[U.cardIndex]={kind:"tool",call:Z,state:"done",summary:J.summary,detail:J.text},U.collected.push({toolCallId:Z.id,content:J.text})}catch(J){const ie=Su(J);k.current[U.cardIndex]={kind:"tool",call:Z,state:"failed",error:ie},U.collected.push({toolCallId:Z.id,content:`工具执行失败:${ie}`})}_()}await K(U.calls,U.index+1,U.collected)},[K,_]),$=x.useCallback(async M=>{const U=M.trim();if(!(!U||f||g)){if(O.current=0,k.current.push({kind:"user",text:U}),E.current.push({role:"user",content:U}),b(""),_(),!e){k.current.push({kind:"notice",text:r("助手设置没读出来,现在还不能发消息 —— 看输入框下方的提示。"),bad:!0}),_();return}if(!e.model){k.current.push({kind:"notice",text:r("还没有选择对话模型:先在下方选一个(或去「设置 → AI 助手」里选)。"),bad:!0}),_();return}await X()}},[g,f,e,X,_]),Y=x.useCallback(()=>{C.current?.abort()},[]),F=x.useCallback(()=>{C.current?.abort(),D.current=null,k.current=[],E.current=[],v(!1),p(!1),w(""),_()},[_]),G=x.useCallback(async M=>{if(!M)return;if(!e){w(r("助手设置没读出来,暂时存不了对话模型 —— 看输入框下方的提示。"));return}const U={...e,model:M};t(U);try{await pG(U)}catch(Z){w(r("保存对话模型失败:{message}",{message:Su(Z)}))}},[e]),W=f||g,le=x.useRef(null);return s.jsxs("div",{className:"asst-layout",children:[s.jsxs("div",{className:"asst-top",children:[s.jsxs(ft,{value:Q??"",onValueChange:M=>{G(String(M))},children:[s.jsx(mt,{className:"asst-model-pick","aria-label":r("对话模型"),children:s.jsx(pt,{children:Q?s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx("span",{className:Ue("dot","ok")}),s.jsx("span",{className:"mono",children:Q})]}):r("选择模型…")})}),s.jsxs(ht,{children:[a.length===0&&s.jsx(qe,{value:"none",disabled:!0,children:r("没有可用的模型")}),a.map(M=>s.jsx(qe,{value:M,children:M},M))]})]}),s.jsx("span",{className:"asst-top-hint",children:r("助手走本地网关,消耗所选账号的额度")}),s.jsx("span",{className:"spacer"}),s.jsx(se,{variant:"ghost",size:"sm",onClick:F,disabled:f||g||!c.length,children:r("新对话")})]}),s.jsxs("div",{className:"asst-scroll",ref:A,children:[c.length===0&&s.jsxs("div",{className:"asst-empty",children:[s.jsx("div",{className:"empty-logo",dangerouslySetInnerHTML:{__html:zf("spark",26)||""}}),s.jsx("h3",{children:r("AI 助手")}),s.jsxs("p",{children:[r("用一句话让我查或改本机的模型转发配置。"),s.jsx("br",{}),r("我会在动手前把改动列给你确认。")]}),s.jsx("div",{className:"asst-suggests",children:[r("看看哪些模型在多家重复了"),r("测一下当前最快的模型通不通"),r("CodeArts 的账号余额还剩多少?"),r("把重复的模型加上家名前缀区分开")].map(M=>s.jsxs("button",{type:"button",onClick:()=>{$(M)},children:["“",M,"”"]},M))}),e!==null&&z===0&&s.jsx("div",{className:"asst-empty-warn",children:r("当前一个工具都没勾选,助手只能纯聊天。去「设置 → AI 助手 → 工具」里勾上需要的工具。")}),S&&s.jsx("div",{className:"asst-empty-warn bad",children:j||r("助手设置读取失败,工具可能已过时。")})]}),c.map((M,U)=>M.kind==="user"?s.jsx("div",{className:"asst-msg user",children:s.jsx("div",{className:"bubble",children:M.text})},U):M.kind==="bot"?!M.text&&M.streaming?s.jsxs("div",{className:"asst-msg bot",children:[s.jsxs("div",{className:"who",children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:zf("spark",14)||""}})," ",r("助手")]}),s.jsx("div",{className:"body",children:s.jsx("span",{className:"spin"})})]},U):s.jsxs("div",{className:"asst-msg bot",children:[s.jsxs("div",{className:"who",children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:zf("spark",14)||""}})," ",r("助手")]}),s.jsxs("div",{className:"body",children:[s.jsx("span",{dangerouslySetInnerHTML:{__html:CG(M.text)}}),M.streaming&&s.jsx("span",{className:"asst-caret"})]})]},U):M.kind==="notice"?s.jsx("div",{className:"asst-msg bot",children:s.jsx("div",{className:Ue("asst-empty-warn",M.bad&&"bad"),style:{margin:0},children:M.text})},U):s.jsx(EG,{item:M,onConfirm:Z=>{q(Z)}},U))]}),s.jsxs("div",{className:"asst-composer",children:[s.jsxs("div",{className:"asst-ta-wrap",children:[s.jsx(Qc,{ref:le,rows:1,value:y,placeholder:r(W?"等这一轮跑完…":"直接说要改什么 / 查什么…(Enter 发送,Shift+Enter 换行)"),disabled:W,onChange:M=>{b(M.currentTarget.value);const U=M.currentTarget;U.style.height="auto",U.style.height=`${Math.min(U.scrollHeight,132)}px`},onKeyDown:M=>{M.key==="Enter"&&!M.shiftKey&&!M.nativeEvent.isComposing&&(M.preventDefault(),$(y))}}),f?s.jsx("button",{type:"button",className:"asst-send stop",title:r("停止"),onClick:Y,children:"■"}):s.jsx("button",{type:"button",className:"asst-send",title:r("发送"),disabled:W||!y.trim(),onClick:()=>{$(y)},children:"➤"})]}),s.jsxs("div",{className:"asst-composer-foot",children:[s.jsxs("span",{className:"tools-state",children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:zf("settings",12)||""}}),r("已注入 {n} / {total} 个工具 · 系统提示词:{state}",{n:z,total:bg.length,state:e?.systemPromptEnabled?r("开"):r("关")})]}),s.jsx("span",{className:"spacer"}),j?s.jsxs("span",{className:"hint",children:[j,S&&s.jsx("button",{type:"button",className:"asst-tc-more",onClick:()=>{L()},children:r("重试")})]}):Q?s.jsx("span",{className:"hint",children:r("回复由 {model} 生成 · 走本地网关",{model:Q})}):null]})]})]})}const TO='.page[data-page="assistant"]';let Xj=null;function EO(){if(Xj)return;const e=document.querySelector(TO);e&&(e.replaceChildren(),Xj=vn.createRoot(e),Xj.render(s.jsx(AG,{})))}document.querySelector(TO)?EO():document.addEventListener("DOMContentLoaded",EO,{once:!0}),$j().catch(()=>{});function Ir(){return Pe().workbuddyDesktop??{}}function AO(){return window}const RO="workbuddy-desktop-checkin-tab",RG=["center","schedule","records"];function OG(){try{const e=localStorage.getItem(RO);return RG.includes(e)?e:"center"}catch{return"center"}}function OO(e){if(e!==hs.tab){try{localStorage.setItem(RO,e)}catch{}Js({tab:e})}}async function vg(e){OO(e),hs.loaded||await Ol()}let hs={version:0,tab:OG(),snapshot:null,loaded:!1,loadError:"",expanded:new Set,runningAll:!1,autoSaving:!1,autoTimeDraft:null,keepaliveSaving:!1,keepaliveDraft:null,signing:new Set,onboarding:new Map,growth:new Map};const Qj=new Set;function MG(){for(const e of Qj)e()}function Js(e){hs={...hs,...e,version:hs.version+1},MG()}function ur(){return hs}function MO(e){return Qj.add(e),()=>Qj.delete(e)}function DG(e){const t=typeof e?.key=="string"?e.key:"";return t?{key:t,title:typeof e.title=="string"&&e.title?e.title:t,group:typeof e.group=="string"&&e.group?e.group:"",points:Number(e.points)||0,done:e.done===!0,blocked:e.blocked===!0}:null}function Zj(e){return(Array.isArray(e)?e:[]).map(DG).filter(a=>a!==null)}function cs(e){return Number(e)||0}async function Ol(){try{const e=await Ir().getCheckinCenter?.();if(!e)throw new Error(r("后端未返回签到中心数据"));Js({snapshot:e,loaded:!0,loadError:"",autoTimeDraft:null,keepaliveDraft:null}),IG(e.extras?.onboarding??[])}catch(e){Js({loaded:!0,loadError:ut(e)})}}function IG(e){for(const t of e){const a=t.settled;if(!a||typeof a!="object")continue;const o=hs.onboarding.get(t.id);if(o?.status==="loaded"&&o.unclaimed>0)continue;const c=Zj(a.tasks),d=cs(a.at);Co(t.id,{status:"loaded",error:void 0,checkedAt:void 0,settled:!0,settledAt:d>0?d:void 0,tasks:c,unclaimed:0,earned:cs(a.earned),total:cs(a.total)})}}function DO(e){const t=new Set(hs.expanded);t.has(e)?t.delete(e):t.add(e),Js({expanded:t})}function Wj(e){const t=`onb:${e}`,a=new Set(hs.expanded);a.has(t)?a.delete(t):a.add(t),Js({expanded:a})}function IO(e){return hs.expanded.has(`onb:${e}`)}async function PG(){if(!hs.runningAll){Js({runningAll:!0});try{const e=await Ir().runAutoCheckinNow?.();if(e){const t=cs(e.succeeded),a=cs(e.active),o=cs(e.total),c=cs(e.failedCount),d=a>0?r(",日活保活 {n} 个",{n:a}):"";c>0?Le(r("签到完成:{succeeded}/{total} 成功{active},{failed} 个失败",{succeeded:t,total:o,active:d,failed:c}),"err"):Le(r("✅ 签到完成:{succeeded}/{total} 个账号成功领取{active}",{succeeded:t,total:o,active:d})),AO().wbAccountsView?.refreshUsageAfterCheckin?.(null)}}catch(e){Le(r("签到失败:{error}",{error:ut(e)}),"err")}finally{Js({runningAll:!1}),await Ol(),PO(ur().snapshot?.extras.onboarding??[]),Pe().wbApp?.refresh?.()}}}async function yg(e,t="checkin"){const a=`${e}:${t}`;if(hs.signing.has(a))return;const o=new Set(hs.signing);o.add(a),Js({signing:o});try{let c;t==="checkin"?c=(await Ir().checkinAllAccounts?.(e))?.results?.[0]:c=await Ir().runCheckinActivity?.(e,t)??void 0;const d=c?.claim,f=c?.activity,p=f?.report?.succeeded===!0;c?.error?Le(r("签到失败:{error}",{error:String(c.error)}),"err"):t==="keepalive"?f?.pokeSucceeded===!0||p?Le(r("✅ {message}",{message:d?.msg||r("活跃保活完成")})):Le(d?.msg||r("活跃保活失败"),"err"):d?.success===!0?Le(r("✅ {message}",{message:d.msg||r("签到成功")})):d?.alreadyCompleted===!0?Le(d?.msg||r("今日已领取"),"err"):p?Le(r("✅ {message}",{message:d?.msg||r("活跃上报完成,但活动未开启")})):f?.pokeSucceeded===!0?Le(r("✅ {message}",{message:d?.msg||r("活跃保活完成,但活动未开启")})):Le(d?.msg||r("未领取"),"err"),AO().wbAccountsView?.refreshUsageAfterCheckin?.(e)}catch(c){Le(r("签到失败:{error}",{error:ut(c)}),"err")}finally{const c=new Set(ur().signing);c.delete(a),Js({signing:c}),await Ol();const d=(ur().snapshot?.extras.onboarding??[]).filter(f=>f.id===e);PO(d),Pe().wbApp?.refresh?.()}}function jg(e){Js({keepaliveDraft:e.map(t=>t.trim()).filter(Boolean)})}async function _G(e){const t=e.map(a=>a.trim()).filter(Boolean);if(!ur().keepaliveSaving){Js({keepaliveSaving:!0});try{const a=await Ir().saveCheckinKeepalive?.(t);if(a){const o=ur().snapshot;Js({snapshot:o&&{...o,keepalive:a},keepaliveDraft:null}),Le(r("已保存:保活模型链"))}}catch(a){Le(r("保存失败:{error}",{error:ut(a)}),"err")}finally{Js({keepaliveSaving:!1})}}}async function PO(e){for(const t of e)LG(t.id)||await Jj(t.id);for(const t of e){const a=ur().onboarding.get(t.id);a?.status!=="loaded"||a.claiming||a.settled||(t.provider==="officeace"||a.unclaimed>0)&&await _O(t.id)}}function LG(e){return hs.onboarding.get(e)?.settled===!0}function Nu(e){return hs.onboarding.get(e)??{status:"idle",tasks:[],unclaimed:0,earned:0,total:0,claiming:!1}}function Co(e,t){const a=new Map(hs.onboarding);a.set(e,{...Nu(e),...t}),Js({onboarding:a})}async function Jj(e,t){const a=Nu(e);if(!(a.status==="loading"||a.claiming)){Co(e,{status:"loading",error:void 0,settled:!1});try{const o=await Ir().getOnboardingTasks?.(e,t?.refresh===!0),c=Zj(o?.tasks),d=o?.settled===!0;Co(e,{status:"loaded",checkedAt:Date.now(),tasks:c,unclaimed:c.filter(f=>!f.done&&!f.blocked).length,earned:cs(o?.earned),total:cs(o?.total),settled:d,settledAt:d&&cs(o?.settledAt)||void 0}),t?.expand===!0&&c.length>0&&!IO(e)&&Wj(e)}catch(o){Co(e,{status:"error",error:ut(o),settled:!1})}}}async function _O(e){const t=Nu(e);if(!(t.claiming||t.status!=="loaded")){Co(e,{claiming:!0});try{Co(e,{tasks:Nu(e).tasks.map(b=>b.done?b:{...b,claiming:!0,error:void 0})});const a=await Ir().claimOnboardingTasks?.(e),o=new Map,c=Array.isArray(a?.results)?a.results:[];for(const b of c){const j=typeof b?.key=="string"?b.key:"";j&&b?.ok!==!0&&o.set(j,String(b?.error||r("领取失败")))}const d=Zj(a?.tasks),f=(d.length?d:Nu(e).tasks).map(b=>({...b,claiming:!1,error:o.get(b.key)})),p=f.filter(b=>b.done&&!o.has(b.key)).length,g=a?.settled===!0;Co(e,{claiming:!1,checkedAt:Date.now(),tasks:f,unclaimed:f.filter(b=>!b.done&&!b.blocked).length,earned:cs(a?.earned),total:cs(a?.total),settled:g,settledAt:g&&cs(a?.settledAt)||void 0});const v=f.filter(b=>b.error&&!b.done).length,y=typeof a?.message=="string"?a.message.trim():"";v?Le(r("新手福利有 {n} 项领取失败,可重试",{n:v}),"err"):y?Le(y,"ok"):p&&Le(r("✅ 新手福利领取完成,累计 {n} 积分",{n:cs(a?.earned)}))}catch(a){const o=ut(a);Co(e,{claiming:!1,tasks:Nu(e).tasks.map(c=>({...c,claiming:!1,error:c.done?void 0:o}))}),Le(r("领取失败:{error}",{error:o}),"err")}finally{await Ol()}}}function LO(e){return(Array.isArray(e)?e:[]).map(a=>{const o=a??{},c=typeof o.code=="string"?o.code:"";return c?{code:c,title:typeof o.title=="string"&&o.title?o.title:c,description:typeof o.description=="string"?o.description:"",status:typeof o.status=="string"?o.status:"",current:cs(o.current),target:cs(o.target),locked:o.locked===!0,unlockAt:o.unlockAt,supported:o.supported===!0,unforgeable:o.unforgeable===!0,unforgeableReason:typeof o.unforgeableReason=="string"?o.unforgeableReason:"",kind:typeof o.kind=="string"?o.kind:"",source:typeof o.source=="string"?o.source:""}:null}).filter(a=>a!==null)}function zO(e){return(Array.isArray(e)?e:[]).map(a=>{const o=a??{},c=typeof o.code=="string"?o.code:"";return c?{code:c,outcome:typeof o.outcome=="string"?o.outcome:"failed",message:typeof o.message=="string"?o.message:"",credit:cs(o.credit),energy:cs(o.energy)}:null}).filter(a=>a!==null)}function Vi(e){return hs.growth.get(e)??{status:"idle",energy:null,streak:null,tasks:[],travel:null,school:null,running:!1,runningSchool:!1,runningTravel:!1}}function Pr(e,t){const a=new Map(hs.growth);a.set(e,{...Vi(e),...t}),Js({growth:a})}function zG(e){return hs.expanded.has(`growth:${e}`)}function BO(e){const t=`growth:${e}`,a=new Set(hs.expanded);a.has(t)?a.delete(t):a.add(t),Js({expanded:a})}async function wg(e){const t=Vi(e);if(!(t.status==="loading"||t.running)){Pr(e,{status:"loading",error:void 0});try{const a=await Ir().getGrowthStatus?.(e),o=a?.tasks??{},c=a?.travel??null,d=a?.school??null;Pr(e,{status:"loaded",checkedAt:Date.now(),energy:a?.energy===null||a?.energy===void 0?null:cs(a.energy),streak:a?.streak===null||a?.streak===void 0?null:cs(a.streak),tasks:LO(o.tasks),travel:c,school:d?{...d,tasks:LO(d.tasks)}:null,error:typeof o.error=="string"?o.error:void 0})}catch(a){Pr(e,{status:"error",error:ut(a)})}}}async function HO(e,t){const a=Vi(e);if(a.running)return;const o=(a.tasks??[]).filter(g=>!g.supported||g.unforgeable===!0||g.locked===!0?!1:t==="claim"?g.status==="completed"||g.current>=g.target&&g.status!=="claimed":g.status!=="claimed");if(o.length===0){Le(r("没有需要执行的任务"));return}Pr(e,{running:!0,results:[],error:void 0});let c=0,d=0,f=0,p=0;for(const g of o)try{const v=await Ir().runGrowthTask?.(e,g.code,t),y=zO([v])[0];y&&(Pr(e,{results:[...Vi(e).results??[],y]}),c+=y.credit??0,d+=y.energy??0,(y.outcome==="done"||y.outcome==="already")&&(f+=1),y.outcome==="failed"&&(p+=1))}catch(v){p+=1,Pr(e,{results:[...Vi(e).results??[],{code:g.code,outcome:"failed",message:ut(v),credit:0,energy:0}]})}Pr(e,{running:!1}),p>0?Le(r("成长任务完成({done} 项成功、{failed} 项失败),积分 +{credit} 能量 +{energy}",{done:f,failed:p,credit:c,energy:d}),"err"):Le(r("✅ 成长任务执行完成:积分 +{credit} 能量 +{energy}",{credit:c,energy:d})),await wg(e)}async function BG(e,t){if(!Vi(e).runningSchool){Pr(e,{runningSchool:!0,error:void 0});try{const o=await Ir().runGrowthSchool?.(e,t),c=zO(o?.results),d=o?.lottery??null;Pr(e,{runningSchool:!1,results:c,schoolText:c.length?c.map(f=>`${f.code}:${f.message}`).join(";"):void 0,lotteryText:d?String(d.message??r("已抽 {n} 次",{n:cs(d.drawn)})):void 0,checkedAt:Date.now()}),Le(d?r("开学季执行完成:{message}",{message:String(d.message??"")}):r("✅ 开学季任务执行完成")),await wg(e)}catch(o){Pr(e,{runningSchool:!1,error:ut(o)}),Le(r("开学季执行失败:{error}",{error:ut(o)}),"err")}}}async function HG(e){if(!Vi(e).runningTravel){Pr(e,{runningTravel:!0,error:void 0});try{const a=await Ir().runGrowthTravel?.(e),o=String(a?.message??""),c=String(a?.outcome??"");Pr(e,{runningTravel:!1,checkedAt:Date.now()}),c==="failed"?Le(r("猫猫旅行失败:{message}",{message:o}),"err"):Le(r("猫猫旅行:{message}",{message:o})),await wg(e)}catch(a){Pr(e,{runningTravel:!1,error:ut(a)}),Le(r("猫猫旅行失败:{error}",{error:ut(a)}),"err")}}}function UG(e){return e.totalCount?e.doneCount>=e.totalCount?"done":e.doneCount>0?"part":"todo":"none"}function VG(e){const a=(Array.isArray(e?.schedules)?e.schedules:[]).filter(o=>o.enabled===!0).map(o=>Number(o.nextRunAt)).filter(o=>Number.isFinite(o)&&o>0);return a.length?Math.min(...a):null}let To={version:0,data:null,loaded:!1,loadError:"",saving:!1,runningId:null,editingId:null};const ew=new Set;function FG(){for(const e of ew)e()}function _r(e){To={...To,...e,version:To.version+1},FG()}function UO(){return To}function $G(e){return ew.add(e),()=>ew.delete(e)}function ku(){return Pe().workbuddyDesktop??{}}async function VO(){try{const e=await ku().getCheckinSchedules?.();if(!e)throw new Error(r("后端未返回定时签到数据"));_r({data:e,loaded:!0,loadError:""})}catch(e){_r({loaded:!0,loadError:ut(e)})}}function Sg(e){e&&_r({data:e,loadError:""}),Ol()}async function qG(e){if(!To.saving){_r({saving:!0});try{const t=await ku().saveAutoCheckin?.({enabled:e});Sg(t),Le(r(e?"✅ 定时签到已开启":"定时签到已关闭"))}catch(t){Le(r("保存失败:{error}",{error:ut(t)}),"err")}finally{_r({saving:!1})}}}async function FO(e){if(!To.saving){_r({saving:!0});try{const t=await ku().saveCheckinSchedule?.(e);Sg(t),_r({editingId:null}),Le(r("已保存:定时条目"))}catch(t){Le(r("保存失败:{error}",{error:ut(t)}),"err")}finally{_r({saving:!1})}}}async function GG(e,t){await FO({id:e.id,label:e.label??"",enabled:t,time:e.time??"",providers:Array.isArray(e.providers)?e.providers:[]})}async function KG(e){if(!To.saving){_r({saving:!0});try{await ku().deleteCheckinSchedule?.(e),Sg(await ku().getCheckinSchedules?.()),Le(r("已删除定时条目"))}catch(t){Le(r("删除失败:{error}",{error:ut(t)}),"err")}finally{_r({saving:!1})}}}async function YG(e){if(!To.runningId){_r({runningId:e});try{const t=await ku().runCheckinSchedule?.(e)??void 0,a=o=>Number(o)||0;if(t){const o=a(t.succeeded),c=a(t.active),d=a(t.total),f=a(t.failedCount),p=c>0?r(",日活保活 {n} 个",{n:c}):"";f>0?Le(r("签到完成:{succeeded}/{total} 成功{active},{failed} 个失败",{succeeded:o,total:d,active:p,failed:f}),"err"):Le(r("✅ 签到完成:{succeeded}/{total} 个账号成功领取{active}",{succeeded:o,total:d,active:p})),Sg(t)}}catch(t){Le(r("执行失败:{error}",{error:ut(t)}),"err")}finally{_r({runningId:null}),await Ol()}}}function tw(e){_r({editingId:e})}const XG=r("到点后自动签到勾选提供商的可用账号(WorkBuddy 国内版走每日签到接口,国际版走每日活跃任务:探测活动、领日活奖励、再用免费模型保活;小浣熊走桌面端每日积分链路;AutoClaw 走官方客户端的每日签到任务;Qoder 中国版走活动领取,没被下发活动的账号会得到中性提示;Qoder 国际版要先带设备风控身份(本机 Qoder 客户端 / qodercli 的 UMID 组件生成)才能看到「每日 100 Credits」活动,缺组件时会得到明确的说明而不是报错;Trae 领 SOLO 的每日签到积分(按自然日 0 点重置),上游没对该账号开活动、或凭据里没有设备号时得到的是「未领取 + 具体原因」而不是报错;Loomy 每天替账号打一次首次登录积分;KukuAI 领「免费领积分」的每日任务;CodeArts 领当日的运营福利(领取 → 确认 → 回读核实,自动执行受每天 6 次 / 间隔 10 分钟的写请求限流);OfficeAce 果办一次领当天全部奖励(每日签到 + 新人礼))。错过时点开机后会自动补签,不会因为当时没开机而漏掉。各家签到接口都是幂等的,重复执行不会重复领取。");function QG(){const[e,t]=x.useState(UO());return x.useEffect(()=>$G(()=>t(UO())),[]),e}function ZG(){const[e,t]=x.useState(ur());return x.useEffect(()=>MO(()=>t(ur())),[]),e}function $O(e,t){const a=Array.isArray(e.providers)?e.providers:[];return t.filter(o=>a.includes(o.id)).map(o=>o.label)}function WG(e,t){const a=$O(e,t);return a.length?t.length>0&&a.length>=t.length?r("全部 {n} 家",{n:t.length}):a.join(r("、")):r("未勾选提供商")}function JG(e,t){const a=$O(e,t);return a.length?a.join(r("、")):r("未勾选提供商")}function e7(e){const t=e.lastResult;if(!t)return r("还没执行过");const a=f=>Number(f)||0,o=[r("成功 {n}",{n:a(t.succeeded)})],c=a(t.active);c>0&&o.push(r("保活 {n}",{n:c}));const d=a(t.failedCount);return d>0&&o.push(r("失败 {n}",{n:d})),`${t.at?Vs(t.at):"—"}${t.reason?` · ${t.reason}`:""} —— ${o.join(r(" · "))}`}function qO({entry:e,store:t}){const a=Array.isArray(t.data?.providerOptions)?t.data.providerOptions:[],o=e===null,[c,d]=x.useState(e?.label??""),[f,p]=x.useState(e?.time??"00:01"),[g,v]=x.useState(new Set(o?a.map(S=>S.id):e?.providers??[]));x.useEffect(()=>{o&&a.length>0&&v(new Set(a.map(S=>S.id)))},[]);const y=f.trim()!==""&&g.size>0,b=()=>v(new Set(a.map(S=>S.id))),j=()=>v(new Set),w=async()=>{await FO({id:e?.id,label:c.trim(),enabled:e?.enabled??!0,time:f.trim(),providers:a.map(S=>S.id).filter(S=>g.has(S))})};return s.jsxs("div",{className:"ck-sched-editor",children:[s.jsxs("div",{className:"ck-set-line",children:[s.jsx("span",{className:"ck-set-k",children:r("名称")}),s.jsx("span",{className:"ck-set-v",children:s.jsx($e,{type:"text",className:"max-w-[220px]",placeholder:r("可选 · 缺省显示时刻"),value:c,disabled:t.saving,onChange:S=>d(S.currentTarget.value)})})]}),s.jsxs("div",{className:"ck-set-line",children:[s.jsx("span",{className:"ck-set-k",children:r("每天时刻")}),s.jsxs("span",{className:"ck-set-v flex items-center gap-2",children:[s.jsx($e,{type:"time",className:"w-[96px] max-w-[96px] font-mono tabular-nums",value:f,disabled:t.saving,onChange:S=>p(S.currentTarget.value)}),s.jsx("span",{className:"text-subtle text-xs",children:r("北京时间 · 错过时点开机后会自动补签")})]})]}),s.jsxs("div",{className:"ck-set-line ck-set-line-top",children:[s.jsx("span",{className:"ck-set-k",children:r("签到范围")}),s.jsxs("span",{className:"ck-set-v",children:[s.jsxs("div",{className:"ck-mini-row",children:[s.jsx("span",{className:"ck-mini-note",children:r("到点时逐个签到,已勾 {n} / {total} 家",{n:g.size,total:a.length})}),s.jsx("button",{type:"button",className:"ck-mini-btn",disabled:t.saving,onClick:b,children:r("全选")}),s.jsx("button",{type:"button",className:"ck-mini-btn",disabled:t.saving||g.size===0,onClick:j,children:r("清空")})]}),s.jsx("div",{className:"ck-range",children:a.map(S=>s.jsxs("label",{className:"ck-range-item",children:[s.jsx(Or,{checked:g.has(S.id),disabled:t.saving,onCheckedChange:N=>{const k=new Set(g);N===!0?k.add(S.id):k.delete(S.id),v(k)}}),s.jsx("span",{className:"ck-range-name",title:S.label,children:S.label})]},S.id))}),g.size===0?s.jsx("div",{className:"ck-mini-warn",children:r("至少勾一家才能保存(不勾等于这条条目不签到)")}):null]})]}),s.jsxs("div",{className:"ck-sched-actions",children:[s.jsx(se,{size:"sm",variant:"outline",disabled:t.saving,onClick:()=>tw(null),children:r("取消")}),s.jsx(se,{size:"sm",variant:"default",disabled:!y||t.saving,onClick:()=>{w()},children:t.saving?r("保存中…"):r("保存")})]})]})}function t7({store:e}){return s.jsxs("div",{className:"ck-sched-row open ck-sched-row-new",children:[s.jsxs("div",{className:"ck-sched-main",children:[s.jsx("span",{className:"ck-new-dot","aria-hidden":!0,children:"+"}),s.jsxs("div",{className:"ck-prov-info",children:[s.jsx("div",{className:"ck-prov-name",children:r("新建定时条目")}),s.jsx("div",{className:"ck-prov-desc",children:r("填好时刻与签到范围后点「保存」;名称可以留空(界面显示时刻)")})]})]}),s.jsx(qO,{entry:null,store:e})]})}function n7({entry:e,store:t}){const a=Array.isArray(t.data?.providerOptions)?t.data.providerOptions:[],o=t.editingId===e.id,c=t.runningId===e.id,d=t.data?.enabled===!0,f=Number(e.nextRunAt),p=async()=>{const g=Pe().wbConfirm?.ask;if(!g)return;const y=(e.displayLabel||e.time||e.id).replace(/&/g,"&").replace(//g,">");await g({title:r("删除定时条目"),html:r("确定删除「{name}」?删除后到点不再执行。",{name:y}),okText:r("删除"),okClass:"danger"})&&await KG(e.id)};return s.jsxs("div",{className:o?"ck-sched-row open":"ck-sched-row",children:[s.jsxs("div",{className:"ck-sched-main",children:[s.jsx(ms,{checked:e.enabled===!0,disabled:t.saving,onCheckedChange:g=>{GG(e,g===!0)}}),s.jsxs("div",{className:"ck-prov-info",children:[s.jsxs("div",{className:"ck-prov-name",children:[e.displayLabel||e.time||e.id,e.enabled===!0?null:s.jsx(ze,{variant:"outline",shape:"tag",children:r("已停用")})]}),s.jsx("div",{className:"ck-prov-desc ck-sched-scope",title:JG(e,a),children:r("每天 {time} · {scope}",{time:e.time??"—",scope:WG(e,a)})}),s.jsx("div",{className:"ck-prov-desc",children:r("上次执行:{line}",{line:e7(e)})})]}),s.jsxs("div",{className:"ck-prov-right",children:[s.jsx("span",{className:"ck-sched-next",children:d&&e.enabled===!0&&Number.isFinite(f)&&f>0?r("下次 {date}",{date:Vs(f)}):"—"}),s.jsx(se,{size:"sm",variant:"ghost",disabled:c||t.runningId!==null,onClick:()=>{YG(e.id)},children:r(c?"执行中…":"立即执行")}),s.jsx(se,{size:"sm",variant:"ghost",onClick:()=>tw(o?null:e.id),children:r(o?"收起":"编辑")}),s.jsx(se,{size:"sm",variant:"ghost",className:"text-destructive",disabled:t.saving,onClick:()=>{p()},children:r("删除")})]})]}),o?s.jsx(qO,{entry:e,store:t}):null]})}function s7(e,t){return e.length===t.length&&e.every((a,o)=>a===t[o])}let Bf=null;function r7(e,t){for(let a=0;ag!==t.row),d=r7(c,e.clientY);if(d===t.from)return;const f=[...t.list],[p]=f.splice(t.from,1);f.splice(d,0,p),t.list=f,t.from=d,t.onChange(f)}function Hf(){const e=Bf;Bf=null,window.removeEventListener("pointermove",GO),window.removeEventListener("pointerup",Hf),window.removeEventListener("pointercancel",Hf),document.body.classList.remove("ck-chain-dragging"),e?.row.classList.remove("dragging")}function a7(e,t,a,o){if(e.button!==0||Bf||a.length<2)return;const c=e.currentTarget.closest(".ck-chain-row");c&&(e.preventDefault(),Bf={list:[...a],from:t,row:c,onChange:o},c.classList.add("dragging"),document.body.classList.add("ck-chain-dragging"),window.addEventListener("pointermove",GO),window.addEventListener("pointerup",Hf),window.addEventListener("pointercancel",Hf))}function l7({models:e,defaultModels:t,dirty:a,saving:o}){const[c,d]=x.useState(""),f=()=>{const p=c.trim();if(p){if(e.includes(p)){Le(r("清单里已经有「{name}」",{name:p}),"err");return}jg([...e,p]),d("")}};return s.jsxs("section",{className:"panel ck-chain-panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("保活模型链")}),s.jsx("span",{className:"panel-sub",children:r("WorkBuddy 国际版日活任务的免费模型 · 全局一份,与条目无关")}),s.jsx(se,{size:"sm",variant:"default",className:"ml-auto",disabled:!a||o,onClick:()=>{_G(e)},children:r(o?"保存中…":"保存")})]}),s.jsxs("div",{className:"p-4",children:[s.jsxs("div",{className:"ck-set-line ck-set-line-top",children:[s.jsx("span",{className:"ck-set-k",children:r("模型清单")}),s.jsxs("span",{className:"ck-set-v",children:[s.jsxs("div",{className:"ck-mini-row",children:[s.jsx("span",{className:"ck-mini-note",children:r("按序逐个尝试,共 {n} 个",{n:e.length})}),s.jsx("button",{type:"button",className:"ck-mini-btn",disabled:o||t.length===0,title:r("把缺省链填进清单,再点「保存」生效"),onClick:()=>jg([...t]),children:r("填入缺省链")})]}),s.jsxs("div",{className:"ck-chain",children:[e.map((p,g)=>s.jsxs("div",{className:"ck-chain-row",children:[s.jsx("span",{className:"ck-chain-grip",role:"button",tabIndex:-1,"aria-label":r("按住拖动调整顺序"),title:r("按住拖动,调整这个模型在链里的顺序"),onPointerDown:v=>a7(v,g,e,jg),dangerouslySetInnerHTML:{__html:Pe().wbIcons?.icon?.("gripVertical",14)||""}}),s.jsx("span",{className:"ck-chain-name",title:p,children:p}),s.jsxs("span",{className:"ck-chain-index",children:["#",g+1]}),s.jsx("button",{type:"button",className:"ck-chain-del",disabled:o,"aria-label":r("移除 {name}",{name:p}),title:r("从清单里移除"),onClick:()=>jg(e.filter((v,y)=>y!==g)),children:"×"})]},p)),e.length===0?s.jsx("div",{className:"ck-chain-empty",children:r("清单为空 —— 保存后恢复缺省链")}):null]}),s.jsxs("div",{className:"ck-chain-add",children:[s.jsx($e,{type:"text",className:"max-w-[260px] font-mono text-xs",placeholder:r("WorkBuddy 国际版保活模型,按顺序回退"),value:c,disabled:o,onChange:p=>d(p.currentTarget.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),f())}}),s.jsx(se,{size:"sm",variant:"outline",disabled:o||c.trim()==="",onClick:f,children:r("添加模型")}),a?s.jsx("span",{className:"ck-chain-dirty",children:r("有未保存的改动")}):null]})]})]}),s.jsx("div",{className:"ck-note",children:r("「保活模型链」是 WorkBuddy 国际版领日活时用来保活的免费模型,按顺序逐个尝试、 第一个成功即止;清空清单并保存 = 恢复缺省链(当前缺省:{defaults})。 当天去重 + 幂等领取:重复执行只会拿到「已领取」,不会重复加分。",{defaults:t.join(r("、"))})})]})]})}function o7(){const e=QG(),t=ZG();if(x.useEffect(()=>{VO()},[]),!e.loaded)return s.jsxs("div",{className:"ck-loading",children:[s.jsx(Wd,{className:"size-5"}),s.jsx("span",{children:r("正在读取定时签到数据…")})]});const a=e.data,o=a?.enabled===!0,c=Array.isArray(a?.schedules)?a.schedules:[],d=t.snapshot?.keepalive,f=Array.isArray(d?.models)?d.models:[],p=Array.isArray(d?.defaultModels)?d.defaultModels:[],g=t.keepaliveDraft,v=g??f,y=g!==null&&!s7(g,f);return s.jsxs("div",{children:[e.loadError?s.jsxs("div",{className:"ck-page-error",children:[s.jsx("span",{children:r("读取定时签到数据失败:{error}",{error:e.loadError})}),s.jsx(se,{size:"sm",variant:"outline",onClick:()=>{VO()},children:r("重试")})]}):null,s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("定时签到")}),s.jsx("span",{className:"tip-q","data-tip":XG}),s.jsx("span",{className:"panel-sub",children:r("每条条目各有时刻与范围 · 各自当天去重 · 错过时点开机自动补签")}),s.jsx(se,{size:"sm",variant:"outline",className:"ml-auto flex-none",disabled:e.saving,onClick:()=>tw(e.editingId==="new"?null:"new"),children:e.editingId==="new"?r("收起新建"):r("添加条目")})]}),s.jsx("div",{className:"p-4",children:s.jsxs("div",{className:"ck-set-line",children:[s.jsx("span",{className:"ck-set-k",children:r("总开关")}),s.jsxs("span",{className:"ck-set-v flex items-center gap-2",children:[s.jsx(ms,{checked:o,disabled:e.saving,onCheckedChange:b=>{qG(b===!0)}}),s.jsx("span",{className:"text-subtle text-xs",children:r(o?"开着:启用的条目按各自时刻执行":"关着:所有条目都不执行")})]})]})}),s.jsxs("div",{children:[e.editingId==="new"?s.jsx(t7,{store:e}):null,c.map(b=>s.jsx(n7,{entry:b,store:e},b.id)),c.length===0?s.jsx("div",{className:"ck-empty",children:r("还没有定时条目 —— 点「添加条目」建一条,或到「签到中心」手动签到。")}):null]})]}),s.jsx(l7,{models:v,defaultModels:p,dirty:y,saving:t.keepaliveSaving})]})}const Ng="checkin-records",KO=["today","7","30","month","all"],Cu="all",i7=[{value:"today",label:r("今天")},{value:"7",label:r("7 天")},{value:"30",label:r("30 天")},{value:"month",label:r("本月")},{value:"all",label:r("全部")}],YO="workbuddy-desktop-checkin-records-range";function kg(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function XO(e){const t=new Date;switch(e){case"today":return kg(t);case"7":return kg(new Date(t.getFullYear(),t.getMonth(),t.getDate()-6));case"30":return kg(new Date(t.getFullYear(),t.getMonth(),t.getDate()-29));case"month":return kg(new Date(t.getFullYear(),t.getMonth(),1));default:return null}}function c7(){try{const e=localStorage.getItem(YO);return e!==null&&KO.includes(e)?e:Cu}catch{return Cu}}function QO(e){try{localStorage.setItem(YO,e)}catch{}}function ZO(e){return typeof e=="number"&&e>0?e:du}const nw={success:{label:"成功领取",variant:"success"},already:{label:"今日已领",variant:"brand"},pending:{label:"等待窗口",variant:"warning"},failed:{label:"失败",variant:"destructive"}},u7={schedule:"定时",startup:"补签",manual:"手动",single:"单签",activity:"活动"},sw=[{key:"time",label:r("时间")},{key:"account",label:r("账号")},{key:"provider",label:r("提供商")},{key:"source",label:r("来源")},{key:"outcome",label:r("结果")},{key:"detail",label:r("说明")}];let rw=null;function WO(){return rw?rw.apply([...sw]):sw.map(e=>({...e,align:e.align??"left"}))}function JO(){window.wbTableColumns?.repaint?.(Ng)}function eM(e){return(ur().snapshot?.auto?.providerOptions??[]).find(a=>a.id===e)?.label??e}function d7(e,t){const a=`ck-col-${t.key} ta-${t.align}`;switch(t.key){case"time":return s.jsxs("td",{className:a,children:[e.ts?Vs(e.ts):"—",s.jsx("span",{className:"ck-record-date",children:e.date||""})]},t.key);case"account":return s.jsx("td",{className:a,children:e.accountName||e.accountId||"—"},t.key);case"provider":return s.jsx("td",{className:a,children:e.provider?eM(e.provider):"—"},t.key);case"source":return s.jsxs("td",{className:a,children:[s.jsx("span",{className:"ck-record-source",children:u7[e.source??""]??e.source??"—"}),e.reason?s.jsx("span",{className:"ck-record-reason",children:e.reason}):null]},t.key);case"outcome":{const o=nw[e.outcome??""]??{label:e.outcome||"—",variant:"outline"};return s.jsxs("td",{className:a,children:[s.jsx(ze,{variant:o.variant,shape:"tag",children:o.label}),e.keptActive?s.jsx(ze,{variant:"outline",shape:"tag",className:"ml-1",children:r("保活")}):null]},t.key)}case"detail":return s.jsx("td",{className:e.error?`${a} ck-record-detail-fail`:a,children:e.error||e.message||"—"},t.key);default:return null}}function f7(){const[e,t]=x.useState([]),[a,o]=x.useState(0),[c,d]=x.useState(1),[f,p]=x.useState(()=>c7()),[g,v]=x.useState(()=>ZO(sg(Ng,tg))),[y,b]=x.useState({outcome:"",provider:"",keyword:""}),[j,w]=x.useState(""),[S,N]=x.useState(!1),[k,E]=x.useState(""),[D,C]=x.useState(0),A=x.useRef(null),R=x.useRef(0),[,I]=x.useReducer(Y=>Y+1,0),P=ur().snapshot?.auto?.providerOptions??[],O=WO(),_=Math.max(1,Math.ceil(a/g)),L=Math.min(c,_),H=y.outcome!==""||y.provider!==""||y.keyword!==""||f!==Cu,B=a?{start:(L-1)*g+1,end:Math.min(a,L*g)}:null,z=x.useCallback(async Y=>{const F=R.current+1;R.current=F,N(!0),E("");try{const W=await Pe().workbuddyDesktop?.getCheckinRecords?.({limit:Y.size,offset:(Y.page-1)*Y.size,outcome:Y.filters.outcome,provider:Y.filters.provider,keyword:Y.filters.keyword,start:XO(Y.range)});if(F!==R.current)return;t(Array.isArray(W?.records)?W.records:[]),o(Number(W?.total)||0)}catch(G){if(F!==R.current)return;E(G instanceof Error?G.message:String(G))}finally{F===R.current&&N(!1)}},[]);x.useEffect(()=>{z({page:c,size:g,range:f,filters:y})},[z,c,g,f,y]),x.useEffect(()=>{c>_&&d(_)},[c,_]),x.useLayoutEffect(()=>{const Y=Pe().wbColSettings;if(!Y?.register){const F=window.setTimeout(()=>C(G=>G+1),50);return()=>window.clearTimeout(F)}rw=Y.register({id:Ng,label:r("签到记录表"),columns:sw.map(F=>({key:F.key,label:F.label,align:F.align??"left"})),mount:()=>A.current,onChange:()=>{ks.flushSync(()=>I()),JO()}}),I()},[D]),x.useLayoutEffect(()=>{JO()}),x.useEffect(()=>()=>{Pe().wbColSettings?.close()},[]);const Q=Y=>{b(Y),d(1)},K=Y=>{const F=KO.includes(Y)?Y:Cu;F!==f&&(QO(F),p(F),d(1))},X=Y=>{v(ZO(Y)),rg(Ng,Y),d(1)},q=()=>{w(""),QO(Cu),p(Cu),Q({outcome:"",provider:"",keyword:""})},$=async()=>{const Y=Pe().wbConfirm?.ask;if(!Y)return;const F=r(H?"确定清空当前筛选出的签到记录?清空后无法恢复。":"确定清空全部签到记录?清空后无法恢复。");if(await Y({title:r("清空签到记录"),html:F,okText:r("清空"),okClass:"danger"}))try{await Pe().workbuddyDesktop?.clearCheckinRecords?.(H?{outcome:y.outcome,provider:y.provider,keyword:y.keyword,start:XO(f)}:{all:"1"}),tM("签到记录已清空"),await z({page:1,size:g,range:f,filters:y}),d(1)}catch(G){tM(r("清空失败:{error}",{error:G instanceof Error?G.message:String(G)}),"err")}};return s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("签到记录")}),s.jsx("span",{className:"panel-sub",children:r("每执行一次签到 · 每个账号一条明细 · 结果与收益以后端落账为准")}),s.jsxs("div",{ref:A,className:"ml-auto flex items-center gap-2",children:[s.jsx(se,{size:"sm",variant:"outline",disabled:S,onClick:()=>{z({page:c,size:g,range:f,filters:y})},children:r(S?"刷新中…":"刷新")}),s.jsx(se,{size:"sm",variant:"ghost",className:"text-destructive",onClick:()=>{$()},children:r("清空")})]})]}),s.jsxs("div",{className:"ck-records-filters",children:[s.jsx(In,{options:i7,value:f,onValueChange:K,"aria-label":r("签到记录时间范围"),className:"shrink-0"}),s.jsxs(ft,{value:y.outcome,onValueChange:Y=>Q({...y,outcome:Y??""}),children:[s.jsx(mt,{className:"w-[128px] shrink-0","aria-label":r("按结果筛选"),children:s.jsx(pt,{children:y.outcome?nw[y.outcome]?.label??y.outcome:r("全部结果")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"",children:r("全部结果")}),Object.entries(nw).map(([Y,F])=>s.jsx(qe,{value:Y,children:F.label},Y))]})]}),s.jsxs(ft,{value:y.provider,onValueChange:Y=>Q({...y,provider:Y??""}),children:[s.jsx(mt,{className:"w-[148px] shrink-0","aria-label":r("按提供商筛选"),children:s.jsx(pt,{children:y.provider?eM(y.provider):r("全部提供商")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"",children:r("全部提供商")}),P.map(Y=>s.jsx(qe,{value:Y.id,children:Y.label},Y.id))]})]}),s.jsx("div",{className:"spacer"}),s.jsx($e,{type:"search",className:"ck-records-search w-[200px] basis-[200px] min-w-[150px] grow-0 shrink",placeholder:r("搜账号 / 收益 / 错误 / 触发原因"),value:j,onChange:Y=>w(Y.currentTarget.value),onBlur:()=>{j!==y.keyword&&Q({...y,keyword:j.trim()})},onKeyDown:Y=>{Y.key==="Enter"&&Y.currentTarget.blur(),Y.key==="Escape"&&(w(y.keyword),Y.currentTarget.blur())}}),H?s.jsx(se,{size:"sm",variant:"ghost",onClick:q,children:r("清除筛选")}):null,s.jsx("span",{className:"panel-sub",children:S?r("读取中…"):r("{n} 条",{n:a})})]}),k?s.jsxs("div",{className:"ck-page-error",children:[s.jsx("span",{children:r("读取签到记录失败:{error}",{error:k})}),s.jsx(se,{size:"sm",variant:"outline",onClick:()=>{z({page:c,size:g,range:f,filters:y})},children:r("重试")})]}):null,e.length===0&&!S?s.jsx("div",{className:"ck-empty",children:r(H?"没有符合筛选条件的签到记录":"还没有签到记录 —— 手动签到或等定时条目执行后,明细会出现在这里。")}):s.jsx("div",{className:"ck-records-scroll",children:s.jsxs("table",{className:"ck-table ck-records-table",children:[s.jsx("colgroup",{children:O.map(Y=>s.jsx("col",{"data-col":Y.key,className:`ck-col-${Y.key}`},Y.key))}),s.jsx("thead",{children:s.jsx("tr",{children:O.map(Y=>s.jsx("th",{"data-col":Y.key,className:`ck-col-${Y.key} ta-${Y.align}`,children:Y.label},Y.key))})}),s.jsx("tbody",{children:e.map(Y=>s.jsx("tr",{children:O.map(F=>d7(Y,F))},Y.rowId))})]})}),s.jsx(Li,{total:a,range:B,page:L,pageCount:_,size:g,sizes:tg,onSizeChange:X,onPageChange:d,disabled:S})]})}function tM(e,t){Pe().wbApp?.toast?.(e,t)}window.wbCheckinRecords={visibleColumns:()=>WO().map(e=>({key:e.key}))};const nM={workbuddy:r("腾讯每日签到接口 · 仅国内版"),"workbuddy-intl":r("每日活跃任务 · 领取才加积分,保活只维持活跃 · 两者可分开执行"),raccoon:r("桌面端每日积分链路"),autoclaw:r("官方客户端的每日签到任务"),"autoclaw-intl":r("与国内版同一套任务接口 · 站点不同"),qoder:r("活动(campaign)领取 · 每天 10:00 刷新"),"qoder-intl":r("带设备风控身份领取「每日 100 Credits」 · 需要 UMID 组件"),trae:r("SOLO 的 checkin_credits 领取 · 按自然日 0 点刷新"),loomy:r("无独立签到接口 · 每天替账号打一次首次登录积分"),kuku:r("「免费领积分」的每日任务 · 逐个领取"),officeace:r("一次领当天全部奖励(每日签到 + 新人礼) · 幂等由上游保证"),codearts:r("每日福利 · 领取 → 确认 → 回读核实 · 按北京时间自然日重置")},p7=[{value:"center",label:r("签到中心")},{value:"schedule",label:r("定时签到")},{value:"records",label:r("签到记录")}];function m7(e){return e==="raccoon"?"小浣熊":e==="loomy"?"Loomy":e==="codearts"?"CodeArts":e==="officeace"?"OfficeAce 果办":e}function h7(){const[e,t]=x.useState(ur());return x.useEffect(()=>MO(()=>t(ur())),[]),e}function g7({group:e}){const t=UG(e);return t==="none"?s.jsx(ze,{variant:"outline",shape:"tag",children:r("无账号")}):t==="done"?s.jsx(ze,{variant:"success",shape:"tag",children:r("已签")}):t==="part"?s.jsx(ze,{variant:"warning",shape:"tag",children:r("部分")}):s.jsx(ze,{variant:"brand",shape:"tag",children:r("待签")})}function Uf({id:e,label:t}){const a=ug[e==="workbuddy-intl"?"workbuddy":e];return s.jsx("span",{className:"ck-prov-logo",children:a?s.jsx("img",{src:a,alt:""}):t.slice(0,1)||"·"})}function x7({group:e}){const t=ur().signing,a=(o,c)=>t.has(`${o}:${c}`);return s.jsxs("table",{className:"ck-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:r("账号")}),s.jsx("th",{children:r("今日签到")}),s.jsx("th",{children:r("上次签到时间")}),s.jsx("th",{"aria-label":r("操作")})]})}),s.jsx("tbody",{children:e.accounts.map(o=>{const c=e.id==="workbuddy-intl";return s.jsxs("tr",{children:[s.jsx("td",{children:o.name||o.id}),s.jsx("td",{children:o.checkedInToday?s.jsx(ze,{variant:"success",shape:"tag",children:r("已签")}):s.jsx(ze,{variant:"brand",shape:"tag",children:r("待签")})}),s.jsx("td",{className:"text-subtle",children:o.checkinAt?Vs(o.checkinAt):"—"}),s.jsx("td",{className:"text-right",children:c?s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(se,{size:"sm",variant:"ghost",disabled:a(o.id,"keepalive"),title:r("用免费模型维持账号活跃 · 不领取奖励"),onClick:()=>{yg(o.id,"keepalive")},children:a(o.id,"keepalive")?r("保活中…"):r("保活")}),s.jsx(se,{size:"sm",variant:"ghost",disabled:a(o.id,"claim"),title:r("探测活动并领取日活奖励 · 不做保活"),onClick:()=>{yg(o.id,"claim")},children:a(o.id,"claim")?r("领取中…"):r("领取")}),s.jsx(se,{size:"sm",variant:"ghost",disabled:a(o.id,"full"),title:r("探测 + 领取 + 保活 · 与定时签到同一套组合"),onClick:()=>{yg(o.id,"full")},children:a(o.id,"full")?r("执行中…"):r("保活+领取")})]}):s.jsx(se,{size:"sm",variant:"ghost",disabled:a(o.id,"checkin"),onClick:()=>{yg(o.id)},children:a(o.id,"checkin")?r("签到中…"):o.checkedInToday?r("重签"):r("签到")})})]},o.id)})})]})}function b7({group:e,expanded:t}){const a=e.totalCount>0;return s.jsxs("div",{className:t?"ck-prov-row open":"ck-prov-row",children:[s.jsxs("div",{className:"ck-prov-main",onClick:()=>a&&DO(e.id),onKeyDown:o=>{a&&(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),DO(e.id))},role:a?"button":void 0,tabIndex:a?0:-1,"aria-expanded":a?t:void 0,children:[s.jsx(Uf,{id:e.id,label:e.label}),s.jsxs("div",{className:"ck-prov-info",children:[s.jsx("div",{className:"ck-prov-name",children:e.label}),s.jsx("div",{className:"ck-prov-desc",children:nM[e.id]??""})]}),s.jsxs("div",{className:"ck-prov-right",children:[s.jsx("span",{className:"ck-prov-count",children:a?r("{total} 账号 · {done} 已签",{total:e.totalCount,done:e.doneCount}):"—"}),s.jsx(g7,{group:e}),a?s.jsx("span",{className:"ck-chev","aria-hidden":!0,children:"›"}):null]})]}),e.id==="qoder-intl"?s.jsx(sM,{}):null,t?s.jsx("div",{className:"ck-prov-detail",children:s.jsx(x7,{group:e})}):null]})}function sM(){const[e,t]=x.useState(null),a=x.useCallback(async()=>{try{t(await Ir().getQoderUmid?.()??null)}catch{}},[]);x.useEffect(()=>{a()},[a]);const o=e?.installing===!0&&e.available!==!0;if(x.useEffect(()=>{if(!o)return;const d=window.setInterval(()=>{a()},3e3);return()=>{window.clearInterval(d)}},[o,a]),!e||e.available)return null;const c=async()=>{try{t(d=>d&&{...d,installing:!0}),await Ir().installQoderUmid?.(),Pe().wbApp?.toast?.(r("✅ UMID 组件已安装,下轮签到即可领取国际版积分"))}catch(d){Pe().wbApp?.toast?.(r("UMID 组件安装失败:{error}",{error:d instanceof Error?d.message:String(d)}),"err")}finally{a()}};return s.jsxs("div",{className:"flex flex-wrap items-center gap-2 pb-2.5 pl-[58px] pr-4 text-[12px] text-muted-foreground",children:[s.jsx("span",{children:r("国际版签到需要 UMID 组件生成设备风控身份(本机未检测到)。")}),e.installSupported?s.jsx(se,{variant:"outline",size:"sm",disabled:e.installing===!0,onClick:()=>{c()},children:e.installing?r("安装中…"):r("一键安装组件")}):s.jsx("span",{children:r("安装 Qoder 客户端或 qodercli 后即可(无需重启网关)。")})]})}function v7({row:e}){const t=e.provider??"loomy",a=ur().onboarding.get(e.id),o=a?.tasks??[],c=a?.unclaimed??0,d=a?.status==="loaded"&&o.length>0,f=d&&IO(e.id);return s.jsxs("div",{className:f?"ck-prov-row open":"ck-prov-row",children:[s.jsxs("div",{className:"ck-prov-main",onClick:d?()=>Wj(e.id):void 0,onKeyDown:p=>{d&&(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),Wj(e.id))},role:d?"button":void 0,tabIndex:d?0:-1,"aria-expanded":d?f:void 0,children:[s.jsx(Uf,{id:t,label:m7(t)}),s.jsxs("div",{className:"ck-prov-info",children:[s.jsx("div",{className:"ck-prov-name",children:e.name||e.id}),s.jsxs("div",{className:"ck-prov-desc",children:[a?.status==="loaded"?r("已领 {claimed}/{total} · 累计 {earned} 积分",{claimed:o.length-c,total:o.length,earned:a.total?`${a.earned} / ${a.total}`:a.earned}):r("尚未查询任务状态"),a?.settled&&a.settledAt?` · ${r("结算于 {time}",{time:Vs(a.settledAt)})}`:a?.checkedAt?` · ${r("查询于 {time}",{time:Vs(a.checkedAt)})}`:""]})]}),s.jsxs("div",{className:"ck-prov-right",onClick:p=>p.stopPropagation(),children:[a?.status==="loaded"&&c>0?s.jsx(ze,{variant:"warning",shape:"tag",children:r("{n} 项待领",{n:c})}):a?.status==="loaded"?s.jsx(ze,{variant:"success",shape:"tag",children:r("全部领取")}):a?.status==="error"?s.jsx(ze,{variant:"destructive",shape:"tag",children:r("查询失败")}):null,s.jsx(se,{size:"sm",variant:"outline",disabled:a?.status==="loading"||a?.claiming===!0,onClick:()=>{Jj(e.id,{expand:!0,refresh:!0})},children:a?.status==="loading"?r("查询中…"):r("查询任务")}),s.jsx(se,{size:"sm",variant:"outline",disabled:a?.status!=="loaded"||t!=="officeace"&&c===0||a?.claiming===!0,onClick:()=>{_O(e.id)},children:a?.claiming?r("领取中…"):c>0?r("一键领取({n})",{n:c}):r("领取")}),d?s.jsx("span",{className:"ck-chev","aria-hidden":!0,children:"›"}):null]})]}),a?.status==="error"?s.jsx("div",{className:"ck-fold-note",children:r("查询失败:{error}",{error:a.error??""})}):null,f?s.jsx("div",{className:"ck-prov-detail",children:o.map(p=>s.jsxs("div",{className:"ck-task-line",children:[s.jsx("span",{className:p.done?"ck-task-tick done":"ck-task-tick",children:p.done?"✓":"·"}),s.jsx("span",{children:p.title}),s.jsxs("span",{className:"ck-task-pts",children:["+",p.points]}),s.jsx("span",{className:"ck-task-st",children:p.claiming?s.jsx(ze,{variant:"warning",shape:"tag",children:r("领取中")}):p.done?s.jsx(ze,{variant:"success",shape:"tag",children:r("已领取")}):p.blocked?s.jsx(ze,{variant:"outline",shape:"tag",children:r("暂不可领")}):p.error?s.jsx(ze,{variant:"destructive",shape:"tag",children:p.error}):s.jsx(ze,{variant:"brand",shape:"tag",children:r("可领取")})})]},p.key))}):null]})}function y7({row:e}){const t=$h({claimPlans:e.claimPlans}),a=t.length>0;return s.jsxs("div",{className:"ck-welfare-row",children:[s.jsx(Uf,{id:"zcode",label:"ZCode"}),s.jsxs("div",{className:"ck-prov-info",children:[s.jsxs("div",{className:"ck-prov-name",children:[e.name||e.id,a?s.jsx(ze,{variant:"success",shape:"tag",title:r("本地台账里今天(北京时间)领过的套餐:{plans}",{plans:t.join(r("、"))}),children:r("今天已领 {n} 份",{n:t.length})}):s.jsx(ze,{variant:"outline",shape:"tag",title:r("本地台账里今天还没领过;活动期内每天发一份新套餐"),children:r("今天未领")})]}),s.jsx("div",{className:"ck-prov-desc",children:a?r("点「套餐明细」看领到了哪几份、什么时候生效;活动期内每天可再领"):e.claimAt?r("上次领取 {time} · 领取需通过滑块验证码",{time:Vs(e.claimAt)}):r("限时体验套餐(start-plan),活动期内每天一份 · 领取需滑块验证码")})]}),s.jsx("div",{className:"ck-prov-right",children:s.jsx(se,{size:"sm",variant:"outline",onClick:()=>mR(e.id,e.name),children:r(a?"套餐明细":"去领取")})})]})}function j7({row:e}){const t=ur().growth.get(e.id),a=t?.tasks??[],o=a.filter(b=>b.supported&&!b.unforgeable),c=o.filter(b=>b.status!=="claimed"&&b.current0,f=d&&zG(e.id),p=t?.travel,g=t?.school,v=t?.results??[],y=b=>v.find(j=>j.code===b);return s.jsxs("div",{className:f?"ck-prov-row open":"ck-prov-row",children:[s.jsxs("div",{className:"ck-prov-main",onClick:d?()=>BO(e.id):void 0,onKeyDown:b=>{d&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),BO(e.id))},role:d?"button":void 0,tabIndex:d?0:-1,"aria-expanded":d?f:void 0,children:[s.jsx(Uf,{id:"workbuddy",label:"WorkBuddy"}),s.jsxs("div",{className:"ck-prov-info",children:[s.jsx("div",{className:"ck-prov-name",children:e.name||e.id}),s.jsxs("div",{className:"ck-prov-desc",children:[t?.status==="loaded"?r("{total} 项任务 · {pending} 项可完成",{total:o.length,pending:c.length}):r("查询任务树并一键点亮 / 领奖(含开学季与猫猫旅行)"),t?.checkedAt?` · ${r("查询于 {time}",{time:Vs(t.checkedAt)})}`:""]})]}),s.jsxs("div",{className:"ck-prov-right",onClick:b=>b.stopPropagation(),children:[t?.status==="loaded"?c.length>0?s.jsx(ze,{variant:"warning",shape:"tag",children:r("{n} 项可完成",{n:c.length})}):s.jsx(ze,{variant:"success",shape:"tag",children:r("全部完成")}):t?.status==="error"?s.jsx(ze,{variant:"destructive",shape:"tag",children:r("查询失败")}):null,s.jsx(se,{size:"sm",variant:"outline",disabled:t?.status==="loading"||t?.running===!0,onClick:()=>{wg(e.id)},children:t?.status==="loading"?r("查询中…"):r("查询任务")}),s.jsx(se,{size:"sm",variant:"outline",disabled:t?.status!=="loaded"||t?.running===!0,title:r("接单 + 点亮 + 领奖(只处理已实测沉淀的任务)"),onClick:()=>{HO(e.id,"full")},children:t?.running?r("执行中…"):r("一键完成")}),s.jsx(se,{size:"sm",variant:"ghost",disabled:t?.status!=="loaded"||t?.running===!0,title:r("只领取已完成任务的奖励(幂等,重复点不会重复入账)"),onClick:()=>{HO(e.id,"claim")},children:r("领取")}),d?s.jsx("span",{className:"ck-chev","aria-hidden":!0,children:"›"}):null]})]}),t?.status==="error"?s.jsx("div",{className:"ck-fold-note",children:r("查询失败:{error}",{error:t.error??""})}):null,f?s.jsxs("div",{className:"ck-prov-detail",children:[s.jsxs("div",{className:"ck-fold-note",children:[t?.energy!==null&&t?.energy!==void 0?r("能量 {n}",{n:t.energy}):"",t?.streak!==null&&t?.streak!==void 0?` · ${r("连登 {n} 天",{n:t.streak})}`:"",t?.energy===null&&t?.streak===null?r("(能量 / 连登读数本次未取到)"):""]}),a.map(b=>{const j=y(b.code);return s.jsxs("div",{className:"ck-task-line",children:[s.jsx("span",{className:b.status==="claimed"?"ck-task-tick done":"ck-task-tick",children:b.status==="claimed"?"✓":"·"}),s.jsxs("span",{title:b.description||b.source||b.code,children:[b.title||b.code,b.target>1?` (${b.current}/${b.target})`:""]}),j?s.jsx("span",{className:"ck-task-pts",children:j.message}):null,s.jsx("span",{className:"ck-task-st",children:b.unforgeable?s.jsx(ze,{variant:"outline",shape:"tag",children:r("需真实操作")}):b.supported?b.status==="claimed"?s.jsx(ze,{variant:"success",shape:"tag",children:r("已领取")}):b.status==="completed"?s.jsx(ze,{variant:"brand",shape:"tag",children:r("可领取")}):b.locked?s.jsx(ze,{variant:"outline",shape:"tag",children:r("未解锁")}):s.jsx(ze,{variant:"warning",shape:"tag",children:r("可完成")}):s.jsx(ze,{variant:"outline",shape:"tag",children:r("暂不支持")})})]},b.code)}),s.jsxs("div",{className:"ck-task-line",children:[s.jsx("span",{className:"ck-task-tick",children:"🐾"}),s.jsxs("span",{children:[r("猫猫旅行"),p&&p.hasBuddy===!0?`:${p.buddyName||r("已领养")} · ${p.state==="traveling"?r("在途"):p.state==="arrived"?r("可领奖"):p.state==="idle"?p.dailyLimitReached?r("今日已派出"):r("可派出"):p.state??""}`:p&&p.hasBuddy===!1?`:${r("未领养(领养需先完成当日对话量)")}`:":"+(p?.error?String(p.error):r("尚未查询"))]}),s.jsx("span",{className:"ck-task-st",children:s.jsx(se,{size:"sm",variant:"ghost",disabled:t?.runningTravel===!0||t?.status!=="loaded",onClick:()=>{HG(e.id)},children:t?.runningTravel?r("执行中…"):r("巡检一次")})})]}),s.jsxs("div",{className:"ck-task-line",children:[s.jsx("span",{className:"ck-task-tick",children:"🎓"}),s.jsxs("span",{children:[r("开学季活动"),g&&g.inPeriod===!0?`:${r("进行中")}${g.lottery?.balance!==void 0&&g.lottery?.balance!==null?` · ${r("抽奖机会 {n} 次",{n:g.lottery.balance})}`:""}`:g&&g.inPeriod===!1?`:${r("非活动期")}`:":"+(g?.error?String(g.error):r("尚未查询"))]}),s.jsx("span",{className:"ck-task-st",children:s.jsx(se,{size:"sm",variant:"ghost",disabled:t?.runningSchool===!0||t?.status!=="loaded",title:r("执行开学季任务并抽空抽奖机会(分享 / 对话 / 专家事件)"),onClick:()=>{BG(e.id,!0)},children:t?.runningSchool?r("执行中…"):r("执行并抽奖")})})]}),t?.schoolText?s.jsx("div",{className:"ck-fold-note",children:t.schoolText}):null,t?.lotteryText?s.jsx("div",{className:"ck-fold-note",children:t.lotteryText}):null]}):null]})}function w7({group:e}){return s.jsxs("div",{className:"ck-prov-row",children:[s.jsxs("div",{className:"ck-prov-main",style:{cursor:"default"},children:[s.jsx(Uf,{id:e.id,label:e.label}),s.jsxs("div",{className:"ck-prov-info",children:[s.jsx("div",{className:"ck-prov-name",children:e.label}),s.jsx("div",{className:"ck-prov-desc",children:nM[e.id]??""})]}),s.jsx("div",{className:"ck-prov-right",children:s.jsx(ze,{variant:"outline",shape:"tag",children:r("无账号")})})]}),e.id==="qoder-intl"?s.jsx(sM,{}):null]})}function S7({store:e}){const t=e.snapshot,[a,o]=x.useState(null);x.useEffect(()=>{let N=!0;return(async()=>{try{const E=await Pe().workbuddyDesktop?.getCheckinRecords?.({limit:1});N&&o(Number(E?.total)||0)}catch{}})(),()=>{N=!1}},[e.version]);const c=t?.daily,d=t?.auto,f=(c?.outOfScope??[]).reduce((N,k)=>N+(Number(k.count)||0),0),p=t?.extras.onboarding??[],g=p.filter(N=>e.onboarding.get(N.id)?.status==="loaded"),v=p.reduce((N,k)=>N+(e.onboarding.get(k.id)?.unclaimed??0),0),y=t?.extras.plans??[],b=t?.extras.growth??[],j=Array.isArray(d?.schedules)?d.schedules:[],w=j.filter(N=>N.enabled===!0).length,S=VG(d);return s.jsxs("div",{children:[s.jsxs("div",{className:"ck-stats",children:[s.jsxs("div",{className:"ck-stat",children:[s.jsx("div",{className:"ck-stat-label",children:r("今日签到进度")}),s.jsx("div",{className:"ck-stat-value",children:c?s.jsxs(s.Fragment,{children:[" ",c.todayDone,s.jsxs("small",{children:[" / ",c.todayEligible]})]}):s.jsx("span",{className:"ck-pending",children:"—"})}),s.jsx(Jd,{className:"ck-stat-bar",value:c&&c.todayEligible>0?c.todayDone/c.todayEligible*100:0}),s.jsx("div",{className:"ck-stat-foot",children:f>0?r("另有 {n} 个账号不参与每日签到",{n:f}):r("全部账号均可签到")})]}),s.jsxs("div",{className:"ck-stat ck-stat-link",onClick:()=>{vg("schedule")},role:"button",tabIndex:0,onKeyDown:N=>{N.key==="Enter"&&vg("schedule")},children:[s.jsx("div",{className:"ck-stat-label",children:r("定时签到")}),s.jsx("div",{className:"ck-stat-value",children:d?s.jsxs(s.Fragment,{children:[w,s.jsxs("small",{children:[" / ",j.length," ",r("条启用")]})]}):s.jsx("span",{className:"ck-pending",children:"—"})}),s.jsx("div",{className:"ck-stat-foot",children:d?.enabled!==!0?r("总开关已关闭 · 在「定时签到」页打开"):S?r("下次 {date} · 点此管理条目",{date:Vs(S)}):r("暂无启用的条目 · 点此添加")})]}),s.jsxs("div",{className:"ck-stat",children:[s.jsx("div",{className:"ck-stat-label",children:r("待领新手福利")}),s.jsx("div",{className:"ck-stat-value",children:p.length?s.jsxs(s.Fragment,{children:[v,s.jsxs("small",{children:[" ",r("项")]})]}):s.jsx("span",{className:"ck-pending",children:r("无")})}),s.jsx("div",{className:"ck-stat-foot",children:p.length?r("已有结果 {checked} / 共 {total} 个账号",{checked:g.length,total:p.length}):r("没有支持新手福利的账号")})]}),s.jsxs("div",{className:"ck-stat ck-stat-link",onClick:()=>{vg("records")},role:"button",tabIndex:0,onKeyDown:N=>{N.key==="Enter"&&vg("records")},children:[s.jsx("div",{className:"ck-stat-label",children:r("累计签到记录")}),s.jsx("div",{className:"ck-stat-value",children:a===null?s.jsx("span",{className:"ck-pending",children:"—"}):a}),s.jsx("div",{className:"ck-stat-foot",children:r("每账号一条明细 · 点此查看「签到记录」")})]})]}),s.jsxs("div",{className:"ck-main",children:[s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("每日签到")}),s.jsx("span",{className:"panel-sub",children:r("点击行展开账号明细 · 单账号签到不受范围限制")}),s.jsx(se,{size:"sm",variant:"default",className:"ml-auto",disabled:e.runningAll||d?.running===!0,onClick:()=>{PG()},children:e.runningAll||d?.running===!0?r("签到中…"):r("立即全部签到")})]}),s.jsxs("div",{children:[(c?.providers??[]).map(N=>N.totalCount>0?s.jsx(b7,{group:N,expanded:e.expanded.has(N.id)},N.id):s.jsx(w7,{group:N},N.id)),(c?.outOfScope??[]).length>0?s.jsx("div",{className:"ck-fold-note",children:r("不参与每日签到:{list}。CodeArts 的一次性奖励在下方「新手福利」,它的每日福利就在上方「每日签到」里;ZCode 的套餐领取见「活动福利」。",{list:c.outOfScope.map(N=>r("{label} ×{count}({reason})",{label:N.label,count:N.count,reason:N.reason})).join(r(";"))})}):null]})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("新手福利")}),s.jsx("span",{className:"panel-sub",children:r("一次性福利 · 签到后自动查询并领取,领完记在本机不再查上游 · 点击行展开任务清单")}),p.length>0?s.jsx(se,{size:"sm",variant:"outline",className:"ml-auto",onClick:()=>{for(const N of p)N.settled&&typeof N.settled=="object"||Jj(N.id)},children:r("全部查询")}):null]}),p.length?s.jsx("div",{children:p.map(N=>s.jsx(v7,{row:N},N.id))}):s.jsx("div",{className:"ck-empty",children:r("没有支持新手福利的账号 —— 目前有 Loomy、小浣熊、CodeArts 三家。")})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("活动福利")}),s.jsx("span",{className:"panel-sub",children:r("限时体验套餐 · 领取需滑块验证码 · 逐份查看与领取")})]}),y.length>0?s.jsx("div",{children:y.map(N=>s.jsx(y7,{row:N},N.id))}):s.jsx("div",{className:"ck-empty",children:r("没有可领套餐的账号(ZCode 未添加)。")})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("成长任务")}),s.jsx("span",{className:"panel-sub",children:r("WorkBuddy 国内版 · 查询任务树后一键点亮 / 领奖 · 含开学季与猫猫旅行 · 点击行展开明细")})]}),b.length>0?s.jsx("div",{children:b.map(N=>s.jsx(j7,{row:N},N.id))}):s.jsx("div",{className:"ck-empty",children:r("没有支持成长任务的账号(需要 WorkBuddy 国内版)。")})]})]})]})}function N7(){const e=h7(),t=e.snapshot;if(x.useEffect(()=>{Ol()},[]),x.useEffect(()=>{window.wbApp?.renderTopbarStatus?.()},[e.version]),!e.loaded)return s.jsxs("div",{className:"ck-loading",children:[s.jsx(Wd,{className:"size-5"}),s.jsx("span",{children:r("正在读取签到数据…")})]});const a=t?.auto,o=a?.enabled===!0;return s.jsxs("div",{children:[e.loadError?s.jsxs("div",{className:"ck-page-error",children:[s.jsx("span",{children:r("读取签到数据失败:{error}",{error:e.loadError})}),s.jsx(se,{size:"sm",variant:"outline",onClick:()=>{Ol()},children:r("重试")})]}):null,s.jsxs("div",{className:"ck-tabs",children:[s.jsx(In,{options:p7,value:e.tab,onValueChange:c=>OO(c),"aria-label":r("签到中心分区")}),s.jsx(ze,{id:"checkin-badge",className:"ml-auto",variant:a?o?"success":"outline":"destructive","data-tone":a?o?"ok":"":"bad",children:a?o?a?.lastFiredToday?r("今日已执行"):r("已开启"):r("已关闭"):r("不可用")})]}),e.tab==="center"?s.jsx(S7,{store:e}):null,e.tab==="schedule"?s.jsx(o7,{}):null,e.tab==="records"?s.jsx(f7,{}):null]})}const rM='.page[data-page="checkin"]';let aM=!1;function lM(){if(aM)return;const e=document.querySelector(rM);e&&(aM=!0,e.replaceChildren(),vn.createRoot(e).render(s.jsx(N7,{})))}const oM=()=>Ol();window.wbCheckinPanel={load:oM},document.querySelector(rM)?lM():document.addEventListener("DOMContentLoaded",lM,{once:!0}),Pe().wbApp?.currentPage==="checkin"&&oM();function k7(e){return String(e??"").replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}function C7({options:e,onSettle:t}){const{title:a="确认操作",html:o="",text:c="",okText:d="确定",okClass:f="primary",bodyClass:p="danger-zone",cancelText:g="取消"}=e,v=x.useRef(null);return x.useEffect(()=>{function y(b){b.key==="Escape"&&t(!1)}return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[t]),x.useEffect(()=>{function y(b){b.target?.dataset.slot==="alert-dialog-overlay"&&t(!1)}return document.addEventListener("click",y),()=>document.removeEventListener("click",y)},[t]),s.jsx(xV,{open:!0,onOpenChange:y=>{y||t(!1)},children:s.jsxs(jV,{initialFocus:v,showCloseButton:!0,children:[s.jsx(wV,{className:"pr-10",children:s.jsx(vV,{children:a})}),s.jsx(SV,{children:s.jsx(kV,{tone:p==="danger-zone"?"danger":"neutral",dangerouslySetInnerHTML:{__html:o||k7(c).replace(/\n/g,"
")}})}),s.jsxs(NV,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{ref:v,variant:"outline",onClick:()=>t(!1),children:g}),s.jsx(se,{variant:f==="danger"?"destructive":"default",onClick:()=>t(!0),children:d})]})]})})}let Vf=null,Tu=null,Cg=null;function T7(){Vf&&(Vf.unmount(),Vf=null),Tu&&(Tu.remove(),Tu=null)}function iM(e){const t=Cg;Cg=null,T7(),t?.(e)}function E7(e={}){return new Promise(t=>{Cg&&iM(!1),Cg=t,Tu=document.createElement("div"),document.body.append(Tu),Vf=vn.createRoot(Tu),Vf.render(s.jsx(C7,{options:e,onSettle:iM}))})}window.wbConfirm={ask:E7};const A7=r("Base URL 填进客户端的「API 地址 / Base URL」栏;对话协议按客户端支持的类型三选一(Chat Completions / Responses / Anthropic Messages),三者共用同一套模型与账号池,可随时切换;鉴权用「网关 Key」页里任一启用 Key。");function Ff({id:e,name:t,note:a}){return s.jsxs("div",{className:"ep-row",children:[s.jsxs("div",{className:"ep-head",children:[s.jsx("span",{className:"ep-name",children:t}),s.jsx("span",{className:"ep-note",children:a})]}),s.jsxs("div",{className:"ep-line",children:[s.jsx("code",{className:"ep-value",id:e,children:"—"}),s.jsx(se,{variant:"ghost",size:"icon-xs",className:"copy-btn size-[21px] rounded-[var(--r-xs)]","data-copy-from":e,title:r("复制地址"),children:"⧉"})]})]})}function R7(){return s.jsxs("section",{className:"panel ep-panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("接口地址")}),s.jsx("span",{className:"tip-q","data-tip":A7})]}),s.jsxs("div",{className:"ep-list",children:[s.jsx(Ff,{id:"api-base",name:"Base URL",note:r("填进客户端的「API 地址 / Base URL」")}),s.jsx("div",{className:"ep-group",children:r("对话协议(按客户端支持的类型选一行)")}),s.jsx(Ff,{id:"api-chat",name:"OpenAI Chat Completions",note:r("多数 OpenAI 兼容客户端的默认协议")}),s.jsx(Ff,{id:"api-responses",name:"OpenAI Responses",note:r("OpenAI 新协议(Codex、新版 SDK)")}),s.jsx(Ff,{id:"api-messages",name:"Anthropic Messages",note:r("Claude Code / Anthropic SDK(token 计数:/v1/messages/count_tokens)")}),s.jsx("div",{className:"ep-group",children:r("模型清单")}),s.jsx(Ff,{id:"api-models",name:r("模型列表"),note:r("客户端自动拉取可用模型;不受鉴权限制,配 Key 之前就能拉")})]}),s.jsx("div",{className:"panel-foot",children:s.jsxs("span",{children:[r("鉴权用「网关 Key」页里任一"),s.jsx("b",{children:r("启用")}),r("的 Key:请求带 "),s.jsx("code",{children:"Authorization: Bearer "}),r(" 或 "),s.jsx("code",{children:"x-api-key: "}),r("。一把启用的 Key 都没有时不鉴权(默认网关只监听 127.0.0.1;在设置页开启「局域网访问」后监听所有网卡,鉴权与安全闸门随之启用)。")]})})]})}const cM='.page[data-page="docs"]';let uM=!1;function dM(){if(uM)return;const e=document.querySelector(cM);e&&(uM=!0,e.replaceChildren(),vn.createRoot(e).render(s.jsx(R7,{})))}document.querySelector(cM)?dM():document.addEventListener("DOMContentLoaded",dM,{once:!0});function ia(){return window}function aw(e){return e instanceof Error?e.message:String(e)}function $f(e,t){ia().wbApp?.toast?.(e,t)}function O7(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}const lw=[{key:"name",label:r("名称")},{key:"key",label:"Key"},{key:"time",label:r("创建时间")},{key:"state",label:r("启用")},{key:"act",label:r("操作"),align:"right"}],M7={name:"cell-name",key:"cell-key",time:"cell-time",state:"cell-state state",act:"cell-act r"},fM='.page[data-page="keys"]';let Tg=null,ow=null;function pM(){return Tg?Tg.apply([...lw]):lw.map(e=>({...e,align:e.align??"left"}))}function mM(){ia().wbColSettings?.syncStaticHead?.("keys",document.querySelector("table.keys-table"))}function D7(){if(Tg)return;const e=ia().wbColSettings?.register({id:"keys",label:r("网关 Key 表"),columns:lw,mount:()=>document.querySelector('.page[data-page="keys"] .panel-head .head-actions'),onChange:()=>{mM(),ow?.()}});e&&(Tg=e,mM())}function I7(e){return Array.isArray(e?.keys)?e.keys:[]}function P7(e){return Array.isArray(e?.providers)?e.providers:[]}function _7(e){const t=e?.modelsByProvider;return t&&typeof t=="object"?t:{}}function iw(e){return ia().wbProviders?.labelOf?.(e)||e}function L7(e,t,a){const o=new Map,c=f=>{const p=String(f??"").trim();if(!p)return;const g=p.toLowerCase();o.has(g)||o.set(g,p)};t.forEach(f=>{const p=e[f]??e[String(f).toLowerCase()];Array.isArray(p)&&p.forEach(c)}),a.forEach(c);const d=[...o.values()].map(f=>({value:f,label:r(f)}));return d.sort((f,p)=>f.value.toLowerCase()String(t)):[]}function gM(e,t){const a=new Map(t.map(c=>[c.value.toLowerCase(),c.value])),o=new Set;return e.forEach(c=>{const d=a.get(String(c).toLowerCase());d&&o.add(d)}),t.filter(c=>o.has(c.value)).map(c=>c.value)}function U7({target:e,providers:t,modelsByProvider:a,onClose:o,onSaved:c}){const d=e?.id??null,f=!!d,[p,g]=x.useState(e?.name??""),[v,y]=x.useState(""),[b,j]=x.useState(""),[w,S]=x.useState(!1),N=x.useRef(!1),[k,E]=x.useState(()=>hM(e?.allowedProviders)),[D,C]=x.useState(()=>hM(e?.allowedModels)),A=x.useMemo(()=>t.map(H=>({value:String(H.id),label:r(String(H.label??H.id))})),[t]),R=x.useMemo(()=>gM(k,A),[k,A]),I=x.useMemo(()=>L7(a,R,D),[a,R,D]),P=x.useMemo(()=>gM(D,I),[D,I]),O=I.length?r("没有匹配的选项"):R.length?r("这几家当前没有可用模型(账号未登录或清单为空)"):r("请先在上面选择可用提供商");function _(){N.current=!1,S(!1)}async function L(){if(!N.current){N.current=!0,S(!0),j(r("保存中…"));try{const H=ia().workbuddyDesktop;if(!H)throw new Error(r("后端桥不可用"));if(d){const Q=await H.updateKey(d,{allowedProviders:R,allowedModels:P});_(),c(Q),o(),$f(r("✅ 可用范围已保存"));return}const B=v.trim();if(B&&B.length<8){j(r("Key 至少需要 8 个字符"));return}const z=await H.createKey({name:p.trim(),key:B||void 0,allowedProviders:R,allowedModels:P});_(),c(z,z?.created?.id),o(),$f(r("✅ Key 已创建,记得复制给客户端"))}catch(H){j(r("保存失败:{reason}",{reason:aw(H)}))}finally{_()}}}return s.jsx(Qt,{open:!0,onOpenChange:(H,B)=>{if(!H){if(N.current){B.cancel();return}o()}},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:f?r("可用范围 · {name}",{name:e?.name||r("未命名")}):r("新建 API Key")})}),s.jsxs(Bt,{children:[s.jsxs(Vn,{children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(Je,{htmlFor:"key-name",className:"text-[12.5px] whitespace-nowrap text-subtle",children:r("名称")}),s.jsx($e,{id:"key-name",type:"text",maxLength:60,placeholder:r("例如 Cursor / 公司电脑"),autoComplete:"off",value:p,disabled:f,onChange:H=>g(H.currentTarget.value)})]}),!f&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(Je,{htmlFor:"key-value",className:"text-[12.5px] whitespace-nowrap text-subtle",children:"Key"}),s.jsx($e,{id:"key-value",type:"text",placeholder:r("留空自动生成;手填至少 8 个字符"),autoComplete:"off",spellCheck:!1,value:v,onChange:H=>y(H.currentTarget.value),onKeyDown:H=>{H.key==="Enter"&&L()}})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(Je,{className:"text-[12.5px] whitespace-nowrap text-subtle",children:r("可用提供商")}),s.jsx(_h,{value:R,onValueChange:E,options:A,placeholder:r("留空 = 不限制"),searchPlaceholder:r("搜索提供商…"),"aria-label":r("可用提供商"),className:"flex-auto min-w-[180px] max-w-[260px]"})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(Je,{className:"text-[12.5px] whitespace-nowrap text-subtle",children:r("可用模型")}),s.jsx(_h,{value:P,onValueChange:C,options:I,placeholder:r("留空 = 不限制"),emptyHint:O,searchPlaceholder:r("搜索模型…"),"aria-label":r("可用模型"),className:"flex-auto min-w-[180px] max-w-[260px]"})]}),s.jsx("p",{children:r("留空表示不限制;同时设置时请求需同时满足两个条件(模型在白名单内且路由到允许的提供商)。 「可用模型」的候选跟着上面勾选的提供商走:没勾提供商时它是空的(还没有约束范围), 勾了几家就列出这几家能收的全部对外名。")}),s.jsx("p",{id:"key-restrict-summary",children:H7(R,P)})]}),s.jsx("div",{className:"min-h-[18px] text-[11.5px] text-muted-foreground",children:b})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:o,disabled:w,children:r("取消")}),s.jsx(se,{variant:"default",disabled:w,onClick:()=>{L()},children:r(f?"保存范围":"创建")})]})]})})}let Eg=null;async function V7(){await Eg?.load()}function F7(){Eg?.render()}function $7(){const[e,t]=x.useState(null),[a,o]=x.useState(()=>new Set),[c,d]=x.useState(()=>new Set),[f,p]=x.useState(null),[,g]=x.useState(0),v=x.useRef(new Set),y=x.useRef(!1),b=x.useCallback(L=>{t(L)},[]),j=x.useCallback(L=>{L&&Array.isArray(L.keys)&&b(L)},[b]),w=x.useCallback(async()=>{if(!y.current){y.current=!0;try{const L=ia().workbuddyDesktop;if(!L)throw new Error(r("后端桥不可用"));b(await L.getKeys()??null)}catch(L){$f(r("读取 Key 列表失败:{reason}",{reason:aw(L)}),"err")}finally{y.current=!1}}},[b]);async function S(L,H,B){if(!v.current.has(L)){v.current.add(L),d(new Set(v.current));try{j(await H()),B&&$f(B)}catch(z){$f(r("操作失败:{reason}",{reason:aw(z)}),"err")}finally{v.current.delete(L),d(new Set(v.current))}}}function N(L){o(H=>{const B=new Set(H);return B.has(L)?B.delete(L):B.add(L),B})}async function k(L){const H=ia().workbuddyDesktop,B=ia().wbConfirm?.ask;if(!H||!B)return;const z=O7(L.name||L.masked||L.id);await B({title:r("删除网关 Key"),html:r("确定删除 Key「{name}」?使用它的客户端会立刻无法访问。",{name:z}),okText:r("删除"),okClass:"danger"})&&S(L.id,()=>H.deleteKey(L.id),r("Key 已删除"))}function E(L,H){const B=ia().workbuddyDesktop;B&&S(L.id,()=>B.updateKey(L.id,{enabled:H}),r(H?"Key 已启用":"Key 已停用"))}x.useLayoutEffect(()=>(Eg={load:w,render:()=>g(L=>L+1)},ow=()=>g(L=>L+1),D7(),g(L=>L+1),()=>{Eg=null,ow=null}),[w]),x.useEffect(()=>{ia().wbApp?.currentPage==="keys"&&w()},[w]),x.useEffect(()=>{ia().wbApp?.renderTopbarStatus?.()},[e]);const D=I7(e),C=ag(D.length,"keys"),A=C.paged?C.slice(D):D,R=pM(),I=e?.authRequired===!0,P=A.filter(L=>L.enabled).length,O=I?r("已启用鉴权 · {n} 把 Key 生效",{n:P}):r("未启用鉴权");function _(L,H,B){switch(L){case"name":return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mid",children:s.jsx("span",{className:"t",children:H.name||r("未命名")})}),s.jsx("div",{className:"mname",title:B7(H),children:z7(H)})]});case"key":{const z=a.has(H.id);return s.jsxs("div",{className:"keycell",children:[s.jsx("code",{className:"kv",children:z?H.key:H.masked}),s.jsx(se,{size:"sm",variant:"ghost",onClick:()=>N(H.id),children:r(z?"隐藏":"显示")}),s.jsx(se,{size:"sm",variant:"ghost","data-copy":H.key,title:r("复制 Key"),children:r("复制")})]})}case"time":return s.jsx("span",{className:"muted",children:H.createdAt?ia().wbApp?.formatTime?.(H.createdAt):"—"});case"state":return s.jsx(ms,{checked:H.enabled===!0,disabled:B,"aria-label":r("启用「{name}」",{name:H.name||r("未命名")}),onCheckedChange:z=>E(H,z)});case"act":return s.jsxs("div",{className:"row-actions",children:[s.jsx(se,{size:"sm",variant:"ghost",disabled:B,onClick:()=>p({key:H}),children:r("可用范围")}),s.jsx(se,{size:"sm",variant:"destructive",disabled:B,onClick:()=>{k(H)},children:r("删除")})]});default:return null}}return s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("API Key 列表")}),s.jsx(ze,{id:"keys-status",variant:I?"success":"warning","data-tone":I?"ok":"warn",children:O}),s.jsx("div",{className:"head-actions",children:s.jsx(se,{variant:"default",onClick:()=>p({key:null}),children:r("+ 新建 Key")})})]}),s.jsx("div",{className:"models-table-wrap",children:s.jsxs("table",{className:"models-table keys-table",children:[s.jsxs("colgroup",{children:[s.jsx("col",{className:"k-name","data-col":"name"}),s.jsx("col",{className:"k-key","data-col":"key"}),s.jsx("col",{className:"k-time","data-col":"time"}),s.jsx("col",{className:"k-state","data-col":"state"}),s.jsx("col",{className:"k-act","data-col":"act"})]}),s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"data-col":"name",children:r("名称")}),s.jsx("th",{"data-col":"key",children:"Key"}),s.jsx("th",{"data-col":"time",children:r("创建时间")}),s.jsx("th",{"data-col":"state",children:r("启用")}),s.jsx("th",{className:"r","data-col":"act",children:r("操作")})]})}),s.jsx("tbody",{children:A.length?A.map(L=>{const H=c.has(L.id);return s.jsx("tr",{className:L.enabled?"":"off","data-id":L.id,children:R.map(B=>s.jsx("td",{className:`${M7[B.key]??""} ta-${B.align}`,children:_(B.key,L,H)},B.key))},L.id)}):s.jsx("tr",{children:s.jsx("td",{colSpan:R.length,className:"empty",children:r(e?"还没有 Key,当前不鉴权":"加载中…")})})})]})}),s.jsx(Li,{leading:s.jsxs("span",{children:[r("客户端请求需带 "),s.jsx("code",{children:"Authorization: Bearer "}),r(" 或 "),s.jsx("code",{children:"x-api-key: "}),r("; 修改后立即生效,本程序自身会自动使用第一把启用的 Key。每把 Key 可单独限制"),s.jsx("b",{children:r("可用提供商")}),r("与"),s.jsx("b",{children:r("可用模型")}),r("(行内「可用范围」):留空 = 不限制,两个都设时 按交集生效 —— 被限制的模型对这把 Key 表现为「不存在」(拉 /v1/models 也看不到它), 提供它的家不在可用列表里时请求同样被拒。")]}),total:D.length,range:C.paged?{start:C.rangeStart,end:C.rangeEnd}:null,page:C.page,pageCount:C.pageCount,size:C.size,onSizeChange:C.setSize,onPageChange:C.goto}),f?s.jsx(U7,{target:f.key,providers:P7(e),modelsByProvider:_7(e),onClose:()=>p(null),onSaved:(L,H)=>{H&&o(B=>new Set(B).add(H)),j(L)}}):null]})}let xM=!1;function bM(){if(xM)return;const e=document.querySelector(fM);e&&(xM=!0,e.replaceChildren(),vn.createRoot(e).render(s.jsx($7,{})))}document.querySelector(fM)?bM():document.addEventListener("DOMContentLoaded",bM,{once:!0}),window.wbKeysPanel={load:V7,render:F7,visibleColumns:pM};const q7="login-app",G7=x.createElement("panel-captcha",{id:"captcha"});function K7(){return s.jsxs("div",{className:"w-[min(400px,100%)] rounded-lg border border-border bg-card p-[36px_34px_30px] shadow-3",children:[s.jsxs("div",{className:"mb-[26px] flex flex-col items-center gap-3 text-center",children:[s.jsxs("svg",{viewBox:"0 0 24 24",role:"img","aria-label":"Agent2API",className:"size-[52px] rounded-[12px] shadow-[0_6px_18px_rgba(0,122,255,0.35)]",children:[s.jsx("rect",{width:"24",height:"24",rx:"5.4",fill:"#007AFF"}),s.jsxs("g",{fill:"none",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M5.23 9.24h10.71"}),s.jsx("path",{d:"M15.94 6.72 18.77 9.24 15.94 11.76"}),s.jsx("path",{d:"M18.77 14.76H8.06"}),s.jsx("path",{d:"M8.06 12.24 5.23 14.76 8.06 17.28"})]})]}),s.jsxs("div",{children:[s.jsx("h1",{className:"m-0 text-[21px] font-bold tracking-[0.2px]",children:"Agent2API"}),s.jsx("div",{className:"text-[12.5px] text-muted-foreground",children:r("OpenAI 兼容网关 · 管理面板")})]})]}),s.jsx("div",{id:"mode-tip",className:"mb-[18px] text-center text-[13px] text-muted-foreground"}),s.jsxs("form",{id:"form",autoComplete:"on",children:[s.jsx(Je,{htmlFor:"username",className:"mt-3.5 mb-[5px] text-[12.5px]",children:r("账号")}),s.jsx($e,{id:"username",autoComplete:"username",placeholder:r("管理员账号")}),s.jsx(Je,{htmlFor:"password",className:"mt-3.5 mb-[5px] text-[12.5px]",children:r("密码")}),s.jsx($e,{id:"password",type:"password",autoComplete:"new-password",placeholder:r("至少 8 位")}),G7,s.jsx(se,{id:"submit",type:"submit",size:"lg",className:"w-full",children:r("继续")}),s.jsx("div",{id:"error",className:"mt-3 min-h-5 text-center text-[13px] whitespace-pre-wrap text-destructive"})]}),s.jsx("div",{className:"mt-[22px] text-center text-[12px] text-muted-foreground",children:r("登录后可在「网关 Key」页为 API 客户端创建密钥")})]})}function Y7(){const e=document.getElementById(q7);e&&ks.flushSync(()=>{vn.createRoot(e).render(s.jsx(K7,{}))})}Y7();function Lr(){return window}function cw(e){return e instanceof Error?e.message:String(e)}function Ag(e,t){Lr().wbApp?.toast?.(e,t)}const vM=1e3,X7=ng,Q7=500,yM="workbuddy-desktop-logs-range",uw="workbuddy-desktop-logs-filters",Z7=300,W7="~/.agent2api/logs.jsonl",dw=["today","7","30","month","all"],fw="all",J7={today:r("今天"),7:r("7 天"),30:r("30 天"),month:r("本月"),all:r("全部")},e9=dw.map(e=>({value:e,label:J7[e]})),pw=[{value:"",label:r("全部级别")},{value:"debug",label:r("debug 及以上")},{value:"info",label:r("info 及以上")},{value:"warn",label:r("warn 及以上")},{value:"error",label:r("仅 error")}],t9=r("全部级别"),jM=r("全部分类"),n9={debug:r("调试"),info:r("信息"),warn:r("警告"),error:r("错误")};let Rg=vM,Og=!0,mw=!1,hw=!1,gw=!1,xw=null,Eo=null,bw=null,Mg=null,vw=!1,yw=!1;const jw={level:"",category:"",keyword:""};function s9(){const e=Lr().wbFilterMemory;if(!e)return{...jw};vw=!0;const t=e.load(uw,{...jw});return{level:pw.some(a=>a.value===t.level)?t.level:"",category:t.category,keyword:t.keyword}}function Dg(e){Lr().wbFilterMemory?.save(uw,{level:e.level||"",category:e.category||"",keyword:e.keyword.trim()||""})}function r9(){try{const e=localStorage.getItem(yM);return e!==null&&dw.includes(e)?e:fw}catch{return fw}}function a9(e){try{localStorage.setItem(yM,e)}catch{}}function Ig(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function l9(e){const t=new Date;switch(e){case"today":return Ig(t);case"7":return Ig(new Date(t.getFullYear(),t.getMonth(),t.getDate()-6));case"30":return Ig(new Date(t.getFullYear(),t.getMonth(),t.getDate()-29));case"month":return Ig(new Date(t.getFullYear(),t.getMonth(),1));default:return null}}function o9(e){if(!e)return"—";const t=new Date(e),a=d=>String(d).padStart(2,"0"),o=`${a(t.getHours())}:${a(t.getMinutes())}:${a(t.getSeconds())}`,c=`${a(t.getMonth()+1)}-${a(t.getDate())}`;return t.getFullYear()===new Date().getFullYear()?`${c} ${o}`:`${t.getFullYear()}-${c} ${o}`}function i9(e){const t=e.data;if(!t)return"";const a=[];return(t.from||t.to)&&a.push([t.from,t.to].filter(Boolean).join(" → ")),t.model&&a.push(r("模型 {model}",{model:t.model})),t.resetAtText?a.push(r("{time} 恢复",{time:t.resetAtText})):t.status&&!t.from&&!t.to&&a.push(`HTTP ${t.status}`),a.length?a.join(" · "):""}function ww(e){return Array.isArray(e?.entries)?e.entries:[]}function Pg(e,t,a){const o=Math.max(1,a==="all"?1:Math.ceil(t.length/a));return Math.min(Math.max(1,e),o)}function Sw(e,t){return Object.hasOwn(e,t)}function c9(e){const t={};if(e&&typeof e=="object")for(const[a,o]of Object.entries(e))typeof o=="string"&&(t[a]=o);return t}function wM(e,t){const a=new URLSearchParams,o=e.keyword.trim(),c=l9(t);return e.level&&a.set("level",e.level),e.category&&a.set("category",e.category),o&&a.set("keyword",o),c!==null&&a.set("start",String(c)),a}function u9(e,t){const a=wM(e,t);return a.set("limit",String(Q7)),a.toString()}function d9(e,t){return wM(e,t).toString()}function f9(e){xw=e||null,Lr().wbApp?.updateLogsBadge?.(xw)}async function p9(){if(!mw)try{const e=await Lr().workbuddyDesktop?.getScheduledTasks(),t=(e?.tasks||[]).find(a=>a.id==="logsAutoRefresh");Nw(t||null),mw=Array.isArray(e?.tasks)}catch(e){console.warn("读取日志自动刷新间隔失败,按默认 10 秒:",cw(e)),Nw(null)}}function Nw(e){mw=!0;const t=Number(e?.interval);!!e&&typeof e=="object"&&Number.isFinite(t)&&t>0&&(e.unit==="seconds"||e.unit==="minutes")?(Og=e.enabled!==!1,Rg=e.unit==="minutes"?t*6e4:t*1e3):(Og=!0,Rg=vM),Eo?.applyAutoConfig(Rg,Og)}async function m9(e={}){await Eo?.load(e)}function h9(e){if(!Eo){Mg={data:e??null};return}Eo.render(e)}function g9(){return xw}async function x9(e){if(!Eo){bw=e;return}await Eo.showCategory(e)}const b9={entries:[],total:0,matched:0,file:W7,categories:{},loaded:!1};function kw(e,t){return{entries:ww(e),total:Number(e?.total)||0,matched:Number(e?.matched)||0,file:e?.file||t.file,categories:Object.keys(t.categories).length?t.categories:c9(e?.categories),loaded:!0}}function v9(e){return e.loaded?e.total?r("没有符合筛选条件的日志"):r("暂无日志"):r("正在加载日志…")}function y9(){const[e,t]=x.useState(b9),[a,o]=x.useState(s9),[c,d]=x.useState(r9),[f,p]=x.useState(1),[g,v]=x.useState(()=>sg("logs")),[y,b]=x.useState(null),[j,w]=x.useState(()=>({ms:Rg,enabled:Og})),S=x.useRef(null),N=x.useRef(null),k=x.useRef(null),E=x.useRef(null),D=x.useRef(a),C=x.useRef(c),A=x.useRef(f),R=x.useRef(g),I=x.useRef(e),P=x.useCallback(re=>{const de={...D.current,...re};return D.current=de,o(de),de},[]),O=x.useCallback(re=>{C.current=re,d(re)},[]),_=x.useCallback(re=>{A.current=re,p(re)},[]),L=x.useCallback(re=>{R.current=re,v(re),rg("logs",re)},[]),H=x.useCallback(re=>{I.current=re,t(re)},[]),B=x.useCallback(()=>{if(vw)return;const re=Lr().wbFilterMemory;if(!re||(vw=!0,yw))return;const de=re.load(uw,{...jw});P({level:de.level,category:de.category,keyword:de.keyword})},[P]),z=x.useCallback(async(re={})=>{const{silent:de=!1,resetPage:ke=!1}=re;ke&&_(1),p9(),B();const Ee=u9(D.current,C.current),ve=A.current;try{const he=Lr().workbuddyDesktop;if(!he)throw new Error(r("后端桥不可用"));const[ye,we]=await Promise.all([he.getLogs(Ee),he.getLogStats()]),xe=ke?0:S.current?.scrollTop??0,Te=kw(ye,I.current);H(Te),_(Pg(A.current,ww(ye),R.current)),N.current=A.current===ve?xe:0,f9(we),Object.keys(Te.categories).length&&D.current.category&&!Sw(Te.categories,D.current.category)&&(Dg(P({category:""})),z({resetPage:!0}))}catch(he){de||(console.warn("读取运行日志失败:",cw(he)),H(kw(null,I.current)),_(Pg(A.current,[],R.current)))}},[H,_,B]),Q=x.useCallback(re=>{re!==void 0&&(H(kw(re,I.current)),_(Pg(A.current,ww(re),R.current)))},[H,_]),K=x.useCallback(async re=>{if(Sw(I.current.categories,re)||await z({silent:!0}),!Sw(I.current.categories,re))return;const de=P({category:re});Dg(de),_(1),await z({resetPage:!0}),Lr().wbApp?.showPage?.("logs",{persist:!0})},[P,_,z]);x.useEffect(()=>{if(Eo={load:z,render:Q,showCategory:K,applyAutoConfig:(de,ke)=>w({ms:de,enabled:ke})},Mg){const de=Mg;Mg=null,Q(de.data)}const re=bw;return re!==null?(bw=null,K(re)):z({silent:!0}),()=>{Eo=null,k.current!==null&&window.clearTimeout(k.current),k.current=null}},[z,Q,K]),x.useEffect(()=>{if(!j.enabled||j.ms<=0)return;const re=window.setInterval(()=>{document.hidden||Lr().wbApp?.currentPage!=="logs"||hw||(hw=!0,z({silent:!0}).finally(()=>{hw=!1}))},j.ms);return()=>{window.clearInterval(re)}},[j,z]),x.useLayoutEffect(()=>{const re=N.current;if(re===null)return;N.current=null;const de=S.current;de&&(de.scrollTop=re)});async function X(re,de,ke){if(!gw){gw=!0,b({which:re,label:de});try{await ke()}catch(Ee){Ag(r("操作失败:{error}",{error:cw(Ee)}),"err")}finally{gw=!1,b(null)}}}async function q(){const re=d9(D.current,C.current),de=re.length>0,ke=de?r("确定清空当前筛选出的 {count} 条日志?清空后无法恢复。",{count:Number(I.current.matched)||0}):r("确定清空全部运行日志?清空后无法恢复。"),Ee=Lr().wbConfirm?.ask;Ee&&await Ee({title:r("清空运行日志"),html:ke,okText:r("清空"),okClass:"danger"})&&await X("clear",r("清空中…"),async()=>{const ve=Lr().workbuddyDesktop;if(!ve)throw new Error(r("后端桥不可用"));await ve.clearLogs(de?re:"all=1"),await z({resetPage:!0}),Ag(r("运行日志已清空"))})}async function $(){await X("export",r("导出中…"),async()=>{const re=Lr().workbuddyDesktop;if(!re)throw new Error(r("后端桥不可用"));const de=await re.exportLogs();if(!(!de||de.canceled)){if(de.count===0){Ag(r("暂无日志可导出"),"err");return}Ag(r("✅ 已导出 {count} 条日志到 {file}",{count:String(de.count),file:String(de.file)}))}})}function Y(re){const de=Pg(re,I.current.entries,R.current);de!==A.current&&(_(de),N.current=0)}function F(re){if(re===R.current)return;const de=I.current.entries.length,ke=de?(A.current-1)*(R.current==="all"?de:R.current):0;L(re),_(re==="all"?1:Math.floor(ke/re)+1),N.current=0}function G(re){yw=!0,Dg(P(re)),z({resetPage:!0})}function W(re){yw=!0,P({keyword:re}),k.current!==null&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{k.current=null,Dg(D.current),z({resetPage:!0})},Z7)}function le(re){const de=dw.includes(re)?re:fw;de!==C.current&&(O(de),a9(de),z({resetPage:!0}))}const M=e.entries,U=g!=="all",Z=Math.max(1,U?Math.ceil(M.length/g):1),ae=Math.min(Math.max(1,f),Z),ce=U?M.slice((ae-1)*g,ae*g):M,J=M.length?U?(ae-1)*g+1:1:0,ie=M.length?U?J+ce.length-1:M.length:0,ge=e.categories,ee=e.matched===e.total?r("{n} 条",{n:e.total}):r("{matched} / {total} 条",{matched:e.matched,total:e.total});x.useEffect(()=>{const re=e.loaded?ee:"—";E.current!==re&&(E.current=re,Lr().wbApp?.renderTopbarStatus?.())},[e.loaded,ee]);function fe(re,de){const ke=re.level||"",Ee=i9(re);return s.jsxs("div",{className:`log-row ${ke}`,children:[s.jsx("span",{className:"log-rail",children:s.jsx("span",{className:`log-dot ${ke}`})}),s.jsxs("div",{className:"log-main",children:[s.jsxs("div",{className:"log-line",children:[s.jsx("span",{className:"log-cat",children:ge[re.category||""]||re.category}),s.jsx("span",{className:`log-lvl ${ke}`,children:n9[ke]||re.level}),s.jsx("span",{className:"msg",children:re.message})]}),Ee?s.jsx("div",{className:"log-extra-wrap",children:s.jsx("span",{className:"extra",children:Ee})}):null]}),s.jsx("span",{className:"time",children:o9(re.ts)})]},re.id??de)}const te=y?.which==="export",Ce=y?.which==="clear";return s.jsxs("section",{className:"panel",id:"logs-panel-events",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("系统事件")}),s.jsx(ze,{id:"logs-badge",variant:"outline","data-tone":"",children:e.loaded?ee:"—"}),s.jsxs("div",{className:"head-actions",children:[s.jsx(se,{id:"btn-logs-export",variant:"outline",disabled:y!==null,onClick:()=>{$()},children:te?y?.label:r("导出")}),s.jsx(se,{id:"btn-logs-clear",variant:"destructive",disabled:y!==null,onClick:()=>{q()},children:Ce?y?.label:r("清空")})]})]}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"log-filters",children:[s.jsx(In,{options:e9,value:c,onValueChange:le,"aria-label":r("事件日志时间范围"),className:"shrink-0"}),s.jsxs(ft,{value:a.level,onValueChange:re=>G({level:String(re??"")}),children:[s.jsx(mt,{id:"logs-level",className:"min-w-[120px]",title:r("按最低级别筛选"),"aria-label":r("按最低级别筛选"),children:s.jsx(pt,{children:pw.find(re=>re.value===a.level)?.label??t9})}),s.jsx(ht,{children:pw.map(re=>s.jsx(qe,{value:re.value,children:re.label},re.value))})]}),s.jsxs(ft,{value:a.category,onValueChange:re=>G({category:String(re??"")}),children:[s.jsx(mt,{id:"logs-category",className:"min-w-[120px]",title:r("按分类筛选"),"aria-label":r("按分类筛选"),children:s.jsx(pt,{children:a.category?ge[a.category]||a.category:jM})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"",children:jM}),Object.entries(ge).map(([re,de])=>s.jsx(qe,{value:re,children:de},re))]})]}),s.jsxs(Ci,{className:"w-auto flex-auto",children:[s.jsx(Ei,{id:"logs-keyword",type:"search",placeholder:r("搜索消息关键词…"),autoComplete:"off","aria-label":r("搜索消息关键词"),value:a.keyword,onChange:re=>W(re.currentTarget.value)}),s.jsx(Ti,{"aria-hidden":"true",children:"⌕"})]})]}),s.jsx("div",{className:"log-list",id:"log-list",ref:S,children:ce.length?ce.map((re,de)=>fe(re,de)):s.jsx("div",{className:"log-empty",children:v9(e)})})]}),s.jsx(Li,{total:M.length,range:U?{start:J,end:ie}:null,page:ae,pageCount:Z,size:g,sizes:X7,onSizeChange:F,onPageChange:Y})]})}const SM='.page[data-page="logs"]';let NM=!1;function kM(){if(NM)return;const e=document.querySelector(SM);e&&(NM=!0,e.replaceChildren(),vn.createRoot(e).render(s.jsx(y9,{})))}document.querySelector(SM)?kM():document.addEventListener("DOMContentLoaded",kM,{once:!0}),window.wbLogsPanel={load:m9,render:h9,lastStats:g9,applyAutoRefresh:Nw,showCategory:x9};const Eu=["maxInputTokens","maxOutputTokens","supportsToolCall","supportsImages","supportsVideo","supportsReasoning"],qf=["maxInputTokens","maxOutputTokens"],CM=["supportsToolCall","supportsImages","supportsVideo","supportsReasoning"],Au={maxInputTokens:r("上下文窗口"),maxOutputTokens:r("最大输出 Token"),supportsToolCall:r("工具调用"),supportsImages:r("图片识别"),supportsVideo:r("视频识别"),supportsReasoning:r("支持思考")};r("工具"),r("图片"),r("视频"),r("思考");const j9=1e8;function Cw(e){return qf.includes(e)}function Tw(e,t){if(Cw(e)){const a=typeof t=="number"?t:Number(t);return!Number.isFinite(a)||a<1||a>j9?null:Math.trunc(a)}return typeof t=="boolean"?t:null}function TM(e){const t={};if(!e||typeof e!="object")return t;const a=e;for(const o of Eu){const c=Tw(o,a[o]);c!==null&&(t[o]=c)}return t}function Ew(e){return Array.isArray(e)?Eu.filter(t=>e.some(a=>a===t)):[]}function Aw(e){return TM(e?.capabilities)}function EM(e){const t=Number(e);if(!Number.isFinite(t)||t<=0)return"—";const a=o=>o.toFixed(1).replace(/\.0$/,"");return t>=1e6?`${a(t/1e6)}M`:t>=1e3?`${a(t/1e3)}K`:String(Math.round(t))}function Gf(e){const t=Number(e);return!Number.isFinite(t)||t<=0?r("未声明"):Math.round(t).toLocaleString("en-US")}function Rw(e){return e===!0?"on":e===!1?"off":"unset"}function w9(e){const t=e?.reasoningLevels;if(!Array.isArray(t))return null;const a=t.filter(c=>typeof c=="string"&&c.trim()!=="");if(!a.length)return null;const o=e?.reasoningDefaultLevel;return{levels:a,defaultLevel:typeof o=="string"?o.trim():""}}function S9(e,t,a,o=""){const c=Au[e],d=a?r("(已被手动覆盖,弹窗里可恢复继承)"):"",f=N9(o);if(Cw(e))return t==null?r("{label}:上游未声明{suffix}",{label:c,suffix:d}):r("{label}:{value}(对下游声明的精确值){origin}{suffix}",{label:c,value:Gf(t),origin:f,suffix:d});const p=Rw(t);return p==="on"?r("{label}:支持{origin}{suffix}",{label:c,origin:f,suffix:d}):p==="off"?r("{label}:不支持{origin}{suffix}",{label:c,origin:f,suffix:d}):r("{label}:上游未声明(下游会按不支持处理){suffix}",{label:c,suffix:d})}function Ru(e,t){const a=e?.capSources?.[t];return a==="upstream"||a==="modelsdev"||a==="user"?a:""}function N9(e){return e==="modelsdev"?r("(由 models.dev 补齐)"):e==="user"?r("(手动设定)"):""}function k9(e){const t={};for(const a of Eu){const o=e[a];Cw(a)?t[a]=Tw(a,o.trim()):t[a]=o==="on"?!0:o==="off"?!1:null}return t}function Kf(){return window}const AM=e=>String(e??"").trim().toLowerCase(),Fs=(e,t)=>AM(e)===AM(t);function Jn(e){return typeof e=="string"&&e.startsWith("custom-")}function Fi(){return(Kf().wbProviders?.customList?.()||[]).filter(e=>Jn(e?.id))}function RM(){return Kf().wbProviders?.customList?.()||[]}function Ao(e){return Fi().find(t=>t.id===e)||null}function C9(e){const t=TM(e),a={};for(const o of Eu){const c=t[o];(typeof c=="number"||typeof c=="boolean")&&(a[o]=c)}return Object.keys(a).length?a:void 0}function OM(e){const t=(Array.isArray(e?.models)?e.models:[]).map(c=>{const d={id:String(c?.id??"").trim(),enabled:c?.enabled!==!1,reasoning:typeof c?.reasoning=="string"?c.reasoning:""};return d.capabilities=C9(c?.capabilities),d}).filter(c=>c.id),a=(Array.isArray(e?.mappings)?e.mappings:[]).map(c=>({alias:String(c?.alias??"").trim(),target:String(c?.target??"").trim(),enabled:c?.enabled!==!1,reasoning:typeof c?.reasoning=="string"?c.reasoning:""})).filter(c=>c.alias&&c.target);for(const c of t){const d=a.find(f=>Fs(f.alias,c.id)&&Fs(f.target,c.id));d&&(c.enabled=c.enabled&&d.enabled,c.reasoning=d.reasoning||c.reasoning)}const o=a.filter(c=>!(Fs(c.alias,c.target)&&t.some(d=>Fs(d.id,c.target))));return{models:t,mappings:o}}function MM(e){const t=Ao(e);if(!t)return null;const a=OM(t),o=t.name||e,c=[],d=[];for(const f of a.models)c.push({id:f.id,name:"",provider:e,providerLabel:o,source:"",enabled:f.enabled,aliases:[],capabilities:f.capabilities||{},capOverrides:[]}),d.push({alias:f.id,target:f.id,provider:e,enabled:f.enabled,reasoning:f.reasoning,isDefault:!0,dangling:!1,carried:!0});for(const f of a.mappings){const p=c.find(g=>Fs(g.id,f.target));d.push({alias:f.alias,target:f.target,provider:e,enabled:f.enabled,reasoning:f.reasoning,isDefault:!1,dangling:!p,carried:!!p}),p&&p.aliases.push(f.alias)}return{models:c,mappings:d}}async function $i(e,t){const a=Kf().wbProviders;if(!a?.customRequest)throw new Error(r("目录模块未就绪"));const o=Ao(e);if(!o)throw new Error(r("该自定义提供商已不存在(可能已被删除),请刷新后重试"));const c=OM(o),d=t(c);return await a.customRequest("POST","/api/custom-providers/models",{providerId:e,models:c.models,mappings:c.mappings}),await a.refreshCustom?.(),d}async function DM(e,t,a,o={}){const{enabled:c,reasoning:d}=o;await $i(e,f=>{if(Fs(t,a)){const g=f.models.find(v=>Fs(v.id,a));if(!g)throw new Error(r("该提供商的清单里没有模型「{name}」",{name:a}));return c!==void 0&&(g.enabled=!!c),d!==void 0&&(g.reasoning=String(d??"")),null}const p=f.mappings.find(g=>Fs(g.alias,t)&&Fs(g.target,a));if(p)return c!==void 0&&(p.enabled=!!c),d!==void 0&&(p.reasoning=String(d??"")),null;if(c===!1)throw new Error(r("映射「{alias} → {target}」不存在",{alias:t,target:a}));return f.mappings.push({alias:t,target:a,enabled:c??!0,reasoning:String(d??"")}),null})}async function IM(e,t,a){await $i(e,o=>{const c=o.mappings.length;if(o.mappings=o.mappings.filter(d=>!(Fs(d.alias,t)&&Fs(d.target,a))),o.mappings.length===c)throw new Error(r("映射「{alias} → {target}」不存在",{alias:t,target:a}));return null})}async function PM(e,t){const a=String(t??"").trim();if(!a)throw new Error(r("请填写模型 ID"));await $i(e,o=>{if(o.models.some(c=>Fs(c.id,a)))throw new Error(r("模型「{name}」已存在(忽略大小写判重)",{name:a}));return o.models.push({id:a,enabled:!0,reasoning:""}),null})}async function T9(e,t){const a=(Array.isArray(t)?t:[]).map(o=>String(o??"").trim()).filter(Boolean);if(!a.length)throw new Error(r("没有选中任何模型"));return $i(e,o=>{let c=0;for(const d of a)o.models.some(f=>Fs(f.id,d))||(o.models.push({id:d,enabled:!0,reasoning:""}),c++);return c})}async function _M(e,t,a){await $i(e,o=>{const c=o.models.find(f=>Fs(f.id,t));if(!c)throw new Error(r("该提供商的清单里没有模型「{name}」",{name:t}));const d={...c.capabilities||{}};for(const[f,p]of Object.entries(a))p==null?delete d[f]:d[f]=p;return c.capabilities=Object.keys(d).length?d:void 0,null})}async function LM(e,t){return $i(e,a=>{const o=a.mappings.length;a.mappings=a.mappings.filter(d=>!Fs(d.target,t));const c=o-a.mappings.length;return a.models=a.models.filter(d=>!Fs(d.id,t)),{removedMappings:c}})}async function E9(e){const t=Kf().wbProviders;if(!t?.customRequest)throw new Error(r("目录模块未就绪"));const a=await t.customRequest("POST","/api/custom-providers/fetch-models",{providerId:e}),o=(Array.isArray(a?.models)?a.models:[]).map(d=>String(d??"").trim()).filter(Boolean),c=await $i(e,d=>{let f=0;for(const p of o)d.models.some(g=>Fs(g.id,p))||(d.models.push({id:p,enabled:!0,reasoning:""}),f++);return f});return{total:o.length,added:Number(c)||0}}Kf().wbModelsCustom={isCustom:Jn,list:Fi,listSource:RM,record:Ao,buildView:MM,setBinding:DM,removeMapping:IM,addModel:PM,addModels:T9,removeModel:LM,setCapabilities:_M,fetchModels:E9};const ca="__custom__",A9=["off","none","minimal","low","medium","high","xhigh","max"];function Yf(e,t){const a=zM(t);if(a.length)return a;const o=e?.reasoningLevels;return Array.isArray(o)&&o.length?o.filter(c=>typeof c=="string"):[...A9]}function zM(e){const t=e?.reasoningLevels;return Array.isArray(t)?t.filter(a=>typeof a=="string"&&a.trim()!==""):[]}function R9(e,t){const a=t.map(zM).filter(f=>f.length>0);if(!a.length||a.length!==t.length)return Yf(e);const[o,...c]=a,d=o.filter(f=>c.every(p=>p.includes(f)));return d.length?d:Yf(e)}function BM(e,t,a){return`${String(e??"").trim().toLowerCase()}${String(t??"").trim().toLowerCase()}${String(a??"").trim().toLowerCase()}`}function O9(e){const t=new Map;for(const a of Array.isArray(e)?e:[]){const o=typeof a?.reasoning=="string"?a.reasoning.trim():"";o&&t.set(BM(a.alias,a.target,a.provider),o)}return(a,o,c)=>t.get(BM(a,o,c))||""}function Wt(){return window}function Ro(e){return e instanceof Error?e.message:String(e)}function yr(e,t){Wt().wbApp?.toast?.(e,t)}function Ow(e){const t=Wt().wbApp?.esc;return t?t(e):String(e??"").replace(/[&<>"']/g,a=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[a]||a)}function M9(e){const t=Wt().formatTime??Wt().wbApp?.formatTime;return String(t?.(e)??"")}const HM=e=>String(e??"").trim().toLowerCase(),Oo=(e,t)=>HM(e)===HM(t),UM=8,VM="workbuddy-desktop-models-filters",Mw=["all","enabled","disabled","mapped"],D9={all:r("全部"),enabled:r("已启用"),disabled:r("已禁用"),mapped:r("有映射")},I9=Mw.map(e=>({value:e,label:D9[e]})),Dw=["default","rate-asc","rate-desc"],P9={default:r("默认"),"rate-asc":r("倍率升序"),"rate-desc":r("倍率降序")},_9=Dw.map(e=>({value:e,label:P9[e]})),Iw=[{key:"check",label:r("选择"),align:"center"},{key:"model",label:r("上游模型")},{key:"rate",label:r("倍率")},{key:"source",label:r("来源")},{key:"budget",label:r("上下文 / 输出")},{key:"caps",label:r("能力")},{key:"alias",label:r("模型映射")},{key:"act",label:r("操作"),align:"right"}],FM=new Set(["rate","source"]),Xf="custom-all",Pw={models:[],mappings:[]},$M={provider:"all",state:"all",search:"",sort:"default"};function qM(){const e=Wt().wbFilterMemory;if(!e)return{...$M};const t=e.load(VM,{...$M});return{provider:String(t.provider||"all"),state:Mw.includes(t.state)?t.state:"all",search:String(t.search||""),sort:Dw.includes(t.sort)?t.sort:"default"}}const _g=qM();let GM=!!Wt().wbFilterMemory,Lg=!1,es={provider:_g.provider,stateFilter:_g.state,search:_g.search,sort:_g.sort,data:null,expanded:new Set,pending:new Set,mapping:null,customModel:null,capability:null};const _w=new Set;function Qf(){return es}function L9(e){return _w.add(e),()=>{_w.delete(e)}}function Is(e){const t={...es,...e},a=Bg(t),o=Bg(es)!==a;es=a===t.provider?t:{...t,provider:a},B9(),o&&Hg();for(const c of _w)c()}function zg(e){Wt().wbFilterMemory?.save(VM,e)}function KM(){if(GM||Lg||!Wt().wbFilterMemory)return;GM=!0;const e=qM();(e.provider!==es.provider||e.state!==es.stateFilter||e.search!==es.search||e.sort!==es.sort)&&Is(e)}function Bg(e){const t=e.provider;return t==="all"||t===Xf||Fi().some(a=>a.id===t)||Array.isArray(e.data?.models)&&e.data.models.some(a=>(a.provider||"")===t)||!e.data||!Lw()?t:"all"}function Ou(){return Bg(es)}function Lw(){return!!Wt().wbProviders}function Mu(){return Ou()===Xf}function YM(){return Mu()||Jn(Ou())}let Zf=null;function zw(e){const t=Ao(e);return(!Zf||Zf.id!==e||Zf.record!==t)&&(Zf={id:e,record:t,view:MM(e)||Pw}),Zf.view}let Wf=null;function z9(){const e=RM();if(Wf&&Wf.directory===e)return Wf.view;const t=[],a=[];for(const o of Fi()){const c=zw(String(o.id||""));t.push(...c.models||[]),a.push(...c.mappings||[])}return Wf={directory:e,view:t.length||a.length?{models:t,mappings:a}:Pw},Wf.view}function Bw(){const e=Ou();return Jn(e)?zw(e):e===Xf?z9():es.data||Pw}function Jf(){const e=Bw();return Array.isArray(e.models)?e.models:[]}function XM(){const e=Bw();return Array.isArray(e.mappings)?e.mappings:[]}let QM=(e,t,a)=>"";function B9(){QM=O9(XM())}function Hw(){const e=new Map,t=Array.isArray(es.data?.models)?es.data.models:[];for(const a of t){const o=a.provider||"";if(!o)continue;const c=e.get(o)||{label:a.providerLabel||o,n:0};c.n++,e.set(o,c)}return e}function H9(){const e=new Map;for(const t of Fi()){const a=String(t.id||"");if(!a)continue;const o=zw(a);e.set(a,{label:String(t.name||a),n:(o.models||[]).length})}return e}function U9(){return[...Hw().keys()]}function V9(e){const a=(Array.isArray(es.data?.models)?es.data.models:[]).find(o=>o.provider===e);return Number(a?.refreshedAt)||0}function Uw(){const e=new Map;for(const t of Jf()){const a=t.provider||"";a&&!e.has(a)&&e.set(a,t.providerLabel||a)}return[...e].map(([t,a])=>({id:t,label:a}))}function ZM(e){return e?Jf().filter(t=>(t.provider||"")===e).sort((t,a)=>+(t.enabled===!1)-+(a.enabled===!1)).map(t=>({id:t.id,label:t.name&&t.name!==t.id?r("{id}({name})",{id:t.id,name:t.name}):t.id,off:t.enabled===!1})):[]}function F9(){const e=[],t=Wt().wbProviders?.all?.();if(Array.isArray(t))for(const a of t){const o=String(a?.id||"");o&&e.push({id:o,label:String(a?.label||o)})}for(const a of Fi()){const o=String(a.id||"");o&&e.push({id:o,label:String(a.name||o)})}return e.length?e:Uw()}let ep=null,Vw=null;function WM(){const e=ep?ep.apply(Iw):Iw;return YM()?e.filter(t=>!FM.has(t.key)):e}function Hg(){Wt().wbColSettings?.syncStaticHead("models",Vw,YM()?FM:null)}function $9(){if(ep)return;ep=Wt().wbColSettings?.register({id:"models",label:r("模型管理表"),columns:Iw,mount:()=>document.querySelector('.page[data-page="gateway"] .panel-head .head-actions'),buttonPlacement:"last",onChange:()=>{Hg(),qi()}})||null,ep&&qi()}let Ug=0,Fw=!1;async function Vg({force:e=!1}={}){if(Fw&&!e)return;const t=++Ug;Fw=!0,KM();try{const a=await Wt().workbuddyDesktop?.getModelManage();if(t!==Ug)return;Is({data:a&&Array.isArray(a.models)?a:null})}catch(a){if(t!==Ug)return;qi(),yr(r("读取模型清单失败:{message}",{message:Ro(a)}),"err")}finally{t===Ug&&(Fw=!1)}}async function JM(){try{await Wt().wbProviders?.refreshCustom?.()}catch{}await Vg({force:!0})}function qi(){Is({})}function Gi(e){const t=e;if(t&&Array.isArray(t.models)){Is({data:t});return}qi()}async function Fg(e,t,a,o){if(Jn(e))return DM(e,t,a,o);const c=Wt().workbuddyDesktop;if(!c)throw new Error(r("后端桥不可用"));return c.addModelMapping(t,a,e,o.reasoning,o.enabled)}async function q9(e,t,a){if(Jn(e))return IM(e,t,a);const o=Wt().workbuddyDesktop;if(!o)throw new Error(r("后端桥不可用"));return o.removeModelMapping(t,a,e)}async function G9(e,t){if(Jn(e))return PM(e,t);const a=Wt().workbuddyDesktop;if(!a)throw new Error(r("后端桥不可用"));return a.addCustomModel(e,t)}async function e2(e,t){if(Jn(e))return LM(e,t);const a=Wt().workbuddyDesktop;if(!a)throw new Error(r("后端桥不可用"));return a.removeCustomModel(e,t)}async function K9(e,t,a){if(Jn(e))return _M(e,t,a);const o=Wt().workbuddyDesktop;if(!o)throw new Error(r("后端桥不可用"));return o.setModelCapabilities(e,t,a)}async function $w(e,t,a){if(!es.pending.has(e)){Is({pending:new Set(es.pending).add(e)});try{Gi(await t()),a&&yr(a)}catch(o){yr(r("操作失败:{message}",{message:Ro(o)}),"err")}finally{const o=new Set(es.pending);o.delete(e),Is({pending:o})}}}function tp(e){return Du(e).some(t=>t.enabled!==!1)}function Du(e){const t=e.provider||"",a=XM().filter(p=>Oo(p.target,e.id)&&(!p.provider||Oo(p.provider,t))),o=new Map;for(const p of a){const g=String(p.alias).toLowerCase();(!o.has(g)||p.provider)&&o.set(g,p)}const c=String(e.id).toLowerCase(),d=o.get(c);o.delete(c);const f=[{alias:e.id,target:e.id,provider:t,enabled:e.enabled!==!1&&d?.enabled!==!1,isDefault:!0}];return f.push(...o.values()),f}const Ki=e=>`${e.provider||""}:${e.id}`,qw=(e,t,a)=>`${e}:${t}:${a||""}`;function Y9(e){Is({expanded:new Set(es.expanded).add(e)})}function X9(e){const t=new Set(es.expanded);t.delete(e),Is({expanded:t})}function Q9(e){const t=Mw.includes(e)?e:"all";t!==es.stateFilter&&(Lg=!0,Is({stateFilter:t}),zg({state:t}))}function Z9(e){const t=Dw.includes(e)?e:"default";t!==es.sort&&(Lg=!0,Is({sort:t}),zg({sort:t}))}function W9(e){Lg=!0,Is({search:e}),zg({search:e})}function np(e){Is({provider:String(e??"").trim()||"all"}),zg({provider:es.provider}),Hg()}async function J9(e){const t=Wt().wbCustomProvidersUi;if(!t?.remove){yr(r("删除入口未就绪,请重试或重启应用"),"err");return}await t.remove(e)&&await Vg({force:!0})}function eK(){Wt().wbAccountAddForms?.openNewCustomForm?.()}function t2(e){Is({mapping:e})}function tK(){Is({mapping:null})}function nK(){const e=Ou(),t=Jn(e);Is({customModel:{provider:t||e!=="all"&&e!==Xf?e:"",locked:t}})}function sK(){Is({customModel:null})}function n2(e,t){Is({capability:{provider:e,id:t}})}function rK(){Is({capability:null})}function s2(e,t){return Jf().find(a=>(a.provider||"")===e&&Oo(a.id,t))||null}function Gw(e){if(Jn(e)){const t=Ao(e)?.name;return typeof t=="string"&&t||e}return Wt().wbProviders?.labelOf?.(e)||e}function r2(){const e=Ou(),t=Jn(e),a=t?Ao(e)?.name||e:r("内置提供商");Wt().wbModelsFetchModal?.open({providerId:e===Xf?"":e,custom:t,name:a,onDone:()=>qi(),onRefreshed:()=>{Vg({force:!0})}})}window.wbModelsPanel={render:qi,load:Vg,refreshAll:JM,refreshModels:r2,visibleColumns:WM,selectProvider:np,builtinProviders:U9,providerRefreshedAt:V9};function Kw(e,t,a){return QM(e,t,a)}function aK(e){Vw=e}function lK(){const e=Vw;if(!e)return;const t=o=>Object.keys(o).some(c=>c.startsWith("__reactFiber$")||c.startsWith("__reactInternalInstance$"));for(const o of[...e.children])o.tagName==="TBODY"?o.id!=="models"&&o.remove():o.tagName==="TR"&&!t(o)&&o.remove();const a=e.querySelector("tbody#models");if(a)for(const o of[...a.children])t(o)||o.remove()}const oK=e=>[{value:"inherit",label:e},{value:"on",label:r("支持")},{value:"off",label:r("不支持")}];function iK(e){const t=Rw(e);return r(t==="on"?"支持":t==="off"?"不支持":"未声明")}function a2(e,t,a,o,c=""){const d=t!=null,f=qf.includes(e)?Gf(t):iK(t);return a?o?r("已填写:对下游声明 {value}",{value:f}):r("已覆盖:对下游声明 {value}",{value:f}):o?r("未填写(下游按未声明处理)"):d?c==="modelsdev"?r("models.dev 补齐:对下游声明 {value}",{value:f}):r("继承上游:{value}",{value:f}):r("上游未声明(下游会按不支持处理)")}function cK(e,t,a){return a?Eu.filter(o=>{const c=e[o];return c!=null}):t}function uK(e,t){const a={};for(const o of Eu){const c=t.includes(o),d=e[o];qf.includes(o)?a[o]=c&&typeof d=="number"?String(d):"":a[o]=c?d===!0?"on":"off":"inherit"}return a}function dK({context:e,onClose:t}){const a=Jn(e.provider),o=s2(e.provider,e.id),c=w9(o),d=Aw(o),f=cK(d,Ew(o?.capOverrides),a),[p,g]=x.useState(()=>uK(d,f)),[v,y]=x.useState(""),[b,j]=x.useState(!1);if(!o)return s.jsx(Qt,{open:!0,onOpenChange:R=>{R||t()},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("模型能力")})}),s.jsx(Bt,{children:s.jsx("p",{className:"text-sm leading-[1.7] text-subtle",children:r("这一行已不在当前清单里(模型被移除、或目录刷新后上游不再提供它)。关闭后刷新列表再试。")})}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("关闭")})]})]})});const w=o.id,S=o.providerLabel||Gw(e.provider),N=r(a?"未声明":"继承上游"),k=r(a?"清除":"恢复继承");function E(R){const I=d[R];return D(R)?"":a?r("未填写"):typeof I=="number"?r("继承上游 {value}",{value:Gf(I)}):r("上游未声明")}function D(R){return f.includes(R)}function C(R,I){g(P=>({...P,[R]:I}))}async function A(){if(!b){for(const R of qf){const I=p[R].trim();if(I&&Tw(R,I)===null){y(r("{label}要填 1 ~ 1 亿之间的整数(留空 = {inherit})",{label:Au[R],inherit:N}));return}}j(!0),y(r("保存中…"));try{Gi(await K9(e.provider,e.id,k9(p))),t(),yr(r("✅ 已保存 {id} 的能力位({provider})",{id:w,provider:S}))}catch(R){y(r("保存失败:{message}",{message:Ro(R)})),j(!1)}}}return s.jsx(Qt,{open:!0,onOpenChange:(R,I)=>{if(!R){if(b){I.cancel();return}t()}},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("模型能力")})}),s.jsxs(Bt,{children:[s.jsxs("div",{className:"rounded-md border border-border bg-surface-inset px-3 py-2.5 font-mono text-[12px] text-subtle",children:[s.jsx("b",{className:"text-primary-fg",children:o.id}),r("({provider})",{provider:S})]}),qf.map(R=>s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-[7px]",children:[s.jsx(Je,{htmlFor:`cap-${R}`,children:Au[R]}),D(R)?s.jsx(se,{variant:"ghost",size:"2xs",disabled:b,title:r(a?"清除这一项(回到未声明)":"清除覆盖,回到上游声明值"),onClick:()=>C(R,""),children:k}):null]}),s.jsx($e,{id:`cap-${R}`,inputMode:"numeric",autoComplete:"off",spellCheck:!1,placeholder:E(R),disabled:b,value:p[R],onChange:I=>C(R,I.currentTarget.value),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),A())}}),s.jsx("p",{className:"text-xs leading-[1.6] text-subtle",children:a2(R,d[R]??null,D(R),a,Ru(o,R))})]},R)),CM.map(R=>s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{children:Au[R]}),s.jsx(In,{options:oK(N),value:p[R],"aria-label":Au[R],className:"self-start",onValueChange:I=>C(R,String(I))}),s.jsx("p",{className:"text-xs leading-[1.6] text-subtle",children:a2(R,d[R]??null,D(R),a,Ru(o,R))})]},R)),c?s.jsxs("div",{className:"rounded-md border border-border bg-surface-inset px-3 py-2.5 text-xs leading-[1.7] text-subtle",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[s.jsx("span",{children:r("可配思考档位")}),s.jsx("span",{className:"font-mono text-[12px] text-primary-fg",children:c.levels.join(" / ")}),c.defaultLevel?s.jsxs("span",{children:[r("(默认 "),s.jsx("span",{className:"font-mono text-[12px] text-primary-fg",children:c.defaultLevel}),r(")")]}):null]}),s.jsx("div",{className:"mt-1",children:r("这是模型自己能配的档位(来自上游目录),只读;要改某一档请到映射弹窗里选。")})]}):null,s.jsxs("p",{className:"text-xs leading-[1.65] text-subtle",children:[r("这几项是给"),s.jsx("b",{children:r("下游客户端")}),r("看的能力声明("),s.jsx("code",{children:"/v1/models"}),r(" 里的 "),s.jsx("code",{children:"max_input_tokens"})," / ",s.jsx("code",{children:"supports_*"}),r(" 与 "),s.jsx("code",{children:"input_modalities"}),r("),下游按它们决定发不发图片、按多大的窗口堆历史。"),s.jsx("b",{children:r("不影响网关的转发与路由")}),r("。上游清单给的值不准时,在这里改;"),r(a?"这家的清单是你自己登记的,不填的项下游按未声明处理。":"「恢复继承」会把这一项交还给上游清单的值。")]}),s.jsx("div",{className:"min-h-[18px] text-xs text-subtle",children:v})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:b,onClick:t,children:r("取消")}),s.jsx(se,{variant:"default",disabled:b,onClick:()=>{A()},children:r("保存")})]})]})})}function sp(){return window}const fK="你好",l2=4e3,pK=[{value:"chat_completions",label:"OpenAI - Chat Completions"},{value:"responses",label:"OpenAI - Responses"},{value:"anthropic",label:"Anthropic - Messages"}],mK={chat_completions:"Chat Completions",responses:"Responses",anthropic:"Anthropic Messages"},hK="direct",gK={remote:r("远程目录"),builtin:r("内置清单"),manual:r("手动登记")},xK=[{test:e=>e===429,hint:r("该账号对这个模型正在限额冷却,等一会儿自己会好;也可以先测别的账号。")},{test:e=>e===401||e===403,hint:r("上游拒绝了这条登录态:重新登录一次,或把这条账号删掉。")},{test:e=>e===404,hint:r("上游不认识这个模型名:先点「获取模型」刷新清单,或核对默认绑定指向的上游模型。")},{test:e=>e===504,hint:r("上游没在预算内给完回答。可以只勾一个账号再测一次,看是普遍慢还是某一个账号慢。")},{test:e=>e>=500,hint:r("多半是上游自己的问题,过一会儿再试。同一个错误出现在所有账号上时,先查模型目录与映射。")}];function o2(){return sp().wbApp?.getState?.()?.accounts?.accounts||[]}function i2(e){return o2().filter(t=>(t.provider||ou)===e&&t.available!==!1&&t.enabled!==!1).sort(Vh)}function c2(e){const t=String(e.email||"").trim();return t&&ir(e.provider).emailAsName?t:cu(e)||t||r("未命名账号")}function bK(){const e=globalThis.crypto?.randomUUID?.();if(e)return e;const t=a=>Array.from({length:a},()=>Math.floor(Math.random()*16).toString(16)).join("");return`${t(8)}-${t(4)}-4${t(3)}-a${t(3)}-${t(12)}`}function Yw(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"—":t<1e3?`${Math.round(t)} ms`:`${(t/1e3).toFixed(t<1e4?2:1)} s`}function vK(e,t){return i2(e).length?"":r("该提供商没有可用账号(要在账号页启用一个、且凭证完整),一行都发不出去")}function u2({children:e,plain:t=!1}){return s.jsxs("p",{className:t?"flex items-center gap-2 text-xs leading-[1.6] text-subtle":"flex gap-2 rounded-md border border-border bg-surface-2 px-3 py-2.5 text-xs leading-[1.65] text-subtle",children:[s.jsx("span",{"aria-hidden":"true",className:t?"size-4 flex-none rounded-full border border-border-strong text-center text-[10px] leading-[14px]":"mt-px size-4 flex-none rounded-full border border-border-strong text-center text-[10px] leading-[14px]",children:"i"}),s.jsx("span",{children:e})]})}function yK({open:e,label:t,text:a,onToggle:o}){return s.jsxs("div",{className:"overflow-hidden rounded-sm border border-border",children:[s.jsxs(se,{variant:"ghost",size:"xs",className:"w-full","aria-expanded":e,onClick:o,children:[s.jsx("span",{className:"truncate",children:t}),s.jsx("span",{"aria-hidden":"true",className:"ml-auto text-[10px]",children:e?"▴":"▾"})]}),e?s.jsx("div",{className:"border-t border-hairline bg-surface px-2.5 py-2",children:s.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11.5px] leading-[1.65] text-subtle",children:a})}):null]})}function jK(e){const[t,a]=x.useState(()=>Date.now());return x.useEffect(()=>{if(!e)return;a(Date.now());const o=window.setInterval(()=>a(Date.now()),400);return()=>window.clearInterval(o)},[e]),t}function d2(e){if(e.transport||!e.result||e.result.error)return!1;const t=Number(e.result.status)||0;return t>=200&&t<300}function wK({target:e,onClose:t}){const a=e.provider,o=s2(a,e.id),c=i2(a),d=cj(o2()),[f,p]=x.useState(""),[g,v]=x.useState(fK),[y,b]=x.useState("chat_completions"),[j,w]=x.useState(""),[S,N]=x.useState(null),[k,E]=x.useState(""),[D,C]=x.useState(""),[A,R]=x.useState(!0),[I,P]=x.useState(()=>{const te=c.find(Ce=>!xf(Ce,e.id))||c[0];return te?[te.id]:[]}),[O,_]=x.useState([]),[L,H]=x.useState(()=>new Set),B=x.useRef(0),z=x.useRef([]);z.current=O;const Q=O.some(te=>te.state==="running"),K=jK(Q);x.useEffect(()=>{let te=!0;return(async()=>{try{const Ce=sp().workbuddyDesktop?.getProxyPool;if(typeof Ce!="function")throw new Error(r("当前环境不支持代理池"));const re=await Ce();if(!te)return;if(!re||typeof re!="object"||!Array.isArray(re.items))throw new Error(r("代理池响应异常"));N(re.items),E("")}catch(Ce){if(!te)return;N([]),E(Ro(Ce))}})(),()=>{te=!1}},[]);const X=x.useCallback((te=!1)=>{const Ce=z.current.filter(re=>re.state==="running");B.current+=1;for(const re of Ce)sp().workbuddyDesktop?.terminateStatsRequest?.(re.testId)?.catch(()=>{});_([]),Ce.length&&!te&&yr(r("已中止在途测试({n} 个账号)",{n:Ce.length}))},[]);x.useEffect(()=>()=>{X(!0)},[X]);async function q(te,Ce){const re={provider:a,model:e.id,account_id:te.accountId,prompt:g.trim(),system_prompt:f.trim(),reasoning:D,stream:A,protocol:y,...j?{proxy:j}:{},test_id:te.testId},de=ke=>{B.current===Ce&&_(Ee=>Ee.map(ve=>ve.testId===te.testId?{...ve,...ke}:ve))};try{const ke=await sp().workbuddyDesktop?.testModel(re);if(!ke){de({state:"done",transport:r("桥接调用返回空(本机网关没有响应这次测试)")});return}de({state:"done",result:ke})}catch(ke){de({state:"done",transport:Ro(ke)})}}function $(){const te=c.filter(ke=>I.includes(ke.id));if(!te.length){yr(r("至少选一个测试账号"),"err");return}const Ce=B.current+1;B.current=Ce;const re=Date.now(),de=te.map(ke=>({accountId:ke.id,label:c2(ke),position:d.get(ke.id)?.position||0,testId:bK(),startedAt:re,state:"running"}));H(new Set),_(de);for(const ke of de)q(ke,Ce)}function Y(){Q?X():_([])}const F=s.jsx("span",{className:"ml-2 font-mono text-[12px] font-normal text-subtle",children:e.id});if(!o)return s.jsx(Qt,{open:!0,onOpenChange:te=>{te||t()},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("测试模型")})}),s.jsx(Bt,{children:s.jsx("p",{className:"text-sm leading-[1.7] text-subtle",children:r("这一行已不在当前清单里(模型被移除、或目录刷新后上游不再提供它)。关闭后刷新列表再试。")})}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("关闭")})]})]})});const G=Du(o).find(te=>te.isDefault)?.enabled===!1,W=Kw(o.id,o.id,a),le=Du(o).filter(te=>!te.isDefault).map(te=>te.alias),M=Yf(Qf().data,o).filter(te=>te!=="off"&&te!=="none"),U=G?r("跟随映射(该行未启用,本次不注入)"):W?r("跟随映射(当前 {level})",{level:W}):r("跟随映射(未绑定等级)"),Z=[r("以模型本名直发"),le.length?r("另有 {n} 条别名映射({aliases}),别名不参与本次",{n:le.length,aliases:le.join(r("、"))}):"",G?r("该行当前未启用:测试照常按本名直发(「先测通、再决定要不要启用」正是这颗按钮的用法),但本行的思考等级绑定不参与本次,生产路由也要等绑定打开后才会放行"):W?r("映射上绑定的思考等级是 {level},「跟随映射」按它注入",{level:W}):r("映射上未绑定思考等级,「跟随映射」等于这次不注入")].filter(Boolean).join(r(";"))+r("。"),ae=sp().wbProviders?.PROTOCOL_OPTIONS||pK,ce=ae.find(te=>te.value===y)?.label||y,J=[{value:"",label:r("跟随账号配置")},{value:hK,label:r("直连(不使用代理)")},...(S??[]).map(te=>({value:`${Ya}${te.id}`,label:au(te)}))];S===null?J.push({value:"__hint_pool__",label:r("正在读取代理列表…"),disabled:!0}):S.length||J.push({value:"__hint_pool__",label:r(k?"代理列表读取失败":"还没有代理(去「网络代理」页添加)"),disabled:!0});const ie=J.find(te=>te.value===j)?.label||r("跟随账号配置"),ge=c.map(te=>({value:te.id,label:`#${d.get(te.id)?.position||0} ${c2(te)}`+(xf(te,e.id)?r(" · 限额中"):"")}));function ee(te){const Ce=(he,ye)=>s.jsxs("div",{className:"flex items-center gap-2.5 border-b border-hairline px-3 py-2",children:[he,s.jsx("b",{className:"min-w-0 truncate text-[12.5px] text-foreground",title:te.label,children:te.label}),te.position?s.jsxs("span",{className:"flex-none text-xs text-subtle",children:["#",te.position]}):null,s.jsx("span",{className:"ml-auto flex-none font-mono text-[11.5px] tabular-nums text-subtle",children:ye})]},"head");if(te.state==="running"){const he=(K-te.startedAt)/1e3;return s.jsxs("div",{className:"flex items-center gap-2.5 rounded-md border border-border bg-surface-2 px-3 py-2.5 text-xs text-subtle",children:[s.jsx(Wd,{className:"flex-none"}),s.jsxs("span",{className:"min-w-0 truncate",children:[r("账号 "),s.jsx("b",{className:"text-foreground",children:te.label}),r(" 已发出,等待上游首帧…")]}),s.jsx("span",{className:"ml-auto flex-none font-mono tabular-nums",children:r("已等待 {seconds}s",{seconds:he.toFixed(1)})})]},te.testId)}const re=te.result;if(!d2(te)){const he=Number(re?.status)||0,ye=xK.find(we=>we.test(he))?.hint??(te.transport?r("确认桌面端还在运行,再重试一次。"):"");return s.jsxs("div",{className:"rounded-md border border-border bg-surface-2",children:[Ce(s.jsx(ze,{shape:"tag",variant:"destructive",className:"flex-none",children:he||r("失败")}),r("用时 {time}",{time:Yw(re?.duration_ms)})),s.jsxs("div",{className:"flex flex-col gap-1.5 px-3 py-2.5",children:[s.jsxs("div",{className:"text-[12.5px] leading-[1.7]",children:[te.transport?s.jsxs(s.Fragment,{children:[s.jsx("b",{className:"text-destructive",children:r("本机网关没有返回结论")}),r(":"),te.transport]}):s.jsxs(s.Fragment,{children:[s.jsx("b",{className:"text-destructive",children:r("测试未通过")}),r(":"),re?.error||r("上游没有给出可读的错误说明")]}),Number(re?.attempts)>1?r("(中间共尝试 {n} 次)",{n:Number(re?.attempts)}):""]}),ye?s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:ye}):null]})]},te.testId)}const de=String(re?.reply??""),ke=String(re?.reasoning??""),Ee=`think-${te.testId}`,ve=[re?.upstream_model&&re.upstream_model!==e.id?r("上游 {model}",{model:re.upstream_model}):"",re?.upstream_reasoning?r("思考等级 {level}",{level:re.upstream_reasoning}):"",re?.protocol&&re.protocol!=="chat_completions"?mK[re.protocol]||re.protocol:"",re?.proxy?r("节点 {proxy}",{proxy:re.proxy}):"",Number(re?.attempts)>1?r("尝试 {n} 次",{n:Number(re?.attempts)}):""].filter(Boolean).join(" · ");return s.jsxs("div",{className:"rounded-md border border-border bg-surface-2",children:[Ce(s.jsx(ze,{shape:"tag",variant:"success",className:"flex-none",children:Number(re?.status)||200}),r("用时 {time} · 首字 {ttfb}",{time:Yw(re?.duration_ms),ttfb:Yw(re?.ttfb_ms)})),s.jsxs("div",{className:"flex flex-col gap-2 px-3 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[11.5px] text-subtle",children:[s.jsx("span",{className:"flex-none",children:r("回复")}),ve?s.jsx("span",{className:"min-w-0 truncate",title:ve,children:ve}):null,s.jsx(se,{variant:"ghost",size:"2xs",className:"ml-auto flex-none","data-copy":de,children:r("复制")})]}),s.jsx("div",{className:"max-h-[220px] overflow-y-auto whitespace-pre-wrap rounded-sm border border-border bg-surface px-3 py-2 text-[12.5px] leading-[1.7]",children:de||s.jsx("span",{className:"text-subtle",children:r("(上游这一次返回了空正文)")})}),ke?s.jsx(yK,{open:L.has(Ee),label:r("思考过程({n} 字)",{n:ke.length}),text:ke,onToggle:()=>H(he=>{const ye=new Set(he);return ye.has(Ee)?ye.delete(Ee):ye.add(Ee),ye})}):null]})]},te.testId)}function fe(){if(Q){const Ce=O.length-O.filter(re=>re.state==="running").length;return s.jsxs(s.Fragment,{children:[O.length>1?s.jsxs("p",{className:"text-xs text-subtle",children:[r("正在测 "),s.jsx("b",{className:"text-foreground",children:O.length}),r(" 个账号"),Ce?s.jsxs(s.Fragment,{children:[r(",已完成 "),s.jsx("b",{className:"text-foreground",children:Ce})]}):null,r("。")]}):null,O.map(re=>ee(re))]})}const te=O.filter(d2).length;return s.jsxs(s.Fragment,{children:[O.length>1?s.jsxs("p",{className:"text-xs text-subtle",children:[s.jsx("b",{className:te?"text-success":"text-foreground",children:te}),r(" 成功 ·"),s.jsxs("b",{className:O.length-te?"text-destructive":"text-foreground",children:[" ",O.length-te]}),r(" 失败")]}):null,O.map(Ce=>ee(Ce)),te===0?s.jsxs(u2,{children:[r("两边原因不一样时各自处理。如果"),s.jsx("b",{className:"text-foreground",children:r("同一条错误出现在所有账号上")}),r(",通常就不是账号问题了:先确认这个模型还在上游目录里(「获取模型」刷一次),再看默认绑定指向的上游模型对不对。")]}):null]})}return s.jsx(Qt,{open:!0,onOpenChange:te=>{te||t()},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsxs(Gt,{children:[r("测试模型"),F]})}),s.jsxs(Bt,{children:[s.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border bg-surface-inset px-3 py-2.5",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[12.5px] font-semibold text-primary-fg",title:o.id,children:o.id}),s.jsx(ze,{shape:"tag",variant:"brand",children:Gw(a)}),s.jsx(ze,{shape:"tag",variant:"outline",children:Jn(a)?r("自定义家"):gK[o.source]||r("来源未知")}),s.jsxs(Ii,{children:[s.jsx(Pi,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("本次测试的发送口径")}),children:"?"}),s.jsx(_i,{children:Z})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"model-test-system",children:r("系统提示词")}),s.jsx(Qc,{id:"model-test-system",rows:2,maxLength:l2,placeholder:r("留空则不携带;设置页的提示词模式照常生效"),value:f,onChange:te=>p(te.currentTarget.value)})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"model-test-prompt",children:r("用户提示词")}),s.jsx(Qc,{id:"model-test-prompt",rows:2,maxLength:l2,placeholder:r("留空用默认问候「你好」"),value:g,onChange:te=>v(te.currentTarget.value)})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(Je,{htmlFor:"model-test-protocol",children:r("对话协议")}),s.jsxs(Ii,{children:[s.jsx(Pi,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("对话协议的说明")}),children:"?"}),s.jsx(_i,{children:r("按所选网关对话协议组装请求并校验响应转换(Chat Completions / Responses / Anthropic Messages)。")})]})]}),s.jsxs(ft,{value:y,onValueChange:te=>b(String(te)),children:[s.jsx(mt,{id:"model-test-protocol",className:"w-full",children:s.jsx(pt,{className:"min-w-0 truncate",children:ce})}),s.jsx(ht,{children:ae.map(te=>s.jsx(qe,{value:te.value,children:te.label},te.value))})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(Je,{htmlFor:"model-test-proxy",children:r("测试节点")}),s.jsxs(Ii,{children:[s.jsx(Pi,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("测试节点的说明")}),children:"?"}),s.jsx(_i,{children:r("仅本次测试临时生效,不修改账号保存的代理配置。可选「网络代理」页里的节点或强制直连。")})]})]}),s.jsxs(ft,{value:j,onValueChange:te=>w(String(te)),children:[s.jsx(mt,{id:"model-test-proxy",className:"w-full",children:s.jsx(pt,{className:"min-w-0 truncate",children:ie})}),s.jsx(ht,{children:J.map(te=>s.jsx(qe,{value:te.value,disabled:te.disabled,children:te.label},te.value))})]})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"model-test-reasoning",children:r("思考等级")}),s.jsxs(ft,{value:D,onValueChange:te=>C(String(te)),children:[s.jsx(mt,{id:"model-test-reasoning",className:"w-full",children:s.jsx(pt,{children:D?r("{level}(本次指定)",{level:D}):U})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"",children:U}),M.map(te=>s.jsx(qe,{value:te,children:r("{level}(本次指定)",{level:te})},te))]})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(Je,{htmlFor:"model-test-stream",children:r("流式请求")}),s.jsxs(Ii,{children:[s.jsx(Pi,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("流式请求的说明")}),children:"?"}),s.jsx(_i,{children:r("默认开,与真实请求一致:可同时验证 SSE 链路与首字延迟。")})]})]}),s.jsx(ms,{id:"model-test-stream",checked:A,onCheckedChange:te=>R(!!te)})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Je,{htmlFor:"model-test-accounts",children:r("测试账号")}),s.jsxs(Ii,{children:[s.jsx(Pi,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("测试账号的说明")}),children:"?"}),s.jsx(_i,{children:r("勾几个就并行测几次;默认选队列里最靠前的一个。")})]}),s.jsx(se,{variant:"ghost",size:"xs",className:"ml-auto",disabled:!c.length||I.length===c.length,onClick:()=>P(c.map(te=>te.id)),children:r("全选({n})",{n:c.length})})]}),s.jsx(_h,{id:"model-test-accounts",value:I,onValueChange:P,options:ge,placeholder:r("选一个账号(至少一个)"),searchPlaceholder:r("搜索账号…"),emptyHint:r("这家没有可用账号(要在账号页启用一个、且凭证完整)")})]}),s.jsx(u2,{plain:!0,children:r("真实链路 · 消耗少量额度 · 日志带「测试」标记,不计报表")})]}),s.jsxs(nn,{className:"justify-end",children:[s.jsx(se,{variant:"outline",onClick:t,children:r("关闭")}),s.jsx(se,{variant:"default",disabled:!I.length||!c.length,onClick:$,children:r("开始测试")})]}),s.jsx(Qt,{open:O.length>0,onOpenChange:te=>{te||Y()},children:s.jsxs(Zt,{overlayForceRender:!0,className:"w-[min(680px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsxs(Gt,{children:[r(Q?"测试中…":"测试结果"),F]})}),s.jsx(Bt,{children:fe()}),s.jsx(nn,{className:"justify-end",children:Q?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mr-auto text-xs text-subtle",children:r("关闭即中止")}),s.jsx(se,{variant:"outline",onClick:()=>X(),children:r("中止测试")}),s.jsx(se,{variant:"default",disabled:!0,children:r("测试中…")})]}):s.jsxs(s.Fragment,{children:[s.jsx(se,{variant:"outline",onClick:Y,children:r("关闭")}),s.jsx(se,{variant:"default",onClick:$,children:r("再测一次")})]})})]})})]})})}const f2=[{value:"enable",label:r("启用")},{value:"disable",label:r("禁用")},{value:"reasoning",label:r("设置思考等级")},{value:"delete",label:r("删除")}];function p2(e){return e.source==="manual"||Jn(e.provider)}function SK(e){return(e.name&&e.name!==e.id?r("{name}({id})",{name:e.name,id:e.id}):e.id)||e.id}function NK({models:e,onClose:t,onDone:a}){const[o,c]=x.useState("enable"),d=R9(Qf().data,e),[f,p]=x.useState(()=>({select:d[0]||"",custom:""})),[g,v]=x.useState(!1),[y,b]=x.useState(""),j=f.select===ca?f.custom.trim():f.select,w=e.filter(p2).length,S=f2.find(E=>E.value===o)?.label||r("操作");async function N(E){return Promise.resolve(Wt().wbConfirm?.ask?.({title:r("删除选中的模型"),html:r("确定删除选中的 {count} 个模型登记?删除后 /v1/models 不再广告它们、请求也会被拒。",{count:E})+(e.length>E?"
"+r("另有 {n} 个非手动登记的模型将被跳过。",{n:e.length-E}):""),okText:r("删除"),okClass:"danger"})??!1)}async function k(){if(g)return;if(!e.length){yr(r("没有选中的模型"),"err");return}if(o==="reasoning"&&f.select===ca&&!j){b(s.jsx("span",{className:"text-destructive",children:r("请填写自定义思考等级,或改选候选档 / 「清除」")}));return}if(o==="delete"){if(w===0){b(s.jsx("span",{className:"text-destructive",children:r("选中的模型都不是手动登记,无法删除(开关映射才是它们的手段)")}));return}if(!await N(w))return}v(!0),b("");let E=0,D=0,C=0,A="";for(const R of e){const I=R.provider||"";try{if(o==="delete"){if(!p2(R)){D+=1;continue}Gi(await e2(I,R.id))}else if(o==="enable"||o==="disable"){const P=o==="enable";for(const O of Du(R))Gi(await Fg(I,O.alias,R.id,{enabled:P}))}else for(const P of Du(R))Gi(await Fg(I,P.alias,R.id,{reasoning:j}));E+=1}catch(P){C+=1,A||(A=Ro(P)),b(s.jsx("span",{className:"text-destructive",children:r("失败 {n} 个 · 首个失败:{error}",{n:C,error:A})}))}}C===0?(yr(D?r("✅ 批量{action}完成:共 {n} 个模型(跳过不可删除的 {skipped} 个)",{action:S,n:E,skipped:D}):r("✅ 批量{action}完成:共 {n} 个模型",{action:S,n:E})),a()):(yr(r("批量{action}完成:成功 {ok} 个,失败 {failed} 个",{action:S,ok:E,failed:C}),"err"),b(s.jsxs("span",{className:"text-destructive",children:[r("成功 {ok} 个,失败 {failed} 个",{ok:E,failed:C}),D?r(",跳过 {n} 个",{n:D}):"",A?r(";首个失败:{error}",{error:A}):""]}))),v(!1)}return s.jsx(Qt,{open:!0,onOpenChange:E=>{E||g||t()},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("批量操作 · 已选 {n} 个模型",{n:e.length})})}),s.jsxs(Bt,{children:[s.jsxs(Vn,{children:[s.jsx("h3",{children:r("将作用于以下模型")}),s.jsx("p",{style:{maxHeight:84,overflowY:"auto"},children:e.map(SK).join(r("、"))})]}),s.jsxs(Vn,{children:[s.jsx("h3",{children:r("操作")}),s.jsx(kh,{value:o,onValueChange:E=>c(E),className:"flex-row flex-wrap items-center gap-5","aria-label":r("批量动作"),children:f2.map(E=>s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(bo,{value:E.value}),E.label]},E.value))}),o==="reasoning"?s.jsxs("div",{className:"mt-2.5",children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:"batch-model-reasoning",children:r("思考等级")}),s.jsxs(ft,{value:f.select,onValueChange:E=>p(D=>({...D,select:String(E)})),children:[s.jsx(mt,{id:"batch-model-reasoning",className:"min-w-[220px]",children:s.jsx(pt,{children:f.select===ca?r("自定义等级…"):f.select||r("清除(不覆盖)")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"",children:r("清除(不覆盖)")}),d.map(E=>s.jsx(qe,{value:E,children:E},E)),s.jsx(qe,{value:ca,children:r("自定义等级…")})]})]})]}),f.select===ca?s.jsxs("div",{className:"field-row mt-2",children:[s.jsx("label",{htmlFor:"batch-model-reasoning-custom",children:r("自定义等级")}),s.jsx($e,{id:"batch-model-reasoning-custom",maxLength:32,value:f.custom,onChange:E=>p(D=>({...D,custom:E.currentTarget.value}))})]}):null,s.jsxs("p",{className:"detail mt-1.5",children:[r("设置 / 清除会应用到选中模型的"),s.jsx("b",{children:r("全部映射")}),r("(默认绑定与别名 chips);「清除」= 不给这些映射指定等级(选「不覆盖」的口径与映射弹窗一致)")]})]}):null,o==="delete"?s.jsx("p",{className:"detail mt-2",children:w===0?r("选中的都不是手动登记的模型,删除不可用(上游目录带回来的行由清单决定存在性)"):r("可删除 {n} 个(手动登记 / 自定义家);",{n:w})+(e.length>w?r("其余 {n} 个会被跳过。",{n:e.length-w}):"")}):null]}),s.jsx("div",{className:"detail",style:{minHeight:18},children:y})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:g,onClick:t,children:r("关闭")}),s.jsx(se,{variant:o==="delete"?"destructive":"default",disabled:g,onClick:()=>{k()},children:g?r("执行中…"):r("执行{action}",{action:S})})]})]})})}function er(){return window}const m2={intl:"fm-table-intl",custom:"fm-table-custom"},h2={intl:"fetch-models",custom:"fetch-models-custom"},Xw=["provider","source","state","count","note","updated","op"],Qw=["pick","model","state"],kK={provider:"w-[13%]",source:"w-[21%]",state:"w-[9%]",count:"w-[6%]",note:"w-[20%]",updated:"w-[16%]",op:"w-[15%]"},CK={pick:"w-[8%]",model:"w-[74%]",state:"w-[18%]"},TK={pick:"",provider:r("提供商"),source:r("模型来源"),state:r("状态"),count:r("模型数"),note:r("说明"),updated:r("更新日期"),model:r("上游模型"),op:r("操作")},EK={refreshed:{variant:"brand",label:r("已刷新")},failed:{variant:"destructive",label:r("失败")},skipped:{variant:"outline",label:r("跳过")}},g2=new Set(["cline-free","cline-pass"]),x2="workbuddy-desktop-fetch-model-source";function rp(e){return String(e??"").trim().toLowerCase()}function Zw(e,t){er().wbApp?.toast?.(e,t)}function Ww(e){return e instanceof Error?e.message:String(e)}function b2(e){const t=er().formatTime??er().wbApp?.formatTime;return String(t?.(e)??"")}function v2(){return er().wbApp?.getState?.()?.accounts?.accounts||[]}function AK(e){const a=(er().wbProviders?.customList?.()||[]).find(o=>o.id===e)?.models;return new Set((Array.isArray(a)?a:[]).map(o=>rp(o?.id)).filter(Boolean))}function y2(e){if(e?.nameCustom===!0&&e?.name)return e.name;const t=String(e?.email||"").trim();return er().wbAccountsModel?.providerFeatures?.(e?.provider)?.emailAsName&&t?t:String(e?.nickname||e?.name||t||e?.id||"").trim()||r("未命名账号")}function RK(e){if(g2.has(e))return[];const t=er().wbAccountsModel?.byPriorityOrder,a=v2().filter(o=>(o?.provider||"workbuddy")===e&&o?.available!==!1&&o?.enabled!==!1);return t?a.sort(t):a}function j2(){const e=new Set(er().wbModelsPanel?.builtinProviders?.()||[]);for(const t of v2())t?.available===!1||t?.enabled===!1||e.add(t?.provider||"workbuddy");return[...e]}function OK(){const e=new Set(j2());return(er().wbProviders?.all?.()||[]).filter(t=>e.has(t?.id??""))}function MK(e){return b2(Number(e.refreshedAt)||0)||"—"}function DK(e){return EK[String(e.status)]??{variant:"outline",label:String(e.status||r("未知"))}}function IK(){try{const e=JSON.parse(localStorage.getItem(x2)||"{}");if(!e||typeof e!="object")return{};const t={};for(const[a,o]of Object.entries(e))typeof o=="string"&&o&&(t[a]=o);return t}catch{return{}}}function PK(e){er().wbFilterMemory?.save?.(x2,e)}function _K({options:e,onClose:t}){const a=e.providerId,o=!!e.custom,c=e.name||a,{onDone:d,onRefreshed:f}=e,[p,g]=x.useState("idle"),[v,y]=x.useState(""),[b,j]=x.useState(""),[w,S]=x.useState(null),[N,k]=x.useState(""),E=w!==null,[D,C]=x.useState(!1),[A,R]=x.useState([]),[I,P]=x.useState(()=>new Set),[O,_]=x.useState(()=>new Set),[L,H]=x.useState([]),[B,z]=x.useState(""),[Q,K]=x.useState(IK);x.useEffect(()=>{er().wbTableColumns?.repaint?.(o?h2.custom:h2.intl)},[o]);const X=o?[]:OK(),q=o?[]:G(),$=B.trim().toLowerCase(),Y=A.filter(ve=>!$||ve.toLowerCase().includes($)),F=o?D?r("已选 {picked} 个 · 上游共 {upstream} 个 · 清单已有 {managed} 个",{picked:O.size,upstream:A.length,managed:I.size}):r("尚未获取"):W(q);function G(){const ve=new Map(L.map(we=>[String(we.provider||""),we])),he=X.map(we=>{const xe=String(we.id||"");return{provider:xe,label:String(we.label||xe),item:ve.get(xe)}}),ye=new Set(he.map(we=>we.provider));for(const we of L){const xe=String(we.provider||"");ye.has(xe)||he.push({provider:xe,label:String(we.providerLabel||xe),item:we})}return he}function W(ve){if(p==="loading")return r("正在刷新…");if(p==="error")return"";const he=ve.map(xe=>xe.item).filter(xe=>!!xe);if(!he.length)return D?r("刷新完成,但没有得到任何结果"):ve.length?r("共 {n} 家 · 点「获取模型」开始",{n:ve.length}):r("0 家");const ye=he.filter(xe=>xe.status==="refreshed").length,we=he.filter(xe=>xe.status==="failed").length;return we?r("{total} 家 · 成功 {done} · 失败 {failed}",{total:ve.length,done:ye,failed:we}):r("{total} 家 · 成功 {done}",{total:ve.length,done:ye})}function le(ve,he){const ye=RK(ve);if(!ye.length)return{list:ye,selected:""};const we=String(Q[ve]||""),xe=String(he||""),Te=Oe=>ye.some(Ne=>String(Ne.id)===Oe);return{list:ye,selected:Te(we)?we:Te(xe)?xe:String(ye[0].id)}}function M(ve){const he={};for(const[ye,we]of Object.entries(Q))we&&(he[ye]=we);for(const ye of ve){const{selected:we}=le(ye.provider,ye.reported);we&&(he[ye.provider]=we)}return he}const U=q.map(ve=>({provider:ve.provider,reported:ve.item?.accountId}));function Z(ve,he){K(ye=>({...ye,[ve]:he})),PK({[ve]:he})}async function ae(){if(!E){S("load"),j(""),y(""),g("loading");try{if(o){const he=await er().wbProviders?.customRequest?.("POST","/api/custom-providers/fetch-models",{providerId:a}),ye=new Set,we=(Array.isArray(he?.models)?he.models:[]).map(Te=>String(Te??"").trim()).filter(Te=>{const Oe=rp(Te);return!Te||ye.has(Oe)?!1:(ye.add(Oe),!0)}),xe=AK(a);R(we),P(xe),_(new Set(we.filter(Te=>!xe.has(rp(Te))))),C(!0),g("ready");return}const ve=await er().workbuddyDesktop?.refreshModels({accounts:M(U),providers:j2()});H(Array.isArray(ve?.results)?ve.results:[]),C(!0),g("ready"),Number(ve?.refreshed)>0&&f?.()}catch(ve){const he=Ww(ve);y(he),g("error"),j(he)}finally{S(null)}}}async function ce(ve){if(!(E||!ve.provider)){S("row"),k(ve.provider),j("");try{const he=await er().workbuddyDesktop?.refreshModels({accounts:M([{provider:ve.provider,reported:ve.item?.accountId}]),providers:[ve.provider]});H(ye=>J(ye,Array.isArray(he?.results)?he.results:[])),C(!0),g("ready"),Number(he?.refreshed)>0&&f?.()}catch(he){const ye=Ww(he);j(ye),Zw(r("获取失败:{message}",{message:ye}),"err")}finally{S(null),k("")}}}function J(ve,he){const ye=new Map(he.map(Te=>[String(Te.provider||""),Te])),we=ve.map(Te=>ye.get(String(Te.provider||""))??Te),xe=new Set(we.map(Te=>String(Te.provider||"")));for(const Te of he)xe.has(String(Te.provider||""))||we.push(Te);return we}async function ie(){if(!o||E||!O.size)return;const ve=[...O];S("import"),j("");try{const he=Number(await er().wbModelsCustom?.addModels?.(a,ve))||0;Zw(r("✅ 已导入 {added} 个模型({skipped} 个已存在,跳过)",{added:he,skipped:ve.length-he})),S(null),t(),d?.()}catch(he){const ye=Ww(he);Zw(r("导入失败:{message}",{message:ye}),"err"),j(ye),S(null)}}function ge(){E||t()}function ee(){const ve=new Set(O);for(const he of A)I.has(rp(he))||ve.add(he);_(ve)}function fe(ve){return s.jsx(kl,{children:s.jsx(Nn,{colSpan:o?Qw.length:Xw.length,className:"py-[26px] text-center text-muted-foreground",children:ve})})}function te(ve){return s.jsx("span",{className:"font-mono text-[11.5px] tabular-nums text-muted-foreground",children:ve})}function Ce(ve){return s.jsx("div",{className:"truncate font-mono text-[12px] font-semibold",children:ve})}function re(ve,he){const{list:ye,selected:we}=le(ve,he);if(!ye.length){const Te=g2.has(ve)?r("这家的模型清单是全局的,不跟账号走"):r("这家还没有可用账号,刷新会使用默认登录态");return s.jsx("span",{className:"text-[11.5px] text-muted-foreground",title:Te,children:"—"})}const xe=ye.find(Te=>String(Te.id)===we);return s.jsxs(ft,{value:we,onValueChange:Te=>Z(ve,String(Te)),children:[s.jsx(mt,{className:"w-full",title:r("用哪个账号去拉这家的模型清单"),"aria-label":r("模型来源"),children:s.jsx(pt,{children:xe?y2(xe):"—"})}),s.jsx(ht,{children:ye.map(Te=>s.jsx(qe,{value:String(Te.id),children:y2(Te)},String(Te.id)))})]})}function de(){return p==="idle"?fe(r("点右侧「获取模型」从上游拉取这家的模型清单")):p==="loading"?fe(r("正在获取…")):p==="error"?fe(r("获取失败:{message}",{message:v})):Y.length?Y.map(ve=>{const he=I.has(rp(ve));return s.jsxs(kl,{className:he?"opacity-50":void 0,children:[s.jsx(Nn,{children:s.jsx(Or,{checked:O.has(ve),disabled:he,"aria-label":ve,onCheckedChange:ye=>_(we=>{const xe=new Set(we);return ye?xe.add(ve):xe.delete(ve),xe})})}),s.jsx(Nn,{children:Ce(ve)}),s.jsx(Nn,{children:he?s.jsx(ze,{variant:"brand",title:r("这个模型已经在这家的清单里,不重复导入"),children:r("已添加")}):s.jsx(ze,{variant:"outline",title:r("勾上它,导入后即进入这家的清单"),children:r("未添加")})})]},ve)}):fe(A.length?r("没有匹配「{keyword}」的模型",{keyword:$}):r("上游没有返回任何模型"))}function ke(ve){const he=w==="row"&&N===ve.provider;return s.jsx(se,{variant:"outline",size:"sm",className:"w-full",disabled:E,title:r("只刷新这一家的模型清单"),onClick:()=>{ce(ve)},children:he?r("获取中…"):ve.item?r("重新获取"):r("获取")})}function Ee(){return p==="loading"?fe(r("正在获取…")):p==="error"?fe(r("获取失败:{message}",{message:v})):q.length?q.map(ve=>{const he=ve.item;if(!he){const Te=b2(Number(er().wbModelsPanel?.providerRefreshedAt?.(ve.provider))||0);return s.jsxs(kl,{children:[s.jsx(Nn,{children:Ce(ve.label)}),s.jsx(Nn,{children:re(ve.provider)}),s.jsx(Nn,{children:s.jsx(ze,{variant:"outline",children:r("待获取")})}),s.jsx(Nn,{children:te("—")}),s.jsx(Nn,{children:te("—")}),s.jsx(Nn,{children:te(Te||"—")}),s.jsx(Nn,{children:ke(ve)})]},ve.provider)}const ye=DK(he),we=Number(he.count),xe=he.status==="refreshed"?r("远程目录已更新,「来源」列会显示为「远程」"):he.message||(he.fixed?r("这家用固定模型清单,无可刷新"):r("本次没有取到新内容"));return s.jsxs(kl,{children:[s.jsx(Nn,{children:Ce(ve.label)}),s.jsx(Nn,{children:re(ve.provider,he.accountId)}),s.jsx(Nn,{children:s.jsx(ze,{variant:ye.variant,children:ye.label})}),s.jsx(Nn,{children:te(we?r("{n} 个",{n:we}):"—")}),s.jsx(Nn,{children:s.jsx("span",{className:"text-[11.5px] leading-[1.5] text-muted-foreground",children:xe})}),s.jsx(Nn,{children:te(MK(he))}),s.jsx(Nn,{children:ke(ve)})]},ve.provider)}):fe(r("还没有可刷新的提供商:先在账号页添加一个账号"))}return s.jsx(Qt,{open:!0,onOpenChange:(ve,he)=>{if(!ve){if(E){he.cancel();return}t()}},children:s.jsxs(Zt,{className:o?"w-[min(552px,calc(100vw-48px))]":"w-[min(920px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("获取模型 — {name}",{name:c})})}),s.jsxs(Bt,{children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx("span",{className:"text-[11.5px] text-muted-foreground",children:F}),o&&s.jsxs(Ci,{className:"w-[240px] flex-none",children:[s.jsx(Ei,{type:"search",placeholder:r("搜索模型 ID…"),autoComplete:"off",value:B,onChange:ve=>z(ve.currentTarget.value)}),s.jsx(Ti,{"aria-hidden":"true",children:"⌕"})]}),s.jsx("div",{className:"mr-auto"}),o&&s.jsxs(s.Fragment,{children:[s.jsx(se,{variant:"ghost",size:"sm",onClick:ee,children:r("全选未添加")}),s.jsx(se,{variant:"ghost",size:"sm",onClick:()=>_(new Set),children:r("清空")})]}),s.jsx(se,{variant:"outline",size:"sm",title:r("刷新全部家(逐家打上游)"),disabled:E,onClick:()=>{ae()},children:r(w==="load"?"获取中…":D?"重新获取":"获取模型")})]}),s.jsxs(Vy,{id:o?m2.custom:m2.intl,className:"table-fixed",containerClassName:"max-h-[min(48vh,460px)]",children:[s.jsx("colgroup",{children:(o?Qw:Xw).map(ve=>s.jsx("col",{"data-col":ve,className:o?CK[ve]:kK[ve]},ve))}),s.jsx(pE,{children:s.jsx(kl,{children:(o?Qw:Xw).map(ve=>s.jsx(mE,{"data-col":ve,children:TK[ve]},ve))})}),s.jsx(Fy,{className:"[&_tr:last-child>td]:border-b-0",children:o?de():Ee()})]})]}),s.jsxs(nn,{children:[s.jsx("span",{className:"min-w-0 text-[11.5px] text-muted-foreground",children:b}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:ge,children:r(o?"取消":"完成")}),o&&s.jsx(se,{variant:"default",disabled:!O.size||E,onClick:()=>{ie()},children:w==="import"?r("导入中…"):O.size?r("导入选中的 {n} 个模型",{n:O.size}):r("导入")})]})]})})}let ap=null,Iu=null;function w2(){ap&&(ap.unmount(),ap=null),Iu&&(Iu.remove(),Iu=null)}function LK(e){e?.providerId&&(w2(),Iu=document.createElement("div"),document.body.append(Iu),ap=vn.createRoot(Iu),ap.render(s.jsx(_K,{options:e,onClose:w2})))}window.wbModelsFetchModal={open:LK};const Mo=(e,t)=>t?`${e} ta-${t}`:e;function S2(e,t){const a=(t||"").trim();if(a)return Jf().find(o=>Oo(o.provider,e)&&Oo(o.id,a))}const zK="[.pv-row:hover_&_[data-slot=nav-item-count]]:invisible";function BK(e){const t=/x\s*([\d.]+)/i.exec(String(e||""));return t?`${t[1]}x`:String(e||"")}function N2(e){const t=/x\s*([\d.]+)/i.exec(String(e||""));if(!t)return null;const a=Number(t[1]);return Number.isFinite(a)?a:null}const HK={workbuddy:250,"workbuddy-intl":295,raccoon:60,catpaw:85,autoclaw:250,"autoclaw-intl":295,qoder:330,"qoder-intl":350,"cline-free":200,"cline-pass":200,codearts:210,loomy:155,kuku:15,accio:320,"accio-intl":335,trae:170,zcode:285};function UK(e){const t=HK[e];if(t!==void 0)return t;let a=0;for(let o=0;o>>0;return a%360}function VK(e){const t=String(e||"").trim();if(!t)return"?";const a=t.match(/[A-Za-z]/);return(a?a[0]:t[t.length-1]).toUpperCase()}const FK=e=>({"--av-h":String(UK(e))}),Jw=s.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:s.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{x:"3.5",y:"3.5",width:"7",height:"7",rx:"1.5"}),s.jsx("rect",{x:"13.5",y:"3.5",width:"7",height:"7",rx:"1.5"}),s.jsx("rect",{x:"13.5",y:"13.5",width:"7",height:"7",rx:"1.5"}),s.jsx("rect",{x:"3.5",y:"13.5",width:"7",height:"7",rx:"1.5"})]})});function $K(e){if(!e)return"";const t=Wt().wbPresetProviders?.list;if(!Array.isArray(t))return"";const a=t.find(o=>o.name===e);return a&&Wt().wbPresetProviders?.iconOf?.(String(a.key||""))||""}function qK(e,t){return Jn(e)?$K(t):ug[e==="workbuddy-intl"?"workbuddy":e]||""}function Pu(e,t,a){const o=a?"":qK(e,t),c=e==="all"||e==="custom-all";return s.jsx("span",{className:Ue("pv-ico",c&&"mute",o&&"img"),style:o?void 0:FK(e),"aria-hidden":"true",children:o?s.jsx("img",{src:o,alt:""}):a??VK(t)})}const GK={supportsToolCall:s.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:s.jsx("path",{fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),supportsImages:s.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:s.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2.5"}),s.jsx("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),s.jsx("path",{d:"M21 15l-5-5L5 21"})]})}),supportsVideo:s.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:s.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M10 8.5l6 3.5-6 3.5z"})]})}),supportsReasoning:s.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:s.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"}),s.jsx("path",{d:"M9 18h6M10 22h4"})]})})};function KK(e,t,a,o){return o==="enabled"&&!tp(e)||o==="disabled"&&tp(e)||o==="mapped"&&!(e.aliases||[]).length||a!=="all"&&(e.provider||"")!==a?!1:t?[e.id,e.name,...e.aliases||[]].join(" ").toLowerCase().includes(t):!0}function YK(){const e=x.useSyncExternalStore(L9,Qf),t=Bg(e),a=Jn(t)||t==="custom-all",[o,c]=x.useState(null),[d,f]=x.useState(!1),[p,g]=x.useState(new Set),v=a&&!Mu()&&Lw()&&!Ao(t);x.useEffect(()=>{$9(),Hg(),KM(),Wt().wbApp?.currentPage==="gateway"&&JM().then(()=>Wt().wbProviders?.refreshCustom?.()).then(()=>{qi()})},[]),x.useEffect(()=>{lK()});const y=Bw(),b=Array.isArray(y.models)?y.models:[],j=e.search.trim().toLowerCase(),w=b.filter(G=>KK(G,j,t,e.stateFilter)),S=e.sort,N=WM(),k=N.length,E=t==="all"?r("全部"):t==="custom-all"?r("自定义 · 全部"):a?String(Ao(t)?.name||t):Hw().get(t)?.label||Gw(t),D=b.filter(tp).length,C=b.filter(G=>(G.aliases||[]).length>0).length,A=ag(w.length,"models"),R=b.filter(G=>p.has(Ki(G))),I=(G,W)=>{const le=new Set(p);W?le.add(G):le.delete(G),g(le)},P=w.map(Ki),O=P.length>0&&P.every(G=>p.has(G)),_=P.some(G=>p.has(G)),L=s.jsx(Or,{checked:O,indeterminate:!O&&_,disabled:!P.length,"aria-label":r("全选当前筛选结果"),title:r("全选当前筛选出的模型(跨分页);再点取消"),onCheckedChange:G=>{const W=new Set(p);for(const le of P)G===!0?W.add(le):W.delete(le);g(W)}});function H(){const G=Hw(),W=Fi(),le=H9(),M=[...G.values()].reduce((ce,J)=>ce+J.n,0),U=r("全部({n} 家)",{n:G.size}),Z=[...le.values()].reduce((ce,J)=>ce+J.n,0),ae=r("全部({n} 家)",{n:[...le.values()].filter(ce=>ce.n>0).length});return s.jsxs("aside",{className:"prov-rail",id:"prov-rail","aria-label":r("按提供商选择"),children:[s.jsxs("div",{className:"rail-scroll",children:[s.jsx("div",{className:"rail-label",children:r("内置提供商")}),s.jsx(ru,{active:t==="all","data-provider":"all",title:U,count:M,icon:Pu("all","",Jw),className:"shadow-none",onClick:()=>np("all"),children:U}),[...G].map(([ce,J])=>s.jsx(ru,{active:t===ce,"data-provider":ce,title:J.label,count:J.n,icon:Pu(ce,J.label),className:"shadow-none",onClick:()=>np(ce),children:J.label},ce)),s.jsx("div",{className:"rail-label",children:r("自定义提供商")}),W.length?[...Z>0?[s.jsx(ru,{active:Mu(),"data-provider":"custom-all",title:ae,count:Z,icon:Pu("custom-all","",Jw),className:"shadow-none",onClick:()=>np("custom-all"),children:ae},"custom-all")]:[],...W.map(ce=>{const J=String(ce.id||""),ie=String(ce.name||J);return s.jsxs("div",{className:"pv-row",children:[s.jsx(ru,{active:t===J,"data-provider":J,title:ie,count:le.get(J)?.n??0,icon:Pu(J,ie),className:Ue("shadow-none",zK),onClick:()=>np(J),children:ie}),s.jsx("button",{type:"button",className:"pv-del","aria-label":r("删除自定义提供商"),title:r("删除这个自定义提供商(连同名下账号)"),onClick:()=>{J9(J)},children:"×"})]},J)})]:s.jsx("div",{className:"rail-empty",children:r("还没有自定义提供商")})]}),s.jsx("div",{className:"rail-foot",children:s.jsx(ru,{variant:"add",id:"rail-add-custom",title:r("新建一个自定义提供商(同时创建它的第一个账号)"),onClick:()=>eK(),children:r("+ 新建自定义提供商")})})]})}function B(G,W,le,M){const U=Kw(G,W,le);return s.jsx(se,{variant:U?"secondary":"dashed",size:"2xs",disabled:M,className:"font-mono font-bold shadow-none",title:U?r("思考等级 {level}(点击修改)",{level:U}):r("设置思考等级(当前未绑定)"),onClick:()=>t2({alias:G,target:W,provider:le}),children:U||r("+等级")})}function z(G){const W=G.provider||"",le=Du(G),[M,...U]=le;async function Z(ce){await Wt().wbConfirm?.ask?.({title:r("删除映射"),html:r("确定删除映射「{alias} → {target}」?",{alias:Ow(ce),target:Ow(G.id)}),okText:r("删除"),okClass:"danger"})&&$w(qw(ce,G.id,W),()=>q9(W,ce,G.id),r("映射已删除"))}const ae=ce=>{const J=ce.alias,ie=ce.enabled!==!1,ge=e.pending.has(qw(J,G.id,W));return s.jsxs("span",{className:Ue("alias",!ie&&"map-off"),children:[s.jsx(ms,{size:"sm",checked:ie,disabled:ge,title:r(ie?"映射已启用,点击关闭":"映射已关闭,点击启用"),"aria-label":r("{action}映射 {alias}",{action:r(ie?"关闭":"启用"),alias:J}),onCheckedChange:ee=>{$w(qw(J,G.id,W),()=>Fg(W,J,G.id,{enabled:ee}),r(ee?"映射已启用":"映射已关闭"))}}),s.jsx("span",{className:"t","data-copy":J,title:r("点击复制:{name}",{name:J}),children:J}),ce.isDefault?s.jsx("span",{className:"binding-default",children:r("默认")}):null,B(J,G.id,W,ge),ce.isDefault?null:s.jsx(se,{variant:"ghost",size:"icon-2xs",className:"text-[12px] leading-none",disabled:ge,title:r("删除映射 {alias}",{alias:J}),onClick:()=>{Z(J)},children:"×"})]},`${J}${ce.isDefault?"d":"m"}`)};return s.jsxs("div",{className:"aliases",children:[s.jsxs("div",{className:"alias-row",children:[M?ae(M):null,s.jsx(se,{variant:"dashed",size:"xs",onClick:()=>t2({target:G.id,provider:W}),children:r("+ 映射")})]}),U.map(ae)]})}function Q(G){if(G.source==="manual")return s.jsxs("span",{className:"src manual",title:r("手动登记的上游模型;移除它会直接删掉这条登记"),children:[s.jsx("i",{"aria-hidden":"true"}),r("手动")]});if(!G.source&&Jn(G.provider))return s.jsxs("span",{className:"src manual",title:r("用户登记的自定义模型;整份清单只属于这一家"),children:[s.jsx("i",{"aria-hidden":"true"}),r("自定义")]});if(G.source!=="remote"&&G.source!=="builtin")return s.jsx("span",{className:"rate",children:"—"});const W=G.source==="remote",le=M9(Number(G.refreshedAt)||0),M=W?le?r("来自上游目录接口,清单拉取于 {at};刷新失败时保留上一份成功结果",{at:le}):r("来自上游目录接口;刷新失败时保留上一份成功结果"):r("上游目录尚未拉到,用的是内置静态清单;点「刷新模型清单」可重试");return s.jsxs("span",{className:Ue("src",W?"remote":"builtin"),title:M,children:[s.jsx("i",{"aria-hidden":"true"}),r(W?"远程":"内置")]})}function K(G){const W=Aw(G),le=Ew(G.capOverrides),M=typeof W.maxInputTokens=="number"?W.maxInputTokens:null,U=typeof W.maxOutputTokens=="number"?W.maxOutputTokens:null,Z=r("上下文窗口 {input} / 最大输出 Token {output} —— 点击修改模型能力",{input:Gf(M),output:Gf(U)})+X(G);return s.jsxs("button",{type:"button",className:"caps-open",title:Z,onClick:()=>n2(G.provider||"",G.id),children:[s.jsxs("span",{className:Ue("cap-num",M===null&&"unset",Ru(G,"maxInputTokens")==="modelsdev"&&"filled"),children:[EM(M),le.includes("maxInputTokens")?s.jsx("i",{className:"cap-mark",title:r("已覆盖上游值")}):null]}),s.jsx("span",{className:"cap-sep",children:"/"}),s.jsxs("span",{className:Ue("cap-num",U===null&&"unset",Ru(G,"maxOutputTokens")==="modelsdev"&&"filled"),children:[EM(U),le.includes("maxOutputTokens")?s.jsx("i",{className:"cap-mark",title:r("已覆盖上游值")}):null]})]})}function X(G){const W=["maxInputTokens","maxOutputTokens"].filter(le=>Ru(G,le)==="modelsdev").map(le=>Au[le]);return W.length?r(";其中 {keys} 由 models.dev 补齐",{keys:W.join(r("、"))}):""}function q(G){const W=Aw(G),le=Ew(G.capOverrides);return s.jsx("button",{type:"button",className:"caps-open caps-badges",title:r("对下游声明的能力(工具调用 / 图片识别 / 视频识别 / 支持思考)—— 点击修改"),onClick:()=>n2(G.provider||"",G.id),children:CM.map(M=>{const U=W[M]??null,Z=Rw(U),ae=le.includes(M),ce=Ru(G,M);return s.jsxs("span",{className:Ue("cap-dot",Z,ce==="modelsdev"&&"filled",ae&&"marked"),title:S9(M,U,ae,ce),children:[GK[M],ae?s.jsx("i",{className:"cap-mark"}):null]},M)})})}function $(G,W,le){async function M(){await Wt().wbConfirm?.ask?.({title:r("移除自定义模型"),html:r("确定移除自定义模型「{id}」?这条登记会被直接移除,之后 /v1/models 不再广告它、请求它也会被拒。",{id:Ow(W.id)}),okText:r("移除"),okClass:"danger"})&&$w(Ki(W),()=>e2(W.provider||"",W.id),Jn(W.provider||"")?r("模型已移除"):r("自定义模型已移除"))}switch(G.key){case"check":return s.jsx("td",{className:Mo("cell-check",G.align),children:s.jsx(Or,{checked:p.has(Ki(W)),title:r("勾选后可批量操作"),"aria-label":r("勾选后可批量操作"),onCheckedChange:U=>I(Ki(W),U===!0)})});case"model":return s.jsxs("td",{className:Mo("cell-model",G.align),children:[s.jsx("div",{className:"mid",children:s.jsx("span",{className:"t","data-copy":W.id,title:r("点击复制:{name}",{name:W.id}),children:W.id})}),W.name&&W.name!==W.id?s.jsx("div",{className:"mname",children:W.name}):null]});case"rate":return s.jsx("td",{className:Mo("cell-rate",G.align),children:s.jsx("span",{className:"rate",children:W.credits?BK(W.credits):"—"})});case"source":return s.jsx("td",{className:Mo("cell-source",G.align),children:Q(W)});case"budget":return s.jsx("td",{className:Mo("cell-budget",G.align),children:K(W)});case"caps":return s.jsx("td",{className:Mo("cell-caps",G.align),children:q(W)});case"alias":return s.jsx("td",{className:Mo("cell-alias",G.align),children:z(W)});case"act":{const U=vK(W.provider||""),Z=W.source==="manual"||Jn(W.provider||"");return s.jsx("td",{className:Mo("cell-act r",G.align),children:s.jsxs("div",{className:"row-actions",children:[s.jsx(se,{variant:"ghost",size:"sm",disabled:!!U,title:U||r("以这个上游模型发一次最小请求,走真实转发链路"),onClick:()=>c({provider:W.provider||"",id:W.id}),children:r("测试")}),Z?s.jsx(se,{variant:"ghost",size:"sm",className:"text-destructive",disabled:le,onClick:()=>{M()},children:r("移除")}):null]})})}default:return null}}function Y(G){const W=e.pending.has(Ki(G)),le=p.has(Ki(G));return s.jsx("tr",{className:Ue(le&&"sel"),children:N.map(M=>s.jsx(x.Fragment,{children:$(M,G,W)},M.key))},`${G.provider||""}${G.id}`)}function F(){if(!b.length){const Z=a?Lw()?Mu()?r("自定义提供商还没有模型:先在左栏选一家,点「添加模型」登记,或「获取上游模型」从上游拉取"):r(v?"该提供商已不存在(可能已被删除),请刷新列表":"这家还没有模型:点「添加模型」登记,或「获取上游模型」从上游拉取"):r("加载中…"):e.data?r("暂无模型(请先添加账号)"):r("加载中…");return s.jsx("tr",{children:s.jsx("td",{colSpan:k,className:"empty",children:Z})})}if(!w.length)return s.jsx("tr",{children:s.jsx("td",{colSpan:k,className:"empty",children:j?r("没有匹配「{keyword}」的模型",{keyword:j}):r("没有匹配当前筛选的模型")})});const G=t==="all"||Mu(),W=G&&!j&&e.stateFilter==="all"&&!A.paged,le=new Map;for(const Z of w){const ae=Z.provider||"";le.has(ae)||le.set(ae,{label:Z.providerLabel||ae||r("未知"),items:[]}),le.get(ae)?.items.push(Z)}const M=[];let U=0;for(const[Z,ae]of le){ae.items.sort((te,Ce)=>{const re=+!tp(te)-+!tp(Ce);if(re!==0||S==="default")return re;const de=N2(te.credits),ke=N2(Ce.credits);return de===null||ke===null?de===ke?0:de===null?1:-1:S==="rate-asc"?de-ke:ke-de});const ce=e.expanded.has(Z)||!W,J=ce?ae.items:ae.items.slice(0,UM),ie=ae.items.length-J.length,ge=A.paged?Math.max(0,A.rangeStart-1-U):0,ee=A.paged?Math.min(J.length,A.rangeEnd-U):J.length,fe=ge0?r("(续)"):"",r("{n} 个模型",{n:ae.items.length})]})},`group:${Z}`));for(const te of fe)M.push(Y(te));U+=J.length,ie>0?M.push(s.jsx("tr",{className:"tr-more",children:s.jsx("td",{colSpan:k,children:s.jsx(se,{variant:"ghost",size:"sm",onClick:()=>Y9(Z),children:r("展开其余 {n} 个模型 ▾",{n:ie})})})},`more:${Z}`)):ce&&W&&ae.items.length>UM&&M.push(s.jsx("tr",{className:"tr-more",children:s.jsx("td",{colSpan:k,children:s.jsx(se,{variant:"ghost",size:"sm",onClick:()=>X9(Z),children:r("收起 ▴")})})},`collapse:${Z}`))}return M}return s.jsxs(s.Fragment,{children:[s.jsx("section",{className:"panel",children:s.jsxs("div",{className:"mm",children:[H(),s.jsxs("div",{className:"mm-main",children:[s.jsxs("div",{className:"panel-head",children:[s.jsxs("div",{className:"mm-titlebar",children:[s.jsxs("div",{className:"mm-title",children:[t==="all"||t==="custom-all"?Pu(t,"",Jw):Pu(t,E),s.jsx("h2",{children:E}),s.jsxs("span",{className:"mm-meta",children:[s.jsx("b",{children:b.length}),r(" 个模型 · 已启用 "),s.jsx("b",{children:D}),r(" · 有映射 "),s.jsx("b",{children:C})]})]}),s.jsxs("div",{className:"head-actions",children:[s.jsx(se,{id:"btn-refresh-models",title:Jn(t)?r("从这一家的上游拉一份模型清单,勾选要哪些再导入(已添加的不会重复导入)"):r("刷新模型管理页里各提供商的远程模型目录,逐家结果列在弹窗里"),onClick:()=>r2(),children:r("获取模型")}),s.jsx(se,{id:"btn-add-custom-model",variant:"outline",size:"sm",onClick:()=>nK(),children:r("+ 添加模型")})]})]}),s.jsxs("div",{className:"mm-filters",children:[s.jsx(In,{options:I9,value:e.stateFilter,onValueChange:Q9,"aria-label":r("按状态筛选"),className:"shrink-0"}),s.jsx(In,{options:_9,value:e.sort,onValueChange:Z9,"aria-label":r("按倍率排序"),className:"shrink-0"}),s.jsxs(Ci,{className:"w-full min-[768px]:w-[240px] flex-none min-[768px]:flex-none",id:"models-search",children:[s.jsx(Ei,{type:"search",placeholder:r("搜索模型 ID / 名称 / 映射名…"),"aria-label":r("搜索模型"),autoComplete:"off",value:e.search,onChange:G=>W9(G.currentTarget.value)}),s.jsx(Ti,{"aria-hidden":"true",children:"⌕"})]}),R.length>0?s.jsxs("span",{className:"batch-chip",children:[r("已选 "),s.jsx("b",{children:R.length}),r(" 个"),s.jsx(se,{id:"btn-batch-models",variant:"outline",size:"xs",title:r("对选中的 {n} 个模型执行批量操作",{n:R.length}),onClick:()=>f(!0),children:r("批量操作")})]}):null]})]}),s.jsx("div",{className:"models-table-wrap",children:s.jsxs("table",{className:"models-table",ref:G=>aK(G),children:[s.jsxs("colgroup",{children:[s.jsx("col",{className:"c-check","data-col":"check"}),s.jsx("col",{className:"c-model","data-col":"model"}),s.jsx("col",{className:"c-rate","data-col":"rate"}),s.jsx("col",{className:"c-source","data-col":"source"}),s.jsx("col",{className:"c-budget","data-col":"budget"}),s.jsx("col",{className:"c-caps","data-col":"caps"}),s.jsx("col",{className:"c-alias","data-col":"alias"}),s.jsx("col",{className:"c-act","data-col":"act"})]}),s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"data-col":"check",children:L}),s.jsx("th",{"data-col":"model",children:r("上游模型")}),s.jsx("th",{"data-col":"rate",children:r("倍率")}),s.jsx("th",{"data-col":"source",children:r("来源")}),s.jsxs("th",{"data-col":"budget",children:[r("上下文 / 输出"),s.jsx("span",{className:"th-help","aria-hidden":"true",title:r("数字带虚线底 = 由 models.dev 补齐;右上角小点 = 你手动覆盖过;— = 未声明。点任意一格可改。"),children:s.jsx("svg",{viewBox:"0 0 24 24",children:s.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M12 16v-4"}),s.jsx("path",{d:"M12 8h.01"})]})})})]}),s.jsxs("th",{"data-col":"caps",children:[r("能力"),s.jsx("span",{className:"th-help","aria-hidden":"true",title:r("圆点带内侧描边 = 由 models.dev 补齐;右上角小点 = 你手动覆盖过;虚线圈 = 未声明。悬停某一枚可看逐项出处。"),children:s.jsx("svg",{viewBox:"0 0 24 24",children:s.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M12 16v-4"}),s.jsx("path",{d:"M12 8h.01"})]})})})]}),s.jsxs("th",{"data-col":"alias",children:[r("模型映射"),s.jsx("span",{className:"th-help","aria-hidden":"true",title:r("每条映射 = 对外名 → 上游模型;原始 ID 与别名有独立开关,默认绑定永远存在(没有映射时是合成的那条)。"),children:s.jsx("svg",{viewBox:"0 0 24 24",children:s.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M12 16v-4"}),s.jsx("path",{d:"M12 8h.01"})]})})})]}),s.jsx("th",{className:"r","data-col":"act",children:r("操作")})]})}),s.jsx("tbody",{id:"models",children:F()})]})}),s.jsx(Li,{className:"models-panel-foot",leading:Mu()?s.jsxs(s.Fragment,{children:[r("这里是"),s.jsx("b",{children:r("全部自定义提供商")}),r("的模型合集:每家的清单互相独立,别名也只在自己那家内生效;要改名称 / 协议 / Base URL,到账号页该家账号的「设置」→ 提供商一栏。")]}):a?s.jsxs(s.Fragment,{children:[r("自定义提供商的清单"),s.jsx("b",{children:r("只属于这一家")}),r(":这里的模型不会出现在其他家,别名也只在这一家内生效。改名称 / 协议 / Base URL 在账号页该家账号的「设置」→ 提供商一栏;整家不要了,鼠标移到左栏这家上点 × 删除(连同名下账号)。")]}):void 0,total:w.length,range:A.paged?{start:A.rangeStart,end:A.rangeEnd}:null,page:A.page,pageCount:A.pageCount,size:A.size,onSizeChange:A.setSize,onPageChange:A.goto})]})]})}),e.mapping?s.jsx(QK,{context:e.mapping,onClose:tK}):null,e.customModel?s.jsx(ZK,{initial:e.customModel,onClose:sK}):null,e.capability?s.jsx(dK,{context:e.capability,onClose:rK}):null,o?s.jsx(wK,{target:o,onClose:()=>c(null)}):null,d?s.jsx(NK,{models:R,onClose:()=>f(!1),onDone:()=>{g(new Set),f(!1)}}):null]})}const XK=r("绑定在「对外名 → 上游模型」这一条映射上的思考等级(列表照抄 OmniProxy 的手动绑定),选「不覆盖」表示不给这条映射指定等级。它会跟着这条映射注入转发,由承载的那家翻译成自己的档位字段(CatPaw 归并成 low/high/max,Qoder 按模型声明的档位归一)。以下几种情况故意不注入:① off / none(关闭思考)—— 本项目没有安全的表达方式;② 表外的自定义等级(各家能力范围不同,无法判断上游收不收);③ 客户端请求体里已经自己指定了档位(那是更明确的意图,绑定不覆盖);④ 这家上游不认识档位字段(如 WorkBuddy / 小浣熊 / AutoClaw / Cline)。注入与跳过都会写进详细日志。");function k2(e,t,a){const o=ZM(e),c=(t||"").trim(),d=o.find(f=>f.id.toLowerCase()===c.toLowerCase());return d?d.id:c||o[0]?.id||""}function QK({context:e,onClose:t}){const a=!!e.alias,[o,c]=x.useState(()=>e.provider||Uw()[0]?.id||""),[d,f]=x.useState(e.alias||""),[p,g]=x.useState(()=>k2(o,e.target)),[v,y]=x.useState(""),[b,j]=x.useState(!1),[w,S]=x.useState(()=>{const _=Yf(Qf().data,S2(o,p)),L=a?Kw(e.alias,e.target,e.provider):"";return L&&_.includes(L)?{select:L,custom:""}:{select:L?ca:"",custom:L}}),N=Yf(Qf().data,S2(o,p)),k=(()=>{const _=Uw();for(const L of[e.provider,o])L&&!_.some(H=>H.id===L)&&_.push({id:L,label:Wt().wbProviders?.labelOf?.(L)||L});return _})(),E=(()=>{const _=ZM(o),L=(p||"").trim();return L&&!_.some(H=>H.id.toLowerCase()===L.toLowerCase())&&_.unshift({id:L,label:r("{name}(不在该家当前清单里)",{name:L}),off:!0}),_})(),D=k.find(_=>_.id===o)?.label||o||r("(全局)"),C=w.select&&w.select!==ca&&!N.includes(w.select)?{select:ca,custom:w.custom||w.select}:w,A=C.select===ca?C.custom.trim():C.select,R=C.select===ca;function I(_){c(_),g(k2(_,p))}async function P(){if(b)return;const _=a?e.alias||"":d.trim(),L=p;if(!_){y(r("请填写对外映射名"));return}if(!L){y(r("该提供商当前没有可选的上游模型"));return}if(!o){y(r("请选择提供商"));return}if(!a&&Oo(_,L)&&Jf().some(H=>Oo(H.id,L)&&Oo(H.provider,o))){y(r("原始 ID 已作为默认绑定,请直接使用该绑定的开关或等级按钮"));return}j(!0),y(r("保存中…"));try{Gi(await Fg(o,_,L,{reasoning:A})),j(!1),t();const H=A?r(" · 思考等级 {level}",{level:A}):"",B=Wt().wbProviders?.labelOf?.(o)||o;yr(a?r("✅ 已更新 {name} 的思考等级",{name:_}):r("✅ 已添加映射 {name} → {target}({label}){suffix}",{name:_,target:L,label:B,suffix:H}))}catch(H){y(r("保存失败:{message}",{message:Ro(H)})),j(!1)}}const O=_=>{_.key==="Enter"&&(_.preventDefault(),P())};return s.jsx(Qt,{open:!0,onOpenChange:(_,L)=>{if(!_){if(b){L.cancel();return}t()}},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r(a?"设置思考等级":"添加模型映射")})}),s.jsxs(Bt,{children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"mapping-provider",children:r("提供商")}),s.jsxs(ft,{value:o,disabled:!0,onValueChange:_=>I(String(_)),children:[s.jsx(mt,{id:"mapping-provider",className:"w-full",children:s.jsx(pt,{children:k.find(_=>_.id===o)?.label||o})}),s.jsx(ht,{children:k.map(_=>s.jsx(qe,{value:_.id,children:_.label},_.id))})]})]}),s.jsxs("div",{className:"grid grid-cols-[1fr_24px_1fr] items-end gap-2.5",children:[s.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"mapping-alias",children:r("对外映射名(下游请求时用)")}),s.jsx($e,{id:"mapping-alias",maxLength:128,placeholder:r("例如 gpt-4o"),autoComplete:"off",autoFocus:!a,value:d,disabled:a,onChange:_=>f(_.currentTarget.value),onKeyDown:O})]}),s.jsx("div",{className:"pb-2 text-center text-muted-foreground",children:"→"}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"mapping-upstream",children:r("转发到上游模型")}),s.jsxs(ft,{value:p,disabled:!0,onValueChange:_=>g(String(_)),children:[s.jsx(mt,{id:"mapping-upstream",className:"w-full",children:s.jsx(pt,{children:E.find(_=>_.id===p)?.label||p})}),s.jsx(ht,{children:E.map(_=>s.jsxs(qe,{value:_.id,children:[_.label,_.off?r("(已禁用)"):""]},_.id))})]})]})]}),s.jsxs("div",{className:"rounded-md border border-border bg-surface-inset px-3 py-2.5 font-mono text-[12px] text-subtle",children:[r("下游请求 "),s.jsx("b",{className:"text-primary-fg",children:d.trim()||r("<对外名>")}),r(" → 转发")," ",s.jsx("b",{className:"text-primary-fg",children:p||r("<上游模型>")}),r("({label})",{label:D}),A?s.jsxs(s.Fragment,{children:[r(" · 思考等级 "),s.jsx("b",{className:"text-primary-fg",children:A})]}):null]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-[7px]",children:[s.jsx(Je,{htmlFor:"mapping-reasoning",children:r("思考等级")}),s.jsxs(Ii,{children:[s.jsx(Pi,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("思考等级的注入规则")}),children:"?"}),s.jsx(_i,{children:XK})]})]}),s.jsxs(ft,{value:C.select,onValueChange:_=>{const L=String(_);S(H=>({...H,select:L}))},children:[s.jsx(mt,{id:"mapping-reasoning",className:"w-full",autoFocus:a,children:s.jsx(pt,{children:C.select===ca?r("自定义等级…"):C.select||r("不覆盖")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"",children:r("不覆盖")}),N.map(_=>s.jsx(qe,{value:_,children:_},_)),s.jsx(qe,{value:ca,children:r("自定义等级…")})]})]}),R?s.jsx($e,{id:"mapping-reasoning-custom",maxLength:32,autoFocus:!0,placeholder:r("自定义等级(例如 custom-high)"),autoComplete:"off",disabled:b,value:C.custom,onChange:_=>S(L=>({...L,custom:_.currentTarget.value})),onKeyDown:O}):null]}),s.jsxs("p",{className:"text-xs leading-[1.65] text-subtle",children:[r("对外名可自由命名,允许与上游模型 ID 同名(同名时该上游的原生路由优先,映射作兜底); 支持字母、数字与 "),s.jsx("code",{children:"- _ . / :"}),r("。同一对外名可在多个提供商各添加一条: 下游用同一个名字请求,网关按账号优先级主备切换,失败自动落到下一个提供商。")]}),s.jsx("div",{className:"min-h-[18px] text-xs text-subtle",children:v})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("取消")}),s.jsx(se,{variant:"default",disabled:b,onClick:()=>{P()},children:r(a?"保存等级":"保存映射")})]})]})})}function ZK({initial:e,onClose:t}){const[a,o]=x.useState(e.provider),[c,d]=x.useState(""),[f,p]=x.useState(""),[g,v]=x.useState(!1),y=(()=>{const N=F9();return a&&!N.some(k=>k.id===a)&&N.push({id:a,label:Wt().wbProviders?.labelOf?.(a)||a}),N})(),b=y.some(N=>N.id===a)?a:y[0]?.id||"",j=y.find(N=>N.id===b)?.label||b||r("(未选)");async function w(){if(g)return;const N=c.trim();if(!b){p(r("请选择提供商"));return}if(!N){p(r("请填写上游模型 ID"));return}v(!0),p(r("保存中…"));try{const k=await G9(b,N);Gi(k),v(!1),t();const E=y.find(D=>D.id===b)?.label||b;if(Jn(Ou()))yr(r("✅ 已登记模型 {name}({label})",{name:N,label:E}));else{const D=k;Array.isArray(D?.models)&&D.models.some(A=>A.id===N&&(A.provider||"")===b)?yr(r("✅ 已登记自定义模型 {name}({label})",{name:N,label:E})):yr(r("✅ 已登记 {name}({label}),但该提供商还没有可用账号,这一行要加上账号后才会显示",{name:N,label:E}),"err")}}catch(k){p(r("保存失败:{message}",{message:Ro(k)})),v(!1)}}const S=N=>{N.key==="Enter"&&(N.preventDefault(),w())};return s.jsx(Qt,{open:!0,onOpenChange:(N,k)=>{if(!N){if(g){k.cancel();return}t()}},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("添加自定义模型")})}),s.jsxs(Bt,{children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"custom-model-provider",children:r("提供商")}),s.jsxs(ft,{value:b,disabled:e.locked,onValueChange:N=>o(String(N)),children:[s.jsx(mt,{id:"custom-model-provider",className:"w-full",children:s.jsx(pt,{children:j})}),s.jsx(ht,{children:y.map(N=>s.jsx(qe,{value:N.id,children:N.label},N.id))})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"custom-model-id",children:r("上游模型 ID")}),s.jsx($e,{id:"custom-model-id",maxLength:128,placeholder:r("例如 gpt-5.5-preview"),autoComplete:"off",spellCheck:!1,autoFocus:!0,value:c,onChange:N=>d(N.currentTarget.value),onKeyDown:S})]}),s.jsxs("div",{className:"rounded-md border border-border bg-surface-inset px-3 py-2.5 font-mono text-[12px] text-subtle",children:[r("在 "),s.jsx("b",{className:"text-primary-fg",children:j}),r(" 上登记上游模型")," ",s.jsx("b",{className:"text-primary-fg",children:c.trim()||r("<上游模型 ID>")}),r("(登记后即可用这个名字请求)")]}),s.jsxs("p",{className:"text-xs leading-[1.65] text-subtle",children:[r("填上游真正认识的那个模型 ID(不是给下游用的名字)。登记后它会进入该家的模型清单: 表格里出现这一行、"),s.jsx("code",{children:"/v1/models"}),r(" 会广告它、请求它也会被转发到这家。 支持字母、数字与 "),s.jsx("code",{children:"- _ . / :"}),r("。")]}),s.jsxs("p",{className:"text-xs leading-[1.65] text-subtle",children:[r("「来源」列会标成"),s.jsx("b",{children:r("手动")}),r(",与远程目录 / 内置清单区分开。删除自定义模型是"),s.jsx("b",{children:r("直接移除")}),r("这条登记(不像内置模型那样只是隐藏),因为它的存在完全由这次登记决定。")]}),s.jsx("div",{className:"min-h-[18px] text-xs text-subtle",children:f})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("取消")}),s.jsx(se,{variant:"default",disabled:g,onClick:()=>{w()},children:r("保存")})]})]})})}const C2='.page[data-page="gateway"]';let e0=null;function T2(){if(e0)return;const e=document.querySelector(C2);e&&(e.replaceChildren(),e0=vn.createRoot(e),e0.render(s.jsx(YK,{})))}document.querySelector(C2)?T2():document.addEventListener("DOMContentLoaded",T2,{once:!0});const E2=3065;function WK(){if(el().workbuddyDesktop?.platform!=="web")return null;const e=typeof window>"u"?"":window.location?.origin;return e&&e!=="null"?e:null}function A2(e,t){return WK()??(e?`http://127.0.0.1:${e}`:t)}function el(){return window}function $g(e){return e instanceof Error?e.message:String(e)}function _u(e,t){el().wbApp?.toast?.(e,t)}let lp={backend:null,gatewayBase:A2(0,`http://127.0.0.1:${E2}`)};const t0=new Set;function n0(){return lp}function JK(e){return t0.add(e),()=>{t0.delete(e)}}function eY(e){lp=e;for(const t of t0)t()}function R2(){return lp.gatewayBase.replace(/^https?:\/\//,"")}function tY(){return lp.backend?.ready===!0}function O2(e){const t=(a,o)=>{const c=document.getElementById(a);c&&(c.textContent=o)};t("api-base",`${e}/v1`),t("api-chat",`POST ${e}/v1/chat/completions`),t("api-responses",`POST ${e}/v1/responses`),t("api-messages",`POST ${e}/v1/messages`),t("api-models",`GET ${e}/v1/models`)}let s0=!1;async function Lu(){if(!s0){s0=!0;try{const e=el().workbuddyDesktop;if(!e)throw new Error("后端桥不可用");const t=await e.getBackendStatus(),a=Number(t?.port)||0,o=n0(),c={backend:t??null,gatewayBase:A2(a,o.gatewayBase)};c.gatewayBase!==o.gatewayBase&&O2(c.gatewayBase),eY(c),el().wbApp?.renderTopbarStatus?.()}catch(e){console.warn("读取后端状态失败:",$g(e))}finally{s0=!1}}}function nY(){O2(lp.gatewayBase),Lu()}async function M2(e){_u(e||r("正在重启…"));try{await el().workbuddyDesktop?.restartApp()}catch(t){_u(r("重启失败:{reason}",{reason:$g(t)}),"err")}}const sY={idle:r("结束占用进程"),querying:r("查询中…"),ending:r("结束中…")};function rY({container:e}){const{backend:t,gatewayBase:a}=x.useSyncExternalStore(JK,n0),[o,c]=x.useState("idle"),d=t?.failure||null,f=R2(),p=t?.ready;let g="live off",v=r("正在检查… · {port}",{port:f});p===!0?(g="live pulse",v=r("网关运行中 · {port}",{port:f})):d?(g="live bad",v=r("{label} · {port}",{label:d.label||r("网关启动失败"),port:f})):p===!1&&(v=r("网关启动中… · {port}",{port:f}));const y=d?d.message??"":p===!0?r("本地网关正在监听 {url},可直接调用 OpenAI 兼容接口",{url:a}):r("正在确认网关是否已就绪");x.useEffect(()=>{Lu()},[]),x.useEffect(()=>{const j=el().workbuddyDesktop?.onBackendError?.(()=>{Lu()});return typeof j=="function"?j:void 0},[]),x.useEffect(()=>{e.title=y},[e,y]);async function b(){if(o!=="idle")return;const j=el().workbuddyDesktop;if(j){c("querying");try{const w=await j.getPortOccupant(),S=w?.occupant;if(!S){_u(r("端口 {port} 上没有查到监听进程,请改用「更换端口」",{port:w?.port??""}),"err");return}const N=[r("即将结束以下进程:"),"",r("进程名:{name}",{name:String(S.name)}),r("PID:{pid}",{pid:String(S.pid)}),r("路径:{path}",{path:S.path||r("(未知)")}),"",r("结束它会强制退出该程序未保存的数据。确认继续?")],k=el().wbConfirm?.ask;if(!k||!await k({title:r("结束占用端口的进程"),text:N.join(` -`),okText:r("结束进程"),okClass:"danger"}))return;c("ending"),(await j.endPortOccupant())?.released?(_u(r("已结束进程 {name}(PID {pid}),端口已释放",{name:String(S.name),pid:String(S.pid)})),await k({title:r("重启程序"),text:r("端口已释放。现在重启程序让网关用这个端口启动?"),okText:r("重启")})?await M2(r("重启中…")):await Lu()):(_u(r("进程已结束,但端口仍被占用,建议改用「更换端口」"),"err"),await Lu())}catch(w){_u(r("结束失败:{reason}",{reason:$g(w)}),"err")}finally{c("idle")}}}return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"status-line",children:[s.jsx("span",{className:g}),s.jsx("span",{className:"txt",children:v})]}),d?.conflict?s.jsxs("div",{className:"status-actions",children:[d.canEndOccupant===!0?s.jsx(se,{size:"sm",disabled:o!=="idle",onClick:()=>{b()},children:sY[o]}):null,s.jsx(se,{size:"sm",onClick:()=>{oY()},children:r("更换端口")})]}):null]})}let r0=null;function D2(){if(r0)return;const e=document.getElementById("sidebar-status");e&&(e.replaceChildren(),r0=vn.createRoot(e),r0.render(s.jsx(rY,{container:e})))}const aY={idle:r("保存并重启"),checking:r("校验中…"),saving:r("保存中…")};function lY({status:e,onClose:t}){const a=Number(e?.port)||E2,[o,c]=x.useState(()=>a<65535?String(a+1):String(a-1)),[d,f]=x.useState("idle"),[p,g]=x.useState(""),[v,y]=x.useState(""),b=x.useRef(!0),j=Number(o)||0,w=e?.failure?.message||r("当前端口 {port},网关运行正常。",{port:a});async function S(){if(d!=="idle")return;const N=el().workbuddyDesktop;if(!N)return;const k=Number(o)||0;if(!k||k<1024||k>65535){y(r("端口需在 1024-65535 之间"));return}f("checking"),y(""),g("");try{const E=await N.checkPort(k);if(!E?.ok){g(E?.message||r("该端口不可用"));return}if(E.same){g(E.message??"");return}if(f("saving"),(await N.changePort(k))?.changed===!1){g(r("与当前端口相同,无需重启"));return}t(),await M2(r("端口已改为 {port},正在重启…",{port:k}))}catch(E){y($g(E))}finally{f("idle")}}return s.jsx(Qt,{open:!0,onOpenChange:N=>{N||t()},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("更换网关端口")})}),s.jsxs(Bt,{children:[s.jsxs(Vn,{children:[s.jsx("h3",{children:r("当前状态")}),s.jsx("p",{children:w})]}),s.jsxs(Vn,{children:[s.jsx("h3",{children:r("新端口")}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(Je,{htmlFor:"port-input",className:"text-[12.5px] whitespace-nowrap text-subtle",children:r("端口号")}),s.jsx($e,{id:"port-input",type:"number",min:1024,max:65535,step:1,placeholder:r("例如 3066"),autoComplete:"off",className:"max-w-[130px]",value:o,onChange:N=>{c(N.currentTarget.value)},onKeyDown:N=>{N.key==="Enter"&&S()},autoFocus:!0,onFocus:N=>{b.current&&(b.current=!1,N.currentTarget.select())}})]}),p?s.jsx("p",{children:p}):null,s.jsx("p",{children:r("端口需在 1024-65535 之间。1023 及以下是系统保留范围,普通程序无法监听。")})]}),s.jsxs(Vn,{children:[s.jsx("h3",{children:r("换端口后要改的地方")}),s.jsxs("p",{children:[r("网关地址会变成 "),s.jsx("code",{children:`http://127.0.0.1:${j||"—"}`}),r("。已经把这个地址填进其它工具(Claude Code、Cherry Studio 等)的,需要一并改成新地址,否则那些工具会连不上。")]})]}),s.jsx("p",{className:"min-h-[18px] text-[11.5px] text-muted-foreground",children:v})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("取消")}),s.jsx(se,{variant:"default",disabled:d!=="idle",onClick:()=>{S()},children:aY[d]})]})]})})}let op=null,zu=null;function I2(){op&&(op.unmount(),op=null),zu&&(zu.remove(),zu=null)}async function oY(){let e=n0().backend;e||(e=await el().workbuddyDesktop?.getBackendStatus().catch(()=>null)??null),I2(),zu=document.createElement("div"),document.body.append(zu),op=vn.createRoot(zu),op.render(s.jsx(lY,{status:e,onClose:I2}))}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",D2,{once:!0}):D2(),window.wbPortPanel={render:nY,sync:Lu,portLabel:R2,isReady:tY};function iY(e){return e.source==="subscription"&&(e.port===null||e.port===void 0)}function tr(){return window}function Fn(e,t){tr().wbApp?.toast?.(e,t)}function Aa(e){return e instanceof Error?e.message:String(e)}function P2(e){return tr().wbApp?.formatTime?.(e)||""}function a0(e){const t=Number(e);return!Number.isFinite(t)||t<0?"":t<1e3?`${Math.round(t)}ms`:`${(t/1e3).toFixed(1)}s`}function l0(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]||t)}function Bu(e){return String(e?.name||e?.id||"")}function _2(e){return e.source==="clash"}function ip(e){return e.source==="subscription"}function qg(e){return _2(e)||ip(e)}function cY(e){return e.localDisabled===!0||e.enabled===!1}function L2(e){return qg(e)&&e.enabled===!1&&e.localDisabled!==!0}function uY(e){return ip(e)&&cY(e)}function Gg(e){return ip(e)&&e.orphan===!0}function z2(e){return!qg(e)||Gg(e)}const dY=r("来自 Clash Verge 同步(名称、端口跟随 Clash),请到 Clash Verge 中修改;启用可在本页关闭"),fY=r("该节点来自订阅(名称、端口跟随订阅与内核),请在「订阅管理」里修改;启用可在本页关闭"),B2=r("该节点所属订阅已删除,不会再被同步更新,可手动删除清理");function H2(e){return Gg(e)?B2:ip(e)?fY:dY}const pY=r("禁用后本端不再用它(引用它的账号回退直连);端口在 Clash Verge 侧,不受影响"),mY=r("禁用后本端不再用它(引用它的账号回退直连),并会关掉它的本地监听端口"),hY=r("已在本页禁用(打开开关即恢复)"),gY=r("这条在 Clash Verge 里是停用的,本页启用不生效 —— 到 Clash Verge 里打开它");function xY(e){if(Gg(e))return B2;if(e.localDisabled===!0)return hY;if(L2(e))return gY;if(ip(e))return mY;if(_2(e))return pY}let gs={data:null,loading:!1,error:"",testing:null,pending:new Set,syncing:!1,batchBusy:!1,batchProgress:null,selected:new Set};const o0=new Set;function bY(e){return o0.add(e),()=>{o0.delete(e)}}function vY(){return gs}function ts(e){gs={...gs,...e},o0.forEach(t=>t())}function Kg(){return gs.data?.items??[]}function yY(e){return gs.selected.has(e)}function jY(e,t){const a=new Set(gs.selected);t?a.add(e):a.delete(e),ts({selected:a})}function wY(e,t){const a=new Set(gs.selected);for(const o of e)t?a.add(o):a.delete(o);ts({selected:a})}function SY(){ts({selected:new Set})}function Do(e){if(!e||typeof e!="object"||!Array.isArray(e.items))return;const t=new Set(e.items.map(o=>o.id)),a=new Set([...gs.selected].filter(o=>t.has(o)));ts({data:e,error:"",selected:a})}async function cp(e=!1){const t=tr().workbuddyDesktop;if(typeof t?.getProxyPool!="function"){ts({error:r("当前环境不支持代理池(桥接方法缺失)")});return}e||ts({loading:!0});try{Do(await t.getProxyPool())}catch(a){ts({error:Aa(a)}),e||Fn(r("代理列表加载失败:{reason}",{reason:Aa(a)}),"err")}finally{ts({loading:!1})}}async function NY(){const e=tr().workbuddyDesktop;if(typeof e?.syncClashToProxyPool!="function"){Fn(r("当前环境不支持同步(桥接方法缺失)"),"err");return}if(!gs.syncing){ts({syncing:!0});try{const t=await e.syncClashToProxyPool();Do(t),t?.syncError?Fn(r("没能同步:{reason}",{reason:t.syncError}),"err"):t?.changes?Fn(r("✅ 已同步 Clash Verge 出口({n} 项变更)",{n:t.changes})):Fn(r("已是最新,没有需要同步的变更"))}catch(t){Fn(r("同步失败:{reason}",{reason:Aa(t)}),"err")}finally{ts({syncing:!1})}}}async function kY(e){const t=tr().workbuddyDesktop;if(typeof t?.testProxyPoolItem!="function"){Fn(r("当前环境不支持代理测试(桥接方法缺失)"),"err");return}if(!gs.testing){ts({testing:e.id});try{const a=await t.testProxyPoolItem(e.id);if(a?.items&&Do({items:a.items}),a?.success){const o=a0(a.durationMs);Fn(r("✅ 「{name}」出口可用{ip}{took}",{name:Bu(e),ip:a.ip?r(" 出口 IP {ip}",{ip:a.ip}):"",took:o?` ${o}`:""}))}else Fn(r("❌ 「{name}」{error}",{name:Bu(e),error:a?.error||r("连接失败")}),"err");a?.saveError&&Fn(r("测试结果没能记下:{reason}",{reason:a.saveError}),"err")}catch(a){Fn(r("测试失败:{reason}",{reason:Aa(a)}),"err")}finally{ts({testing:null})}}}async function CY(e,t){const a=tr().workbuddyDesktop;if(typeof a?.setProxyPoolItemEnabled!="function"){Fn(r("当前环境不支持启停(桥接方法缺失)"),"err");return}const o=new Set(gs.pending);o.add(e.id),ts({pending:o});try{const c=await a.setProxyPoolItemEnabled({id:e.id,enabled:t});Do(c);const d=Bu(e),f=c?.listener??"none";Fn(t?f==="opening"?r("已启用「{name}」,正在补建监听端口(内核重建中)",{name:d}):r("已启用「{name}」",{name:d}):f==="closing"?r("已禁用「{name}」,监听端口正在关闭(内核重建中)",{name:d}):r("已禁用「{name}」",{name:d})),(f==="closing"||f==="opening")&&TY(e.id,f)}catch(c){Fn(r("保存失败:{reason}",{reason:Aa(c)}),"err")}finally{const c=new Set(gs.pending);c.delete(e.id),ts({pending:c})}}async function TY(e,t){for(let a=0;a<12;a+=1){await new Promise(d=>setTimeout(d,1500)),await cp(!0);const o=Kg().find(d=>d.id===e);if(!o)return;const c=o.port!==null&&o.port!==void 0;if(t==="closing"?!c:c)return}}async function U2(e){const t=tr().workbuddyDesktop;if(typeof t?.removeProxyPoolItem!="function")return;if(!z2(e)){Fn(H2(e),"err");return}const a=e.usedBy||[],o=a.length?`

${r("有 {n} 个账号正在使用它({names})—— 删除后这些账号会回退直连。",{n:a.length,names:a.map(f=>l0(String(f.name||f.id||""))).join(r("、"))})}

`:"";if(!await tr().wbConfirm?.ask?.({title:r("删除代理"),html:r("确定删除「{name}」?{used}",{name:l0(Bu(e)),used:o}),okText:r("删除"),okClass:"danger"}))return;const d=new Set(gs.pending);d.add(e.id),ts({pending:d});try{const f=await t.removeProxyPoolItem(e.id);Do(f),Fn(r("已删除「{name}」",{name:Bu(e)}))}catch(f){Fn(r("删除失败:{reason}",{reason:Aa(f)}),"err")}finally{const f=new Set(gs.pending);f.delete(e.id),ts({pending:f})}}async function EY(){const e=tr().workbuddyDesktop;if(typeof e?.testProxyPoolItem!="function"){Fn(r("当前环境不支持代理测试(桥接方法缺失)"),"err");return}if(gs.batchBusy||gs.testing)return;const t=Kg().filter(f=>gs.selected.has(f.id));if(!t.length)return;ts({batchBusy:!0,batchProgress:{done:0,total:t.length}});let a=0,o=0,c="";for(const[f,p]of t.entries()){ts({testing:p.id,batchProgress:{done:f,total:t.length}});try{const g=await e.testProxyPoolItem(p.id);g?.items&&Do({items:g.items}),g?.success?a+=1:o+=1,g?.saveError&&!c&&(c=g.saveError)}catch{o+=1}}ts({testing:null,batchBusy:!1,batchProgress:null});const d=o?r("批量测试完成:{ok} 个可用、{failed} 个失败(共 {total} 个)",{ok:a,failed:o,total:t.length}):r("批量测试完成:{ok} 个可用(共 {total} 个)",{ok:a,total:t.length});Fn(o?d:`✅ ${d}`,o?"err":"ok"),c&&Fn(r("部分测试结果没能记下:{reason}",{reason:c}),"err")}async function AY(){const e=tr().workbuddyDesktop;if(typeof e?.removeProxyPoolItem!="function"||gs.batchBusy||gs.testing)return;const t=Kg().filter(S=>gs.selected.has(S.id)),a=t.filter(S=>z2(S)),o=t.length-a.length;if(!a.length){Fn(o?r("选中的 {n} 条都是同步来的只读条目(Clash / 订阅),不能删除",{n:o}):r("没有可删除的条目"),"err");return}const c=a.slice(0,8).map(S=>l0(Bu(S))).join(r("、")),d=a.length>8?r("{names} 等 {n} 条",{names:c,n:a.length}):c,f=a.filter(S=>(S.usedBy||[]).length).length,p=f?`

${r("其中 {n} 条正被账号使用 —— 删除后那些账号会回退直连。",{n:f})}

`:"",g=o?`

${r("另有 {n} 条是同步来的只读条目(Clash / 订阅),将跳过。",{n:o})}

`:"";if(!await tr().wbConfirm?.ask?.({title:r("批量删除代理"),html:`${r("确定删除选中的 {n} 个代理?",{n:a.length})}

${d}

${p}${g}`,okText:r("删除"),okClass:"danger"}))return;ts({batchBusy:!0,batchProgress:{done:0,total:a.length}});let y=0,b=0,j="";for(const[S,N]of a.entries()){ts({batchProgress:{done:S,total:a.length}});try{const k=await e.removeProxyPoolItem(N.id);Do(k),y+=1}catch(k){b+=1,j||(j=Aa(k))}}ts({batchBusy:!1,batchProgress:null});const w=[r("已删除 {n} 个代理",{n:y})];o&&w.push(r("跳过 {n} 个(同步只读条目)",{n:o})),b&&w.push(r("失败 {n} 个({reason})",{n:b,reason:j})),Fn(b?w.join(r(",")):`✅ ${w.join(r(","))}`,b?"err":"ok")}async function RY(e,t){const a=tr().workbuddyDesktop,o=e?{...t,id:e.id}:t,c=e?await a?.updateProxyPoolItem?.(o):await a?.createProxyPoolItem?.(o);return Do(c),c}async function V2(){const e=tr().workbuddyDesktop;if(typeof e?.getProxySettings!="function")throw new Error(r("当前环境不支持代理设置(桥接方法缺失)"));const t=await e.getProxySettings();if(!t||typeof t!="object")throw new Error(r("代理设置响应异常"));return t}async function OY(e){const t=tr().workbuddyDesktop;if(typeof t?.saveProxySettings!="function")throw new Error(r("当前环境不支持代理设置(桥接方法缺失)"));const a=await t.saveProxySettings(e);if(!a||typeof a!="object")throw new Error(r("代理设置响应异常"));return a}function MY({item:e,onClose:t}){const a=e!==null,[o,c]=x.useState(e?.name||""),[d,f]=x.useState(e?.protocol==="socks5"?"socks5":"http"),[p,g]=x.useState(e?.host||""),[v,y]=x.useState(e?.port?String(e.port):""),[b,j]=x.useState(e?.username||""),[w,S]=x.useState(e?.password||""),[N,k]=x.useState(e?e.enabled:!0),[E,D]=x.useState(!1),[C,A]=x.useState(!1),[R,I]=x.useState(null);function P(){const L=o.trim();if(!L)return{error:r("请填写代理名称")};const H=p.trim();if(!H)return{error:r("请填写代理主机地址")};const B=Number(v);return!Number.isInteger(B)||B<1||B>65535?{error:r("代理端口必须是 1-65535 的整数")}:{payload:{name:L,source:"manual",protocol:d,host:H,port:B,username:b.trim(),password:w,enabled:N}}}async function O(){if(C)return;const L=P();if("error"in L){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",L.error]}));return}const H=L.payload,B={source:"custom",protocol:H.protocol,host:H.host,port:H.port,username:H.username,password:H.password};A(!0),I(r("正在连接上游…"));try{const z=await tr().workbuddyDesktop?.testProxy?.({proxy:B});if(z?.success){const Q=a0(z.durationMs);I(s.jsxs("span",{className:"text-success",children:[r("✅ 出口可用"),z.ip?r(" 出口 IP {ip}",{ip:z.ip}):"",Q?` ${Q}`:""]}))}else I(s.jsxs("span",{className:"text-destructive",children:["❌ ",z?.error||r("连接失败")]}))}catch(z){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",Aa(z)]}))}finally{A(!1)}}async function _(){if(E)return;const L=P();if("error"in L){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",L.error]}));return}D(!0),I(null);try{await RY(e,L.payload),Fn(a?r("已保存「{name}」",{name:o.trim()}):r("已新增「{name}」",{name:o.trim()})),t()}catch(H){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",Aa(H)]})),D(!1)}}return s.jsx(Qt,{open:!0,onOpenChange:L=>{!L&&!E&&t()},children:s.jsxs(Zt,{className:"max-w-[560px]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r(a?"编辑代理":"新增代理")})}),s.jsxs(Bt,{className:"flex flex-col gap-3.5",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-name",children:r("名称")}),s.jsx($e,{id:"proxy-name",maxLength:60,autoComplete:"off",spellCheck:!1,placeholder:r("例如:香港 HTTP 出口"),value:o,onChange:L=>c(L.currentTarget.value)})]}),s.jsxs("div",{className:"flex flex-row items-end gap-2.5",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-protocol",children:r("协议")}),s.jsxs(ft,{value:d,onValueChange:L=>f(L),children:[s.jsx(mt,{id:"proxy-protocol",className:"min-w-[110px]",children:s.jsx(pt,{children:d==="socks5"?"SOCKS5":"HTTP"})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"http",children:"HTTP"}),s.jsx(qe,{value:"socks5",children:"SOCKS5"})]})]})]}),s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-host",children:r("主机")}),s.jsx($e,{id:"proxy-host",placeholder:"127.0.0.1",autoComplete:"off",spellCheck:!1,value:p,onChange:L=>g(L.currentTarget.value)})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-port",children:r("端口")}),s.jsx($e,{id:"proxy-port",type:"number",min:1,max:65535,className:"max-w-[110px]",placeholder:"7890",value:v,onChange:L=>y(L.currentTarget.value)})]})]}),s.jsxs("div",{className:"flex flex-row items-end gap-2.5",children:[s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-user",children:r("用户名")}),s.jsx($e,{id:"proxy-user",placeholder:r("可选"),autoComplete:"off",value:b,onChange:L=>j(L.currentTarget.value)})]}),s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-pass",children:r("密码")}),s.jsx($e,{id:"proxy-pass",placeholder:r("可选"),autoComplete:"off",value:w,onChange:L=>S(L.currentTarget.value)})]})]}),s.jsxs("div",{className:"flex flex-row items-center gap-2.5",children:[s.jsx(ms,{checked:N,onCheckedChange:k,"aria-label":r("启用这条代理")}),s.jsx("span",{className:"text-[12.5px]",children:r("启用(禁用的条目不会被账号使用,被引用时账号回退直连;仍可测试)")})]}),s.jsxs("p",{className:"text-xs leading-[1.65] text-subtle",children:[r("想要 Clash Verge 的出口?那类条目由工具条的"),s.jsx("b",{children:r("「同步 Clash Verge」")}),r("整体 镜像进来(进本页时也会自动同步一次),名称与端口跟随 Clash、因此是只读的 —— 不必(也不能)在这里手工填。")]}),s.jsx("div",{className:"min-h-[18px] text-xs text-subtle",children:R})]}),s.jsxs(nn,{children:[s.jsx(se,{variant:"outline",disabled:C||E,onClick:()=>{O()},children:r(C?"测试中…":"测试出口")}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:E,onClick:t,children:r("取消")}),s.jsx(se,{variant:"default",disabled:E,onClick:()=>{_()},children:r(E?"保存中…":"保存")})]})]})})}function DY({onClose:e}){const[t,a]=x.useState(!0),[o,c]=x.useState(!1),[d,f]=x.useState(""),[p,g]=x.useState(""),[v,y]=x.useState(""),[b,j]=x.useState({}),[w,S]=x.useState(""),[N,k]=x.useState(!1);x.useEffect(()=>{let A=!0;return(async()=>{try{const R=await V2();if(!A||R===null)return;f(String(R.listenerPortBase??"")),g(String(R.listenerPortEnd??"")),y(String(R.testUrl??"")),j(R.defaults??{}),a(!1)}catch(R){if(!A)return;S(Aa(R)),a(!1)}})(),()=>{A=!1}},[]);function E(){const A=Number(d),R=Number(p);if(!Number.isInteger(A)||A<1||A>65535||!Number.isInteger(R)||R<1||R>65535)return S(r("端口范围必须是 1-65535 的整数")),null;if(A>R)return S(r("起始端口不能大于结束端口")),null;const I=v.trim();return I&&!I.startsWith("http://")&&!I.startsWith("https://")?(S(r("测试网址要以 http:// 或 https:// 开头")),null):(S(""),{listenerPortBase:A,listenerPortEnd:R,testUrl:I})}async function D(){if(o||t)return;const A=E();if(A){c(!0);try{await OY(A),k(!0)}catch(R){S(Aa(R))}finally{c(!1)}}}function C(){f(String(b.listenerPortBase??"")),g(String(b.listenerPortEnd??"")),y(String(b.testUrl??"")),k(!1),S("")}return s.jsx(Qt,{open:!0,onOpenChange:A=>{!A&&!o&&e()},children:s.jsxs(Zt,{className:"max-w-[560px]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("代理设置")})}),s.jsx(Bt,{className:"flex flex-col gap-3.5",children:t?s.jsx("p",{className:"text-xs text-subtle",children:r("加载中…")}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-row items-end gap-2.5",children:[s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-settings-base",children:r("节点端口范围(起始)")}),s.jsx($e,{id:"proxy-settings-base",type:"number",min:1,max:65535,placeholder:String(b.listenerPortBase??""),autoComplete:"off",value:d,onChange:A=>{f(A.currentTarget.value),k(!1)}})]}),s.jsx("span",{"aria-hidden":"true",className:"flex-none pb-[7px] text-subtle",children:"—"}),s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-settings-end",children:r("节点端口范围(结束)")}),s.jsx($e,{id:"proxy-settings-end",type:"number",min:1,max:65535,placeholder:String(b.listenerPortEnd??""),autoComplete:"off",value:p,onChange:A=>{g(A.currentTarget.value),k(!1)}})]})]}),s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:r("订阅节点会在本机各占一个监听端口,从该范围里挑空闲的分配;节点多的大订阅把默认范围({base}-{end})用尽时会报「没有可用的节点端口」,这时把范围调大再重启内核。已分配出去的端口不会因改范围而失效。",{base:b.listenerPortBase??"",end:b.listenerPortEnd??""})}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-settings-url",children:r("出口测试网址")}),s.jsx($e,{id:"proxy-settings-url",placeholder:b.testUrl||"",autoComplete:"off",spellCheck:!1,className:"font-mono text-[12px]",value:v,onChange:A=>{y(A.currentTarget.value),k(!1)}})]}),s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:r("「测试」与「批量测试」访问的目标;留空用默认(打 WorkBuddy 上游)。判据是能否拿到 HTTP 响应,不用考虑该网址返回什么内容。")}),s.jsxs("div",{className:"min-h-[18px] text-xs",children:[w?s.jsxs("span",{className:"text-destructive",children:["❌ ",w]}):null,!w&&N?s.jsxs("span",{className:"text-success",children:["✅ ",r("已保存。重启内核后,新分配的节点端口才会按新范围来。")]}):null]})]})}),s.jsxs(nn,{children:[s.jsx(se,{variant:"ghost",disabled:t||o,onClick:C,children:r("恢复默认")}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:o,onClick:e,children:r("关闭")}),s.jsx(se,{variant:"default",disabled:t||o,onClick:()=>{D()},children:r(o?"保存中…":"保存")})]})]})})}function Pn(){return window}function nr(e,t){Pn().wbApp?.toast?.(e,t)}function zr(e){return e instanceof Error?e.message:String(e)}function F2(e){const t=String(e||"").trim();return/^https?:\/\//i.test(t)?t:""}async function $2(e){const t=F2(e);if(!t){nr(r("链接地址不受支持"),"err");return}try{await Pn().workbuddyDesktop?.openReleasePage(t)}catch(a){nr(r("打开链接失败:{error}",{error:zr(a)}),"err")}}const Yg="1127656296",IY=`assets/qq-group/${Yg}.jpg`;function q2(e){return Pn().wbMarkdown?.render?.(e)||""}function G2(e){const a=e.target?.closest?.("[data-external]");a&&(e.preventDefault(),$2(a.dataset.external||""))}const up="__proxy_other__",K2={proxyChoice:null,pool:null,poolError:""};async function PY(){const e=Pn().workbuddyDesktop,t={...K2};if(!e?.getUpdateProxy)return t;try{t.proxyChoice=(await e.getUpdateProxy())?.proxy??null}catch{}try{if(typeof e.getProxyPool!="function")throw new Error("桥未提供代理池方法");const a=(await e.getProxyPool())?.items;if(!Array.isArray(a))throw new Error("代理池响应异常");t.pool=a}catch(a){t.pool=[],t.poolError=zr(a)}return t}async function _Y(e){if(e===up)return null;const t=Pn().workbuddyDesktop;if(!t?.setUpdateProxy)return null;const a=e===""?null:{source:"pool",proxyId:e.slice(Ya.length)};try{const o=await t.setUpdateProxy({proxy:a}),c=o?.proxy??null,d=o?.saved!==!1;return d?nr(c?r("✅ 更新出网已切换为 {label}",{label:c.label||r("指定代理")}):r("✅ 更新出网已切换为直连")):nr(r("出网线路已切换,但写入磁盘失败(重启后会恢复原线路)"),"err"),{choice:c,saved:d}}catch(o){return nr(r("保存失败:{error}",{error:zr(o)}),"err"),null}}function Y2(e){const t=e.proxyChoice,a=t?.config?.source||t?.source,o=t?.label||r(a==="custom"?"自定义代理":"已设置"),c=!!t?.error,d=Array.isArray(e.pool)?e.pool:[];let f="";a==="pool"&&t?.config?.proxyId?f=`${Ya}${t.config.proxyId}`:t&&(f=up);const p=[{value:"",label:r("直连")}];for(const g of d)p.push({value:`${Ya}${g.id}`,label:au(g)});if(e.pool===null?p.push({value:"__hint_pool__",label:r("正在读取代理列表…"),disabled:!0}):d.length||p.push({value:"__hint_pool__",label:e.poolError?r("代理列表读取失败"):r("还没有代理(去「网络代理」页添加)"),disabled:!0}),f===up){const g=a==="clash"?r("Clash 出口:"):a==="custom"?r("自定义:"):"";p.push({value:up,label:`${g}${o}${c?r("(不可用)"):""}`})}else a==="pool"&&!d.some(g=>`${Ya}${g.id}`===f)&&p.push({value:f,label:`${o}${c?r("(不可用)"):""}`});return{current:f,items:p,selected:p.find(g=>g.value===f),broken:c,title:c?r("当前线路不可用:{error};请重新选择代理或切回直连",{error:String(t?.error||"")}):r("检查更新与下载安装包走哪条线路(当前:{current});选择即保存。选项来自「网络代理」页;直连失败时会自动借 Clash 混合端口重试一次,选定指定代理后只走它",{current:t?o:r("直连")})}}function sr(){return window}function sn(e,t){sr().wbApp?.toast?.(e,t)}function jr(e){return e instanceof Error?e.message:String(e)}let Ht={data:null,loading:!1,error:"",pending:!1,refreshing:null};const i0=new Set;function Xg(e){return i0.add(e),()=>{i0.delete(e)}}function Qg(){return Ht}function yn(e){Ht={...Ht,...e},i0.forEach(t=>t())}function LY(){return Ht.data?.items??[]}function Hu(){return Ht.data?.kernel??null}function Yi(e){!e||typeof e!="object"||!Array.isArray(e.items)||yn({data:e,error:""})}function Io(){cp(!0)}async function Ml(e=!1){const t=sr().workbuddyDesktop;if(typeof t?.getSubscriptions!="function"){yn({error:r("当前环境不支持订阅(桥接方法缺失)")});return}e||yn({loading:!0});try{Yi(await t.getSubscriptions())}catch(a){yn({error:jr(a)})}finally{e||yn({loading:!1})}}const zY=20;function BY(e){const t=e.kernel;if(!t||t.download.state==="downloading")return!1;if(!t.installed||t.lastError&&!t.running)return!0;const a=t.providerSync??{};return(e.items??[]).filter(o=>o.enabled!==!1).every(o=>!!a[o.id])}async function Xi(){const e=sr().workbuddyDesktop;if(typeof e?.getSubscriptions=="function")for(let t=0;tsetTimeout(o,1500)),Io();let a;try{a=await e.getSubscriptions()}catch{return}if(Yi(a),t>=1&&a&&Array.isArray(a.items)&&BY(a))return}}async function X2(e){const a=await sr().workbuddyDesktop?.addSubscription?.({enabled:!0,kind:"url",url:"",...e});return Yi(a),sn(r("已新增订阅「{name}」,内核正在同步节点…",{name:e.name.trim()})),Io(),Xi(),a??null}async function Q2(e,t){const o=await sr().workbuddyDesktop?.saveSubscription?.({id:e.id,...t});Yi(o),sn(r("已保存「{name}」",{name:t.name.trim()})),Io(),Xi()}async function HY(e,t){const a=sr().workbuddyDesktop;if(!Ht.pending){yn({pending:!0});try{const o=await a?.saveSubscription?.({id:e.id,name:e.name,url:e.url,kind:e.kind,enabled:t});Yi(o),sn(t?r("已启用「{name}」",{name:e.name}):r("已禁用「{name}」",{name:e.name})),Io(),Xi()}catch(o){sn(r("保存失败:{reason}",{reason:jr(o)}),"err")}finally{yn({pending:!1})}}}async function UY(e){const t=sr().workbuddyDesktop;if(!(Ht.refreshing||Ht.pending)){yn({refreshing:e.id});try{const a=await t?.refreshSubscription?.(e.id);Yi(a),sn(r("已刷新「{name}」,正在同步节点…",{name:e.name})),Io(),Xi()}catch(a){sn(r("刷新失败:{reason}",{reason:jr(a)}),"err")}finally{yn({refreshing:null})}}}async function VY(e){const t=sr().workbuddyDesktop;if(await window.wbConfirm?.ask?.({title:r("删除订阅"),html:r("确定删除「{name}」?它在代理池里的节点会一并移除,引用这些节点的账号会回退直连。",{name:e.name||e.id}),okText:r("删除"),okClass:"danger"})&&!Ht.pending){yn({pending:!0});try{const o=await t?.removeSubscription?.(e.id);Yi(o),sn(r("已删除「{name}」",{name:e.name||e.id})),Io(),Xi()}catch(o){sn(r("删除失败:{reason}",{reason:jr(o)}),"err")}finally{yn({pending:!1})}}}async function FY(e){const t=sr().workbuddyDesktop;if(typeof t?.downloadKernel!="function"){sn(r("当前环境不支持订阅(桥接方法缺失)"),"err");return}if(!Ht.pending){yn({pending:!0});try{const a=await t.downloadKernel(e);a&&Ht.data&&yn({data:{...Ht.data,kernel:a}}),a?.saved===!1&&sn(r("下载线路 / 存放目录没能写进配置(本次下载已按新设置走,重启后会恢复原值)"),"err");for(let c=0;c<300;c+=1){await new Promise(f=>setTimeout(f,1e3));const d=await t.getKernelStatus?.();if(d&&Ht.data&&yn({data:{...Ht.data,kernel:d}}),!d||d.download.state!=="downloading")break}const o=Ht.data?.kernel;o?.download.state==="error"?sn(r("内核下载失败:{reason}",{reason:o.download.error||r("未知错误")}),"err"):o?.download.state==="canceled"?sn(r("已停止下载内核(未下载完的临时文件已删除)")):o?.download.state==="done"&&(sn(r("✅ 内核下载完成,正在启动…")),Xi())}catch(a){sn(r("内核下载失败:{reason}",{reason:jr(a)}),"err")}finally{yn({pending:!1})}}}async function $Y(){const e=sr().workbuddyDesktop;if(typeof e?.cancelKernelDownload!="function")return"none";try{const t=await e.cancelKernelDownload();if(t&&Ht.data&&yn({data:{...Ht.data,kernel:t}}),t?.canceled===!1)return"none";for(let o=0;o<20;o+=1){const c=await e.getKernelStatus?.();if(c&&Ht.data&&yn({data:{...Ht.data,kernel:c}}),c&&c.download.state!=="downloading")break;await new Promise(d=>setTimeout(d,250))}const a=Ht.data?.kernel?.download.state;return a==="canceled"?"canceled":a==="done"?"done":"stalled"}catch(t){return sn(r("停止下载失败:{reason}",{reason:jr(t)}),"err"),"none"}}async function qY(){const e=sr().workbuddyDesktop;if(!Ht.pending){yn({pending:!0});try{const t=await e?.restartKernel?.();t&&Ht.data&&yn({data:{...Ht.data,kernel:t}}),sn(r("内核正在启动…")),Io(),Xi()}catch(t){sn(r("内核启动失败:{reason}",{reason:jr(t)}),"err")}finally{yn({pending:!1})}}}async function GY(){const e=sr().workbuddyDesktop;if(typeof e?.stopKernel!="function"){sn(r("当前环境不支持订阅(桥接方法缺失)"),"err");return}if(!Ht.pending){yn({pending:!0});try{const t=await e.stopKernel();t&&Ht.data&&yn({data:{...Ht.data,kernel:t}});for(let o=0;o<10;o+=1){const c=await e.getKernelStatus?.();if(c&&Ht.data&&yn({data:{...Ht.data,kernel:c}}),c&&c.running===!1)break;await new Promise(d=>setTimeout(d,500))}const a=Ht.data?.kernel;if(a?.running===!1)sn(r("内核已关闭(订阅与端口注册表保留,「启动内核」后原位恢复)"));else{const o=a?.lastError||r("内核没有在超时内停下来");sn(r("关闭内核失败:{reason}",{reason:o}),"err")}Ml(!0)}catch(t){sn(r("关闭内核失败:{reason}",{reason:jr(t)}),"err"),Ml(!0)}finally{yn({pending:!1})}}}async function KY(){const e=sr().workbuddyDesktop;if(typeof e?.removeKernel!="function"){sn(r("当前环境不支持订阅(桥接方法缺失)"),"err");return}const t=Hu()?.version;if(!await window.wbConfirm?.ask?.({title:r("删除内核"),html:r("确定删除已下载的内核{version}?内核文件与端口映射会被移除,订阅节点会变成「未分配端口」,引用它们的账号会暂时回退直连;订阅本身保留,重新下载内核后会重新分配端口。",{version:t?`(${t})`:""}),okText:r("删除内核"),okClass:"danger"})||Ht.pending)return;yn({pending:!0});const o=Hu()?.lastError||"";try{const c=await e.removeKernel();c&&Ht.data&&yn({data:{...Ht.data,kernel:c}});for(let f=0;f<20;f+=1){const p=await e.getKernelStatus?.();if(p&&Ht.data&&yn({data:{...Ht.data,kernel:p}}),p&&p.installed===!1||p?.lastError&&p.lastError!==o)break;await new Promise(g=>setTimeout(g,500))}const d=Ht.data?.kernel;if(d?.installed===!1)sn(r("已删除内核(订阅与账号引用保留,重新下载后会重新分配端口)")),Io();else{const f=d?.lastError&&d.lastError!==o?d.lastError:r("内核目录没能删掉(可能仍被进程占用),稍后重试一次");sn(r("删除内核失败:{reason}",{reason:f}),"err")}Ml(!0)}catch(c){sn(r("删除内核失败:{reason}",{reason:jr(c)}),"err"),Ml(!0)}finally{yn({pending:!1})}}async function YY(e){const t=sr().workbuddyDesktop;if(typeof t?.decodeQrImage!="function")throw new Error(r("当前环境不支持订阅(桥接方法缺失)"));const a=await new Promise((d,f)=>{const p=new FileReader;p.onload=()=>d(String(p.result||"")),p.onerror=()=>f(new Error(r("图片读取失败"))),p.readAsDataURL(e)}),c=(await t.decodeQrImage({imageBase64:a}))?.url;if(!c)throw new Error(r("二维码里没有订阅链接"));return c}function XY(e){return new Promise((t,a)=>{const o=new FileReader;o.onload=()=>t(String(o.result||"")),o.onerror=()=>a(new Error(r("文件读取失败"))),o.readAsDataURL(e)})}function Z2(e){return(Math.max(0,Number(e)||0)/1024/1024).toFixed(1)}function QY(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")||e.startsWith("/")}function ZY({onClose:e}){const t=x.useSyncExternalStore(Xg,Qg),a=Hu(),o=a?.download,c=o?.state==="downloading",d=c&&o&&o.total>0?Math.round(o.received/o.total*100):null,[f,p]=x.useState(null),[g,v]=x.useState(""),[y,b]=x.useState(null),[j,w]=x.useState(a?.kernelDir||""),[S,N]=x.useState(!1),[k,E]=x.useState(!1),[D,C]=x.useState("");x.useEffect(()=>{let H=!0;return(async()=>{try{const B=(await sr().workbuddyDesktop?.getProxyPool?.())?.items;if(!Array.isArray(B))throw new Error(r("代理池响应异常"));H&&p(B)}catch(B){if(!H)return;p([]),v(jr(B))}})(),()=>{H=!1}},[]),x.useEffect(()=>{a?.installed&&e()},[a?.installed]);const A=Y2({proxyChoice:a?.downloadProxy??null,pool:f,poolError:g}),R=y??A.current,I=A.items.find(H=>H.value===R)??A.selected,P=a?.kernelDirDefault||"";async function O(){if(S)return;const H=j.trim();if(H&&!QY(H)){C(r("存放位置要填绝对路径,例如 D:\\proxy-kernel"));return}C(""),N(!0);try{const B={dir:H};R!==up&&(B.proxy=R===""?null:{source:"pool",proxyId:R.slice(Ya.length)}),FY(B)}finally{N(!1)}}async function _(){if(!k){E(!0);try{const H=await $Y();H==="done"?sn(r("下载已经完成,停止没赶上(内核已安装)")):H==="none"?sn(r("当前没有正在进行的下载"),"err"):H==="stalled"&&sn(r("停止请求已发出,但下载还没收手,稍后再看一次进度"),"err")}finally{E(!1)}}}async function L(){const H=sr().workbuddyDesktop;if(typeof H?.pickFolder!="function"){sn(r("当前环境不支持选择文件夹,直接填写绝对路径即可"),"err");return}try{const B=await H.pickFolder(j.trim()||P||null);if(B?.unsupported){sn(r("当前环境不支持选择文件夹,直接填写绝对路径即可"),"err");return}if(B?.canceled||!B?.path)return;w(B.path)}catch(B){sn(r("打开文件夹选择框失败:{reason}",{reason:jr(B)}),"err")}}return s.jsx(Qt,{open:!0,onOpenChange:H=>{H||e()},children:s.jsxs(Zt,{className:"w-[min(520px,calc(100vw-48px))]",children:[s.jsxs(Kt,{children:[s.jsx(Gt,{children:r(c?"正在下载内核":"下载内核")}),s.jsx("span",{className:"text-[11.5px] text-subtle",children:r("内核 {version}({asset})",{version:a?.version||"—",asset:a?.asset||"—"})})]}),c?s.jsxs(Bt,{className:"flex flex-col gap-3",children:[s.jsx(Jd,{value:d??null}),s.jsxs("div",{className:"flex items-center justify-between text-[12px]",children:[s.jsx("span",{className:"text-text-2",children:d!==null?r("{percent}%({received} / {total} MB)",{percent:d,received:Z2(o?.received),total:Z2(o?.total)}):r("正在连接 GitHub…")}),s.jsx("span",{className:"text-subtle",children:r("存放位置 {dir}",{dir:a?.kernelDir||"—"})})]}),s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:r("关掉这个窗口不会中断下载(它在后台继续跑)—— 要停下就点下面的「停止下载」,未下载完的临时文件会被删除。")})]}):s.jsxs(Bt,{className:"flex flex-col gap-3.5",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"kernel-proxy",children:r("下载线路")}),s.jsxs(ft,{value:R,onValueChange:H=>b(String(H)),children:[s.jsx(mt,{id:"kernel-proxy",className:Ue("w-full",A.broken&&"border-destructive-bd"),children:s.jsx(pt,{className:"min-w-0 truncate",children:I?.label||r("直连")})}),s.jsx(ht,{children:A.items.map(H=>s.jsx(qe,{value:H.value,disabled:H.disabled,children:H.label},H.value))})]}),s.jsx("div",{className:"text-[12px] text-subtle",children:A.broken?r("当前线路不可用:{error};重新选一条或切回直连",{error:String(a?.downloadProxy?.error||"")}):r("选项来自「网络代理」页(Clash Verge 同步的出口在这里可用;订阅节点要等内核起来才有端口)。选「直连」时连不上会自动借 Clash 混合端口重试一次;选定某条线路后只走它。")})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"kernel-dir",children:r("存放位置")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx($e,{id:"kernel-dir",className:"min-w-0 flex-1 font-mono text-[12px]",autoComplete:"off",spellCheck:!1,value:j,placeholder:P,onChange:H=>w(H.currentTarget.value)}),s.jsx(se,{variant:"outline",size:"sm",className:"flex-none",onClick:()=>{L()},children:r("选择目录…")}),P&&j.trim()!==P?s.jsx(se,{variant:"ghost",size:"sm",className:"flex-none",title:P,onClick:()=>w(P),children:r("恢复默认")}):null]}),s.jsx("div",{className:"text-[12px] text-subtle",children:r("内核二进制 / 配置 / 端口映射都会放在这里,默认 {dir};目录不存在会在下载开始时自动创建。",{dir:P||"—"})})]}),o?.state==="error"&&o.error?s.jsx("span",{className:"text-[12px] text-destructive",children:r("上次下载失败:{reason}",{reason:o.error})}):null,o?.state==="canceled"?s.jsx("span",{className:"text-[12px] text-subtle",children:r("上次下载已停止,未下载完的临时文件已删除")}):null,D?s.jsx("span",{className:"text-[12px] text-destructive",children:D}):null]}),s.jsx(nn,{children:c?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:e,children:r("后台继续")}),s.jsx(se,{variant:"destructive",disabled:k,onClick:()=>{_()},children:r(k?"正在停止…":"停止下载")})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:e,children:r("取消")}),s.jsx(se,{variant:"default",disabled:S||t.pending,onClick:()=>{O()},children:r(S?"正在开始…":"下载")})]})})]})})}function W2({showPortRange:e=!1}){const t=x.useSyncExternalStore(Xg,Qg),a=Hu(),[o,c]=x.useState(null),[d,f]=x.useState(!1);x.useEffect(()=>{let v=!0;return(async()=>{try{const y=await V2();if(!v||!y)return;const b=Number(y.listenerPortBase),j=Number(y.listenerPortEnd);Number.isFinite(b)&&Number.isFinite(j)&&b>0&&j>0&&c({base:b,end:j})}catch{}})(),()=>{v=!1}},[]);const p=a?.download.state==="downloading",g=p&&a.download.total>0?Math.round(a.download.received/a.download.total*100):null;return s.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border bg-surface-2 px-3 py-2",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(ze,{variant:a?.running?"default":"secondary",children:a?.running?r("内核运行中"):a?.installed?r("内核已停止"):r("内核未安装")}),s.jsxs("span",{className:"text-[12.5px] text-text-2",children:[a?.installed?r("内核 {version}",{version:a.version})+" · ":"",a?.running?r("控制端口 {port} · {n} 个节点监听器",{port:a?.controllerPort??"—",n:a?.listenerCount??0}):a?.installed?r("内核已停止,点「启动内核」拉起"):r("按需下载(约 20-40MB)")]}),e&&o?s.jsx("span",{className:"text-[11.5px] text-subtle",children:r("节点端口范围 {base}–{end}",{base:o.base,end:o.end})}):null,s.jsx("div",{className:"ml-auto flex items-center gap-2",children:a?.installed?s.jsxs(s.Fragment,{children:[s.jsx(se,{size:"sm",variant:"outline",disabled:t.pending||p,onClick:()=>{qY()},children:a?.running?r("重启内核"):r("启动内核")}),a?.running?s.jsx(se,{size:"sm",variant:"outline",disabled:t.pending||p,onClick:()=>{GY()},children:r("关闭内核")}):null,s.jsx(se,{size:"sm",variant:"destructive",disabled:t.pending||p,onClick:()=>{KY()},children:r("删除内核")})]}):s.jsx(se,{size:"sm",variant:"outline",disabled:t.pending&&!p,onClick:()=>f(!0),children:r(p?"下载中…":"下载内核")})})]}),p?s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Jd,{className:"min-w-[200px] flex-1",value:g??null}),s.jsx("span",{className:"text-[11px] text-subtle",children:g!==null?r("{percent}%({received} / {total} MB)",{percent:g,received:J2(a.download.received),total:J2(a.download.total)}):r("下载中…")})]}):null,a?.lastError?s.jsx("span",{className:"text-[12px] text-destructive",children:a.lastError}):null,d?s.jsx(ZY,{onClose:()=>f(!1)}):null]})}function WY({onClose:e}){const t=x.useSyncExternalStore(Xg,Qg),a=LY(),o=t.data!==null,[c,d]=x.useState(null);return x.useEffect(()=>{Ml()},[]),s.jsxs(Qt,{open:!0,onOpenChange:f=>{f||e()},children:[s.jsxs(Zt,{className:"w-[min(880px,calc(100vw-48px))]",children:[s.jsxs(Kt,{children:[s.jsx(Gt,{children:r("订阅管理")}),s.jsxs("span",{className:"text-[11.5px] text-subtle",children:[o?r("{n} 条订阅",{n:a.length}):r("加载中…")," · ",r("节点由内核起成本地监听器,镜像进代理池")]})]}),s.jsxs(Bt,{className:"flex flex-col gap-3",children:[s.jsx(W2,{}),s.jsx("div",{className:"models-table-wrap",children:s.jsxs("table",{className:"models-table",children:[s.jsxs("colgroup",{children:[s.jsx("col",{className:"w-[18%]"}),s.jsx("col",{className:"w-[31%]"}),s.jsx("col",{className:"w-[9%]"}),s.jsx("col",{className:"w-[14%]"}),s.jsx("col",{className:"w-[8%]"}),s.jsx("col",{className:"w-[20%]"})]}),s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:r("名称")}),s.jsx("th",{children:r("订阅来源")}),s.jsx("th",{className:"ta-center",children:r("节点")}),s.jsx("th",{children:r("上次同步")}),s.jsx("th",{className:"ta-center",children:r("启用")}),s.jsx("th",{className:"ta-right",children:r("操作")})]})}),s.jsx("tbody",{children:a.length?a.map(f=>{const p=Hu()?.providerSync?.[f.id];return s.jsxs("tr",{className:f.enabled?"":"off",children:[s.jsx("td",{children:s.jsx("b",{children:f.name||r("未命名")})}),s.jsx("td",{className:"group",children:s.jsx("div",{className:"flex min-w-0 items-center gap-1",children:f.kind==="local"?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"min-w-0 truncate font-mono text-[12px] text-text-2",title:f.fileName,children:f.fileName||r("本地 YAML 文件")}),s.jsx(ze,{variant:"secondary",children:r("本地文件")})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"min-w-0 truncate font-mono text-[12px] text-text-2",title:f.url,children:JY(f.url)}),s.jsx(se,{variant:"ghost",size:"icon-xs",className:"copy-btn size-[21px] rounded-[var(--r-xs)] opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100","data-copy":f.url,title:r("复制订阅链接"),children:"⧉"})]})})}),s.jsx("td",{className:"ta-center",children:eD(p,f)>0?s.jsx(ze,{variant:"secondary",children:r("{n} 个",{n:eD(p,f)})}):s.jsx("span",{className:"text-subtle",children:r("—")})}),s.jsx("td",{children:p?.at?s.jsx("span",{className:"text-[12px] text-text-2",children:P2(p.at)}):s.jsx("span",{className:"text-subtle",children:r("未同步")})}),s.jsx("td",{className:"ta-center",children:s.jsx(ms,{checked:f.enabled,disabled:t.pending,"aria-label":r("启用订阅「{name}」",{name:f.name||r("未命名")}),onCheckedChange:g=>{HY(f,g)}})}),s.jsx("td",{children:s.jsxs("div",{className:"row-actions",children:[s.jsx(se,{size:"sm",variant:"ghost",disabled:t.pending||t.refreshing!==null||f.kind==="local",title:f.kind==="local"?r("本地文件订阅无需更新(要换内容请编辑后重新选择文件)"):void 0,onClick:()=>{UY(f)},children:t.refreshing===f.id?r("更新中…"):r("立即更新")}),s.jsx(se,{size:"sm",variant:"ghost",disabled:t.pending,onClick:()=>d({item:f}),children:r("编辑")}),s.jsx(se,{size:"sm",variant:"destructive",disabled:t.pending,onClick:()=>{VY(f)},children:r("删除")})]})})]},f.id)}):s.jsx("tr",{children:s.jsx("td",{colSpan:6,className:"empty",children:o?s.jsxs("div",{className:"flex flex-col items-center gap-2 py-3",children:[s.jsx("span",{children:r("还没有订阅:粘贴订阅链接、导入本地 YAML 文件,或从图片识别二维码。")}),s.jsx(se,{size:"sm",variant:"outline",disabled:t.pending,onClick:()=>d({item:null}),children:r("+ 新增订阅")}),s.jsx("span",{className:"text-[11px] text-subtle",children:r("订阅里的节点会自动同步进代理池,账号即可引用。")})]}):r("加载中…")})})})]})}),s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:r("订阅里的节点会被内核起成本地监听器,镜像到代理池(账号按 id 引用,与本页其它出口同一用法)。内核只在用到订阅时按需下载(约 20-40MB),不随安装包分发。")}),t.error?s.jsx("span",{className:"text-destructive",children:r("读取失败:{reason}",{reason:t.error})}):null]}),s.jsxs(nn,{children:[s.jsx(se,{variant:"default",disabled:t.pending,onClick:()=>d({item:null}),children:r("+ 新增订阅")}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:e,children:r("完成")})]})]}),c?s.jsx(eX,{item:c.item,onClose:()=>d(null)}):null]})}function J2(e){return!Number.isFinite(e)||e<=0?"—":(e/1e3/1e3).toFixed(1)}function JY(e){try{const t=new URL(e);return t.host+(t.pathname!=="/"?"/…":"")}catch{return e.slice(0,60)}}function eD(e,t){return e?.count??t.nodeCount}function eX({item:e,onClose:t}){const a=e!==null,[o,c]=x.useState(e?.kind==="local"?"local":"url"),[d,f]=x.useState(e?.name||""),[p,g]=x.useState(e?.url||""),[v,y]=x.useState(e?.fileName||""),[b,j]=x.useState(""),[w,S]=x.useState(e?e.enabled:!0),[N,k]=x.useState(!1),[E,D]=x.useState(!1),[C,A]=x.useState(!1),[R,I]=x.useState(null),P=x.useRef(null);async function O(){if(N)return;const z=d.trim();if(!z){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",r("请填写订阅名称")]}));return}const Q=p.trim();if(o==="url"&&!(Q.startsWith("http://")||Q.startsWith("https://"))){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",r("订阅链接必须是 http:// 或 https:// 开头")]}));return}if(!a&&o==="local"&&!b){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",r("请选择要导入的 YAML 文件")]}));return}k(!0);try{a&&o==="local"?await Q2(e,{name:z,enabled:w,kind:"local",fileName:v||void 0,...b?{contentB64:b}:{}}):a?await Q2(e,{name:z,url:Q,enabled:w,kind:"url"}):o==="local"?await X2({name:z,kind:"local",fileName:v||void 0,contentB64:b}):await X2({name:z,kind:"url",url:Q}),t()}catch(K){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",jr(K)]})),k(!1)}}async function _(z){if(!E){D(!0),I(r("正在识别二维码…"));try{const Q=await YY(z);g(Q),I(s.jsxs("span",{className:"text-success",children:["✅ ",r("已识别订阅链接")]}))}catch(Q){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",jr(Q)]}))}finally{D(!1)}}}async function L(z){if(!C){A(!0),I(null);try{const Q=await XY(z);j(Q),y(z.name),I(s.jsxs("span",{className:"text-success",children:["✅ ",r("已选择「{name}」,保存后导入",{name:z.name})]}))}catch(Q){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",jr(Q)]}))}finally{A(!1)}}}function H(z){if(o!=="url")return;const K=Array.from(z.clipboardData?.files||[]).find(X=>X.type.startsWith("image/"));K&&(z.preventDefault(),_(K))}function B(z){z!==o&&(c(z),I(null))}return s.jsx(Qt,{open:!0,onOpenChange:z=>{!z&&!N&&t()},children:s.jsxs(Zt,{className:"max-w-[560px]",overlayForceRender:!0,onPaste:H,children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r(a?"编辑订阅":"新增订阅")})}),s.jsxs(Bt,{className:"flex flex-col gap-3.5",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"sub-name",children:r("名称")}),s.jsx($e,{id:"sub-name",maxLength:60,autoComplete:"off",spellCheck:!1,placeholder:r("例如:我的机场"),value:d,onChange:z=>f(z.currentTarget.value)})]}),a?null:s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{children:r("订阅来源")}),s.jsx(In,{options:[{value:"url",label:r("订阅链接")},{value:"local",label:r("本地 YAML 文件")}],value:o,onValueChange:B,"aria-label":r("订阅来源")})]}),o==="url"?s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"sub-url",children:r("订阅链接")}),s.jsx($e,{id:"sub-url",autoComplete:"off",spellCheck:!1,placeholder:"https://…",value:p,onChange:z=>g(z.currentTarget.value)}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(se,{size:"sm",variant:"outline",disabled:E,onClick:()=>P.current?.click(),children:r(E?"识别中…":"从图片识别二维码")}),s.jsx("span",{className:"text-[11px] text-subtle",children:r("也可以把二维码截图直接粘贴到弹窗里(Ctrl+V)")}),s.jsx("input",{ref:P,type:"file",accept:"image/*",className:"hidden",onChange:z=>{const Q=z.currentTarget.files?.[0];Q&&_(Q),z.currentTarget.value=""}})]})]}):s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"sub-file",children:r("YAML 文件")}),s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[s.jsx(se,{size:"sm",variant:"outline",disabled:C,className:"shrink-0",onClick:()=>P.current?.click(),children:r(C?"读取中…":a?"重新选择文件…":"选择 YAML 文件…")}),s.jsx("span",{className:"min-w-0 truncate font-mono text-[12px] text-text-2",title:v||void 0,children:v||r(a?"保持原文件":"未选择文件")})]}),a?s.jsx("span",{className:"text-[11px] text-subtle",children:r("本地文件不会自动更新:要更新节点,重新选择文件后保存;不重选则内容保持不变。")}):null,s.jsx("input",{ref:P,type:"file",accept:".yaml,.yml,text/yaml,application/yaml,text/plain",className:"hidden",onChange:z=>{const Q=z.currentTarget.files?.[0];Q&&L(Q),z.currentTarget.value=""}})]}),s.jsxs("div",{className:"flex flex-row items-center gap-2.5",children:[s.jsx(ms,{checked:w,onCheckedChange:S,"aria-label":r("启用这条订阅")}),s.jsx("span",{className:"text-[12.5px]",children:r("启用(禁用的订阅不参与内核同步,它的节点会从代理池移除)")})]}),s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:r(o==="url"?"订阅内容由内核定时刷新(每 24 小时);节点数与同步状态在保存后由轮询刷新,稍等几秒。":"本地文件订阅的内容在导入时固定:节点会由内核起成本地监听器并镜像进代理池,节点数稍等几秒由轮询刷新。")}),s.jsx("div",{className:"min-h-[18px] text-xs text-subtle",children:R})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:N,onClick:t,children:r("取消")}),s.jsx(se,{variant:"default",disabled:N||E||C,onClick:()=>{O()},children:r(N?"保存中…":"保存")})]})]})})}const c0=[{key:"pick",label:r("选择"),align:"center"},{key:"name",label:r("节点")},{key:"addr",label:r("地址")},{key:"state",label:r("启用"),align:"center"},{key:"test",label:r("连通性")},{key:"act",label:r("操作"),align:"right"}],tX={pick:"p-pick",name:"",addr:"p-addr",state:"p-state",test:"p-test",act:"p-act"},tD="proxies";function u0(){return window}let Zg=null,nD=null;function sD(){return Zg?Zg.apply([...c0]):c0.map(e=>({...e,align:e.align??"left"}))}function nX(){u0().wbTableColumns?.repaint?.(tD)}function sX(e){if(nD=e,Zg)return!0;const t=u0().wbColSettings;return t?.register?(Zg=t.register({id:tD,label:r("代理池表"),columns:c0.map(a=>({key:a.key,label:a.label,align:a.align??"left"})),mount:()=>document.querySelector('.page[data-page="proxies"] .panel-head .head-actions'),onChange:()=>nD?.()}),!0):!1}function rX(){u0().wbColSettings?.close?.()}function aX(){const e=x.useSyncExternalStore(bY,vY),t=x.useSyncExternalStore(Xg,Qg).data?.items??[],[a,o]=x.useState(null),[c,d]=x.useState(!1),[f,p]=x.useState(!1),[g,v]=x.useState(""),[y,b]=x.useState("all"),[j,w]=x.useState("all"),[S,N]=x.useState("all"),[k,E]=x.useState(0),[,D]=x.useReducer(J=>J+1,0),C=Kg(),A=e.data!==null,R=e.selected.size,I=C.filter(J=>e.selected.has(J.id)&&qg(J)).length,P=e.batchProgress;x.useEffect(()=>{Ml()},[]),x.useLayoutEffect(()=>{if(!sX(()=>D())){const J=window.setTimeout(()=>E(ie=>ie+1),50);return()=>window.clearTimeout(J)}D()},[k]),x.useLayoutEffect(()=>{nX()}),x.useEffect(()=>()=>{rX()},[]);const O=g.trim().toLowerCase(),_=iX(C,t);function L(J){return j==="all"?!0:j==="manual"||j==="clash"||j==="subscription"?tl(J)===j:j===lD?!!J.orphan:J.source==="subscription"&&!J.orphan&&J.providerId===j}function H(J){return!(y!=="all"&&tl(J)!==y||!L(J)||S!=="all"&&aD(J)!==S||O&&![J.name,zh(J),J.host,J.protocol,String(J.port??"")].join(" ").toLowerCase().includes(O))}function B(J){const ie=J??"all";w(ie),b(ie==="all"?"all":ie==="manual"||ie==="clash"?ie:"subscription")}function z(J){b(J),w("all")}const Q=C.filter(H),K=Q.map(J=>J.id),X=K.length>0&&K.every(J=>e.selected.has(J)),q=K.some(J=>e.selected.has(J))&&!X,$=sD(),Y=[];for(const J of rD())Y.push(...Q.filter(ie=>tl(ie)===J.key));const F=ag(Q.length,"proxies"),G=F.paged?F.slice(Y):Y,W=new Map;for(const J of Q)W.set(tl(J),(W.get(tl(J))??0)+1);x.useEffect(()=>{F.goto(1)},[O,y,j,S]);function le(J){const ie=J.lastTest;if(!ie||!ie.at)return s.jsx("span",{className:"text-subtle",children:r("未测试")});const ge=a0(ie.durationMs);return s.jsxs("div",{className:"flex flex-col gap-0.5 leading-[1.5] min-w-0",children:[s.jsxs("span",{className:ie.success?"text-success":"text-destructive",children:[ie.success?r("✅ {ip}",{ip:ie.ip||r("连接成功")}):r("❌ 连接失败"),ge?` ${ge}`:"",s.jsxs("span",{className:"text-[11px] text-subtle",children:[" ",P2(ie.at)]})]}),ie.success?null:s.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-[11px] text-subtle",title:String(ie.error||r("连接失败")),children:String(ie.error||r("连接失败"))})]})}function M(J){const ie=J.usedBy||[],ge=[];return J.protocol&&ge.push(J.protocol),ie.length&&ge.push(s.jsx("span",{className:"text-warn",title:ie.map(ee=>String(ee.name||ee.id||"")).join(r("、")),children:r("{n} 个账号在用",{n:ie.length})})),ge.length?s.jsx("span",{className:"text-[11px] text-subtle",children:ge.map((ee,fe)=>s.jsxs(x.Fragment,{children:[fe?" · ":"",ee]},fe))}):null}function U(J){if(uY(J)&&(J.port===null||J.port===void 0))return s.jsx("span",{className:"text-subtle",children:r("已禁用(未开监听端口)")});if(J.resolveError){const ge=J.source==="subscription"&&(J.port===null||J.port===void 0);return s.jsx("span",{className:ge?"text-subtle":"text-destructive",title:J.resolveError,children:r(ge?"未分配端口":"解析失败")})}if(iY(J)){const ge=Hu()?.installed===!1;return s.jsx("span",{className:"text-subtle",title:r(ge?"代理内核未安装(在「订阅管理」里下载内核后,节点会自动分配监听端口)":"还没有监听端口(还没有账号引用它 —— 在账号里选它并保存后,内核会自动开端口)"),children:zh(J)||r("未分配端口")})}const ie=zh(J);return s.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[s.jsx("span",{className:"min-w-0 flex-1 font-mono text-[12px] leading-[1.45] text-text-2 break-all",title:ie||void 0,children:ie||"—"}),ie?s.jsx(se,{variant:"ghost",size:"icon-xs",className:"copy-btn flex-none","data-copy":ie,title:r("复制地址"),children:"⧉"}):null]})}function Z(J,ie,ge,ee){const fe=ge||e.batchBusy;switch(J){case"pick":return s.jsx(Or,{checked:ee,title:r("勾选后可批量操作"),"aria-label":r("勾选「{name}」",{name:ie.name||r("未命名")}),onCheckedChange:te=>jY(ie.id,te)});case"name":return s.jsxs("div",{className:"flex flex-col gap-0.5 leading-[1.5] min-w-0",children:[s.jsx("b",{children:ie.name||r("未命名")}),M(ie)]});case"addr":return U(ie);case"state":{const te=L2(ie);return s.jsx(ms,{checked:ie.enabled!==!1,disabled:fe||te,"aria-label":r("启用「{name}」",{name:ie.name||r("未命名")}),title:xY(ie),onCheckedChange:Ce=>{CY(ie,Ce)}})}case"test":return le(ie);case"act":{const te=Gg(ie);qg(ie);const Ce=H2(ie),re=e.testing===ie.id;return s.jsxs("div",{className:"row-actions",children:[s.jsx(se,{size:"sm",variant:"ghost",disabled:fe||e.testing!==null,onClick:()=>{kY(ie)},children:r(re?"测试中…":"测试")}),ie.source!=="clash"&&ie.source!=="subscription"?s.jsxs(s.Fragment,{children:[s.jsx(se,{size:"sm",variant:"ghost",disabled:fe,onClick:()=>o({item:ie}),children:r("编辑")}),s.jsx(se,{size:"sm",variant:"destructive",disabled:fe,onClick:()=>{U2(ie)},children:r("删除")})]}):null,te?s.jsx(se,{size:"sm",variant:"destructive",disabled:fe,title:Ce,onClick:()=>{U2(ie)},children:r("删除")}):null]})}default:return null}}function ae(J){const ie=e.pending.has(J.id),ge=yY(J.id);return s.jsx("tr",{className:Ue(J.enabled?"":"off",ge&&"bg-primary-soft"),"data-id":J.id,children:$.map(ee=>s.jsx("td",{className:`ta-${ee.align}`,children:Z(ee.key,J,ie,ge)},ee.key))},J.id)}function ce(){if(!C.length)return s.jsx("tr",{children:s.jsx("td",{colSpan:$.length,className:"empty",children:r(A?"还没有代理。点右上角「+ 新增代理」手填一个,点「同步 Clash Verge」把 Clash 的出口导进来,或在「订阅管理」里导入订阅节点。":"加载中…")})});if(!Q.length)return s.jsx("tr",{children:s.jsx("td",{colSpan:$.length,className:"empty",children:O?r("没有匹配「{kw}」的出口",{kw:g.trim()}):r("没有匹配当前筛选的出口")})});const J=[];let ie="";for(const ge of G){const ee=tl(ge);if(ee!==ie){ie=ee;const fe=rD().find(te=>te.key===ee);J.push(s.jsx("tr",{className:"tr-group",children:s.jsxs("td",{colSpan:$.length,children:[s.jsx("span",{className:"prov-tag",children:fe?.label??ee}),r("{n} 个",{n:W.get(ee)??0}),fe?.note?s.jsxs("span",{className:"font-normal",children:[" · ",fe.note]}):null]})},`group:${ee}:${J.length}`))}J.push(ae(ge))}return s.jsx(s.Fragment,{children:J})}return s.jsx(s.Fragment,{children:s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("代理池")}),s.jsx("span",{className:"panel-sub",children:A?r("{n} 个出口",{n:C.length}):r("加载中…")}),s.jsx("span",{className:"text-[11px] text-subtle",children:r("订阅与 Clash 的出口自动镜像进来")}),s.jsxs("div",{className:"head-actions",children:[s.jsx(se,{variant:"outline",disabled:e.batchBusy,onClick:()=>d(!0),children:r("设置")}),s.jsx(se,{variant:"outline",disabled:e.batchBusy,onClick:()=>p(!0),children:t.length?r("订阅管理({n})",{n:t.length}):r("订阅管理")}),s.jsx(se,{variant:"outline",disabled:e.syncing||e.batchBusy,onClick:()=>{NY()},children:e.syncing?r("同步中…"):r("同步 Clash Verge")}),s.jsx(se,{variant:"outline",disabled:e.loading||e.batchBusy,onClick:()=>{cp(),Ml()},children:e.loading?r("刷新中…"):r("刷新")}),s.jsx(se,{variant:"default",disabled:e.batchBusy,onClick:()=>o({item:null}),children:r("+ 新增代理")})]})]}),s.jsx("div",{className:"px-3 pt-3",children:s.jsx(W2,{showPortRange:!0})}),R>0?s.jsxs("div",{className:"batch-bar active",children:[s.jsxs("span",{className:"batch-count",children:[r("已选")," ",s.jsx("b",{children:R})," ",r("个 · 共")," ",s.jsx("b",{children:Q.length})," ",r("个")]}),I?s.jsx("span",{className:"batch-hidden",children:r("其中 {n} 条是同步来的只读条目(Clash / 订阅):可参与批量测试,删除会跳过",{n:I})}):null,s.jsxs("div",{className:"batch-actions",children:[s.jsx(se,{variant:"outline",disabled:e.batchBusy,onClick:()=>{EY()},children:P?r("测试中 {done}/{total}",{done:P.done,total:P.total}):r("批量测试")}),s.jsx(se,{variant:"destructive",disabled:e.batchBusy,onClick:()=>{AY()},children:r("批量删除")}),s.jsx(se,{variant:"outline",disabled:e.batchBusy,onClick:()=>SY(),children:r("取消选择")})]})]}):s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5 border-b border-border px-4 py-[10px]",children:[s.jsxs(Ci,{className:"w-[clamp(150px,22vw,220px)]",children:[s.jsx(Ei,{type:"search",value:g,"aria-label":r("搜索节点"),placeholder:r("搜索名称 / 地址 / 端口"),onChange:J=>v(J.currentTarget.value)}),s.jsx(Ti,{align:"inline-start","aria-hidden":"true",children:s.jsx(cX,{})})]}),s.jsxs(ft,{value:j,onValueChange:B,children:[s.jsx(mt,{className:"w-[clamp(150px,18vw,210px)]","aria-label":r("按提供方筛选"),children:s.jsx(pt,{children:_.find(J=>J.value===j)?.label??r("全部提供方")})}),s.jsx(ht,{children:_.map(J=>s.jsx(qe,{value:J.value,children:s.jsxs("span",{className:"flex w-full items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate"+(J.count?"":" text-subtle"),children:J.label}),s.jsx("span",{className:"flex-none text-[11px] text-subtle",children:J.count})]})},J.value))})]}),s.jsx(In,{options:lX(C),value:y,onValueChange:z,"aria-label":r("按来源筛选")}),s.jsx(In,{options:oX(C),value:S,onValueChange:N,"aria-label":r("按状态筛选")}),s.jsx("span",{className:"ml-auto text-[11px] text-subtle",children:r("显示 {n} / 共 {total} 个出口",{n:Q.length,total:C.length})})]}),s.jsx("div",{className:"models-table-wrap",children:s.jsxs("table",{className:"models-table proxies-table",children:[s.jsx("colgroup",{children:$.map(J=>s.jsx("col",{"data-col":J.key,className:tX[J.key]||void 0},J.key))}),s.jsx("thead",{children:s.jsx("tr",{children:$.map(J=>s.jsx("th",{"data-col":J.key,className:`ta-${J.align}`,children:J.key==="pick"?s.jsx(Or,{checked:X,indeterminate:q,disabled:!K.length,title:r("全选当前筛选出的出口"),"aria-label":r("全选当前筛选出的出口"),onCheckedChange:ie=>wY(K,ie)}):J.label},J.key))})}),s.jsx("tbody",{children:ce()})]})}),s.jsx(Li,{leading:s.jsxs(s.Fragment,{children:[e.data?.clash&&e.data.clash.available===!1?s.jsx("span",{className:"text-subtle",children:e.data.clash.error?r("未检测到 Clash Verge:{reason}",{reason:e.data.clash.error}):r("未检测到 Clash Verge")}):null,e.error?s.jsx("span",{className:"text-destructive",children:r("读取失败:{reason}",{reason:e.error})}):null]}),total:Q.length,page:F.page,pageCount:F.pageCount,size:F.size,onSizeChange:F.setSize,onPageChange:F.goto,range:F.paged?{start:F.rangeStart,end:F.rangeEnd}:null}),a?s.jsx(MY,{item:a.item,onClose:()=>o(null)}):null,c?s.jsx(DY,{onClose:()=>d(!1)}):null,f?s.jsx(WY,{onClose:()=>p(!1)}):null]})})}function tl(e){return e.source==="clash"?"clash":e.source==="subscription"?"subscription":"manual"}function rD(){return[{key:"manual",label:r("手动"),note:r("本页可编辑、可删除")},{key:"clash",label:"Clash Verge",note:r("名字与端口在 Clash Verge 里改;启用可在本页关闭")},{key:"subscription",label:r("订阅"),note:r("名字与端口跟随订阅与内核;启用可在本页关闭")}]}function lX(e){const t=a=>e.filter(o=>tl(o)===a).length;return[{value:"all",label:r("全部"),count:e.length},{value:"manual",label:r("手动"),count:t("manual")},{value:"clash",label:"Clash",count:t("clash")},{value:"subscription",label:r("订阅"),count:t("subscription")}]}function aD(e){return e.enabled===!1?"off":e.port===null||e.port===void 0?"wait":e.lastTest?.at?e.lastTest.success?"ok":"fail":"none"}function oX(e){const t=a=>e.filter(o=>aD(o)===a).length;return[{value:"all",label:r("全部状态"),count:e.length},{value:"ok",label:r("可用"),count:t("ok")},{value:"fail",label:r("失败"),count:t("fail")},{value:"wait",label:r("未就绪"),count:t("wait")},{value:"off",label:r("已禁用"),count:t("off")}]}const lD="__orphan";function iX(e,t){const a=e.filter(d=>tl(d)==="subscription"),o=t.map(d=>({value:d.id,label:d.name||d.id,count:a.filter(f=>!f.orphan&&f.providerId===d.id).length})).sort((d,f)=>f.count-d.count||d.label.localeCompare(f.label)),c=a.filter(d=>d.orphan).length;return[{value:"all",label:r("全部提供方"),count:e.length},{value:"manual",label:r("手动"),count:e.filter(d=>tl(d)==="manual").length},{value:"clash",label:"Clash Verge",count:e.filter(d=>tl(d)==="clash").length},{value:"subscription",label:r("全部订阅"),count:a.length},...o,...c?[{value:lD,label:r("已移除的订阅"),count:c}]:[]]}function cX(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("path",{d:"m21 21-4.3-4.3"})]})}window.wbProxiesPanel={load:async()=>{await cp(),await Ml()},visibleColumns:()=>sD().map(e=>({key:e.key}))};const oD='.page[data-page="proxies"]';function iD(){const e=document.querySelector(oD);!e||e.dataset.mounted==="1"||(e.dataset.mounted="1",e.replaceChildren(),vn.createRoot(e).render(s.jsx(aX,{})),tr().wbApp?.currentPage==="proxies"&&(cp(),Ml()))}document.querySelector(oD)?iD():document.addEventListener("DOMContentLoaded",iD,{once:!0});const Wg=["today","7","30","month","all","custom"],d0="7",f0="custom",cD="workbuddy-desktop-report-range",uD="workbuddy-desktop-report-custom-range",dD={today:r("今天"),7:r("近 7 天"),30:r("近 30 天"),month:r("本月"),all:r("全部"),custom:r("自定义区间")},uX={today:r("今天"),7:r("7 天"),30:r("30 天"),month:r("本月"),all:r("全部"),custom:r("自定义")};function dX(){try{const e=localStorage.getItem(cD);return e!==null&&Wg.includes(e)?e:d0}catch{return d0}}function p0(e){const t=a=>String(a).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function fX(){const e=new Date;return{start:p0(new Date(e.getFullYear(),e.getMonth(),e.getDate()-6)),end:p0(e)}}const Jg=/^\d{4}-\d{2}-\d{2}$/;function pX(){try{const e=localStorage.getItem(uD);if(e){const t=JSON.parse(e),a=typeof t?.start=="string"?t.start:"",o=typeof t?.end=="string"?t.end:"";if(Jg.test(a)&&Jg.test(o)&&a<=o)return{start:a,end:o}}}catch{}return fX()}function mX(e){try{localStorage.setItem(uD,JSON.stringify(e))}catch{}}const hX=[[0,r("一")],[2,r("三")],[4,r("五")]],fD=400;function Qi(e){const t=m0();return t.formatInt?t.formatInt(e):(Number(e)||0).toLocaleString("zh-CN")}function m0(){return window.wbUnits||{}}function ns(e){const t=m0();return t.formatTokens?t.formatTokens(e):String(Number(e)||0)}function pD(e,t){const a=m0();return a.formatAxis?a.formatAxis(e,t):String(e)}function Zi(e){return`${((Number(e)||0)*100).toFixed(1)}%`}function Pt(e){return Math.round(e*10)/10}function ex(e){return[...e].reduce((t,a)=>t+(/[\u2e80-\u9fff]/.test(a)?9.7:5.4),0)}function tx(e){const[t,a,o]=String(e||"").split("-").map(Number);return new Date(t||1970,(a||1)-1,o||1)}const gX=[r("日"),r("一"),r("二"),r("三"),r("四"),r("五"),r("六")];function nx(e){const t=tx(e);return r("{m}月{d}日 周{wd}",{m:t.getMonth()+1,d:t.getDate(),wd:gX[t.getDay()]})}function mD(e){const t=String(e||"").slice(11,13);return t?`${t}:00`:"—"}const xX=8;function hD(e,t){const a=(Array.isArray(e)?e:[]).map(d=>({name:String(d?.label??d?.model??"").trim()||r("未知模型"),tokens:Number(d?.tokens)||0})).filter(d=>d.tokens>0);if(!a.length)return[];const o=a.slice(0,xX),c=o.map(d=>`${t?`[${t(d.name)}]`:""}${r("{model}:{tokens} tokens",{model:d.name,tokens:ns(d.tokens)})}`);return a.length>o.length&&c.push(r("…还有 {n} 个模型",{n:a.length-o.length})),c}function gD(e,t){return[nx(e.date),r("总 Token:{tokens}({n} 次请求)",{tokens:ns(e.tokens),n:Qi(e.requests)}),...hD(e.models,t)].join(` -`)}function bX(e,t){return[`${nx(String(e.hour).slice(0,10))} ${mD(e.hour)}`,r("命中率 {rate}(命中 {hit} / 输入 {input})",{rate:Zi(e.rate),hit:ns(e.hitTokens),input:ns(e.inputTokens)}),r("总 Token:{tokens}",{tokens:ns(e.totalTokens)}),...hD(e.models,t)].join(` -`)}const vX=[1,1.5,2,2.5,3,4,5,6,8,10];function yX(e){if(!(e>0))return 1;const t=10**Math.floor(Math.log10(e)),a=e/t;return(vX.find(c=>c>=a-1e-9)??10)*t}function h0(e){return yX(e/4)*4}function jX(e,t,a){const o=e||{},c=o.topModel,d=Number(o.requests)||0,f=Number(o.successful)||0,p=d?`${(f/d*100).toFixed(1)}%`:"—",g=[{key:"requests",label:r("总请求数"),value:Qi(d),sub:dD[t]||"",mono:!1},{key:"successful",label:r("成功请求数"),value:Qi(f),sub:r("成功率 {rate}",{rate:p}),mono:!1},{key:"tokens",label:r("总 Token"),value:ns(o.tokens),sub:r("输入 + 输出"),mono:!1},{key:"activeDays",label:r("活跃天数"),value:Qi(o.activeDays),sub:r("区间共 {n} 天",{n:a}),mono:!1},{key:"streak",label:r("当前连续天数"),value:Qi(o.streak),sub:r("含今天在内往前数"),mono:!1}];return g.push(c?{key:"topModel",label:r("Top 模型"),value:String(c.model??""),sub:r("{tokens} tokens · 占 {pct}",{tokens:ns(c.tokens),pct:Zi(c.percentage)}),mono:!0}:{key:"topModel",label:r("Top 模型"),value:"—",sub:r("所选范围内还没有模型用量"),mono:!1}),g}function xD(e){if(!Array.isArray(e))return null;const t=e.map(c=>({id:String(c?.id??"").trim(),label:String(c?.label??"").trim(),tokens:Number(c?.totalTokens??c?.tokens)||0})).filter(c=>c.tokens>0);if(!t.length)return[];const a=t.reduce((c,d)=>c+d.tokens,0),o=c=>a?c/a*100:0;return[...t].sort((c,d)=>d.tokens-c.tokens).map((c,d)=>{const f=o(c.tokens),p=ns(c.tokens),g=c.label||c.id||r("未知"),v=c.id?r("{name}({id})",{name:g,id:c.id}):g;return{key:`${d}-${c.id||g}`,id:c.id,name:g,full:v,tip:r("{name}:{tokens} tokens · 占 {pct}%",{name:v,tokens:p,pct:f.toFixed(1)}),tokensText:p,percentText:`${f.toFixed(1)}%`,barWidth:`${f.toFixed(1)}%`}})}function bD(e){return`${ns(e.reduce((t,a)=>t+(Number(a?.totalTokens??a?.tokens)||0),0))} tokens`}const sx=["#f73b00","#f7bb07","#4aaa4d","#1872cb","#3444a3","#13c2c2","#722ed1","#eb2f96","#a0d911","#34d399","#d946ef","#ff85c0","#b37feb","#9d174d","#ffa39e","#69b1ff"],wX={size:220,inner:.62,outer:.88,padAngle:2};function SX(e,t,a,o,c,d){const f=D=>(D-90)*Math.PI/180,p=(D,C)=>[Pt(e+D*Math.cos(f(C))),Pt(t+D*Math.sin(f(C)))],g=d-c;if(g>=359.999){const[D,C]=p(a,0),[A,R]=p(a,180),[I,P]=p(o,0),[O,_]=p(o,180);return`M ${D} ${C} A ${a} ${a} 0 1 1 ${A} ${R} A ${a} ${a} 0 1 1 ${D} ${C} Z M ${I} ${P} A ${o} ${o} 0 1 0 ${O} ${_} A ${o} ${o} 0 1 0 ${I} ${P} Z`}const[v,y]=p(a,c),[b,j]=p(a,d),[w,S]=p(o,d),[N,k]=p(o,c),E=g>180?1:0;return`M ${v} ${y} A ${a} ${a} 0 ${E} 1 ${b} ${j} L ${w} ${S} A ${o} ${o} 0 ${E} 0 ${N} ${k} Z`}const NX="#9aa0a6";function vD(e){const t=new Map;for(const a of Array.isArray(e)?e:[]){const o=String(a?.label??a?.model??a?.id??"").trim();!o||t.has(o)||(Number(a?.totalTokens??a?.tokens)||0)>0&&t.set(o,sx[t.size%sx.length])}return t}function yD(e,t){const a=(Array.isArray(e)?e:[]).map(k=>({label:String(k?.label??k?.model??k?.id??"").trim()||t,tokens:Number(k?.totalTokens??k?.tokens)||0,requests:Number(k?.requests)||0})).filter(k=>k.tokens>0);if(!a.length)return null;const o=a.reduce((k,E)=>k+E.tokens,0);if(!o)return null;const c=vD(e),{size:d,inner:f,outer:p,padAngle:g}=wX,v=d/2,y=d/2,b=d/2*p,j=d/2*f;let w=0;const S=[],N=[];return a.forEach((k,E)=>{const D=k.tokens/o,C=D*360,A=a.length>1?Math.min(g/2,C/4):0,R=w+A,I=w+C-A;w+=C;const P=c.get(k.label)??sx[E%sx.length];let O=null;if(D>=.03){const _=(R+I)/2,L=j+(b-j)*.6,H=(_-90)*Math.PI/180;O={x:Pt(v+L*Math.cos(H)),y:Pt(y+L*Math.sin(H)),text:`${Math.round(D*100)}%`}}I>R&&S.push({key:`${E}-${k.label}`,d:SX(v,y,b,j,R,I),fill:P,evenOdd:C>=359.999,label:O,tip:`${k.label} · ${ns(k.tokens)} tokens · ${Zi(D)}`}),N.push({key:`${E}-${k.label}`,fill:P,name:k.label,tokensText:ns(k.tokens),percentText:Zi(D),tip:r("{name} · {tokens} tokens · {n} 次请求 · {pct}",{name:k.label,tokens:ns(k.tokens),n:Qi(k.requests),pct:Zi(D)})})}),{size:d,slices:S,legend:N,totalText:ns(o)}}const kX=[1,1.25,1.5,2,2.5,3,4,5,6,8,10];function CX(e){if(!(e>0))return 1;const t=10**Math.floor(Math.log10(e)),a=e/t;let o=1;for(const c of kX)c<=a+1e-9&&(o=c);return o*t}function TX(e){const t=Number(e)||0;if(t<=0)return[0,1,2,3,1/0];const a=Math.max(1,CX(t/4));return[0,a,a*2,a*3,1/0]}function EX(e,t){if(e===0)return"0";const a=t[e-1],o=t[e];return Number.isFinite(o)?a===0?`≤${ns(o)}`:`${ns(a)}–${ns(o)}`:`>${ns(a)}`}function jD(e){const t=Array.isArray(e)?e:[];return TX(t.reduce((a,o)=>Math.max(a,Number(o?.tokens)||0),0))}function AX(e,t){const a=Array.isArray(e)?e:[];if(!a.length)return null;const o=(tx(a[0].date).getDay()+6)%7,c=new Array(o).fill(null).concat(a),d=Math.ceil(c.length/7),f=3,p=20,g=t-p,v=Math.floor((g-f*(d-1))/d),y=Math.max(7,Math.min(26,v)),b=y+3,j=y+f,w=p+d*j-f,S=Math.max(0,Math.round((t-w)/2)),N=b+7*j-f+2,k=Math.max(w,Math.round(t)),E=jD(a),D=O=>E.findIndex(_=>Number(O)<=_),C=[];for(let O=0;O({key:_,x:S+p-6,y:Pt(b+O*j+y/2),text:_})),R=[];let I=-1,P=-9;for(let O=0;O({level:t,text:EX(t,e)}))}function OX(e){const t=e||{};return[["last10m",r("近 10 分钟")],["last1h",r("近 1 小时")],["last24h",r("近 24 小时")],["last7d",r("近 7 天")]].map(([o,c])=>{const d=t[o]||{},f=Number(d.inputTokens)||0;return{key:o,label:c,value:f?Zi(d.rate):"—",sub:r("命中 {hit} / 输入 {input}",{hit:ns(d.hitTokens),input:ns(f)})}})}function MX(e,t,a){const o=Array.isArray(e)?e:[];if(!o.length)return null;const c=230,d={left:44,right:56,top:26,bottom:24},f=Math.max(40,t-d.left-d.right),p=c-d.top-d.bottom,g=o.map(q=>Number(q.rate)||0),v=o.map(q=>Number(q.totalTokens)||0),y=Math.max(1,h0(Math.max(...g))),b=Math.max(...v),j=h0(b),w=b>0,S=q=>d.left+(o.length>1?f*q/(o.length-1):f/2),N=q=>d.top+p-p*q/y,k=q=>d.top+p-p*q/j,E=[],D=[],C=[];for(let q=0;q<=4;q+=1){const $=y*q/4,Y=Pt(N($)),F=$*100;E.push({key:`g${q}`,y:Y}),D.push({key:`r${q}`,x:d.left-8,y:Y,anchor:"end",text:`${Number.isInteger(F)?F:F.toFixed(1)}%`}),w&&C.push({key:`t${q}`,x:Pt(d.left+f+8),y:Y,anchor:"start",text:pD(j*q/4,j)})}const A=o.length===1?4.5:2.5,R=(q,$)=>({points:q.map((Y,F)=>`${Pt(S(F))},${Pt($(Y))}`).join(" "),dots:q.map((Y,F)=>({key:`d${F}`,cx:Pt(S(F)),cy:Pt($(Y))}))}),I=[],P=(q,$,Y,F)=>{const G=ex(Y),W=F==="middle"?q-G/2:F==="end"?q-G:q,le={left:W,right:W+G,top:$-8.5,bottom:$+2.5};return I.some(M=>le.leftM.left-2&&le.topM.top-1)?null:(I.push(le),{key:`${Y}-${q}-${$}`,x:Pt(q),y:Pt($),text:Y,anchor:F})},O=(q,$)=>{const Y=ex($)/2;return q-Yd.left+f+6?"end":"middle"},_=[];w&&o.forEach((q,$)=>{if(!(Number(q.totalTokens)>0))return;const Y=k(v[$]),F=Y-12>=d.top-10,G=ns(v[$]),W=P(S($),F?Y-12:Y+13,G,O(S($),G));W&&_.push({...W,key:`tl${$}`})});const L=[];o.forEach((q,$)=>{if(!((Number(q.inputTokens)||0)+(Number(q.hitTokens)||0)>0))return;const F=N(g[$]),G=F+15<=d.top+p+8,W=Zi(g[$]),le=P(S($),G?F+13:F-7,W,O(S($),W));le&&L.push({...le,key:`rl${$}`})});const H=o.length>1?f/(o.length-1):f,B=d.left,z=d.left+f,Q=o.length<=fD?o.map((q,$)=>{const Y=Math.max(B,S($)-H/2),F=Math.min(z,S($)+H/2);return{key:`h${$}`,x:Pt(Y),width:Pt(F-Y),tip:bX(q,a)}}):null,K=Math.max(1,Math.ceil(o.length/8)),X=[];for(let q=0;q=o.length;X.push({key:`x${q}`,x:Pt(S(q)),y:c-8,anchor:q===0?"start":$?"end":"middle",text:mD(o[q].hour)})}return{width:t,height:c,plotLeft:B,plotW:f,plotH:p,plotTop:d.top,grid:E,rateTicks:D,tokenTicks:C,rateLine:R(g,N),tokenLine:w?R(v,k):null,dotR:A,rateLabels:L,tokenLabels:_,hourTicks:X,hits:Q}}const DX=13;function IX(e,t,a){const o=Array.isArray(e)?e:[];if(!o.length)return null;const c=240,d={left:50,right:14,top:26,bottom:26},f=Math.max(40,t-d.left-d.right),p=f/o.length,g=o.map(K=>Number(K.tokens)>0?ns(K.tokens):""),v=Math.max(0,...g.map(ex)),y=g.every(K=>!K)||v+4<=p,b=!y&&p>=DX;b&&(d.top=10+Math.ceil(v*1.25));const j=c-d.top-d.bottom,w=o.map(K=>Number(K.tokens)||0),S=Math.max(...w),N=h0(S),k=Math.max(1,Math.min(28,p*.68)),E=d.top+j,D=K=>d.top+j-j*K/N,C=o.length<=fD,A=S<=0,R=[],I=[];if(!A)for(let K=0;K<=4;K+=1){const X=N*K/4,q=Pt(D(X));R.push({key:`g${K}`,x1:d.left,y:q,x2:Pt(d.left+f)}),I.push({key:`v${K}`,x:d.left-8,y:q,anchor:"end",text:pD(X,N)})}const P=[];o.forEach((K,X)=>{const q=Number(K.tokens)||0;if(q<=0)return;const $=D(q);P.push({key:String(K.date??X),x:Pt(d.left+p*X+(p-k)/2),y:Pt($),width:Pt(k),height:Pt(Math.max(1,E-$)),rx:k>4?2:1,tip:gD(K),nativeTip:!C})});const O=[],_=[],L=(K,X)=>{const q=g[K],$=D(Number(o[K].tokens)||0),Y=Pt(d.left+p*K+p/2);if(b)return{key:`b${K}`,x:Y,y:Pt($-6),anchor:"start",text:q,rotate:!0};const F=$-6,G=F-9M.leftU.left-2&&M.topU.top-1))return null;_.push(M)}return{key:`b${K}`,x:Y,y:W,anchor:"middle",text:q}};if(y||b)g.forEach((K,X)=>{if(!K)return;const q=L(X,!1);q&&O.push(q)});else{const K=o.map((X,q)=>({index:q,value:Number(X.tokens)||0})).filter(X=>X.value>0).sort((X,q)=>q.value-X.value);for(const X of K){if(O.length>=8)break;const q=L(X.index,!0);q&&O.push(q)}}const H=C?o.map((K,X)=>({key:`h${X}`,x:Pt(d.left+p*X),width:Pt(p),tip:gD(K,a)})):null,B=Math.max(1,Math.ceil(o.length/6)),z=[];for(let K=0;K{const X=o.length===1,q=!X&&K===o.length-1,$=tx(o[K].date);return{key:`d${K}`,x:X?d.left+f/2:q?d.left+f:Pt(d.left+p*K+p/2),y:c-8,anchor:X?"middle":q?"end":K===0?"start":"middle",text:`${$.getMonth()+1}/${$.getDate()}`}});return{width:t,height:c,plotLeft:d.left,plotW:f,plotH:j,plotTop:d.top,grid:R,valueTicks:I,bars:P,barLabels:O,dateTicks:Q,hits:H,blank:A}}function Wi(){return window}const wD=1e3,PX=Wg.map(e=>({value:e,label:uX[e]})),_X=r("所选范围内每个账号各消耗了多少 Token,按 Token 用量从多到少排。账号是比提供商更细的一维:同一家可以挂多个账号,转发时按优先级在候选链上依次尝试,所以这里反映的是「具体哪个登录态在出力」。百分比按本区间的总 Token 数算(这一块只看用量,请求次数与成功率在概览卡片里)。「未知账号」是指那批请求没有账号身份:走默认登录态转发(未配置账号列表)时会这样;这一维上线前写出的旧聚合行也没有账号明细,但它们会在升级导入旧数据时按明细自动补算回来 —— 只有明细已被手动清理掉的那几天补不回来,仍留在「未知账号」里,那是确实无从恢复的部分。"),LX=r("所选范围内每个提供商各消耗了多少 Token,按 Token 用量从多到少排。同一个模型名可能有多家都能提供,网关按设置页「转发路由」的优先级依次尝试,所以占比也反映了实际落到谁身上。百分比按本区间的总 Token 数算(这一块只看用量,请求次数与成功率在概览卡片里)。「未知」是指那批请求没记下承载它的提供商 —— 主要是记录提供商这个功能上线之前的旧明细,其次是请求在选定上游之前就失败了(请求体非法、模型不存在、没有可用账号)。这一维与账号那一维不同:旧明细里根本没有「哪家承载」的信息(早期版本只有单一上游,但那是配置事实而非逐条记录),所以无法回算,旧数据会一直留在「未知」里;此后新产生的请求都会记上具体的提供商。"),zX=r("所选范围内每个模型各消耗了多少 Token,按用量从多到少排,扇区角度即占比。中心是这一维的合计(等于概览里的总 Token),右侧每行给出该模型的 Token 用量与百分比。扇区内的百分比只在 ≥3% 时标出,更小的会挤成一团 —— 完整读数在右侧列表与悬停气泡里。颜色按用量排名分配:最大的那段是红色,依次往后;同一份报表里换个维度看,配色口径不变。"),BX=r("所选范围内每个提供商各消耗了多少 Token,按用量从多到少排,扇区角度即占比。同一个模型名可能有多家都能提供,网关按设置页「转发路由」的优先级依次尝试,所以占比也反映了实际落到谁身上。中心是这一维的合计(等于概览里的总 Token),右侧每行给出该提供商的 Token 用量与百分比。「未知」是指那批请求没记下承载它的提供商 —— 主要是记录提供商这个功能上线之前的旧明细,其次是请求在选定上游之前就失败了。"),HX=r("命中率 = 缓存读取 Token / 输入 Token(promptTokens)。窗口越短越贴近「此刻」:上游把缓存读取与输入分开上报时,该比值合法地可能超过 100%,此处不夹取值、如实展示。"),UX=r("每天的总 Token 用量(输入 + 输出)。柱顶标出当天的读数;区间很长、柱子挤到放不下时只标最高的那几天,其余悬停柱子即可读到。");let rx=wD,ax=!0,g0=!1,x0=!1,b0=0,Po=null,Ji=null,lx=null;function ec(e,t="empty"){return s.jsx("div",{className:t,style:{padding:"14px 0"},children:e})}function ox({text:e}){return s.jsx("span",{className:"tip-q","data-tip":e})}function VX({accountId:e}){const t=(Wi().wbApp?.getState?.()?.accounts?.accounts||[]).find(f=>f?.id===e),a=typeof t?.provider=="string"?t.provider:"";if(!a)return null;const o=Wi().wbProviders?.labelOf?.(a)||a,c=t&&Wi().wbAccountsModel?.editionSuffix?.(t)||"",d=c?`${o} ${c}`:o;return s.jsx("span",{className:`pbadge p-${a}`,title:r("提供商:{text}",{text:d}),children:d})}function FX({summary:e,range:t}){const a=Array.isArray(e.dailyTrend)?e.dailyTrend:[];return s.jsx(s.Fragment,{children:jX(e.overview,t,a.length).map(o=>s.jsxs("div",{className:"field",children:[s.jsx("div",{className:"label",children:o.label}),s.jsxs("div",{className:o.mono?"value mono":"value",children:[o.value,o.sub?s.jsx("div",{className:"sub",children:o.sub}):null]})]},o.key))})}function SD({panelId:e,listId:t,labelId:a,title:o,tip:c,rows:d,totalText:f,withBadge:p,emptyText:g}){return s.jsxs("section",{className:"panel",id:e,children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:o}),s.jsx(ox,{text:c}),s.jsx("span",{className:"panel-sub",id:a,children:f})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"rank-shares",id:t,children:d.length?d.map(v=>s.jsxs("div",{className:"rank-row","data-tip":v.tip,children:[s.jsxs("span",{className:"name",title:v.full,children:[p?s.jsx(VX,{accountId:v.id}):null,v.name]}),s.jsx("span",{className:"track",children:s.jsx("span",{className:"bar",style:{width:v.barWidth}})}),s.jsx("span",{className:"num",title:`${v.tokensText} tokens`,children:v.tokensText}),s.jsx("span",{className:"pct",children:v.percentText})]},v.key)):ec(g)})})]})}function ND({panelId:e,listId:t,title:a,tip:o,ariaLabel:c,view:d,emptyText:f}){return s.jsxs("section",{className:"panel",id:e,children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:a}),s.jsx(ox,{text:o})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{id:t,children:d?s.jsxs("div",{className:"donut-layout",children:[s.jsxs("div",{className:"donut-wrap",children:[s.jsx("svg",{className:"donut-svg",width:d.size,height:d.size,viewBox:`0 0 ${d.size} ${d.size}`,role:"img","aria-label":c,children:d.slices.map(p=>s.jsxs(x.Fragment,{children:[s.jsx("path",{className:"donut-slice",d:p.d,fill:p.fill,fillRule:p.evenOdd?"evenodd":void 0,tabIndex:-1,"data-tip":p.tip}),p.label?s.jsx("text",{className:"donut-label",x:p.label.x,y:p.label.y,textAnchor:"middle",dominantBaseline:"central",children:p.label.text}):null]},p.key))}),s.jsxs("div",{className:"donut-center",children:[s.jsx("div",{className:"donut-center-value",children:d.totalText}),s.jsx("div",{className:"donut-center-label",children:r("总 Token")})]})]}),s.jsx("div",{className:"donut-legend",children:d.legend.map(p=>s.jsxs("div",{className:"donut-legend-row","data-tip":p.tip,children:[s.jsx("span",{className:"donut-dot",style:{background:p.fill}}),s.jsx("span",{className:"donut-legend-name",title:p.name,children:p.name}),s.jsx("span",{className:"donut-legend-tokens",children:p.tokensText}),s.jsx("span",{className:"donut-legend-percent",children:p.percentText})]},p.key))})]}):ec(f)})})]})}function $X({view:e}){return s.jsxs("svg",{className:"report-svg",width:e.width,height:e.height,viewBox:`0 0 ${e.width} ${e.height}`,role:"img","aria-label":r("近 365 天活跃热力图"),children:[e.months.map(t=>s.jsx("text",{className:"hm-axis",x:t.x,y:10,children:t.text},t.key)),e.weekdays.map(t=>s.jsx("text",{className:"hm-axis",x:t.x,y:t.y,textAnchor:"end",dominantBaseline:"middle",children:t.text},t.key)),e.cells.map(t=>s.jsx("rect",{className:`hm-cell l${t.level}`,x:t.x,y:t.y,width:t.size,height:t.size,rx:2,tabIndex:-1,"data-tip":t.tip},t.key))]})}function kD({line:e,cls:t,radius:a}){return s.jsxs(s.Fragment,{children:[s.jsx("polyline",{className:`chart-line ${t}`,points:e.points}),e.dots.map(o=>s.jsx("circle",{className:`chart-dot ${t}`,cx:o.cx,cy:o.cy,r:a},o.key))]})}function v0({items:e,cls:t}){return s.jsx(s.Fragment,{children:e.map(a=>s.jsx("text",{className:`chart-label ${t}`,x:a.x,y:a.y,textAnchor:a.anchor,transform:a.rotate?`rotate(-90 ${a.x} ${a.y})`:void 0,dominantBaseline:a.rotate?"central":void 0,children:a.text},a.key))})}function qX({view:e}){const{width:t,height:a,plotLeft:o,plotW:c,plotTop:d,plotH:f}=e;return s.jsxs(s.Fragment,{children:[s.jsxs("svg",{className:"report-svg",width:t,height:a,viewBox:`0 0 ${t} ${a}`,role:"img","aria-label":r("近 24 小时缓存命中率与总 Token 趋势"),children:[e.grid.map(p=>s.jsx("line",{className:"chart-grid",x1:o,y1:p.y,x2:Pt(o+c),y2:p.y},p.key)),e.rateTicks.map(p=>s.jsx("text",{className:"chart-axis",x:p.x,y:p.y,textAnchor:p.anchor,dominantBaseline:"middle",children:p.text},p.key)),e.tokenTicks.map(p=>s.jsx("text",{className:"chart-axis",x:p.x,y:p.y,textAnchor:p.anchor,dominantBaseline:"middle",children:p.text},p.key)),e.tokenLine?s.jsx(kD,{line:e.tokenLine,cls:"tokens",radius:e.dotR}):null,s.jsx(kD,{line:e.rateLine,cls:"rate",radius:e.dotR}),s.jsx(v0,{items:e.tokenLabels,cls:"tokens"}),s.jsx(v0,{items:e.rateLabels,cls:"rate"}),e.hourTicks.map(p=>s.jsx("text",{className:"chart-axis",x:p.x,y:p.y,textAnchor:p.anchor,children:p.text},p.key))]}),e.hits?s.jsx("svg",{className:"report-svg chart-hit-layer",width:t,height:a,viewBox:`0 0 ${t} ${a}`,"aria-hidden":"true",children:e.hits.map(p=>s.jsx("rect",{className:"chart-hit",x:p.x,y:d,width:p.width,height:Pt(f),tabIndex:-1,"data-tip":p.tip,"data-tip-variant":"plain"},p.key))}):null]})}function GX({view:e}){const{width:t,height:a,plotLeft:o,plotW:c,plotTop:d,plotH:f}=e;return s.jsxs(s.Fragment,{children:[s.jsxs("svg",{className:"report-svg",width:t,height:a,viewBox:`0 0 ${t} ${a}`,role:"img","aria-label":r("按天 Token 趋势"),children:[e.grid.map(p=>s.jsx("line",{className:"chart-grid",x1:p.x1,y1:p.y,x2:p.x2,y2:p.y},p.key)),e.valueTicks.map(p=>s.jsx("text",{className:"chart-axis",x:p.x,y:p.y,textAnchor:p.anchor,dominantBaseline:"middle",children:p.text},p.key)),e.bars.map(p=>p.nativeTip?s.jsx("rect",{className:"bar",x:p.x,y:p.y,width:p.width,height:p.height,rx:p.rx,children:s.jsx("title",{children:p.tip})},p.key):s.jsx("rect",{className:"bar",x:p.x,y:p.y,width:p.width,height:p.height,rx:p.rx},p.key)),s.jsx(v0,{items:e.barLabels,cls:"tokens"}),e.dateTicks.map(p=>s.jsx("text",{className:"chart-axis",x:p.x,y:p.y,textAnchor:p.anchor,children:p.text},p.key)),e.blank?s.jsx("text",{className:"chart-empty",x:Pt(o+c/2),y:Pt(d+f/2),textAnchor:"middle",children:r("所选范围内暂无请求")}):null]}),e.hits?s.jsx("svg",{className:"report-svg chart-hit-layer",width:t,height:a,viewBox:`0 0 ${t} ${a}`,"aria-hidden":"true",children:e.hits.map(p=>s.jsx("rect",{className:"chart-hit",x:p.x,y:d,width:p.width,height:Pt(f),tabIndex:-1,"data-tip":p.tip,"data-tip-variant":"plain"},p.key))}):null]})}const KX=680;function y0(){const e=x.useRef(null),[t,a]=x.useState(0);return x.useLayoutEffect(()=>{const o=e.current;if(!o)return;let c=o.clientWidth;if(c&&a(c),typeof ResizeObserver!="function")return;const d=new ResizeObserver(()=>{const f=o.clientWidth;!f||f===c||(c=f,a(f))});return d.observe(o),()=>d.disconnect()},[]),[e,t||KX]}async function CD(){if(!g0)try{const e=await Wi().workbuddyDesktop?.getScheduledTasks(),t=(e?.tasks||[]).find(a=>a.id==="reportAutoRefresh");j0(t||null),g0=Array.isArray(e?.tasks)}catch(e){console.warn("读取报表自动刷新间隔失败,按默认 1 秒:",e instanceof Error?e.message:e),j0(null)}}function j0(e){g0=!0;const t=Number(e?.interval);!!e&&typeof e=="object"&&Number.isFinite(t)&&t>0&&(e.unit==="seconds"||e.unit==="minutes")?(ax=e.enabled!==!1,rx=e.unit==="minutes"?t*6e4:t*1e3):(ax=!0,rx=wD),Ji?.applyAutoConfig(rx,ax)}const YX={summary:null,error:null};function XX(){const[e,t]=x.useState(YX),[a,o]=x.useState(dX),[c,d]=x.useState(pX),[f,p]=x.useState(()=>({ms:rx,enabled:ax})),[,g]=x.useState(0),v=x.useRef(a),y=x.useRef(c),b=x.useCallback(G=>{t(G)},[]),j=x.useCallback(async(G={})=>{CD();const W=++b0,le=v.current,M=le===f0?y.current:void 0;try{const U=Wi().workbuddyDesktop;if(!U)throw new Error("后端桥不可用");const Z=await U.getStatsSummary(le,M);if(W!==b0)return Po;if(!Z||typeof Z!="object")throw new Error("后端未返回报表数据");return Po=Z,b({summary:Z,error:null}),Po}catch(U){if(W!==b0)return Po;const Z=U instanceof Error?U.message:"";return Po=null,G.silent||console.warn("读取报表数据失败:",Z),b({summary:null,error:Z||r("未知错误")}),null}},[b]),w=x.useCallback(G=>{G!==void 0&&(Po=G||null,G&&b({summary:G,error:null}))},[b]),S=x.useCallback(G=>{const W=Wg.includes(G)?G:d0;if(W!==v.current){v.current=W,o(W);try{localStorage.setItem(cD,W)}catch{}j()}},[j]),N=x.useCallback(G=>{const W={...y.current,...G};if(!Jg.test(W.start)||!Jg.test(W.end))return;const le=W.start<=W.end?W:G.start?{start:W.start,end:W.start}:{start:W.end,end:W.end};y.current=le,d(le),mX(le),v.current===f0&&j()},[j]);x.useEffect(()=>{if(Ji={load:j,render:w,applyAutoConfig:(G,W)=>p({ms:G,enabled:W})},lx){const G=lx;lx=null,w(G.data)}return Wi().wbApp?.currentPage==="overview"&&j({silent:!0}),()=>{Ji=null}},[j,w]),x.useEffect(()=>{if(!f.enabled||f.ms<=0)return;const G=window.setInterval(()=>{document.hidden||Wi().wbApp?.currentPage!=="overview"||x0||(x0=!0,j({silent:!0}).finally(()=>{x0=!1}))},f.ms);return()=>{window.clearInterval(G)}},[f,j]),x.useEffect(()=>{const G=()=>g(W=>W+1);return window.addEventListener("wb-units-changed",G),()=>window.removeEventListener("wb-units-changed",G)},[]);const k=y0(),E=y0(),D=y0(),{summary:C,error:A}=e,R=C&&Wg.includes(C.range??"")?C.range:a,I=C&&Array.isArray(C.heatmap)?C.heatmap:[],P=C&&Array.isArray(C.cacheTrend24h)?C.cacheTrend24h:[],O=C&&Array.isArray(C.dailyTrend)?C.dailyTrend:[],_=C&&Array.isArray(C.providers)?C.providers:null,L=C&&Array.isArray(C.accounts)?C.accounts:null,H=C&&Array.isArray(C.models)?C.models:null,B=A?ec(r("读取报表失败:{error}",{error:A}),"empty report-error"):null,z=ec(r("正在加载…")),Q=B??z,K=x.useMemo(()=>vD(H||[]),[H]),X=x.useCallback(G=>K.get(G)||NX,[K]),q=C?AX(I,k[1]):null,$=C?MX(P,E[1],X):null,Y=C?IX(O,D[1],X):null,F=p0(new Date);return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("统计概览")}),s.jsx("span",{className:"panel-sub",id:"report-range-label",children:dD[R]||""}),s.jsxs("div",{className:"head-actions",children:[s.jsx(In,{options:PX,value:a,onValueChange:S,"aria-label":r("报表时间范围")}),a===f0?s.jsxs("span",{className:"report-date-range",children:[s.jsx($e,{type:"date",className:"report-date-input w-[132px]",value:c.start,max:c.end||F,"aria-label":r("开始日期"),title:r("起始日期(含当天)"),onChange:G=>N({start:G.target.value})}),s.jsx("span",{className:"report-date-sep","aria-hidden":"true",children:"~"}),s.jsx($e,{type:"date",className:"report-date-input w-[132px]",value:c.end,min:c.start||void 0,max:F,"aria-label":r("结束日期"),title:r("结束日期(含当天)"),onChange:G=>N({end:G.target.value})})]}):null]})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"field-grid",id:"report-overview",children:C?s.jsx(FX,{summary:C,range:R}):Q})})]}),s.jsxs("div",{className:"report-rank-grid",children:[L?s.jsx(SD,{panelId:"report-accounts-panel",listId:"report-accounts",labelId:"report-accounts-label",title:r("Top 账号"),tip:_X,rows:xD(L)||[],totalText:bD(L),withBadge:!0,emptyText:r("所选范围内还没有账号用量")}):null,_?s.jsx(SD,{panelId:"report-providers-panel",listId:"report-providers",labelId:"report-providers-label",title:r("Top 提供商"),tip:LX,rows:xD(_)||[],totalText:bD(_),withBadge:!1,emptyText:r("所选范围内还没有请求记录")}):null]}),s.jsxs("div",{className:"report-donut-grid",children:[H?s.jsx(ND,{panelId:"report-models-panel",listId:"report-models-donut",title:r("模型用量"),tip:zX,ariaLabel:r("模型用量占比"),view:yD(H,r("未知模型")),emptyText:r("所选范围内还没有模型用量")}):null,_?s.jsx(ND,{panelId:"report-providers-pie-panel",listId:"report-providers-donut",title:r("提供商用"),tip:BX,ariaLabel:r("提供商用占比"),view:yD(_,r("未知")),emptyText:r("所选范围内还没有提供商用量")}):null]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("活跃热力图")}),s.jsx("span",{className:"panel-sub",children:r("近 365 天,按天 Token 用量着色(档位按本窗口峰值自动定)")})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"heat-wrap",id:"report-heatmap",ref:k[0],children:C?q?s.jsx($X,{view:q}):ec(r("暂无热力图数据")):Q})}),s.jsxs("div",{className:"panel-foot",children:[s.jsx("span",{className:"heat-scale-label",children:r("Token")}),s.jsx("span",{className:"heat-legend",id:"report-heat-legend",children:C?RX(jD(I)).map(G=>s.jsxs("span",{className:"heat-legend-item",children:[s.jsx("span",{className:`l${G.level}`}),G.text]},G.level)):null}),s.jsx("div",{className:"spacer"}),s.jsx("span",{children:r("方格为本地自然日,无请求显示为空槽")})]})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("缓存命中率")}),s.jsx(ox,{text:HX})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"field-grid",id:"report-cache-rates",children:C?OX(C.cacheRates).map(G=>s.jsxs("div",{className:"field rate",children:[s.jsx("div",{className:"label",children:G.label}),s.jsxs("div",{className:"value big",children:[G.value,s.jsx("div",{className:"sub",children:G.sub})]})]},G.key)):Q})})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("近 24 小时缓存命中率趋势")}),s.jsx("span",{className:"panel-sub",children:r("按本地整点,无请求的整点不标注")})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"chart-wrap",id:"report-cache-trend",ref:E[0],children:C?$?s.jsx(qX,{view:$}):ec(r("暂无缓存趋势数据")):Q})}),s.jsxs("div",{className:"panel-foot",children:[s.jsxs("span",{className:"chart-legend",children:[s.jsx("span",{className:"swatch rate"}),r("缓存命中率"),s.jsx("span",{className:"axis-hint",children:r("左轴")})]}),s.jsxs("span",{className:"chart-legend",children:[s.jsx("span",{className:"swatch tokens"}),r("总 Token"),s.jsx("span",{className:"axis-hint",children:r("右轴")})]}),s.jsx("div",{className:"spacer"}),s.jsx("span",{children:r("无请求的整点按 0% 计,但不写读数")})]})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("按天 Token 趋势")}),s.jsx(ox,{text:UX}),s.jsx("span",{className:"panel-sub",id:"report-trend-label",children:C?`${C.startDate||"—"} ~ ${C.endDate||"—"}`:"—"})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"chart-wrap tall",id:"report-daily-trend",ref:D[0],children:C?Y?s.jsx(GX,{view:Y}):ec(r("暂无趋势数据")):Q})})]})]})}async function QX(e={}){return Ji?Ji.load(e):Po}function ZX(e){if(e!==void 0){if(!Ji){lx={data:e??null};return}Ji.render(e)}}function WX(){return Po}window.wbReport={load:QX,render:ZX,lastSummary:WX,applyAutoRefresh:j0};const TD='.page[data-page="overview"]';let ED=!1;function AD(){if(ED)return;const e=document.querySelector(TD);e&&(ED=!0,e.replaceChildren(),vn.createRoot(e).render(s.jsx(XX,{})))}document.querySelector(TD)?AD():document.addEventListener("DOMContentLoaded",AD,{once:!0}),CD();const w0={all:{title:r("全部删除"),desc:r("删除日志记录本身。当前有筛选时只删命中的条目,按天聚合报表不受影响;无筛选时清空全部并重置报表。此方式无法恢复。")},raw:{title:r("仅清空报文原文"),desc:r("保留统计行与报表,只抹掉请求 / 响应正文。清理后详情弹窗的「预览对话」将无原文可看,统计数字分毫不动。")}},JX=["all","raw"],eQ=3e3;function Dl(){return window}let dp=!1;function fp(e,t){Dl().wbApp?.toast?.(e,t)}function tQ(e){const t=Math.max(0,Number(e)||0);if(t<1024)return`${Math.round(t)} B`;const a=t/1024;if(a<1024)return`${a.toFixed(1)} KB`;const o=a/1024;return o<1024?`${o.toFixed(1)} MB`:`${(o/1024).toFixed(2)} GB`}function S0(){const e=Dl().wbRequestsPanel?.clearParams?.();return typeof e=="string"?e:""}function RD(e){return{all:Number(e?.all)||0,raw:Number(e?.raw)||0,dbBytes:Number(e?.dbBytes)||0,vacuumRunning:e?.vacuumRunning===!0}}function N0(e){return e instanceof Error?e.message:String(e)}function OD(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}function nQ({onClose:e}){const[t,a]=x.useState("all"),[o,c]=x.useState({status:"loading"}),[d,f]=x.useState(""),[p,g]=x.useState(!1),[v,y]=x.useState(!1),b=x.useRef(!0),j=x.useRef(null),w=x.useCallback(I=>{dp=I,y(I)},[]),S=x.useCallback(()=>{j.current!==null&&(window.clearInterval(j.current),j.current=null)},[]),N=x.useCallback(I=>{c({status:"ready",all:I.all,raw:I.raw,dbBytes:I.dbBytes}),g(I.vacuumRunning)},[]),k=x.useCallback(async()=>{const I=Dl().workbuddyDesktop;if(!I)return;let P;try{P=await I.getStatsClearPreview(S0())}catch{return}if(!b.current)return;const O=RD(P);N(O),!O.vacuumRunning&&(S(),f(""),fp(r("✅ 压缩完成")),Dl().wbRequestsPanel?.load?.({silent:!0}))},[N,S]),E=x.useCallback(()=>{j.current===null&&(g(!0),j.current=window.setInterval(()=>{k()},eQ))},[k]);async function D(){c({status:"loading"});try{const I=Dl().workbuddyDesktop;if(!I)throw new Error(r("后端桥不可用"));const P=await I.getStatsClearPreview(S0());if(!b.current)return;const O=RD(P);N(O),O.vacuumRunning&&E()}catch(I){if(!b.current)return;c({status:"failed"}),f(r("预览读取失败:{error}",{error:N0(I)}))}}x.useEffect(()=>(b.current=!0,D(),()=>{b.current=!1,S(),dp=!1}),[]);async function C(){const I=Dl().workbuddyDesktop;if(I){g(!0);try{await I.compactStatsDb(),f(r("压缩已在后台开始,完成后会自动提示")),E()}catch(P){const O=N0(P);if(/409|正在进行/.test(O)){fp(r("压缩已在进行中")),f(r("压缩已在进行中,接上它的进度等待完成")),E();return}g(!1),f(r("压缩失败:{message}",{message:O})),fp(r("压缩失败:{message}",{message:O}),"err")}}}async function A(){if(dp)return;const I=Dl().workbuddyDesktop,P=Dl().wbConfirm?.ask;if(!I||!P)return;const O=w0[t].title,_=S0(),L=_.length>0,H=o.status==="ready"?t==="raw"?o.raw:o.all:0;if(await P({title:r("清理请求日志"),html:L?r("确定按当前筛选执行「{label}」?将处理 {count} 条,此操作无法恢复。",{label:OD(O),count:H}):r("确定对全部请求日志执行「{label}」?将处理 {count} 条,此操作无法恢复。",{label:OD(O),count:H}),okText:r(t==="raw"?"抹掉原文":"删除"),okClass:"danger"})){w(!0);try{const z=L?`mode=${t}&${_}`:`mode=${t}&all=1`,Q=await I.clearStatsRequests(z),K=Number(Q?.deleted)||0;fp(t==="raw"?r("已抹掉 {count} 条报文原文",{count:K}):r("已删除 {count} 条",{count:K})),w(!1),e(),Dl().wbRequestsPanel?.notifyCleared?.()}catch(z){const Q=N0(z);f(r("清理失败:{message}",{message:Q})),fp(r("清理失败:{message}",{message:Q}),"err"),w(!1)}}}const R=o.status==="ready"?r("将删除 {count} 条日志 · 其中 {raw} 条仍带报文原文 · 数据库占用 {db}",{count:o.all,raw:o.raw,db:tQ(o.dbBytes)}):o.status==="failed"?r("预览读取失败"):r("正在统计…");return s.jsx(Qt,{open:!0,onOpenChange:(I,P)=>{if(!I){if(dp){P.cancel();return}e()}},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("清理请求日志")})}),s.jsxs(Bt,{children:[s.jsx(kh,{"aria-label":r("清理方式"),value:t,onValueChange:I=>a(I==="raw"?"raw":"all"),children:JX.map(I=>{const P=t===I;return s.jsxs("label",{"data-checked":P?"":void 0,className:"group/card grid cursor-pointer grid-cols-[auto_minmax(0,1fr)] items-center gap-x-2.5 gap-y-0.5 rounded-md border border-border px-3 py-2.5 transition-colors duration-150 ease-out hover:border-border-strong data-checked:border-primary data-checked:bg-primary-soft",children:[s.jsx(bo,{value:I,className:"row-span-2 self-center"}),s.jsx("span",{className:"text-[13px] font-semibold text-foreground group-data-checked/card:text-primary-fg",children:w0[I].title}),s.jsx("span",{className:"text-[11.5px] leading-[1.55] text-subtle",children:w0[I].desc})]},I)})}),s.jsx("p",{className:"text-[11.5px] text-muted-foreground",children:R})]}),s.jsxs(nn,{children:[s.jsx("span",{className:"min-w-0 text-[11.5px] text-muted-foreground",children:d}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",size:"sm",onClick:()=>{C()},disabled:p,title:r(p?"压缩正在后台执行,完成后自动恢复":"回收已删除数据占用的磁盘空间(checkpoint + VACUUM,后台执行)"),children:r(p?"压缩中…":"压缩数据库")}),s.jsx(se,{variant:"outline",onClick:e,disabled:v,children:r("取消")}),s.jsx(se,{variant:"destructive",onClick:()=>{A()},disabled:v,children:r(v?"清理中…":"执行清理")})]})]})})}let pp=null,Uu=null;function MD(){pp&&(pp.unmount(),pp=null),Uu&&(Uu.remove(),Uu=null)}function sQ(){dp||MD()}function rQ(){MD(),Uu=document.createElement("div"),document.body.append(Uu),pp=vn.createRoot(Uu),pp.render(s.jsx(nQ,{onClose:sQ}))}window.wbRequestClearModal={open:rQ};const DD=[{value:"detail",label:r("请求详情")},{value:"preview",label:r("预览对话")},{value:"raw",label:r("原始报文")}],aQ="detail",ID="border-b border-hairline px-2.5 py-[7px] align-top",_o="border border-hairline px-2 py-1 align-top",lQ="border border-hairline bg-surface-2 px-2 py-1 text-[11.5px] tracking-normal",ix="hover:[&>td]:bg-transparent";function Vu(){return window}function k0(){const e=Vu().workbuddyDesktop;if(!e)throw new Error(r("后端桥不可用"));return e}let C0=0;function oQ(e){if(!e)return"—";const t=new Date(e),a=o=>String(o).padStart(2,"0");return`${t.getFullYear()}-${a(t.getMonth()+1)}-${a(t.getDate())} ${a(t.getHours())}:${a(t.getMinutes())}:${a(t.getSeconds())}`}function PD(e){const t=Math.round(Number(e)||0);if(t<1e3)return`${t}ms`;const a=Math.floor(t/1e3);if(a>=60)return r("{m}分{s}秒",{m:Math.floor(a/60),s:a%60});const o=t%1e3;return o>0?r("{s}秒{ms}ms",{s:a,ms:o}):r("{n}秒",{n:a})}function iQ(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"-":PD(t)}const cQ=r("生成速度:输出 token ÷ 流式段用时(总用时 − 首响);流式段不足总用时一半时按总用时计");function uQ(e){const t=Number(e.completionTokens)||0,a=Number(e.durationMs)||0;if(t<=0||a<=0)return"";const o=Number(e.firstResponseMs),c=Number.isFinite(o)&&o>0&&o=500&&c*2>=a,f=t/((d?c:a)/1e3);return`${f>=100?Math.round(f):f.toFixed(1)} tok/s`}function cx(e){return Vu().wbUnits?.formatTokens?.(e)??(Number(e)||0).toLocaleString("zh-CN")}function dQ(e){const t=Math.max(0,Date.now()-(Number(e)||0));return r("{n}秒",{n:Math.max(1,Math.floor(t/1e3))})}function fQ(e){const t=Number(e.status)||0;return t>=200&&t<300&&!e.error}function ux(e){return(Number(e?.status)||0)===0&&!e?.error}function _D(e){const t=String(e.provider??"").trim();return String(e.providerLabel??"").trim()||(t?Vu().wbProviders?.labelOf?.(t)||t:"")}function mp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function T0(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return""}}function E0(e){return e instanceof Error?e.message:String(e)}const LD=[{label:r("请求头"),pick:e=>T0(e.requestHeaders)},{label:r("请求体"),pick:e=>T0(e.requestBody)},{label:r("响应头"),pick:e=>T0(e.responseHeaders)},{label:r("响应体"),pick:e=>e.responseBody?String(e.responseBody):""}];function dx({text:e,loading:t=!1}){return s.jsxs("div",{className:"flex items-center justify-center gap-2 py-6 text-center text-[12.5px] text-muted-foreground",children:[t?s.jsx(Wd,{className:"size-3.5"}):null,e]})}function ua({label:e,children:t}){return s.jsxs(kl,{className:ix,children:[s.jsx("th",{scope:"row",className:`w-[76px] whitespace-nowrap text-left text-[12.5px] font-semibold text-muted-foreground ${ID}`,children:e}),s.jsx(Nn,{className:ID,children:t})]})}function pQ({row:e}){if(ux(e)){const c=Vu().wbRequestPhase;if(!c?.badgeHtml)return s.jsxs(ze,{variant:"info",shape:"tag",title:r("请求正在转发中,用时列显示的是已用时"),children:[s.jsx(ay,{className:"req-live-dot"}),r("进行中")]});const d=c.elapsedLineHtml?.(e)??"";return s.jsxs("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:[s.jsx("span",{dangerouslySetInnerHTML:{__html:c.badgeHtml(e)}}),d?s.jsx("span",{className:"text-[11.5px] text-muted-foreground",dangerouslySetInnerHTML:{__html:d}}):null]})}const t=Number(e.status)||0,a=fQ(e),o=!a&&t>=200&&t<300?r("HTTP {status},但响应体阶段出错",{status:t}):"";return s.jsx(ze,{variant:a?"success":"destructive",shape:"tag",title:o||void 0,children:t||r("失败")})}function mQ({row:e}){const t=String(e.clientModel??"").trim(),a=String(e.upstreamModel??"").trim(),o=String(e.model??"").trim(),c=String(e.clientReasoning??"").trim(),d=String(e.upstreamReasoning??"").trim(),f=(v,y)=>y?`${v}(${y})`:v;if(!t||!a||a.toLowerCase()===t.toLowerCase())return s.jsx(s.Fragment,{children:f(o,d||c)||"—"});const p=f(a,d),g=f(t,c);return s.jsxs("span",{className:"flex flex-col gap-0.5",children:[s.jsxs("span",{title:r("转发到上游的模型:{model}",{model:p}),children:["⬆️ ",p]}),s.jsxs("span",{className:"text-muted-foreground",title:r("下游请求的模型:{model}",{model:g}),children:["⬇️ ",g]})]})}function hQ(e){const t=Number(e?.status),a=e?.status!==null&&e?.status!==void 0&&Number.isFinite(t),o=e?.error?String(e.error):"";if(o){const c=a?r("失败({status}):{error}",{status:String(t),error:o}):r("失败:{error}",{error:o});return s.jsx("span",{className:"break-words text-destructive",children:c})}return a?s.jsx("span",{className:"text-success",children:r("成功({status})",{status:String(t)})}):s.jsx("span",{className:"text-muted-foreground",children:r("无结果记录")})}function gQ({row:e}){const t=Array.isArray(e.attemptDetails)?e.attemptDetails:[];if(!t.length)return s.jsx(s.Fragment,{children:"-"});const a=Number(e.attempts)||1;return s.jsxs(Vy,{className:"text-[11.5px]",children:[s.jsx(pE,{children:s.jsx(kl,{className:ix,children:[r("轮次"),r("提供商"),r("账号"),r("结果"),r("体积"),r("内部重试"),r("提示")].map(o=>s.jsx(mE,{className:lQ,children:o},o))})}),s.jsxs(Fy,{children:[t.map((o,c)=>{const d=Array.isArray(o?.retries)?o.retries:[],f=d.map(b=>{const j=Number(b?.delayMs),w=Number.isFinite(j)&&j>0?j>=1e3?r(",{n}秒后重试",{n:Math.round(j/1e3)}):r(",{n}毫秒后重试",{n:Math.round(j)}):"";return`${String(b?.reason||r("未知原因"))}${w}`}).join(` -`),p=String(o?.notice??"").trim(),g=Number(o?.bodyBytes),v=Number.isFinite(g)&&g>0?g>=1024*1024?`${(g/1024/1024).toFixed(1)} MB`:g>=1024?`${Math.round(g/1024)} KB`:`${g} B`:"—",y=Number.isFinite(g)&&g>0?r("实际发给上游 {bytes} 字节",{bytes:g.toLocaleString()}):void 0;return s.jsxs(kl,{className:ix,children:[s.jsx(Nn,{className:_o,children:c+1}),s.jsx(Nn,{className:_o,children:_D(o)||(o?.provider?String(o.provider):r("未知"))}),s.jsx(Nn,{className:_o,children:o?.account?String(o.account):"—"}),s.jsx(Nn,{className:_o,children:hQ(o)}),s.jsx(Nn,{className:`${_o} whitespace-nowrap`,title:y,children:v}),s.jsx(Nn,{className:`${_o} whitespace-nowrap`,title:f||void 0,children:d.length?r("↻ {n} 次",{n:d.length}):"-"}),s.jsx(Nn,{className:_o,children:p||"—"})]},c)}),t.lengths.jsxs("li",{className:"py-0.5",children:[s.jsxs("b",{children:[y+1,". ",String(v.name||v.id||"—")]}),s.jsxs("span",{className:"text-muted-foreground",children:[" ",String(v.reason||"")]})]},String(v.id??y)))}):null,p.length?s.jsxs("div",{className:"mt-1 text-muted-foreground",children:[r("被跳过:"),p.map(v=>String(v.name||v.id||"")).join("、")]}):null,g?s.jsx("div",{className:"mt-1",children:r("最终承载:{picked}",{picked:g})}):null]})}function bQ({row:e}){if(!e)return s.jsx(dx,{text:r("列表数据已刷新,请重试(关闭后重新打开这条详情)")});const t=String(e.accountName??"").trim(),a=uQ(e);return s.jsx(Vy,{className:"text-[12.5px] text-subtle [&_tr:last-child>td]:border-b-0 [&_tr:last-child>th]:border-b-0",children:s.jsxs(Fy,{children:[s.jsx(ua,{label:r("时间"),children:oQ(e.ts)}),s.jsx(ua,{label:r("状态"),children:s.jsx(pQ,{row:e})}),s.jsx(ua,{label:r("耗时"),children:ux(e)?s.jsxs(s.Fragment,{children:[dQ(e.ts),s.jsx("span",{className:"text-[11.5px] text-muted-foreground",children:r("(请求仍在转发中)")})]}):r("{duration} / 首帧 {first}",{duration:PD(e.durationMs),first:iQ(e.firstResponseMs)})}),s.jsx(ua,{label:r("重试次数"),children:String(Number(e.attempts)||1)}),s.jsx(ua,{label:r("模型"),children:s.jsx(mQ,{row:e})}),s.jsxs(ua,{label:r("提供商"),children:[_D(e)||"—",t?s.jsx("span",{className:"text-[11.5px] text-muted-foreground",children:r("(账号:{account})",{account:t})}):null]}),s.jsxs(ua,{label:r("令牌"),children:[r("输入 {input} · 输出 {output} · 总计 {total} · 缓存读 {cache}",{input:cx(e.promptTokens),output:cx(e.completionTokens),total:cx(e.totalTokens),cache:cx(e.cacheReadTokens)}),a?s.jsxs("span",{title:cQ,children:[" · ",a]}):null]}),e.isTest?s.jsx(ua,{label:r("来源"),children:s.jsx(ze,{variant:"brand",shape:"tag",title:r("模型管理页操作列那颗「测试」发起的请求:与真实请求同一条转发链路,但不计入报表统计"),children:r("模型测试")})}):null,s.jsx(ua,{label:r("错误"),children:e.error?s.jsx("span",{className:"text-destructive",children:String(e.error)}):"—"}),s.jsx(ua,{label:r("尝试明细"),children:s.jsx(gQ,{row:e})}),e.route?s.jsx(ua,{label:r("路由回放"),children:s.jsx(xQ,{row:e})}):null,s.jsx(ua,{label:r("敏感词"),children:Array.isArray(e.sensitiveHits)&&e.sensitiveHits.length?s.jsx("span",{className:"inline-flex flex-wrap gap-1.5",children:e.sensitiveHits.map((o,c)=>s.jsxs(ze,{variant:"sensitive",shape:"tag",children:[String(o?.word??"")," × ",String(Number(o?.count)||0)]},c))}):"—"})]})})}function vQ({state:e}){if(!e)return s.jsx(dx,{text:r("正在读取…"),loading:!0});const t=e==="gone"?null:e.body,a=t&&Vu().wbConversationPreview?.render?.(t.requestBody,t.responseBody)||"";return a?s.jsxs("div",{children:[e!=="gone"&&e.truncated?s.jsx("div",{className:"mb-2 text-[11.5px] text-warning",children:r("正文超过单条上限,可能已被截断")}):null,s.jsx("div",{dangerouslySetInnerHTML:{__html:a}})]}):s.jsx(dx,{text:r("无报文原文(未开启「调试模式」,或已被清理)")})}function yQ({data:e}){const t=e.status===null||e.status===void 0?"-":String(e.status),a=[e.url?`URL: ${e.url}`:"",e.provider?r("提供商: {provider}",{provider:String(e.provider)}):"",r("上游状态码: {status}",{status:t})].filter(Boolean);return s.jsxs("div",{className:"flex flex-col gap-4",children:[a.length?s.jsx("div",{className:"border-b border-hairline pb-2.5 text-xs leading-[1.7] break-all text-subtle",children:a.map((o,c)=>s.jsx("div",{children:o},c))}):null,LD.map(o=>{const c=o.pick(e)||"";return s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx("h3",{className:"text-[11.5px] font-semibold tracking-[.02em] text-muted-foreground",children:o.label}),c?s.jsx("pre",{className:"max-h-80 overflow-auto rounded-md border border-border bg-surface-2 p-[10px_12px] font-mono text-[11.5px] leading-[1.6] break-words whitespace-pre-wrap text-subtle",children:c}):s.jsx(dx,{text:r("这条请求没有保存这一段报文")})]},o.label)})]})}function jQ({id:e,row:t,token:a,onClose:o}){const[c,d]=x.useState(aQ),[f,p]=x.useState(null),[g,v]=x.useState(null),[y,b]=x.useState("—"),[j,w]=x.useState("idle"),S=x.useRef(!0),N=x.useRef(null),k=x.useRef({detail:0,preview:0,raw:0}),E=x.useCallback(()=>!S.current||a!==C0,[a]);async function D(){try{const O=await k0().getStatsRequestRaw(e);if(E())return;const _=mp(O)?O:null,L=String(_?.requestBody??"").trim()!==""||String(_?.responseBody??"").trim()!=="";p(_&&L?{body:_,truncated:!!_.truncated}:"gone")}catch(O){if(E())return;p("gone"),console.warn("读取原始正文失败(预览对话显示空态):",E0(O))}}async function C(){try{const O=await k0().getDebugTraffic(e);if(E())return;const _=mp(O)?O:{};if(!LD.some(L=>(L.pick(_)||"").trim())){v("gone");return}v({data:_}),b(_.truncated?r("报文超过单条上限,请求体 / 响应体已按上限截断"):r("内容按原样保存,请求头中的凭据字段已替换为 [redacted]"))}catch(O){if(E())return;v("gone"),b(r("在设置 → 通用里开启「调试模式」后,新发生的请求才会保存报文")),console.warn("读取调试报文失败(原始报文标签隐藏):",E0(O))}}x.useEffect(()=>(S.current=!0,D(),C(),()=>{S.current=!1}),[]),x.useLayoutEffect(()=>{const O=N.current;O&&(O.scrollTop=k.current[c])},[c]);function A(O){if(O==="raw"&&!mp(g)||O===c)return;const _=N.current;_&&(k.current[c]=_.scrollTop),d(O)}async function R(){if(!e||!ux(t))return;const O=Vu().wbConfirm?.ask;if(!(!O||!await O({title:r("终止请求"),html:r("确定终止这条正在转发的请求?
上游连接会立即断开,明细将记为「请求已被手动终止」。"),okText:r("终止"),okClass:"danger"}))){w("pending");try{if(await k0().terminateStatsRequest(e),!S.current)return;w("accepted"),b(r("已受理终止:上游连接已断开,列表稍后刷新为「请求已被手动终止」"))}catch(L){if(!S.current)return;w("idle"),b(r("终止失败:{error}",{error:E0(L)}))}}}const I=mp(g),P=x.useMemo(()=>I?DD:DD.filter(O=>O.value!=="raw"),[I]);return s.jsx(Qt,{open:!0,onOpenChange:O=>{O||o()},children:s.jsxs(Zt,{className:"w-[min(920px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("请求详情")})}),s.jsxs(Bt,{ref:N,className:"gap-3",children:[s.jsx(In,{options:P,value:c,onValueChange:A,"aria-label":r("详情内容"),className:"self-start"}),s.jsx("section",{hidden:c!=="detail",children:s.jsx(bQ,{row:t})}),s.jsx("section",{hidden:c!=="preview",children:s.jsx(vQ,{state:f})}),I?s.jsx("section",{hidden:c!=="raw",children:s.jsx(yQ,{data:g.data})}):null]}),s.jsxs(nn,{children:[s.jsx("span",{className:"min-w-0 text-[11.5px] text-muted-foreground",children:y}),s.jsx("div",{className:"mr-auto"}),ux(t)?s.jsx(se,{variant:"destructive",disabled:j!=="idle",onClick:()=>{R()},title:r("断开上游连接,明细记为「请求已被手动终止」"),children:r("终止请求")}):null,s.jsx(se,{variant:"outline",onClick:o,children:r("关闭")})]})]})})}let hp=null,Fu=null;function zD(){hp&&(hp.unmount(),hp=null),Fu&&(Fu.remove(),Fu=null)}function BD(){C0+=1,zD()}function wQ(e,t){const a=String(e??"").trim();if(!a)return;zD();const o=++C0;Fu=document.createElement("div"),document.body.append(Fu),hp=vn.createRoot(Fu),hp.render(s.jsx(jQ,{id:a,row:mp(t)?t:null,token:o,onClose:BD}))}window.wbRequestDetail={open:wQ,close:BD};const SQ=150,NQ=80,tc=8,fx=8,kQ=520,CQ=220,TQ=1.1,EQ=900,A0=12,R0="req-hover-panel",AQ=["fixed z-[35] pointer-events-none","max-h-[min(360px,60vh)] overflow-x-hidden overflow-y-auto","rounded-md p-[10px_12px] text-[12px] leading-[1.6] break-normal","bg-surface-2 text-foreground shadow-3","border-0 dark:border dark:border-border-strong dark:bg-surface-3"].join(" "),gp="rh-row rh-dim min-w-0 break-words text-muted-foreground",RQ="rh-row min-w-0 break-words";function OQ(){return window}function O0(e){return typeof e=="object"&&e!==null?e:null}const HD=e=>Array.isArray(e?.attemptDetails)?e.attemptDetails:[],UD=e=>Array.isArray(e?.retries)?e.retries:[],MQ=e=>Array.isArray(e?.sensitiveHits)?e.sensitiveHits:[];function M0(e){const t=String(e??"").trim();return t?OQ().wbProviders?.labelOf?.(t)||t:""}function DQ(e){const t=O0(e);return(Number(t?.attempts)||1)>1?!0:HD(t).some(a=>UD(a).length>0||!!a?.notice)}function VD(e){return e.dataset.reqHover==="sensitive"?"sensitive":"chain"}function IQ({details:e}){if(e.length<2)return null;const t=e.map(a=>M0(a.provider)||r("未知"));return s.jsxs("div",{className:"rh-chain mb-1.5 border-b border-border pb-1.5 break-words",children:[s.jsx("span",{className:"rh-chain-k font-semibold text-muted-foreground",children:r("切换路径:")}),s.jsx("span",{className:"rh-chain-v font-semibold text-foreground",children:t.join(" → ")})]})}function PQ({item:e}){const t=UD(e);return t.length?s.jsxs("div",{className:"rh-retry mt-0.5 mb-1 ml-2.5 border-l-2 border-border-strong pl-2",children:[s.jsx("div",{className:"rh-retry-head text-[11.5px] font-semibold text-warning",children:r("↻ 重试 {n} 次",{n:t.length})}),t.map((a,o)=>{const c=String(a?.reason??"").trim(),d=Number(a?.status),f=a?.status!==null&&a?.status!==void 0&&Number.isFinite(d),p=Number(a?.delayMs),g=Number.isFinite(p)&&p>0?p>=1e3?r(",{n}秒后重试",{n:Math.round(p/1e3)}):r(",{n}毫秒后重试",{n:Math.round(p)}):"";return s.jsxs("div",{className:"rh-retry-row min-w-0 break-words",children:[s.jsx("span",{className:"rh-retry-why mr-1 text-subtle [overflow-wrap:anywhere]",children:c||r("未知原因")}),f?s.jsx("span",{className:"rh-retry-status mr-1 text-muted-foreground tabular-nums whitespace-nowrap",children:`HTTP ${String(d)}`}):null,g?s.jsx("span",{className:"rh-dim text-muted-foreground",children:g}):null]},o)})]}):null}function _Q({item:e,index:t,inFlight:a}){const o=M0(e.provider),c=String(e.account??"").trim(),d=Number(e.status),f=e.status!==null&&e.status!==void 0&&Number.isFinite(d),p=e.error?String(e.error):"",g=String(e.notice??"").trim();return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:RQ,children:[s.jsx("span",{className:"rh-no mr-1 text-muted-foreground",children:r("尝试 {n} ·",{n:t+1})}),s.jsx("span",{className:"rh-who mr-1 font-semibold text-foreground",children:o||r("未知")}),c?s.jsx("span",{className:"rh-account mr-1 text-muted-foreground [overflow-wrap:anywhere]",children:c}):null,s.jsx("span",{className:"rh-arrow mr-1 text-muted-foreground",children:"→"}),p?s.jsx("span",{className:"rh-bad font-medium text-destructive [overflow-wrap:anywhere]",children:f?r("失败({status}):{error}",{status:String(d),error:p}):r("失败:{error}",{error:p})}):f?s.jsx("span",{className:"rh-ok font-medium text-success",children:r("成功({status})",{status:String(d)})}):a?s.jsx("span",{className:"rh-dim text-muted-foreground",children:r("进行中…")}):s.jsx("span",{className:"rh-dim text-muted-foreground",children:r("无结果记录")})]}),g?s.jsx("div",{className:"rh-notice mt-0.5 mb-1 ml-2.5 border-l-2 border-border-strong pl-2 text-warning [overflow-wrap:anywhere]",children:`⚠️ ${g}`}):null,s.jsx(PQ,{item:e})]})}function LQ({entry:e}){const t=Number(e.attempts)||1,a=HD(e);if(!a.length){const c=M0(e.provider),d=c?r("共 {n} 次尝试,最终由 {provider} 承载",{n:t,provider:c}):r("共 {n} 次尝试",{n:t});return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:gp,children:d}),s.jsx("div",{className:gp,children:r("这条记录的尝试明细未采集(该字段上线前的旧数据,或请求在转发前就失败)")})]})}const o=(Number(e.status)||0)===0&&!e.error;return s.jsxs(s.Fragment,{children:[s.jsx(IQ,{details:a}),a.map((c,d)=>s.jsx(_Q,{item:c,index:d,inFlight:o&&d===a.length-1},d)),a.lengths.jsxs("div",{className:"rh-row rh-hit flex items-baseline justify-between gap-2.5",children:[s.jsx("span",{className:"rh-hit-w break-words text-foreground",children:String(a?.word??"")}),s.jsx("span",{className:"rh-hit-c text-muted-foreground tabular-nums whitespace-nowrap",children:`× ${String(Number(a?.count)||0)}`})]},o)),t.length>A0?s.jsx("div",{className:gp,children:r("另有 {n} 个词命中",{n:t.length-A0})}):null]}):s.jsx("div",{className:gp,children:r("这条记录命中了敏感词,但没有留下命中明细")})}function BQ({kind:e,entry:t,panelRef:a}){return s.jsx("div",{ref:a,id:R0,role:"tooltip","data-kind":e,className:AQ,children:e==="sensitive"?s.jsx(zQ,{entry:t}):s.jsx(LQ,{entry:t})})}let Tn=null,Lo=0,xp=0,bp=null,px=null,D0=null,I0=null,nc=null,sc=null,vp=null,FD="chain";function P0(){window.clearTimeout(Lo),window.clearTimeout(xp),Lo=0,xp=0,bp=null}function HQ(){const e=vp?.current,t=Tn;if(!e||!t)return;const a=t.getBoundingClientRect(),o=window.innerWidth-tc*2;e.style.maxWidth="none",e.style.width="max-content";const c=e.offsetWidth,d=FD==="sensitive",p=Math.max(d?CQ:kQ,c)*(d?TQ:1),g=Math.min(p,o,EQ);e.style.maxWidth=`${g}px`,e.style.width=d?`${g}px`:"auto";const v=e.offsetWidth,y=e.offsetHeight,b=window.innerHeight-a.bottom-fx-tc,j=a.top-fx-tc,w=bb,S=a.left+a.width/2,N=Math.max(tc,Math.min(S-v/2,window.innerWidth-tc-v)),k=w?a.top-fx-y:a.bottom+fx;e.style.left=`${Math.round(N)}px`,e.style.top=`${Math.round(Math.max(tc,Math.min(k,window.innerHeight-tc-y)))}px`}function $D(e){if(!Tn)return;const t=e.target;t instanceof Node&&(t===Tn||Tn.contains(t)||Ra())}function qD(){Ra()}function GD(){Ra()}let mx=!1;function UQ(){mx||(mx=!0,document.addEventListener("click",$D,!0),window.addEventListener("scroll",qD,!0),window.addEventListener("resize",GD))}function VQ(){mx&&(mx=!1,document.removeEventListener("click",$D,!0),window.removeEventListener("scroll",qD,!0),window.removeEventListener("resize",GD))}function FQ(){VQ(),sc&&(sc.unmount(),sc=null),nc&&(nc.remove(),nc=null),vp=null}function KD(e,t){FD=e,(!nc||!sc||!vp)&&(nc=document.createElement("div"),document.body.append(nc),vp=x.createRef(),sc=vn.createRoot(nc));const a=sc,o=vp;ks.flushSync(()=>{a.render(s.jsx(BQ,{kind:e,entry:t,panelRef:o}))}),UQ(),HQ()}function YD(e){if(!e.isConnected)return;const t=O0(D0?.(e));t&&(P0(),Tn&&Tn!==e&&Ra(),Tn=e,KD(VD(e),t),e.classList.add("active"),e.setAttribute("aria-describedby",R0))}function Ra(){P0(),Tn&&(Tn.classList.remove("active"),Tn.removeAttribute("aria-describedby"),Tn=null),FQ()}function $Q(){if(!Tn)return;const e=String(Tn.dataset.reqHover||""),t=String(Tn.dataset.reqId||"");I0=!!(e&&t)&&Tn.matches(":hover")&&!xp?{action:"move",kind:e,key:t}:{action:"close"}}function qQ(){const e=I0;if(I0=null,!e||!Tn)return;if(e.action==="close"){Ra();return}const t=px?GQ(px,e.kind,e.key):null,a=t?O0(D0?.(t)):null;if(!t||!a){Ra();return}t!==Tn&&(Tn.classList.remove("active"),Tn.removeAttribute("aria-describedby"),Tn=t,KD(VD(t),a),t.classList.add("active"),t.setAttribute("aria-describedby",R0))}function GQ(e,t,a){for(const o of e.querySelectorAll("[data-req-hover]"))if(String(o.dataset.reqHover||"")===t&&String(o.dataset.reqId||"")===a)return o;return null}function hx(e){const t=e.target;return t instanceof Element?t.closest("[data-req-hover]"):null}function KQ(e){const t=hx(e);if(!t||!px?.contains(t)||(P0(),Tn===t&&sc))return;const a=Tn?0:SQ;Tn&&Ra(),bp=t,Lo=window.setTimeout(()=>{Lo=0,bp=null,YD(t)},a)}function YQ(e){const t=hx(e);if(t){if(bp===t){window.clearTimeout(Lo),Lo=0,bp=null;return}Tn===t&&(window.clearTimeout(Lo),Lo=0,xp=window.setTimeout(()=>{xp=0,Tn===t&&Ra()},NQ))}}function XQ(e){const t=hx(e);t&&YD(t)}function QQ(e){const t=hx(e);t&&Tn===t&&Ra()}function ZQ(e){e.key!=="Escape"||!Tn||Ra()}function WQ(e){const t=e?.host;t&&(px=t,D0=e?.entryOf??null,t.addEventListener("pointerover",KQ),t.addEventListener("pointerout",YQ),t.addEventListener("focusin",XQ),t.addEventListener("focusout",QQ),t.addEventListener("keydown",ZQ))}window.wbRequestHover={bind:WQ,close:Ra,hasProcessFacts:DQ,beforeListRedraw:$Q,afterListRedraw:qQ};function Cs(){return window}function _0(e){return e instanceof Error?e.message:String(e)}function gx(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}const xx={connecting:{label:r("连接中"),cls:"phase-connecting"},waiting:{label:r("等待响应"),cls:"phase-waiting"},streaming:{label:r("响应中"),cls:"phase-streaming"},retrying:{label:r("重试中"),cls:"phase-retrying"},queued:{label:r("排队中"),cls:"phase-queued"}},XD=r("进行中"),JQ="running",QD={connecting:r("请求已受理,正在选路、取凭证、建立上游连接"),waiting:r("上游请求已发出,正在等第一个字节到达(模型的思考时间也在这段)"),streaming:r("首帧已到,上游内容正在下发"),retrying:r("本轮尝试失败,正在退避等待或切换到下一个账号"),queued:r("上游模型繁忙,请求已排进上游队列;网关正按上游建议的时长等待后重发(不是登录态或额度问题)"),"":r("请求正在转发中,用时列显示的是已用时")};function L0(e){const t=String(e?.phase??"").trim().toLowerCase();return Object.prototype.hasOwnProperty.call(xx,t)?t:""}function ZD(e){const t=L0(e);return t?xx[t].label:XD}function WD(e){if(e==null||e==="")return"";const t=Number(e);if(!Number.isFinite(t)||t<0)return"";const a=Math.max(1,Math.floor(t/1e3));return a<60?r("{n}秒",{n:a}):r("{m}分{s}秒",{m:Math.floor(a/60),s:a%60})}function eZ(e){const t=e?.phaseElapsedMs;if(t!=null&&t!==""){const c=Number(t);if(Number.isFinite(c)&&c>=0)return c}const a=Number(e?.phaseStartedAt);if(!Number.isFinite(a)||a<=0)return null;const o=Date.now()-a;return Number.isFinite(o)?Math.max(0,o):null}function tZ(e){const t=L0(e),a=t?xx[t].label:XD,o=t?xx[t].cls:JQ,c=QD[t]||QD[""];return`${gx(a)}`}function nZ(e){const t=WD(eZ(e));if(!t)return"";const a=ZD(e),o=r("进入「{phase}」阶段已持续 {time}",{phase:a,time:t});return`${gx(t)}`}const z0=[{key:"time",label:r("时间"),sel:".req-time",track:"92px"},{key:"target",label:r("提供商 / 账号"),sel:".req-target",track:"minmax(0, 1.1fr)"},{key:"retry",label:r("重试"),sel:".req-retry",track:"52px"},{key:"status",label:r("状态"),sel:".req-status",track:"96px"},{key:"model",label:r("模型"),sel:".req-model",track:"minmax(0, 1.3fr)"},{key:"client",label:r("客户端"),sel:".req-client",track:"110px"},{key:"dur",label:r("用时"),sel:".req-dur",track:"96px",align:"right"},{key:"usage",label:r("用量"),sel:".req-usage",track:"minmax(0, 1.6fr)"},{key:"error",label:r("错误"),sel:".req-error-cell",track:"minmax(0, 1.2fr)"},{key:"detail",label:r("详情"),sel:".req-detail",track:"60px",align:"right"}],JD=1e3,sZ=tg;function eI(e){return typeof e=="number"&&e>0?e:du}const tI="workbuddy-desktop-logs-requests-range",nI="workbuddy-desktop-requests-filters",rZ=3e4,B0=["today","7","30","month","all"],H0="all",aZ={today:r("今天"),7:r("近 7 天"),30:r("近 30 天"),month:r("本月"),all:r("全部")},lZ={today:r("今天"),7:r("7 天"),30:r("30 天"),month:r("本月"),all:r("全部")},oZ=B0.map(e=>({value:e,label:lZ[e]})),sI=[{value:"",label:r("全部状态")},{value:"ok",label:r("成功")},{value:"error",label:r("失败")}],iZ=r("全部状态"),rI=r("全部提供商"),aI=r("全部模型"),bx={status:"",provider:"",model:""};function vx(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function cZ(e){const t=new Date;switch(e){case"today":return vx(t);case"7":return vx(new Date(t.getFullYear(),t.getMonth(),t.getDate()-6));case"30":return vx(new Date(t.getFullYear(),t.getMonth(),t.getDate()-29));case"month":return vx(new Date(t.getFullYear(),t.getMonth(),1));default:return null}}const en={filters:{...bx},range:uZ(),runningOnly:!1,offset:0,size:eI(sg("requests",tg))};let yx={...bx},U0=!1,lI=!1,V0=[],jx=JD,wx=!0,F0=!1,$0=!1,oI=0,q0=0,G0=null,iI=!1,$u=null;function uZ(){try{const e=localStorage.getItem(tI);return e!==null&&B0.includes(e)?e:H0}catch{return H0}}function dZ(e){try{localStorage.setItem(tI,e)}catch{}}function cI(){const e=Cs().wbFilterMemory;return e?(U0=!0,yx=e.load(nI,{...bx}),en.filters={...yx},{...yx}):{...bx}}function fZ(e){yx={...e},Cs().wbFilterMemory?.save(nI,{status:e.status||"",provider:e.provider||"",model:e.model||""})}function uI(){const e=new URLSearchParams,t=cZ(en.range);t!==null&&e.set("start",String(t));const a=en.runningOnly?"running":en.filters.status;return a&&e.set("status",a),en.filters.provider&&e.set("provider",en.filters.provider),en.filters.model&&e.set("model",en.filters.model),e}function pZ(){const e=uI();return e.set("offset",String(en.offset)),e.set("limit",String(en.size)),e.toString()}function K0(e){const t=Math.round(Number(e)||0);if(t<1e3)return`${t}ms`;const a=Math.floor(t/1e3);if(a>=60)return r("{m}分{s}秒",{m:Math.floor(a/60),s:a%60});const o=t%1e3;return o>0?r("{s}秒{ms}ms",{s:a,ms:o}):r("{n}秒",{n:a})}const mZ=r("生成速度:输出 token ÷ 流式段用时(总用时 − 首响);流式段不足总用时一半时按总用时计"),hZ=500;function gZ(e){const t=Number(e.completionTokens)||0,a=Number(e.durationMs)||0;if(t<=0||a<=0)return"";const o=Number(e.firstResponseMs),c=Number.isFinite(o)&&o>0&&o=hZ&&c*2>=a,f=t/((d?c:a)/1e3);return`${f>=100?Math.round(f):f.toFixed(1)} tok/s`}function xZ(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"-":K0(t)}function Sx(e){return Cs().wbUnits?.formatTokens?.(e)??(Number(e)||0).toLocaleString("zh-CN")}function bZ(e){const t=Math.max(0,Date.now()-(Number(e)||0));return r("{n}秒",{n:Math.max(1,Math.floor(t/1e3))})}function vZ(e){const t=Number(e.promptTokens)||0;return t<=0?"-":`${((Number(e.cacheReadTokens)||0)/t*100).toFixed(2)}%`}function Y0(e){const t=Number(e.status)||0;return t>=200&&t<300&&!e.error}function yp(e){return(Number(e?.status)||0)===0&&!e?.error}const dI=e=>String(e?.id||e?.ts||"");function yZ(e){return(Array.isArray(e?.attemptDetails)?e.attemptDetails:[]).reduce((a,o)=>{const c=o?.retries;return a+(Array.isArray(c)?c.length:0)},0)}function fI(e){return Cs().wbProviders?.labelOf?.(e)||e}function jZ(e){const t=new Set;return e.map((a,o)=>{const c=dI(a)||`i${o}`;let d=c,f=1;for(;t.has(d);)d=`${c}#${f++}`;return t.add(d),d})}async function pI(){if(!(Date.now()-q0({value:String(o?.id||""),label:String(o?.label||o?.id||"")})).filter(o=>o.value),a=(Array.isArray(e?.models)?e.models:[]).map(o=>String(o||"")).filter(Boolean);$u?.setFilterOptions(t,a)}catch(e){console.warn("读取请求日志筛选清单失败,筛选项退化为「全部」:",_0(e))}}}async function wZ(){if(!F0)try{const e=await Cs().workbuddyDesktop?.getScheduledTasks(),t=(e?.tasks||[]).find(a=>a.id==="requestsAutoRefresh");X0(t||null),F0=Array.isArray(e?.tasks)}catch(e){console.warn("读取请求日志自动刷新间隔失败,按默认 1 秒:",_0(e)),X0(null)}}function X0(e){F0=!0;const t=Number(e?.interval),a=e?.unit;!!e&&typeof e=="object"&&Number.isFinite(t)&&t>0&&(a==="seconds"||a==="minutes")?(wx=e.enabled!==!1,jx=a==="minutes"?t*6e4:t*1e3):(wx=!0,jx=JD),$u?.setAuto({ms:jx,enabled:wx})}function SZ(){if(iI)return;const e=Cs().wbColSettings;e&&(iI=!0,G0=e.register({id:"requests",label:r("请求日志表"),columns:z0.map(({key:t,label:a,align:o})=>({key:t,label:a,align:o})),mount:()=>document.querySelector('.page[data-page="requests"] .panel-head .head-actions'),onChange:()=>{ks.flushSync(()=>$u?.repaint()),Cs().wbTableColumns?.repaint?.("requests")}}))}function Q0(){return(G0?G0.apply(z0):z0).map(t=>({...t,align:t.align||"left"}))}const NZ={entries:[],total:0,matched:0,running:0,loaded:!1,error:""};function kZ(e){return e.loaded?e.total?r("没有符合筛选条件的请求"):r("暂无请求日志,网关还没有转发过请求"):r("正在加载请求日志…")}function CZ(e){const t=Number(e.firstResponseMs);return!Number.isFinite(t)||t<=0?null:s.jsx("span",{className:"req-dur-line sub",title:r("首响:上游首帧到达的耗时(请求仍在转发中)"),children:r("首响 {time}",{time:K0(t)})})}function TZ(e,t){const{align:a,key:o}=t,c=t.sel.slice(1)+(o==="dur"?" req-num":""),d=`${c} ta-${a}`;switch(o){case"time":{if(!e.ts)return s.jsx("span",{className:d,children:"—"},o);const f=new Date(e.ts),p=g=>String(g).padStart(2,"0");return s.jsxs("span",{className:d,children:[s.jsx("span",{children:`${f.getFullYear()}-${p(f.getMonth()+1)}-${p(f.getDate())}`}),s.jsx("span",{children:`${p(f.getHours())}:${p(f.getMinutes())}:${p(f.getSeconds())}`})]},o)}case"target":{const f=String(e.provider??"").trim(),g=String(e.providerLabel??"").trim()||(f?fI(f):"");return s.jsxs("span",{className:d,children:[g?s.jsx("span",{className:"req-provider",title:f&&f!==g?r("{name}({id})",{name:g,id:f}):g,children:g}):s.jsx("span",{className:"req-provider is-empty",title:r("这条明细没有记录提供商(旧数据或请求未走到转发)"),children:"—"}),e.accountName?s.jsx("span",{className:"req-acct",title:e.accountId||e.accountName,children:e.accountName}):s.jsx("span",{className:"req-acct is-empty",title:r("请求在任何账号接手之前就失败了"),children:"—"})]},o)}case"retry":{const f=Number(e.attempts)||1,p=dI(e),g=[];if(e.isTest&&g.push(s.jsx(ze,{variant:"brand",shape:"tag",title:r("这条明细是一次模型测试(人工发起):走的是真实转发链路,但不计入报表统计"),children:r("测试")},"test")),Cs().wbRequestHover?.hasProcessFacts?.(e)??f>1){const y=f>1?f:yZ(e);g.push(s.jsx(ze,{variant:"warning",shape:"tag",render:s.jsx("button",{type:"button"}),className:"req-hover-tag","data-req-hover":"chain","data-req-id":p,children:y>1?r("重试 {n}",{n:y}):r("重试")},"chain"))}return Array.isArray(e.sensitiveHits)&&e.sensitiveHits.length&&g.push(s.jsx(ze,{variant:"sensitive",shape:"tag",render:s.jsx("button",{type:"button"}),className:"req-hover-tag","data-req-hover":"sensitive","data-req-id":p,"aria-label":r("命中了敏感词"),children:r("敏")},"sensitive")),g.length?s.jsx("span",{className:d,children:g},o):s.jsx("span",{className:`req-none ta-${a}`,children:"-"},o)}case"status":{if(yp(e)){const v=window.wbRequestPhase;if(!v?.badgeHtml)return s.jsx("span",{className:d,children:s.jsx("span",{className:"req-status-badge",children:s.jsxs(ze,{shape:"tag",variant:"info",title:r("请求正在转发中,用时列显示的是已用时"),children:[s.jsx(ay,{className:"req-live-dot","aria-hidden":"true"}),r("进行中")]})})},o);const y=v.elapsedLineHtml?.(e)??"";return s.jsxs("span",{className:d,children:[s.jsx("span",{className:"req-status-badge",dangerouslySetInnerHTML:{__html:v.badgeHtml(e)}}),y?s.jsx("span",{className:"req-status-line",dangerouslySetInnerHTML:{__html:y}}):null]},o)}const f=Number(e.status)||0,p=Y0(e),g=!p&&f>=200&&f<300?r("HTTP {status},但响应体阶段出错:见错误列",{status:f}):void 0;return s.jsx("span",{className:d,children:s.jsx(ze,{shape:"tag",variant:p?"success":"destructive",title:g,children:f||r("失败")})},o)}case"model":{const f=String(e.clientModel??"").trim(),p=String(e.upstreamModel??"").trim(),g=String(e.model??"").trim(),v=String(e.clientReasoning??"").trim(),y=String(e.upstreamReasoning??"").trim(),b=(S,N)=>N?`${S}(${N})`:S;if(!f||!p||p.toLowerCase()===f.toLowerCase()){const S=b(g,y||v);return s.jsx("span",{className:d,title:S,children:S||"—"},o)}const j=b(p,y),w=b(f,v);return s.jsxs("span",{className:`${d} req-model-split`,children:[s.jsxs("span",{className:"req-model-line",title:r("转发到上游的模型:{model}",{model:j}),children:["⬆️ ",j]}),s.jsxs("span",{className:"req-model-line sub",title:r("下游请求的模型:{model}",{model:w}),children:["⬇️ ",w]})]},o)}case"client":{const f=String(e.client??"").trim();if(!f)return s.jsx("span",{className:`${d} is-empty`,title:r("这条明细没有记录来源客户端(旧数据、模型测试,或请求未带 User-Agent)"),children:"—"},o);const p=f==="other"?r("其它"):f;return s.jsx("span",{className:d,title:f==="other"?r("识别到 User-Agent,但不属于已知的客户端类型:{ua}",{ua:f}):r("来源客户端:{client}",{client:p}),children:p},o)}case"dur":return yp(e)?s.jsxs("span",{className:d,children:[s.jsx("span",{className:"req-dur-line",title:r("已用时(请求仍在转发中)"),children:bZ(e.ts)}),CZ(e)]},o):s.jsxs("span",{className:d,children:[s.jsx("span",{className:"req-dur-line",children:K0(e.durationMs)}),s.jsx("span",{className:"req-dur-line sub",title:r("首响:上游首帧到达的耗时"),children:r("首响 {time}",{time:xZ(e.firstResponseMs)})})]},o);case"usage":{if(yp(e))return s.jsx("span",{className:d},o);if(!Y0(e))return s.jsxs("span",{className:d,title:r("失败请求不记录用量"),children:[s.jsx("span",{className:"req-usage-line",children:"in: - / out: - / all: -"}),s.jsx("span",{className:"req-usage-line sub",children:r("缓存读取: - / 命中率: -")})]},o);const f=`in: ${Sx(e.promptTokens)} / out: ${Sx(e.completionTokens)} / all: ${Sx(e.totalTokens)}`,p=r("缓存读取: {cache} / 命中率: {rate}",{cache:Sx(e.cacheReadTokens),rate:vZ(e)}),g=gZ(e),v=g?`${p} · ${g}`:p;return s.jsxs("span",{className:d,title:[f,v].filter(Boolean).join(` -`),children:[s.jsx("span",{className:"req-usage-line",children:f}),s.jsxs("span",{className:"req-usage-line sub",children:[p,g?s.jsxs("span",{title:mZ,children:[" · ",g]}):null]})]},o)}case"error":return yp(e)?s.jsx("span",{className:d},o):e.error?s.jsx("span",{className:d,title:String(e.error),children:String(e.error)},o):s.jsx("span",{className:`req-none ${c} ta-${a}`,children:"-"},o);case"detail":{const f=e.id?String(e.id):"";return f?s.jsx("span",{className:d,children:s.jsx(se,{size:"sm",variant:"outline",className:"req-detail-btn",title:r("查看该请求的上游原始报文"),onClick:()=>{Cs().wbRequestDetail?.open?.(f,e)},children:r("详情")})},o):s.jsx("span",{className:`req-none ${c} ta-${a}`,children:"-"},o)}default:return null}}function EZ(e){return s.jsx("div",{className:"req-head",children:e.map(t=>s.jsx("span",{"data-col":t.key,className:`${t.sel.slice(1)}${t.key==="dur"?" req-num":""} ta-${t.align}`,children:t.label},t.key))},"__head")}function AZ(){const[e,t]=x.useState(NZ),[a,o]=x.useState(()=>cI()),[c,d]=x.useState(()=>en.range),[f,p]=x.useState(!1),[g,v]=x.useState(0),[y,b]=x.useState(()=>en.size),[j,w]=x.useState(()=>({ms:jx,enabled:wx})),[S,N]=x.useState([]),[k,E]=x.useState([]),[,D]=x.useState(0),C=x.useRef(null),A=x.useRef(null),R=x.useRef(!1),I=x.useCallback(ee=>(en.filters={...en.filters,...ee},o({...en.filters}),en.filters),[]),P=x.useCallback(ee=>{en.range=ee,d(ee)},[]),O=x.useCallback(ee=>{en.offset=ee,v(ee)},[]),_=x.useCallback(ee=>{en.runningOnly=ee,p(ee)},[]),L=x.useCallback(()=>{U0||!Cs().wbFilterMemory||(U0=!0,!lI&&I(cI()))},[I]),H=x.useCallback((ee,fe)=>{Cs().wbRequestHover?.beforeListRedraw?.(),fe&&(V0=fe),R.current=!0,t(ee)},[]),B=x.useCallback(ee=>{Cs().wbRequestHover?.beforeListRedraw?.(),R.current=!0,t(fe=>({...fe,error:ee}))},[]),z=x.useCallback(async(ee={})=>{const{silent:fe=!1,resetPage:te=!1}=ee;te&&O(0),wZ(),L(),fe||pI();const Ce=++oI;try{const re=Cs().workbuddyDesktop;if(!re)throw new Error(r("后端桥不可用"));const de=await re.getStatsRequests(pZ());if(Ce!==oI)return;const ke={entries:Array.isArray(de?.entries)?de.entries:[],total:Number(de?.total)||0,matched:Number(de?.matched)||0,running:Number(de?.running)||0,loaded:!0,error:""},Ee=Math.max(0,(Math.ceil(ke.matched/en.size)-1)*en.size);if(en.offset>Ee)return O(Ee),z({silent:fe});te&&(A.current=0),H(ke,ke.entries)}catch(re){fe||(console.warn("读取请求日志失败:",_0(re)),B(r("读取请求日志失败,详见控制台")))}},[O,H,B,L]);x.useEffect(()=>($u={load:z,setAuto:ee=>w(ee),setFilterOptions:(ee,fe)=>{N(ee),E(fe)},repaint:()=>D(ee=>ee+1)},Cs().wbRequestHover?.bind?.({host:C.current,entryOf:ee=>{const fe=ee?.dataset?.reqId||"";return fe&&(V0.find(te=>String(te?.id||"")===fe)||V0.find(te=>String(te?.ts||"")===fe))||null}}),z({silent:!0}),pI(),()=>{$u=null}),[z]),x.useLayoutEffect(()=>{SZ(),D(ee=>ee+1)},[]);const Q=e.error||!e.entries.length?"":Q0().map(ee=>ee.key).join("|");x.useLayoutEffect(()=>{Q&&Cs().wbTableColumns?.repaint?.("requests")},[Q]),x.useEffect(()=>{if(!j.enabled||j.ms<=0)return;const ee=window.setInterval(()=>{document.hidden||Cs().wbApp?.currentPage!=="requests"||$0||($0=!0,z({silent:!0}).finally(()=>{$0=!1}))},j.ms);return()=>{window.clearInterval(ee)}},[j,z]),x.useLayoutEffect(()=>{R.current&&(R.current=!1,Cs().wbRequestHover?.afterListRedraw?.());const ee=A.current;if(ee===null)return;A.current=null;const fe=C.current;fe&&(fe.scrollTop=ee)});function K(ee){const fe=Math.max(1,Math.ceil(e.matched/en.size)),Ce=(Math.min(Math.max(1,ee),fe)-1)*en.size;Ce!==en.offset&&(O(Ce),A.current=0,z())}function X(ee){const fe=eI(ee);if(fe===en.size)return;en.size=fe,b(fe),rg("requests",fe);const te=en.offset+1;O(Math.max(0,Math.floor((te-1)/fe)*fe)),A.current=0,z()}function q(ee){lI=!0,fZ(I(ee)),z({resetPage:!0})}function $(ee){const fe=B0.includes(ee)?ee:H0;fe!==en.range&&(P(fe),dZ(fe),z({resetPage:!0}))}function Y(ee){ee!==en.runningOnly&&(_(ee),z({resetPage:!0}))}const F=Q0(),G=Math.max(1,Math.ceil(e.matched/en.size)),W=Math.min(G,Math.floor(g/en.size)+1),le=e.matched?g+1:0,M=e.matched?g+e.entries.length:0,U=e.error?"—":e.matched===e.total?r("{n} 条",{n:e.total}):r("{matched} / {total} 条",{matched:e.matched,total:e.total}),Z=!f&&e.running>0?r(" · {n} 进行中",{n:e.running}):"",ae=[aZ[c]||r("全部")];f?ae.push(r("只看进行中")):a.status==="ok"?ae.push(r("只看成功")):a.status==="error"&&ae.push(r("只看失败")),a.provider&&ae.push(fI(a.provider)),a.model&&ae.push(a.model);const ce=x.useMemo(()=>!a.provider||S.some(ee=>ee.value===a.provider)?S:[{value:a.provider,label:a.provider},...S],[a.provider,S]),J=x.useMemo(()=>!a.model||k.includes(a.model)?k:[a.model,...k],[a.model,k]),ie=jZ(e.entries),ge=e.entries.map((ee,fe)=>s.jsx("div",{className:`req-row${yp(ee)?" running":Y0(ee)?"":" failed"}`,children:F.map(te=>TZ(ee,te))},ie[fe]));return s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("请求日志列表")}),s.jsx(ze,{id:"req-badge",variant:"outline","data-tone":"",children:U+Z}),s.jsx("span",{className:"panel-sub",children:r("按时间倒序,全量保留")}),s.jsx("div",{className:"head-actions",children:s.jsx(se,{id:"btn-req-clear",variant:"destructive",onClick:()=>{Cs().wbRequestClearModal?.open?.()},children:r("清理")})})]}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"log-filters",children:[s.jsx(In,{options:oZ,value:c,onValueChange:$,"aria-label":r("请求日志时间范围"),className:"shrink-0"}),s.jsxs(ft,{value:a.status,disabled:f,onValueChange:ee=>q({status:String(ee??"")}),children:[s.jsx(mt,{id:"req-status",className:"min-w-[120px]",title:r(f?"「仅看进行中」开启时,状态固定为进行中":"按请求结果筛选"),"aria-label":r("按请求结果筛选"),children:s.jsx(pt,{children:sI.find(ee=>ee.value===a.status)?.label??iZ})}),s.jsx(ht,{children:sI.map(ee=>s.jsx(qe,{value:ee.value,children:ee.label},ee.value))})]}),s.jsxs(ft,{value:a.provider,onValueChange:ee=>q({provider:String(ee??"")}),children:[s.jsx(mt,{id:"req-provider",className:"min-w-[120px]",title:r("按提供商筛选(只列日志里出现过的)"),"aria-label":r("按提供商筛选"),children:s.jsx(pt,{children:a.provider?ce.find(ee=>ee.value===a.provider)?.label||a.provider:rI})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"",children:rI}),ce.map(ee=>s.jsx(qe,{value:ee.value,children:ee.label},ee.value))]})]}),s.jsxs(ft,{value:a.model,onValueChange:ee=>q({model:String(ee??"")}),children:[s.jsx(mt,{id:"req-model",className:"min-w-[120px]",title:r("按模型筛选(只列日志里出现过的;精确匹配模型名)"),"aria-label":r("按模型筛选"),children:s.jsx(pt,{children:a.model||aI})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"",children:aI}),J.map(ee=>s.jsx(qe,{value:ee,children:ee},ee))]})]}),s.jsx(k6,{id:"btn-req-running",variant:"outline",size:"default",pressed:f,onPressedChange:Y,title:r("只显示正在转发中的请求(状态列按阶段显示:连接中 / 等待响应 / 响应中 / 重试中,用时列显示已用时)"),children:r("仅看进行中")}),s.jsx("div",{className:"spacer"}),s.jsx("span",{className:"panel-sub",id:"req-summary",children:ae.join(" · ")})]}),s.jsx("div",{className:"log-list",id:"req-list",ref:C,children:e.error?s.jsx("div",{className:"log-empty",children:e.error}):e.entries.length?[EZ(F),...ge]:s.jsx("div",{className:"log-empty",children:kZ(e)})})]}),s.jsx(Li,{total:e.matched,range:{start:le,end:M},page:W,pageCount:G,size:y,sizes:sZ,onSizeChange:X,onPageChange:K,disabled:!e.loaded&&!e.error})]})}async function mI(e={}){await $u?.load(e)}function RZ(){return uI().toString()}function OZ(){return q0=0,mI({resetPage:!0})}const hI='.page[data-page="requests"]';let gI=!1;function xI(){if(gI)return;const e=document.querySelector(hI);e&&(gI=!0,e.replaceChildren(),vn.createRoot(e).render(s.jsx(AZ,{})))}document.querySelector(hI)?xI():document.addEventListener("DOMContentLoaded",xI,{once:!0}),window.wbRequestsPanel={load:mI,applyAutoRefresh:X0,visibleColumns:Q0,clearParams:RZ,notifyCleared:OZ},window.wbRequestPhase={labelOf:ZD,badgeHtml:tZ,elapsedLineHtml:nZ,elapsedText:WD,phaseOf:L0};function MZ(e){if(e.status==="loading")return Ut.appLoading;if(e.status==="unavailable")return Ut.modelsDevUnavailable;const t=e.source==="builtin"?Ut.modelsDevSourceBuiltin:e.source==="cache"?Ut.modelsDevSourceCache:e.source==="network"?Ut.modelsDevSourceNetwork:e.source,a=e.updatedAt>0?String(tt().wbApp?.formatTime?.(e.updatedAt)??""):"";if(!t&&!a&&!e.count)return Ut.modelsDevEmpty;const o=a?r(",{time}",{time:a}):"",c=e.enabled?r("正在联网更新"):r("仅用现有数据、不联网刷新");return r("{count} 条 · 来自{origin}{at} · {mode}",{count:Number(e.count).toLocaleString("zh-CN"),origin:t||r("未知来源"),at:o,mode:c})}function tt(){return window}function _t(e){return e instanceof Error?e.message:String(e)}function Ve(e,t){tt().wbApp?.toast?.(e,t)}async function DZ(e){try{await tt().workbuddyDesktop?.openReleasePage?.(e)}catch(t){Ve(r("打开链接失败:{error}",{error:_t(t)}),"err")}}const Nx=[{id:"general",label:r("通用"),icon:"sliders"},{id:"display",label:r("显示"),icon:"display"},{id:"gateway",label:r("网关"),icon:"traffic"},{id:"routing",label:r("路由"),icon:"route"},{id:"retry",label:r("重试"),icon:"refresh"},{id:"timeout",label:r("超时"),icon:"timer"},{id:"security",label:r("安全"),icon:"shield"},{id:"data",label:r("数据"),icon:"database"},{id:"feedback",label:r("反馈与需求"),icon:"feedback"},{id:"about",label:r("更新"),icon:"download"}],bI="workbuddy-desktop-settings-cat",IZ="workbuddy-desktop-theme",PZ="workbuddy-desktop-zoom",vI="wb:theme",yI="wb:zoom",Z0=80,jI=130,kx=5,_Z=Array.from({length:(jI-Z0)/kx+1},(e,t)=>Z0+t*kx),LZ=[{value:"system",label:r("跟随系统")},{value:"light",label:r("浅色")},{value:"dark",label:r("深色")}];function zZ(){try{const e=localStorage.getItem(IZ);return e==="light"||e==="dark"?e:"system"}catch{return"system"}}function BZ(){try{const e=localStorage.getItem(PZ);if(e===null||e.trim()==="")return 100;const t=Number(e);if(!Number.isFinite(t))return 100;const a=Math.round(t/kx)*kx;return Math.min(jI,Math.max(Z0,a))}catch{return 100}}const W0=1,J0=99999,eS=[{key:"logRetentionDays",id:"settings-retention-log",label:r("事件日志保留天数"),unit:r("天"),min:W0,max:J0,hint:r("登录 / 账号切换 / 429 切换等系统事件,可填 1–99999 天。")},{key:"requestLogRetentionDays",id:"settings-retention-request",label:r("请求日志保留天数"),unit:r("天"),min:W0,max:J0,hint:r("「请求日志」页的逐条请求记录,默认 99999 天(近似全量保留),可填 1–99999 天。")},{key:"dailyAggregateRetentionDays",id:"settings-retention-daily",label:r("按天聚合保留天数"),unit:r("天"),min:W0,max:J0,hint:r("报表页的热力图与按天趋势,默认 99999 天(近似全量保留),可填 1–99999 天。")}],wI=[{key:"retryCount",id:"settings-retry-count",label:r("同一账号重试次数"),unit:r("次"),min:0,max:10,hint:r("在同一个账号上原地重发几次(不含首发;整条请求共用一份,用完后换来的账号只发一次就继续换)。可填 0–10,0 表示失败立即换号。")},{key:"retryCrossProviderCount",id:"settings-retry-cross-provider-count",label:r("切换账号重试次数"),unit:r("次"),min:0,max:10,hint:r("失败后最多再换几个账号试(填 N = 最多换 N 个,首发那个不算)。换到同一家名下另一个账号、或换到另一家,都各算一次;换满仍失败就返回错误。可填 0–10,0 表示失败立即报错。")},{key:"retryIntervalSeconds",id:"settings-retry-interval",label:r("重试间隔"),unit:r("秒"),min:0,max:300,hint:r("两次重试之间的等待时间,两项共用,可填 0–300 秒。")}],SI=[{key:"connectTimeoutSeconds",id:"settings-timeout-connect",label:r("连接中超时"),unit:r("秒"),min:1,max:3600,hint:r("建立上游 TCP/TLS 连接或代理隧道的最大等待时间(秒),默认 30 秒,范围 1~3600。")},{key:"headersTimeoutSeconds",id:"settings-timeout-headers",label:r("等待响应超时"),unit:r("秒"),min:1,max:3600,hint:r("请求发出后等待上游响应头的最大时间(秒),默认 300 秒,范围 1~3600。")},{key:"streamIdleTimeoutSeconds",id:"settings-timeout-stream-idle",label:r("流式响应空闲超时"),unit:r("秒"),min:1,max:3600,hint:r("流式响应相邻数据之间允许的最大空闲时间(秒),收到新数据后重新计时,默认 300 秒,范围 1~3600。")},{key:"bodyTimeoutSeconds",id:"settings-timeout-body",label:r("非流式响应超时"),unit:r("秒"),min:1,max:3600,hint:r("读取完整非流式响应体允许的最大时间(秒),默认 300 秒,范围 1~3600。")}],NI=[{key:"queueMaxWaits",id:"settings-queue-max-waits",label:r("排队等待次数"),unit:r("次"),min:0,max:10,hint:r("上游模型繁忙时会先排队(回一句「建议 N 秒后再来」,Qoder 免费模型就是这样):网关等一会儿再发同一请求,最多等几次。默认 2 次,可填 0–10;填 0 表示不等待,排队直接返回 503 并说明「不是登录态或额度问题」。")},{key:"queueWaitSeconds",id:"settings-queue-wait-seconds",label:r("排队等待秒数"),unit:r("秒"),min:0,max:120,hint:r("每次等待的时长,默认 0 = 跟随上游建议(实测 9~30 秒,上游没给建议时用 15 秒)。可填 0–120 秒强制一个固定时长。")}],kI="noRetryStatusCodes",tS=100,nS=599,CI=50,zo=[{value:"passthrough",optionLabel:r("透传客户端 system(默认)"),toastLabel:r("透传客户端 system")},{value:"custom",optionLabel:r("替换为网关提示词"),toastLabel:r("替换为网关提示词")},{value:"append",optionLabel:r("追加网关提示词"),toastLabel:r("追加网关提示词")}];function TI(e,t,a,o){const c=String(e??"").trim();if(!c)return{ok:!1,message:r("{noun}不能为空(可填 {min}–{max})",{noun:o,min:t,max:a})};if(!/^\d+$/.test(c))return{ok:!1,message:r("{noun}必须是整数",{noun:o})};const d=Number(c);return da?{ok:!1,message:r("{noun}必须在 {min}–{max} 之间(当前填的是 {text})",{noun:o,min:t,max:a,text:c})}:{ok:!0,value:d}}function HZ(e,t){const a={...t};if(e&&typeof e=="object"){const o=e;typeof o.closeToTray=="boolean"&&(a.closeToTray=o.closeToTray),typeof o.autostart=="boolean"&&(a.autostart=o.autostart),typeof o.lanAccess=="boolean"&&(a.lanAccess=o.lanAccess),typeof o.lanPanel=="boolean"&&(a.lanPanel=o.lanPanel),typeof o.lightweightMode=="boolean"&&(a.lightweightMode=o.lightweightMode)}return a}function EI(e,t,a){if(!t||typeof t!="object")return null;const o=t,c={...a||{}};for(const d of e){const f=Number(o[d.key]);Number.isInteger(f)&&f>=d.min&&f<=d.max&&(c[d.key]=f)}return e.some(d=>Number.isInteger(c[d.key]))?c:null}function AI(e){if(!Number.isFinite(e)||e<=0)return"0 B";if(e<1024)return`${e} B`;const t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;const a=t/1024;return a<1024?`${a.toFixed(1)} MB`:`${(a/1024).toFixed(2)} GB`}function UZ(e){const t=Number(e);return!Number.isFinite(t)||t<0?"—":t.toLocaleString("zh-CN")}const ss={displayTheme:r("控制界面的深浅色,与左侧边栏底部的三个主题按钮是同一个设置(改哪一处,另一处立刻跟上)。「跟随系统」会随操作系统当前的浅色 / 深色自动切换,并在系统主题变化时即时跟上;选「浅色」或「深色」则把界面固定在该模式,不再随系统变化。窗口标题栏的深浅色会一并同步,不会出现深色界面配一条浅色标题栏的情况。"),displayZoom:r("等比放大或缩小整个界面(文字、控件、间距一起变),效果与浏览器按 Ctrl +/- 相同:80%–130%、5% 一档。窗口本身不缩放,变的是页面内容的显示比例,设置立即生效并记住,下次启动直接按这个比例打开。放得越大可视范围越小,窗口较窄或表格较宽时不建议调得太大。"),displayLanguage:r("界面语言。可选简体中文、繁體中文、English、日本語、한국어、Português (Brasil),或「跟随系统」(按浏览器 / 系统的语言列表自动选)。切换后整页立即刷新;该偏好只存在本机(localStorage),不影响账号、密钥与转发。"),tray:r("默认关闭窗口不会退出程序,而是把窗口缩到系统托盘,转发继续在后台运行(OpenAI 客户端不受影响);要彻底退出程序,请在托盘图标上右键选「退出」。关掉这个开关后,点关闭按钮即退出程序、转发随之中断。「开机自动启动」开启后,登录系统时会自动启动本程序(通常直接驻留托盘),不需要手动打开。"),lightweight:r("开启后,关闭窗口不只是隐藏,而是把界面窗口整个销毁:底层的 WebView2 六个常驻进程(约 200MB 内存)随之退出,网关转发、定时签到、余额查询都在后台进程里继续,不受影响;需要界面时点托盘图标重新打开(WebView 冷启动约 1 秒)。注意:界面销毁期间「ZCode 活动套餐」通道的验证码令牌由界面铸造,无法补充 —— 走该通道的请求会以 503 落进请求日志(写明原因),重新打开界面即自动恢复。此开关只在「关闭窗口时最小化到托盘」开启时有意义,最小化窗口不受影响。"),lan:r("默认网关只监听 127.0.0.1,只有本机能访问。开启后网关改听所有网卡,同一局域网内的设备可以把 API 地址指向本机 IP 一起使用。出于安全考虑,开启前必须先注册一个面板管理员:管理接口从此要求管理员会话或网关 Key,模型额度不会对局域网裸奔;一把启用的网关 Key 都没有时,转发接口也会拒绝服务,直到创建第一把。改动需要重启应用生效。「同时开放网页管理面板」把管理界面也出给局域网(其他设备的浏览器打开本机 IP 即可管理),默认关闭 —— 桌面端的面板仍只由本程序自己出。"),units:r("控制报表与请求日志里 Token 读数的写法:开启后按中文量级显示(1.2亿 / 8400万),关闭则用 k / M 缩写(与上游文档、接口字段的写法一致)。这只影响显示口径,不改变任何统计与存储的数值。"),queue:r("只对「排队制」的上游生效(目前是 Qoder 的免费模型):模型繁忙时上游不报错,只回一句「建议 N 秒后再来」(业务码 10605),网关按建议时长等一会儿再发同一请求,等满次数仍排不上才把「排队中」作为错误返回(HTTP 503,文案会说明这不是登录态或额度问题)。等待发生在首个字节之前,吃的是「等待响应超时」那份预算 —— 两项设置一起决定一次请求最多卡多久;排队不会标记账号限额、也不会换账号(换谁都一样在排队)。保存后对下一个请求立即生效,不用重启。"),captchaPool:r("ZCode「活动套餐」通道的每条推理请求都要附一个当次铸造的阿里云无痕验证令牌(一次性、约 2 分钟过期):令牌由界面里的铸造守卫静默铸好、推给网关入池,转发时逐条取用。这里的三个值管的是补货节奏:①「库存目标」= 库存低于它守卫才补铸、补到它为止,默认 3 个;②「轮询间隔」= 守卫多久看一次库存,默认 2500 毫秒,只影响反应速度(库存够用时不会多铸);③「单轮铸造上限」= 发现缺货时一轮最多铸几个,默认 1 个(连铸之间固定隔 500 毫秒)。请求密集、请求日志里连续出现「需要人机验证令牌」的 503 时,把目标与单轮上限适当调大、轮询调快,能让池子跟得上消耗 —— 代价是上游(阿里云)对铸造频率有风控,铸得越多越快越容易触发限流,且用不掉的令牌 2 分钟即过期作废、等于白烧配额,所以建议小步调。保存后对下一轮补货立即生效,不用重启。"),timeouts:r("上游请求四个阶段各自的等待上限(秒,1~3600):①「连接中超时」= 建立 TCP/TLS 连接或代理隧道的最大等待,默认 30 秒;②「等待响应超时」= 请求发出后等上游响应头的最大时间,默认 300 秒 —— 网关请求上游恒带 stream,响应头在 SSE 建立时就到达,与模型思考多久无关;③「流式响应空闲超时」= 流式响应相邻两块数据之间允许的最大空闲,收到新数据即重新计时,默认 300 秒 —— 上游长时间不吐数据即判定连接僵死并断开;④「非流式响应超时」= 读完整份非流式响应体的总预算(一次性计时、不重置),默认 300 秒。四项都是「等待上限」,只要数据还在来,正常的流式回答就一直往下传。保存后对下一个请求立即生效,不用重启。"),retry:r("请求转发到上游失败时(服务器瞬时错误、连接失败,以及 WorkBuddy 的 11-128 敏感词拦截),网关会等一段间隔后再发一次。次数分两档,管的是两件事:①「同一账号重试次数」在同一账号上原地重发几次 —— 一般是提示词被上游拦截、或链路瞬时抖动,等一会儿重发往往就好了;②「切换账号重试次数」这份请求最多再换几个账号试 —— 首发的那个账号不算,每换一个扣一次,不分是不是同一家(换到同一家的下一个账号也算一次),换满还失败就把错误返回给客户端。两项都设为 0 表示失败不重试、直接报错。注意账号级限额(429)不占这里的换号次数 —— 那类失败走「冷却该账号并换下一个账号」的降级,与这里的重试是两条路。另有「指定错误码直接换号」名单(默认 402):命中名单的上游状态码不在同一账号重发,直接按队列换下一个账号继续试(换号也占「切换账号重试次数」),换满仍失败才把错误返回给客户端。"),routing:r("转发一个请求时按什么顺序挑账号:①「路由策略」决定排队规则 —— 顺序优先是排第 1 的接走所有请求、直到它不能答(限流 / 故障 / 额度尽)才轮到下一位;负载均衡是每条请求换下一位,把负载摊到各个账号上。②「会话粘性」让同一会话(相同的模型 + 相同的开头消息)尽量跟住同一个账号 —— 多轮对话的上下文缓存能复用、少换号少浪费;自动档粘 5 分钟、会话内档粘 6 小时、每轮与关闭都不粘。账号的排队位次(账号表的第一列)在所有策略下都是地基,策略在它之上再排。此外路由还有三层自愈保护:转发失败的账号退避休息一会儿(15 分钟起步翻倍、封顶 1 小时)、被 429 的账号垫底排到队尾 30 分钟、余额不足 / Token 周期用量到顶的账号由限制器拦下 —— 前两层可以在下面按需开关,限制器由账号的「限制器」设置管。"),sanitize:r("上游用「逐字精确匹配」的方式审核请求体(不是语义审核):客户端注入的固定模板句、计费头字段名、以及某些裸错误码出现在报文里就会整单拦截,返回 400。开启本项后,网关在每次转发前改写这些指纹 —— 表头键值整段删除,承载语义的模板句只换一个词(如 official CLI for Claude → official CLI tool for Claude),对话内容与语义都不受影响。规则集是内置的,不需要也无法维护词表。关掉本项后客户端模板会原样发往上游,可能重新出现模板句被误拦的报错。"),clineHeaders:r("Cline 上游按请求头判定「调用方是不是 Cline 自家产品」:X-CLIENT-TYPE: cline-sdk 是硬门槛(缺了它免费池模型一律 403),版本号与平台标识让请求更贴近官方客户端的形态。这里列出的是网关默认会发的头:改某一行的值 = 覆盖默认值(也可以新增默认清单之外的自定义头);把值清空保存 = 这个头不发送;在界面删掉被改过的行 = 回落默认值。改完点「保存」,下一个 Cline 请求立即生效。不懂某一行的含义就不要动它 —— 伪装头的价值在「与官方客户端逐字一致」。"),cors:r("网关面(/v1/*)默认不应答浏览器跨源请求:页面直连会被预检拦下,只报「无法连接 API」。注意来源是 * —— 未配「网关 Key」时任何网页都能借本机网关打上游,故默认关闭;只给自己用的话,让页面与网关同源(本地反代 /v1)更稳妥。面板接口(/api/*)不受影响。"),prompt:r("客户端(Claude Code / Codex 等 CLI)会在 system 提示词里注入几十句固定模板,上游按逐字匹配审核,命中就整单拦截(HTTP 400)。指纹脱敏能改写实测命中过的那几句,但换一个客户端版本就可能冒出新的。这里可以把 system 整段换成网关自己那份:①「透传」= 不动客户端 system(默认,行为与之前完全一致);②「替换」= 删掉客户端所有 system / developer 消息,换成网关的提示词(客户端项目规范随之消失);③「追加」= 在开头连续 system 块之后插入一条网关提示词,既有消息逐字不动(客户端规范与网关提示词并用)。那份提示词有两个来源:提示词文件(留空用内置默认),或直接在界面上编辑正文 —— 编辑过就以那份正文为准(优先于文件),清空则回到文件 / 内置默认。另外,透传 / 追加模式下撞了内容拦截(多半是指纹误报)时,网关会自动换一段最小中性提示词重试一次,并把「降级期」开到次日 00:00 —— 期间所有请求直接带中性提示词出门,不再先撞一次 400;这里能看见并提前解除它。上面几项是**默认值**:想给某个提供商单独配,用下面的「按提供商」加一行(带「网关自带」的家默认就列在那里)—— 不同的上游对这些内容的接受程度不一样。"),debug:r("开启后,网关会把每次转发**发给上游的请求**(请求头 + 请求体)与**上游返回的响应**(状态码 + 响应头 + 响应体)完整保存到本地,供请求日志页的「详情」查看。请求头里的 Authorization、Cookie、API Key 等凭据字段一律替换成 [redacted],不会明文落盘;请求体与响应体按原样保存(可能包含你的对话内容)。报文只保留最近 500 条,超出后丢弃最旧的。这是排障用的临时开关,不需要时建议关闭。"),io:r("导出会把全部账号与自定义提供商定义写入一个 JSON 文件,可以拷到另一台机器上导入后继续使用。导入采用合并策略:同提供商下按业务身份(UID / userId / apiKey 等)去重 —— 已存在的账号只更新凭证,保留本机原有的优先级顺序;新账号追加到转发顺序末尾,不会抢占当前正在使用的账号;自定义提供商定义按 id 合并,本机缺失时自动补建。"),backup:r("把整份数据库(账号、网关配置、事件日志、请求统计、调试报文与桌面设置)导出成一个 SQL 文件,恢复时整体替换本机全部数据 —— 与上面「账号导入 / 导出」的逐条合并是两种语义:恢复会连配置、日志与当前启用状态一起换成备份那台机器的状态。导出默认包含日志与调试报文(文件可能很大),不需要时可以取消勾选只备业务数据。恢复前会自动把当前数据备份到配置目录的 backups/ 下,恢复后需要重新登录管理面板。"),retention:r("三档数据各自独立计时,超出保留天数的部分会被删除:事件日志是登录、账号切换、429 切换这类系统事件;请求日志是网关每次转发到上游的逐条记录;按天聚合供报表页的热力图与按天趋势使用。请求日志与按天聚合默认 99999 天(约 274 年,效果上等于全量保留),事件日志默认 30 天。把某一档改小(例如 30 天改成 7 天)保存后会立即删除超出的历史数据,此操作不可恢复;改大或保持不变不会删除任何数据。三档的可填范围均为 1–99999 天。"),storage:r("全部数据(账号、事件日志、请求记录、调试报文、设置)统一保存在配置目录下的 agent2api.db 这一个 SQLite 数据库里。备份时只需拷贝这个文件;更换保存位置请设置环境变量 AGENT2API_PROXY_HOME 后重启程序。"),modelsDev:r("models.dev 是一个开源的模型资料库(社区维护),这里用它补齐「上游没告诉我们」的模型能力:上下文窗口、最大输出、工具调用、图片、视频、是否支持思考,以及这个模型认识哪些思考档位。优先级是:你在「模型能力」里手工改的值 > 上游清单自己声明的值 > models.dev 的值 —— 它只填上游没声明的空位,从不推翻上游已声明的。网关随包内嵌了一份快照,所以离线、首次启动、访问不通时也有数据;开启时会按「模型目录刷新」任务的间隔联网更新(同一轮里一并刷新,也可在这里立即刷新)。关闭只停联网刷新,已经拿到的数据继续用。")},$n={timeouts:r("保存后立即生效,不用重启;超时按上游失败处理(计入请求日志的「错误」列,并按「请求重试」的设置决定是否重试)。"),queue:r("等待期间请求日志的状态列会显示「排队中」阶段,详情弹窗的「内部重试」里能逐次看到等待时长;等待用尽后返回 HTTP 503(不是 401/429:既不会刷新凭证,也不会把账号标成限额)。"),captchaPool:r("保存后对下一轮补货立即生效,不用重启。守卫跑在应用界面里:轻量模式关窗销毁界面期间无法铸造,走活动套餐通道的请求会以 503 落进请求日志(写明原因),重新打开界面即自动恢复。"),retry:r("保存后立即生效,不用重启;次数用尽仍失败时,错误原样返回给客户端。"),routing:r("保存后立即生效,不用重启:策略与粘性作用于**下一次**转发的选路,进行中的请求不受影响。"),retryCodes:r("命中这些上游状态码的失败不在同一账号重发,直接换下一个账号继续试(换号占用「切换账号重试次数」,换满仍失败才把错误原样返回给客户端)。输入 100–599 的状态码后回车添加,点 × 或退格删除;默认 402(积分不足)。清空全部表示任何错误都照常重试。"),sanitize:r("默认开启。命中明细会记进请求日志的「敏」标签(悬停可看命中了哪几条规则)。本项只改发给上游的副本,客户端看到的响应内容不变。"),clineHeaders:r("值与默认值相同的行不占覆盖(存的是「改过的键」,不是全量配置);值留空保存表示这个头不发送,删除改过的行表示回落默认值。改完立即生效,不用重启。"),cors:r("默认关闭。改动立即生效,不用重启;关闭期间的跨源请求会被预检拦下。"),debug:r("开启后新发生的请求才会被记录(已经过去的请求补不回来)。报文统一存放在本地数据库里,只保留最近 500 条(超出后丢弃最旧的),条数见左侧「数据 → 数据存储」的「调试报文」。"),promptMode:r("替换 = 客户端 system / developer 消息全部删掉,换成网关的提示词;追加 = 保留客户端内容,只在开头 system 块之后多插一条。两者都只改发给上游的副本,客户端看到的响应不变。"),promptFile:r("UTF-8 文本文件路径,留空用内置默认提示词(通用编码助手提示词,不含任何会被上游拦截的模板句)。只在「替换 / 追加」模式下生效,透传模式不读它。"),promptText:r("在这里直接编辑提示词正文:保存后以这份文本为准(优先于上面的提示词文件),清空则回到文件 / 内置默认。改一个字不必再去编辑器里开文件。"),promptGatewayText:r("上游按「结构」校验身份:三段必须各自成块,所以这里分开编辑三段(不能合成一段)。动态段里的运行值写成占位符,发请求时才替换:{cwd} 工作目录、{platform} 平台、{shell} shell、{os_version} 系统版本、{git} 是否 git 仓库、{provider} 提供方标识、{model} 模型名。清空某一段 = 那一段恢复官方原文。第三段发出时前面会自带一个空行(官方形状)。"),prompt:r("改完立即生效,不用重启(下一个请求就用新模式)。降级是自动的临时状态,解除后本模式自己的提示词立刻恢复。"),promptProviders:r("「用哪份提示词」本来是按上游分别决定的事,所以每家可以有自己的模式、提示词文件与正文:不在这里列出的提供商一律沿用上面那份默认设置,「跟随默认」把这一家取消、回到默认。带「网关自带」那一行的家(目前是 ZCode 两家)默认就列在这里 —— 那一段是网关自己装上去的文本,不来自客户端也不来自提示词文件,默认开启、可以关掉,也可以改它的正文(改过的那一段以你的文本为准);关掉后还能不能通过上游校验,取决于上游当下的口径,行内说明了实测依据。「模式 / 提示词文件 / 正文」管的是客户端自己的 system 怎么处理,与那个开关是两件事。"),modelsDev:r("「模型管理」里每个能力的来源标记(上游 / models.dev / 已覆盖)读的就是这份数据;映射弹窗的思考档位下拉也按这里的数据只列该模型真实认识的档位。"),retention:r("保存后立即生效:改小保留天数会立刻删除超出的历史数据,且不可恢复。"),storageFile:r("配置目录下的 agent2api.db(账号、日志、请求记录、调试报文与设置都在里面)。"),storageSize:r("库主文件的大小(不含运行期间的 WAL 临时文件,退出时已自动并回)。"),storage:r("数据统一保存在配置目录下的 agent2api.db;如需更换位置,请设置环境变量 AGENT2API_PROXY_HOME 后重启程序。"),captcha:r("开启后,登录页在浏览器后台自动完成验证(对真人无感),而脚本每次尝试都要先算一道题 —— 暴力破解与抢注的成本显著上升。仅影响面板的登录 / 注册,与 API 客户端的 API Key 无关。"),panelLogin:r("当前浏览器以管理员身份登录着本面板。「退出登录」会撤销这台设备的登录会话(30 天内的自动续期一并失效),需要重新输入账号密码;其他已登录的设备不受影响。"),exportDanger:r("导出文件内含 accessToken / refreshToken / apiKey 等凭证与自定义提供商定义,可直接用于登录。请妥善保管,不要外传或上传到公共位置。"),backupDanger:r("备份文件内含全部账号凭证、网关 API Key 与面板管理员凭据,可直接用于登录。请妥善保管,不要外传或上传到公共位置。")},Ut={appLoading:"—",appUnavailable:r("主进程未返回启动设置,请更新桌面端后重试"),appTrayOn:r("关闭窗口时程序不退出,转发继续在后台运行;退出请用托盘菜单"),appTrayOff:r("关闭窗口即退出程序,后台转发随之中断"),appLightOn:r("轻量模式已开启:关窗即销毁界面进程(释放约 200MB 内存),网关在后台继续;界面销毁期间 ZCode 活动套餐通道不可用,相关请求会在请求日志里注明原因"),appLightOff:r("未开启轻量模式:关窗仅隐藏窗口,界面进程常驻内存,随时打开不等待"),unitsOn:r("当前显示为「1.2亿 / 8400万」这类中文量级。"),unitsOff:r("当前显示为「1.20M / 8.4k」这类英文缩写。"),debugUnavailable:r("未能读取调试模式设置,请稍后重试"),debugOn:r("正在保存上游原始报文:"),debugOff:r("未开启,转发时不保存任何原始报文。"),sanitizeUnavailable:r("未能读取指纹脱敏设置,请稍后重试"),sanitizeOn:r("正在剥离出站请求里的审核指纹:表头键值整段删除,模板句最小改写。"),sanitizeOff:r("未开启,客户端 system 模板会原样发往上游,可能被内容审核误拦(400)。"),corsUnavailable:r("未能读取网关跨域访问设置,请稍后重试"),corsOn:r("正在应答跨源请求:浏览器跨域请求可直连 /v1/*。"),corsOff:r("未开启,浏览器跨域无法直连网关。"),modelsDevUnavailable:r("未能读取 models.dev 元数据状态,请稍后重试"),modelsDevSourceBuiltin:r("随包内嵌的快照(发版时的那份)"),modelsDevSourceCache:r("上次成功刷新的结果(存在本机数据库里)"),modelsDevSourceNetwork:r("刚刚从 models.dev 拉到的最新数据"),modelsDevEmpty:r("还没有装载任何数据。"),promptUnavailable:r("未能读取系统提示词设置,请稍后重试"),degradeUntilFallback:r("次日 00:00"),themeSystem:r("当前跟随操作系统的深浅色设置,系统切换时界面会自动跟上。"),themeLight:r("当前固定为浅色模式,不随系统变化。"),themeDark:r("当前固定为深色模式,不随系统变化。"),zoomWeb:r("网页端的界面缩放由浏览器自己控制(Ctrl + / Ctrl -,或浏览器菜单里的缩放),此项不可调。"),zoomDefault:r("当前按 100% 显示(默认比例)。"),languageHint:r("界面语言只保存在本机(localStorage)。切换后整页立即刷新,不影响账号、密钥与转发。")},Cx=[{value:"order",label:r("顺序优先"),tip:r("排第 1 的接走所有请求,直到它不能答(限流 / 故障 / 额度尽)才轮到下一位 —— 就是「从上往下」的现状行为。")},{value:"rotate",label:r("负载均衡"),tip:r("每条请求轮换到下一个可用账号;新会话交给当前最闲的那位。适合想把手里的号摊开用、不让某一个一直扛。")},{value:"provider",label:r("家内轮询"),tip:r("家之间仍按优先级,只有同一家内部轮流用各账号 —— 想优先用某几家、又不愿把某一家的某个账号焊死时用它。")}],Tx=[{value:"auto",label:r("自动"),tip:r("同一会话在 5 分钟内尽量跟住同一个账号;停了 5 分钟再发就算新会话。多数场景用它 —— 多轮对话少换号,也不至于把账号焊死。")},{value:"session",label:r("会话内"),tip:r("同一会话在 6 小时内跟住同一个账号;适合一坐几个小时的长会话,上游的上下文缓存能吃到更多。")},{value:"turn",label:r("每轮"),tip:r("每条请求都重新按策略选路 —— 行为与「关闭」一致,仅保留会话识别的记录。")},{value:"off",label:r("关闭"),tip:r("不做会话识别,每条请求都重新按策略选路。")}],VZ=[{key:"routingFailoverBackoff",label:r("失败退避"),defaultOn:!0,tip:r("转发失败的账号休息一会儿再回来:15 分钟起步,连续失败翻倍,封顶 1 小时;成功一次立即恢复。目的是「让这次失败先凉一会儿」,免得一条条地反复撞同一个坏账号。")},{key:"routingSink",label:r("限流垫底"),defaultOn:!0,tip:r("还有额度时被 429 的账号排到队尾,30 分钟后自动回到队列(成功转发一次也会立即回来)。它标记的是「疑似共享池被别人抢」,不是「这个账号本身有问题」。⚠️ 注意它与路由策略的配合:在「家内轮询」下,队尾意味着这一家整体被往后排 —— 如果某个提供商的账号被批量限流,它们会集体沉到队尾,那个家可能长时间轮不到。这时可以关掉本项,让 429 过的账号只受冷却约束(冷却到点自动回来)。")},{key:"routingBreakerEnabled",label:r("熔断"),defaultOn:!1,tip:r("连续失败到阈值后把这个账号整个打开(默认关)。与失败退避的分工:退避管「单次失败先凉一会儿」,惩罚轻、自动恢复;熔断管「这个账号现在整体不对劲,别再一条条地试」,要连续成功若干次才关。打开期间该账号被跳过,除非全场只剩它 —— 那时仍放行试一次。")}],RI=[{key:"zcodeCaptchaPoolTarget",id:"settings-captcha-pool-target",label:r("库存目标"),unit:r("个"),min:1,max:10,hint:r("ZCode 活动套餐通道每条请求都要消耗一个当次铸造的人机验证令牌(一次性,2 分钟过期),库存低于该值时界面自动补铸到它。默认 3 个。调大能吸收突发并发,但用不掉的令牌 2 分钟就过期作废,烧的是上游风控配额。可填 1–10。")},{key:"zcodeCaptchaPoolPollMs",id:"settings-captcha-pool-poll-ms",label:r("轮询间隔"),unit:r("毫秒"),min:1e3,max:3e4,hint:r("铸造守卫每隔多久看一次库存(毫秒)。只影响发现缺货的反应速度 —— 库存够用时轮询不会铸造任何令牌。默认 2500 毫秒,可填 1000–30000。")},{key:"zcodeCaptchaPoolMaxPerRound",id:"settings-captcha-pool-max-per-round",label:r("单轮铸造上限"),unit:r("个"),min:1,max:5,hint:r("发现缺货时一轮最多铸几个(连铸之间固定隔 500 毫秒)。默认 1 个:SDK 同一实例连铸容易互相干扰。调大补货更快,但单轮连铸越多越容易触发上游风控。可填 1–5。")}];function OI(){return tt().workbuddyDesktop?.platform==="web"}let dt={...{category:Nx[0].id,scrollReset:0,busy:null,app:{status:"loading",closeToTray:!1,autostart:!1,lanAccess:!1,lanPanel:!1,lightweightMode:!1,lanIp:null,port:0,adminRegistered:null},unitsChinese:!0,retention:{status:"loading",values:null},retry:{status:"loading",values:null},retryCodes:null,timeouts:{status:"loading",values:null},queue:{status:"loading",values:null},captchaPool:{status:"loading",values:null},routing:{status:"loading",strategy:"order",sticky:"auto",failoverBackoff:!0,sink:!0,breakerEnabled:!1},debug:{status:"loading",on:!1,count:null,limit:null},sanitize:{status:"loading",on:!1},clineHeaders:{status:"loading",defaults:{},overrides:{},effective:{}},cors:{status:"loading",on:!1},prompt:{status:"loading",mode:"passthrough",file:"",text:"",source:"",lines:0,fileError:"",degradeActive:!1,degradeUntilText:"",providers:[],gateway:{},gatewayText:{},options:[]},storage:{status:"loading",available:!0,file:"",bytes:0,accounts:null,logs:null,requests:null,dailyDays:null,debug:null},captcha:{available:!0,enabled:!1},modelsDev:{status:"loading",enabled:!0,source:"",updatedAt:0,count:0},ioFailure:null,retentionConfirm:null,dbIncludeLogs:!0,dbBackupConfirm:null,dbWarning:null,lanConfirm:null,lanRegister:null,panelLogin:!1},panelLogin:OI()};const sS=new Set;function FZ(e){return sS.add(e),()=>{sS.delete(e)}}function $Z(){return dt}function qZ(){return x.useSyncExternalStore(FZ,$Z)}function Ze(e){dt={...dt,...e};for(const t of sS)t()}function Oa(e){Ze({app:{...dt.app,...e}})}function nl(){Ze({})}let En=null;function us(e){En=e,Ze({busy:e})}function rs(){En=null,Ze({busy:null})}function rS(e){const t=Nx.some(a=>a.id===e)?String(e):Nx[0].id;Ze({category:t,scrollReset:dt.scrollReset+1})}function GZ(e){rS(e);try{localStorage.setItem(bI,e)}catch{}}function MI(){let e=null;try{e=localStorage.getItem(bI)}catch{e=null}rS(e)}function DI(){Ze({unitsChinese:tt().wbUnits?.isChinese?.()!==!1})}function KZ(e){tt().wbUnits?.setChinese?.(e),DI(),Ve(r(e?"✅ 已改用本地量级词(万 / 亿式)":"✅ 已改用 k / M 缩写"))}function aS(e){if(e===void 0)return;if(!e||typeof e!="object"){Oa({status:"unavailable"});return}const t=e;Oa({status:"ready",closeToTray:t.closeToTray===!0,autostart:t.autostart===!0,lanAccess:t.lanAccess===!0,lanPanel:t.lanPanel===!0,lightweightMode:t.lightweightMode===!0})}async function II(){try{aS(await tt().workbuddyDesktop?.getAppSettings())}catch(e){console.warn("读取应用设置失败:",_t(e)),aS(null)}}async function YZ(){const e=tt().workbuddyDesktop;if(e?.localIp){try{Oa({lanIp:await e.localIp()||null})}catch{}try{const t=Number((await e.getBackendStatus?.())?.port)||0;t&&Oa({port:t})}catch{}try{const t=(await e.panelAdminStatus?.())?.registered===!0;Oa({adminRegistered:t})}catch{}}}async function lS(e,t){if(En){nl();return}const a=dt.app,o={closeToTray:e==="tray"?t:a.closeToTray,autostart:e==="autostart"?t:a.autostart,lanAccess:a.lanAccess,lanPanel:a.lanPanel,lightweightMode:e==="lightweight"?t:a.lightweightMode};us("app"),Oa(o);const c=r(e==="autostart"?"开机自动启动":e==="lightweight"?"轻量模式":"关闭窗口时最小化到托盘");try{const d=tt().workbuddyDesktop;if(!d)throw new Error(r("主进程桥不可用"));const f=await d.saveAppSettings(o);Oa({status:"ready",...HZ(f,o)}),Ve(r("✅ 已更新「{label}」",{label:c}))}catch(d){Oa(a),Ve(r("保存失败:{message}",{message:_t(d)}),"err")}finally{rs()}}function XZ(e){if(En){nl();return}Ze({lanConfirm:{mode:e?"enable":"disable",panel:dt.app.lanPanel}})}function QZ(e){if(En){nl();return}Ze({lanConfirm:{mode:"panel",panel:e}})}function oS(e){const t=dt.lanConfirm;if(Ze({lanConfirm:null}),!(!t||!e)){if(t.mode==="disable"){Ex(!1,!1);return}if(t.mode==="panel"){Ex(!0,t.panel);return}ZZ()}}async function ZZ(){const e=tt().workbuddyDesktop;if(!e?.panelAdminStatus){Ve(r("当前环境不支持局域网访问设置"),"err");return}us("lan");let t;try{t=(await e.panelAdminStatus())?.registered===!0}catch(a){rs(),Ve(r("查询管理员状态失败:{message}",{message:_t(a)}),"err");return}if(rs(),Oa({adminRegistered:t}),t){await Ex(!0,dt.app.lanPanel);return}Ze({lanRegister:{busy:!1,error:""}})}async function WZ(e,t){if(En)return;const a=tt().workbuddyDesktop;if(!a?.panelRegister)return;const o=e.trim();if(!o||o.length>64){Ze({lanRegister:{busy:!1,error:r("请填写管理员账号(64 字符以内)")}});return}if(t.length<8){Ze({lanRegister:{busy:!1,error:r("密码至少 8 位")}});return}Ze({lanRegister:{busy:!0,error:""}});try{if(await a.panelRegister(o,t),dt.lanRegister===null)return;Ze({lanRegister:null}),Oa({adminRegistered:!0}),await Ex(!0,dt.app.lanPanel)}catch(c){Ze({lanRegister:{busy:!1,error:_t(c)}})}}function PI(){Ze({lanRegister:null})}async function Ex(e,t){if(En)return;const a=tt().workbuddyDesktop;if(!a?.changeLanAccess){Ve(r("当前环境不支持局域网访问设置"),"err");return}us("lan"),Oa({lanAccess:e,lanPanel:t});try{(await a.changeLanAccess(e,t))?.createdKey&&Ve(r("✅ 已自动创建网关 Key「默认」(可在「网关 Key」页查看)")),Ve(r("✅ 设置已保存,应用正在重启…"))}catch(o){Ve(r("保存失败:{message}",{message:_t(o)}),"err"),await II()}finally{rs()}}async function JZ(){if(!En){Ze({ioFailure:null}),us("export");try{const e=await tt().workbuddyDesktop?.exportAccounts();if(e?.canceled){Ve(r("已取消导出"));return}const t=Number(e?.count)||0,a=Number(e?.customProviders)||0;if(!t&&!a){Ve(r("没有可导出的账号"),"err");return}const o=a?r("、{n} 个自定义提供商",{n:a}):"",c=e?.file?r(" 到 {file}",{file:e.file}):"";Ve(r("✅ 已导出 {count} 个账号{note}{file}",{count:t,note:o,file:c}))}catch(e){Ve(r("操作失败:{message}",{message:_t(e)}),"err")}finally{rs()}}}async function eW(){if(!En){Ze({ioFailure:null}),us("import");try{const e=await tt().workbuddyDesktop?.importAccounts();if(e?.canceled){Ve(r("已取消导入"));return}const t=Number(e?.added)||0,a=Number(e?.updated)||0,o=Number(e?.skipped)||0,c=Number(e?.failed)||0,d=Array.isArray(e?.errors)?e.errors:[],f=e?.customProviders??{},p=Number(f.added)||0,g=Number(f.updated)||0,v=[];o&&v.push(r("跳过 {n} 个",{n:o})),c&&v.push(r("失败 {n} 个",{n:c}));const y=v.length?r(",{items}",{items:v.join(r("、"))}):"",b=p||g?r(",自定义提供商新增 {added} 个、更新 {updated} 个",{added:p,updated:g}):"",j=r("新增 {added} 个、更新 {updated} 个{suffix}{note}",{added:t,updated:a,suffix:y,note:b});if(c){Ve(r("导入完成:{summary}",{summary:j}),"err");const w=d.slice(0,3).map(S=>{const N=S?.customProvider?r("自定义提供商 {id}",{id:S?.id||r("(无 id)")}):S?.id??r("未知账号"),k=S?.message??r("未知原因");return r("{label}({message})",{label:N,message:k})}).join(r(";"));Ze({ioFailure:{failed:c,detail:w,more:d.length>3}})}else Ve(r("✅ 导入完成:{summary}",{summary:j}));(t||a||p||g)&&await tt().wbApp?.refresh?.()}catch(e){Ve(r("操作失败:{message}",{message:_t(e)}),"err")}finally{rs()}}}function tW(e){Ze({dbIncludeLogs:e})}async function nW(){if(!En){us("dbExport");try{const e=tt().workbuddyDesktop;if(!e?.exportDatabase){Ve(r("当前环境不支持整库备份(仅桌面端可用)"),"err");return}const t=await e.exportDatabase(dt.dbIncludeLogs);if(t?.canceled){Ve(r("已取消导出"));return}const a=Number(t?.bytes)||0,o=Array.isArray(t?.tables)?t.tables.length:0;Ve(r("✅ 已备份 {n} 张表({size})到 {file}",{n:o,size:AI(a),file:t?.file||""}))}catch(e){Ve(r("操作失败:{message}",{message:_t(e)}),"err")}finally{rs()}}}function sW(){En||Ze({dbBackupConfirm:{includeLogs:dt.dbIncludeLogs}})}function iS(e){Ze({dbBackupConfirm:null}),e&&rW()}async function rW(){if(En)return;const e=tt().workbuddyDesktop;if(!e?.importDatabase){Ve(r("当前环境不支持整库恢复(仅桌面端可用)"),"err");return}us("dbImport"),Ze({dbWarning:null});try{const t=await e.importDatabase(),a=Array.isArray(t?.tables)?t.tables.length:0,o=t?.safetyBackup?r(",替换前的数据已备份为 {name}",{name:t.safetyBackup}):"";Ve(r("✅ 已恢复 {n} 张表{note}",{n:a,note:o}));const c=typeof t?.warning=="string"?t.warning.trim():"";c&&Ze({dbWarning:c}),await jS(),await tt().wbApp?.refresh?.()}catch(t){Ve(r("恢复失败:{message}",{message:_t(t)}),"err")}finally{rs()}}function Ax(e){if(e===void 0)return;const t=EI(eS,e,dt.retention.values);Ze({retention:{status:t===null?"unavailable":"ready",values:t}})}async function Rx(){try{Ax(await tt().workbuddyDesktop?.getRetention())}catch(e){console.warn("读取数据保留设置失败:",_t(e)),Ax(null)}}let Ox=null;function Mx(e){const t=Ox;Ox=null,Ze({retentionConfirm:null}),t?.(e)}function aW(e){return new Promise(t=>{Ox&&Mx(!1),Ox=t,Ze({retentionConfirm:{head:e}})})}function lW(e,t,a){return t===null?r("没能读到「{label}」的当前值,改为 {days} 天可能会删除超出的历史数据。",{label:e.label,days:a}):r("「{label}」将从 {previous} 天改为 {days} 天。",{label:e.label,previous:t,days:a})}async function oW(e,t){if(En||dt.retentionConfirm)return;const a=TI(t,e.min,e.max,r("天数"));if(!a.ok){Ve(a.message,"err");return}const o=dt.retention.values?.[e.key],c=typeof o=="number"&&Number.isInteger(o)?o:null;if(c!==null&&a.value===c)return;const d=c===null||a.valueNumber.isInteger(d?.[f.key]))){const f=d?.[e.key]??t;Ve(a?r("✅ 已保留 {days} 天,超出部分已清理",{days:f}):r("✅ 已保留 {days} 天",{days:f}));return}await Rx(),Ve(a?r("✅ 已保留 {days} 天,超出部分已清理",{days:t}):r("✅ 已保留 {days} 天",{days:t}))}catch(c){Ve(r("保存失败:{message}",{message:_t(c)}),"err"),await Rx()}finally{rs()}}function jp(e,t){if(t===void 0)return;const a=EI(e.fields,t,e.read().values);e.write({status:a===null?"unavailable":"ready",values:a}),e.syncExtras?.(a===null?null:t)}async function qu(e){try{jp(e,await e.get())}catch(t){console.warn(`${e.consoleLabel}失败:`,_t(t)),jp(e,null)}}async function Dx(e,t,a){if(En)return;const o=TI(a,t.min,t.max,t.label);if(!o.ok){Ve(o.message,"err");return}const c=e.read().values?.[t.key];if(Number.isInteger(c)&&o.value===c)return;us(e.scope);const d=e.read().values;d&&e.write({status:"ready",values:{...d,[t.key]:o.value}});try{const f=await e.save({[t.key]:o.value});jp(e,f);const p=e.read().values?.[t.key],g=Number.isInteger(p)?p:o.value;Ve(r("✅ 已保存:{label} {value}",{label:t.label,value:String(g)}))}catch(f){Ve(r("保存失败:{message}",{message:_t(f)}),"err"),await qu(e)}finally{rs()}}const _I={scope:"queue",fields:NI,consoleLabel:"读取排队等待设置",get:()=>tt().workbuddyDesktop?.getQueue(),save:e=>tt().workbuddyDesktop?.saveQueue(e),read:()=>dt.queue,write:e=>Ze({queue:e})};async function LI(){await qu(_I)}async function cW(e,t){await Dx(_I,e,t)}const zI={scope:"captchaPool",fields:RI,consoleLabel:"读取验证码令牌池设置",get:()=>tt().workbuddyDesktop?.getCaptchaPool(),save:e=>tt().workbuddyDesktop?.saveCaptchaPool(e),read:()=>dt.captchaPool,write:e=>Ze({captchaPool:e})};async function BI(){await qu(zI)}async function uW(e,t){await Dx(zI,e,t)}const HI="routingStrategy",UI="routingSticky",dW="routingFailoverBackoff",fW="routingSink",pW="routingBreakerEnabled",mW={[HI]:new Set(Cx.map(e=>e.value)),[UI]:new Set(Tx.map(e=>e.value))};function VI(e){const t=e&&typeof e=="object"?e:{},a=(c,d)=>{const f=t[c];return typeof f=="string"&&mW[c].has(f)?f:d},o=(c,d)=>{const f=t[c];return typeof f=="boolean"?f:d};return{strategy:a(HI,"order"),sticky:a(UI,"auto"),failoverBackoff:o(dW,!0),sink:o(fW,!0),breakerEnabled:o(pW,!1)}}async function Ix(){try{const e=await tt().workbuddyDesktop?.getRoutingConfig();if(e===void 0){Ze({routing:{...dt.routing,status:"unavailable"}});return}Ze({routing:{status:"ready",...VI(e)}})}catch(e){console.warn("读取路由设置失败:",_t(e)),Ze({routing:{...dt.routing,status:"unavailable"}})}}async function cS(e){if(En)return;const t=tt().workbuddyDesktop;if(!t?.setRoutingConfig){Ve(r("桌面运行时不可用,暂时无法保存"),"err");return}us("routing");try{const a=await t.setRoutingConfig(e);a!==void 0?Ze({routing:{status:"ready",...VI(a)}}):await Ix(),Ve(r("✅ 路由设置已保存"))}catch(a){Ve(r("保存失败:{message}",{message:_t(a)}),"err"),await Ix()}finally{rs()}}const wp={scope:"retry",fields:wI,consoleLabel:"读取请求重试设置",get:()=>tt().workbuddyDesktop?.getRetry(),save:e=>tt().workbuddyDesktop?.saveRetry(e),read:()=>dt.retry,write:e=>Ze({retry:e}),syncExtras:e=>{if(e===null){Ze({retryCodes:null});return}const t=e[kI];if(!Array.isArray(t))return;Ze({retryCodes:t.filter(o=>typeof o=="number"&&Number.isInteger(o)&&o>=tS&&o<=nS)})}};function hW(e){jp(wp,e)}async function FI(){await qu(wp)}async function gW(e,t){await Dx(wp,e,t)}async function uS(e){if(!En){Ze({retryCodes:e}),us("codes");try{const t=await tt().workbuddyDesktop?.saveRetry({[kI]:e});jp(wp,t),Ve(r("✅ 已保存:指定错误码直接换号"))}catch(t){Ve(r("保存失败:{message}",{message:_t(t)}),"err"),await qu(wp)}finally{rs()}}}async function xW(e){const t=dt.retryCodes;if(t===null)return;const a=String(e??"").trim();if(!a)return;if(!/^\d+$/.test(a)||Number(a)nS){Ve(r("状态码必须是 {min}–{max} 的整数(收到: {text})",{min:tS,max:nS,text:a}),"err");return}const o=Number(a);if(t.includes(o)){Ve(r("状态码 {code} 已在名单里",{code:o}));return}if(t.length>=CI){Ve(r("名单最多 {max} 个状态码",{max:CI}),"err");return}await uS([...t,o])}async function bW(e){const t=dt.retryCodes;!t||!t.includes(e)||await uS(t.filter(a=>a!==e))}async function vW(){const e=dt.retryCodes;e?.length&&await uS(e.slice(0,-1))}const $I={scope:"timeouts",fields:SI,consoleLabel:"读取请求超时设置",get:()=>tt().workbuddyDesktop?.getTimeouts(),save:e=>tt().workbuddyDesktop?.saveTimeouts(e),read:()=>dt.timeouts,write:e=>Ze({timeouts:e})};async function qI(){await qu($I)}async function yW(e,t){await Dx($I,e,t)}function Px(e){if(e===void 0)return;if(!e||typeof e!="object"){Ze({debug:{status:"unavailable",on:!1,count:null,limit:null}});return}const t=e,a=Number(t.count),o=Number(t.limit);Ze({debug:{status:"ready",on:t.debugMode===!0,count:Number.isInteger(a)?a:null,limit:Number.isInteger(o)?o:null}})}async function dS(){try{Px(await tt().workbuddyDesktop?.getDebug())}catch(e){console.warn("读取调试模式设置失败:",_t(e)),Px(null)}}async function jW(e){if(En){nl();return}us("debug"),Ze({debug:{...dt.debug,on:e}});try{const t=await tt().workbuddyDesktop?.saveDebug(e);Px(t),Ve(r(e?"✅ 调试模式已开启":"✅ 调试模式已关闭"))}catch(t){Ve(r("保存失败:{message}",{message:_t(t)}),"err"),await dS()}finally{rs()}}function _x(e){if(e===void 0)return;if(!e||typeof e!="object"){Ze({sanitize:{status:"unavailable",on:!1}});return}Ze({sanitize:{status:"ready",on:e.sanitizeBlacklistFingerprints===!0}})}async function fS(){try{_x(await tt().workbuddyDesktop?.getSanitize())}catch(e){console.warn("读取出站指纹脱敏设置失败:",_t(e)),_x(null)}}async function wW(e){if(En){nl();return}us("sanitize"),Ze({sanitize:{status:"ready",on:e}});try{const t=await tt().workbuddyDesktop?.saveSanitize(e);_x(t),Ve(r(e?"✅ 出站指纹脱敏已开启":"已关闭出站指纹脱敏"))}catch(t){Ve(r("保存失败:{message}",{message:_t(t)}),"err"),await fS()}finally{rs()}}function pS(e){if(!e||typeof e!="object")return{};const t={};for(const[a,o]of Object.entries(e))typeof o=="string"&&(t[a]=o);return t}function mS(e){if(e===void 0)return;if(!e||typeof e!="object"){Ze({clineHeaders:{status:"unavailable",defaults:{},overrides:{},effective:{}}});return}const t=e;Ze({clineHeaders:{status:"ready",defaults:pS(t.defaults),overrides:pS(t.overrides),effective:pS(t.effective)}})}async function hS(){try{mS(await tt().workbuddyDesktop?.getClineHeaders())}catch(e){console.warn("读取 Cline 伪装头失败:",_t(e)),mS(null)}}async function SW(){await hS(),Ve(r("Cline 伪装头已刷新"))}async function GI(e){if(En){nl();return}us("clineHeaders");try{const t=await tt().workbuddyDesktop?.saveClineHeaders(e);mS(t),Ve(r("✅ Cline 伪装头已保存"))}catch(t){Ve(r("保存失败:{message}",{message:_t(t)}),"err"),await hS()}finally{rs()}}function gS(e){if(e===void 0)return;if(!e||typeof e!="object"){Ze({cors:{status:"unavailable",on:!1}});return}Ze({cors:{status:"ready",on:e.corsEnabled===!0}})}async function xS(){try{gS(await tt().workbuddyDesktop?.getCors())}catch(e){console.warn("读取网关跨域访问设置失败:",_t(e)),gS(null)}}async function NW(e){if(En){nl();return}us("cors"),Ze({cors:{status:"ready",on:e}});try{const t=await tt().workbuddyDesktop?.saveCors(e);gS(t),Ve(r(e?"网关跨域访问已开启":"已关闭网关跨域访问"))}catch(t){Ve(r("保存失败:{message}",{message:_t(t)}),"err"),await xS()}finally{rs()}}async function KI(){try{const e=await tt().workbuddyDesktop?.getCaptchaSetting();Ze({captcha:{available:!0,enabled:e?.captchaEnabled===!0}})}catch(e){Ze({captcha:{available:!1,enabled:!1}}),console.warn("读取机器人校验设置失败:",_t(e))}}async function kW(e){if(En){nl();return}us("captcha"),Ze({captcha:{...dt.captcha,enabled:e}});try{const t=await tt().workbuddyDesktop?.saveCaptchaSetting(e);Ze({captcha:{available:!0,enabled:t?.captchaEnabled===!0}}),Ve(r(e?"✅ 机器人校验已开启":"⚠️ 机器人校验已关闭"))}catch(t){Ve(r("保存失败:{message}",{message:_t(t)}),"err"),await KI()}finally{rs()}}function bS(e){return!e||typeof e!="object"?{status:"unavailable",enabled:!0,source:"",updatedAt:0,count:0}:{status:"ready",enabled:e.modelsDevEnabled!==!1,source:typeof e.source=="string"?e.source:"",updatedAt:Number(e.updatedAt)||0,count:Number(e.count)||0}}async function vS(){try{const e=await tt().workbuddyDesktop?.getModelsDev?.();Ze({modelsDev:bS(e)})}catch(e){Ze({modelsDev:{...dt.modelsDev,status:"unavailable"}}),console.warn("读取 models.dev 元数据设置失败:",_t(e))}}async function CW(e){if(En){nl();return}us("modelsDev"),Ze({modelsDev:{...dt.modelsDev,enabled:e}});try{const t=await tt().workbuddyDesktop?.saveModelsDev?.(e);Ze({modelsDev:bS(t)}),Ve(r(e?"✅ models.dev 模型元数据已开启":"已关闭 models.dev 联网刷新"))}catch(t){Ve(r("保存失败:{message}",{message:_t(t)}),"err"),await vS()}finally{rs()}}async function TW(){if(En){nl();return}us("modelsDevRefresh");try{const e=await tt().workbuddyDesktop?.refreshModelsDev?.();Ze({modelsDev:bS(e?.status)});const t=e?.result,a=String(t?.status||"");a==="refreshed"?Ve(r("models.dev 元数据已更新({count} 条)",{count:Number(t?.count)||0})):a==="failed"?Ve(r("刷新失败:{message}",{message:String(t?.message||"")}),"err"):Ve(String(t?.message||r("本次无需刷新")))}catch(e){Ve(r("刷新失败:{message}",{message:_t(e)}),"err"),await vS()}finally{rs()}}function Gu(e){if(e===void 0)return;if(!e||typeof e!="object"){Ze({prompt:{...dt.prompt,status:"unavailable"}});return}const t=e,a=RW(t.promptGateway);Ze({prompt:{status:"ready",mode:String(t.promptMode||"passthrough"),file:String(t.promptFile||""),text:String(t.promptText||""),source:String(t.promptSource||""),lines:Number(t.promptLines)||0,fileError:String(t.promptFileError||""),degradeActive:t.degradeActive===!0,degradeUntilText:String(t.degradeUntilText||""),providers:EW(t.promptProviders,a),gateway:a,gatewayText:OW(t.promptGatewayText),options:AW(t.promptProviderOptions)}})}function EW(e,t){return!e||typeof e!="object"?[]:Object.entries(e).filter(([a,o])=>!!a&&!!o&&typeof o=="object").map(([a,o])=>{const c=o;return{id:a,mode:String(c.promptMode||"passthrough"),file:String(c.promptFile||""),text:String(c.promptText||""),source:String(c.promptSource||""),lines:Number(c.promptLines)||0,fileError:String(c.promptFileError||""),gateway:t[a]??!0,configured:!0}}).sort((a,o)=>a.id.localeCompare(o.id))}function AW(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&String(t.id||"")).map(t=>{const a=t;return{id:String(a.id),label:String(a.label||a.id),gatewayNote:String(a.gatewayNote||""),gatewayChars:Number(a.gatewayChars)||0,gatewayBlocks:MW(a.gatewayBlocks)}}):[]}function RW(e){if(!e||typeof e!="object")return{};const t={};for(const[a,o]of Object.entries(e)){const c=String(a||"").trim();!c||typeof o!="boolean"||(t[c]=o)}return t}function OW(e){if(!e||typeof e!="object")return{};const t={};for(const[a,o]of Object.entries(e)){const c=String(a||"").trim();if(!c||!o||typeof o!="object")continue;const d=o,f={identity:"",stable:"",dynamic:""};let p=!1;for(const g of["identity","stable","dynamic"]){const v=String(d[g]||"");f[g]=v,v.trim()&&(p=!0)}p&&(t[c]=f)}return t}function MW(e){if(!e||typeof e!="object")return null;const t=e,a={identity:String(t.identity||""),stable:String(t.stable||""),dynamic:String(t.dynamic||"")};return!a.identity.trim()&&!a.stable.trim()&&!a.dynamic.trim()?null:a}async function rc(){try{Gu(await tt().workbuddyDesktop?.getPrompt())}catch(e){console.warn("读取系统提示词设置失败:",_t(e)),Gu(null)}}async function Sp(e,t){if(En)return await rc(),!1;us("prompt");try{const a=await tt().workbuddyDesktop?.savePrompt(t);return Gu(a),Ve(r("✅ 已保存:{label}",{label:e})),!0}catch(a){return Ve(r("保存失败:{message}",{message:_t(a)}),"err"),await rc(),!1}finally{rs()}}async function DW(e){const t=zo.find(a=>a.value===e);await Sp(r("模式改为「{mode}」",{mode:t?.toastLabel??e}),{promptMode:e})}async function IW(e){await Sp(e.trim()?r("提示词文件已更新"):r("已改回内置默认提示词"),{promptFile:e})}async function PW(e){const t=!e.trim();return Sp(r(t?"已清掉界面编辑的提示词(回落文件 / 内置默认)":"提示词正文已更新"),{promptText:t?"":e})}function Bo(e,t){return e.options.find(a=>a.id===t)?.label||t}function ac(e){const t=e==null?"":String(e).trim();return t&&dt.prompt.options.some(a=>a.id===t)?t:""}async function Np(e,t,a){return Sp(e,{promptProviders:{[t]:a}})}function Lx(e,t){const a=!t.configured;return{promptMode:t.mode,promptFile:t.file,promptText:a&&e.source==="inline"?e.text:""}}async function _W(e){const t=ac(e);if(!t)return;const a=dt.prompt;await Np(r("已为「{label}」单独配置提示词",{label:Bo(a,t)}),t,Lx(a,{mode:a.mode,file:a.file,text:a.text,source:a.source,lines:a.lines,fileError:a.fileError,gateway:a.gateway[t]??!0,configured:!1}))}async function LW(e,t){const a=ac(e.id);if(!a||!zo.some(c=>c.value===t))return;const o=zo.find(c=>c.value===t);await Np(r("「{label}」的模式改为「{mode}」",{label:Bo(dt.prompt,a),mode:o?.toastLabel??t}),a,{...Lx(dt.prompt,e),promptMode:t})}async function zW(e,t){const a=ac(e.id);a&&await Np(t.trim()?r("「{label}」的提示词文件已更新",{label:Bo(dt.prompt,a)}):r("「{label}」改用内置默认提示词",{label:Bo(dt.prompt,a)}),a,{...Lx(dt.prompt,e),promptFile:t})}async function BW(e,t){const a=ac(e.id);if(!a)return!1;const o=!t.trim(),c=Bo(dt.prompt,a);return Np(o?r("已清掉「{label}」界面编辑的正文",{label:c}):r("「{label}」的提示词正文已更新",{label:c}),a,{...Lx(dt.prompt,e),promptText:o?"":t})}async function HW(e){const t=ac(e);t&&await Np(r("已取消「{label}」的单独配置",{label:Bo(dt.prompt,t)}),t,null)}async function UW(e,t){const a=ac(e);if(!a)return;const o=Bo(dt.prompt,a);if(En){await rc();return}us("prompt");try{const c=await tt().workbuddyDesktop?.savePrompt({promptGateway:{[a]:t}});Gu(c),Ve(t?r("✅ 已为「{label}」装上网关自带提示词",{label:o}):r("已关闭「{label}」的网关自带提示词:能否通过上游校验取决于上游当前口径",{label:o}),t?"ok":"err")}catch(c){Ve(r("保存失败:{message}",{message:_t(c)}),"err"),await rc()}finally{rs()}}async function VW(e,t){const a=ac(e);if(!a)return!1;const o=Bo(dt.prompt,a),c=!t||!(t.identity.trim()||t.stable.trim()||t.dynamic.trim());return Sp(c?r("「{label}」的网关自带提示词已改回官方原文",{label:o}):r("「{label}」的网关自带提示词正文已更新",{label:o}),{promptGatewayText:{[a]:c?null:t}})}async function FW(){if(!En){us("prompt");try{const e=await tt().workbuddyDesktop?.savePrompt({clearDegrade:!0});Gu(e),Ve(r("✅ 已解除内容拦截降级"))}catch(e){Ve(r("解除失败:{message}",{message:_t(e)}),"err"),await rc()}finally{rs()}}}function kp(e){const t=Number(e);return Number.isFinite(t)?t:null}function yS(e){if(e===void 0)return;const t=e&&typeof e=="object"?e.database:null;if(!t||typeof t!="object"){Ze({storage:{...dt.storage,status:"unavailable"}});return}const a=t;Ze({storage:{status:"ready",available:a.available!==!1,file:String(a.file||""),bytes:Number(a.bytes)||0,accounts:kp(a.accounts),logs:kp(a.logs),requests:kp(a.requests),dailyDays:kp(a.dailyDays),debug:kp(a.debug)}})}async function YI(){try{yS(await tt().workbuddyDesktop?.getStorage())}catch(e){console.warn("读取数据存储概况失败:",_t(e)),yS(null)}}async function $W(){try{return await tt().workbuddyDesktop?.panelLogout(),window.location.href="/login",!0}catch(e){return Ve(r("退出失败:{message}",{message:_t(e)}),"err"),!1}}async function jS(){MI(),DI(),Ze({panelLogin:OI()}),await Promise.all([II(),YZ(),Rx(),FI(),qI(),LI(),BI(),Ix(),dS(),fS(),hS(),xS(),rc(),YI(),KI(),vS(),tt().wbUpdatePanel?.load?.()])}async function qW(){await Rx(),Ve(r("保留天数已刷新"))}async function GW(){await FI(),Ve(r("重试设置已刷新"))}async function KW(){await qI(),Ve(r("超时设置已刷新"))}async function YW(){await LI(),Ve(r("排队等待设置已刷新"))}async function XW(){await BI(),Ve(r("验证码令牌池设置已刷新"))}async function QW(){await Ix(),Ve(r("路由设置已刷新"))}async function ZW(){await dS(),Ve(r("调试模式设置已刷新"))}async function WW(){await fS(),Ve(r("指纹脱敏设置已刷新"))}async function JW(){await xS(),Ve(r("网关跨域访问设置已刷新"))}async function eJ(){await rc(),Ve(r("系统提示词设置已刷新"))}async function tJ(){await YI(),Ve(r("存储概况已刷新"))}const zx=[{key:"identity",label:r("第一段(身份句)"),short:r("第一段"),hint:r("官方原文只有一句:声明自己是 ZCode。")},{key:"stable",label:r("第二段(稳定段)"),short:r("第二段"),hint:r("工具用法与环境说明那一大段。")},{key:"dynamic",label:r("第三段(动态段)"),short:r("第三段"),hint:r("沟通方式 / 上下文管理 + Environment 段。")}];function nJ(e){return r(e==="inline"?"界面里编辑的正文":e==="file"?"提示词文件":e==="builtin"?"内置默认提示词":"(未生效)")}function XI({title:e,text:t,source:a,file:o,disabled:c,save:d,onClose:f}){const[p,g]=x.useState(t),[v,y]=x.useState(!1),b=v||c,j=p!==t;async function w(S){y(!0);try{await d(S)&&f()}finally{y(!1)}}return s.jsx(Qt,{open:!0,onOpenChange:S=>{S||b||f()},children:s.jsxs(Zt,{className:"w-[min(880px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:e})}),s.jsxs(Bt,{children:[s.jsxs(Vn,{children:[s.jsx("h3",{children:r("保存后以这里的文本为准")}),s.jsxs("p",{children:[r("这一份就是「替换 / 追加」模式下网关要发的 system 正文。"),a==="none"?r("当前是透传模式:存下来也不会发出,切成「替换 / 追加」之后才生效。"):r("当前生效的正文来自{source}{file}。保存后这一份会盖过提示词文件与内置默认{note}。",{source:nJ(a),file:o.trim()&&a!=="inline"?r("(文件:{path})",{path:o.trim()}):"",note:a!=="inline"&&o.trim()?r(",文件里后续的改动在清空这里之前不再生效"):""}),r("想回到原来那份,把这里清空再保存即可(不会删掉你配的文件路径)。")]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"settings-prompt-body",children:r("提示词正文")}),s.jsx(Qc,{id:"settings-prompt-body",rows:18,className:"min-h-[320px]",spellCheck:!1,disabled:b,value:p,onChange:S=>g(S.currentTarget.value)}),s.jsx("div",{className:"hint",children:p.trim()?r("{lines} 行、{chars} 字符(按当前草稿计)",{lines:p.split(` -`).length,chars:p.length}):r("空 = 不要这一份,回落提示词文件 / 内置默认提示词。")})]})]}),s.jsxs(nn,{children:[s.jsx(se,{variant:"outline",className:"mr-auto",disabled:b||a!=="inline",onClick:()=>{w("")},children:r("清除这里的正文")}),s.jsx(se,{variant:"outline",disabled:b,onClick:f,children:r("取消")}),s.jsx(se,{variant:"default",disabled:b||!j,onClick:()=>{w(p)},children:r(v?"保存中…":"保存")})]})]})})}function sJ({prompt:e,locked:t,busy:a}){const[o,c]=x.useState(!1);return s.jsxs(s.Fragment,{children:[s.jsx(se,{id:"btn-prompt-edit-body",variant:"outline",disabled:t||a,onClick:()=>c(!0),children:r("编辑正文")}),o?s.jsx(XI,{title:r("编辑提示词正文 · 全局"),text:e.text,source:e.source,file:e.file,disabled:a,save:PW,onClose:()=>c(!1)}):null]})}function rJ({item:e,label:t,locked:a,busy:o}){const[c,d]=x.useState(!1);return s.jsxs(s.Fragment,{children:[s.jsx(se,{id:`btn-prompt-edit-body-${e.id}`,variant:"outline",disabled:a||o,onClick:()=>d(!0),children:r("编辑正文")}),c?s.jsx(XI,{title:r("编辑提示词正文 · {label}",{label:t}),text:e.text,source:e.source,file:e.file,disabled:o,save:f=>BW(e,f),onClose:()=>d(!1)}):null]})}function aJ({id:e,title:t,official:a,over:o,enabled:c,disabled:d,onClose:f}){const[p,g]=x.useState(()=>({identity:o?.identity?.trim()?o.identity:a.identity,stable:o?.stable?.trim()?o.stable:a.stable,dynamic:o?.dynamic?.trim()?o.dynamic:a.dynamic})),[v,y]=x.useState(!1),b=v||d,j=zx.some(N=>p[N.key]!==a[N.key]),w=zx.filter(N=>o?.[N.key]?.trim()).map(N=>N.label);async function S(N){y(!0);try{await VW(e,N)&&f()}finally{y(!1)}}return s.jsx(Qt,{open:!0,onOpenChange:N=>{N||b||f()},children:s.jsxs(Zt,{className:"w-[min(880px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:t})}),s.jsxs(Bt,{children:[s.jsxs(Vn,{children:[s.jsx("h3",{children:r("三段各自成块,所以分开编辑")}),s.jsxs("p",{children:[r("上游按"),s.jsx("strong",{children:r("结构")}),r("校验身份:这三段必须各自成块排在最前(实测:三段并成一段会被回 405 / 3012)。因此这里按段编辑,不能合成一段。改过的段以你的文本为准,没改的段继续用官方原文;清空某一段 = 那一段恢复官方原文。"),w.length?r("当前已改过:{edited}。",{edited:w.join(r("、"))}):r("当前三段都是官方原文。"),c?"":r("注意:这一家的「网关自带」开关现在是关的,改过的正文要等开关打开才生效。")]}),s.jsx("p",{children:$n.promptGatewayText})]}),zx.map(N=>s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs(Je,{htmlFor:`settings-prompt-block-${e}-${N.key}`,children:[N.label,s.jsx("span",{className:"ml-2 font-normal text-subtle",children:p[N.key]===a[N.key]?r("(官方原文)"):r("(已改)")})]}),s.jsx(Qc,{id:`settings-prompt-block-${e}-${N.key}`,rows:N.key==="identity"?2:10,className:N.key==="identity"?"min-h-[64px]":"min-h-[200px]",spellCheck:!1,disabled:b,value:p[N.key],onChange:k=>{const E=k.currentTarget.value;g(D=>({...D,[N.key]:E}))}}),s.jsx("div",{className:"hint",children:N.hint})]},N.key))]}),s.jsxs(nn,{children:[s.jsx(se,{variant:"outline",className:"mr-auto",disabled:b||!w.length,onClick:()=>{S(null)},children:r("恢复官方原文")}),s.jsx(se,{variant:"outline",disabled:b,onClick:f,children:r("取消")}),s.jsx(se,{variant:"default",disabled:b||!j,onClick:()=>{S(p)},children:r(v?"保存中…":"保存")})]})]})})}function lJ({item:e,option:t,over:a,locked:o,busy:c}){const[d,f]=x.useState(!1),p=t.gatewayBlocks;return p?s.jsxs(s.Fragment,{children:[s.jsx(se,{id:`btn-prompt-gateway-text-${e.id}`,variant:"outline",disabled:o||c,onClick:()=>f(!0),children:r("编辑正文")}),d?s.jsx(aJ,{id:e.id,title:r("编辑网关自带提示词 · {label}",{label:t.label}),official:p,over:a,enabled:e.gateway,disabled:c,onClose:()=>f(!1)}):null]}):null}function oJ(e){return e?zx.filter(t=>(e[t.key]||"").trim()).map(t=>t.short).join(r("、")):""}function QI(e,t){return tt().wbIcons?.icon?.(e,t)||""}function cn({tone:e,children:t}){const a=e==="ok"?"success":e==="bad"?"destructive":"outline";return s.jsx(ze,{variant:a,children:t})}function Qn({title:e,tip:t,badge:a,actions:o}){return s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:e}),t?s.jsx("span",{className:"tip-q","data-tip":t}):null,a,o?s.jsx("div",{className:"head-actions",children:o}):null]})}function iJ({title:e,tip:t,badge:a,actions:o,children:c}){function d(f){f.target.closest(".tip-q, .head-actions")&&f.preventDefault()}return s.jsxs("details",{className:"panel panel-fold",children:[s.jsxs("summary",{className:"panel-head",onClick:d,children:[s.jsx("span",{className:"fold-caret","aria-hidden":!0,dangerouslySetInnerHTML:{__html:QI("caretRight",14)}}),s.jsx("h2",{children:e}),t?s.jsx("span",{className:"tip-q","data-tip":t}):null,a,o?s.jsx("div",{className:"head-actions",children:o}):null]}),c]})}function da({id:e,label:t,checked:a,disabled:o,tip:c,onCheckedChange:d}){return s.jsxs("label",{className:"switch",children:[s.jsx(ms,{id:e,checked:a,disabled:o,onCheckedChange:f=>d(f)}),s.jsx("span",{children:t}),c?s.jsx("span",{className:"tip-q","data-tip":c}):null]})}function Cp({field:e,value:t,disabled:a,onCommit:o}){const[c,d]=x.useState(null),f=c!==null?c:t===null?"":String(t);async function p(){const g=c;if(g!==null)try{await o(g)}finally{d(null)}}return s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:e.id,children:e.label}),s.jsxs("span",{className:"retention-input",children:[s.jsx($e,{id:e.id,type:"number",min:e.min,max:e.max,step:1,inputMode:"numeric",className:"w-[92px] max-w-[92px] text-center tabular-nums",value:f,disabled:a||t===null,onChange:g=>d(g.target.value),onFocus:()=>d(String(t??"")),onBlur:()=>{p()},onKeyDown:g=>{g.key==="Enter"&&g.currentTarget.blur()}}),s.jsx("span",{className:"unit",children:e.unit})]}),s.jsx("div",{className:"hint",children:e.hint})]})}function Tp(e){return e.status==="ready"?s.jsx(cn,{tone:"ok",children:r("已生效")}):e.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")})}function Br({id:e,onClick:t}){return s.jsx(se,{id:e,variant:"outline",onClick:t,children:r("刷新")})}function cJ(e){const{lanAccess:t,lanPanel:a,lanIp:o,port:c}=e.app;if(!t)return r("未开启:网关只监听 127.0.0.1,仅本机可以访问。");const d=`http://${o||r("<本机IP>")}${c?`:${c}`:""}`,f=a?r(";网页管理面板已一并开放(浏览器打开同一地址)"):"";return r("已开启:其他设备把 API 地址指向 {url}{panel}。",{url:`${d}/v1`,panel:f})}function uJ({snap:e}){const t=e.app,a=t.status==="unavailable"?Ut.appUnavailable:t.status==="loading"?Ut.appLoading:t.closeToTray?t.lightweightMode?Ut.appLightOn:Ut.appTrayOn:Ut.appTrayOff;return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("启动与托盘"),tip:ss.tray,badge:t.status==="ready"?s.jsx(cn,{tone:"ok",children:r("已应用")}):t.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"settings-switches",children:[s.jsx(da,{id:"settings-close-to-tray",label:r("关闭窗口时最小化到托盘"),checked:t.closeToTray,disabled:e.busy==="app",onCheckedChange:o=>{lS("tray",o)}}),s.jsx(da,{id:"settings-lightweight",label:r("轻量模式(关窗释放界面内存)"),tip:ss.lightweight,checked:t.lightweightMode,disabled:e.busy==="app"||!t.closeToTray,onCheckedChange:o=>{lS("lightweight",o)}}),s.jsx(da,{id:"settings-autostart",label:r("开机自动启动"),checked:t.autostart,disabled:e.busy==="app",onCheckedChange:o=>{lS("autostart",o)}})]}),s.jsx("div",{className:"settings-state",children:a})]})]}),!e.panelLogin&&s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("局域网访问"),tip:ss.lan}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"settings-switches",children:[s.jsx(da,{id:"settings-lan-access",label:r("允许局域网内的设备访问网关"),checked:e.app.lanAccess,disabled:e.busy==="lan",onCheckedChange:XZ}),s.jsx(da,{id:"settings-lan-panel",label:r("同时开放网页管理面板"),checked:e.app.lanPanel,disabled:e.busy==="lan"||!e.app.lanAccess,onCheckedChange:QZ})]}),s.jsx("div",{className:"settings-state",children:cJ(e)})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("计量单位"),tip:ss.units}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"settings-switches",children:s.jsx(da,{id:"settings-chinese-units",label:r("使用中文单位(亿 / 万)"),checked:e.unitsChinese,onCheckedChange:KZ})}),s.jsx("div",{className:"settings-state",children:e.unitsChinese?Ut.unitsOn:Ut.unitsOff})]})]})]})}function dJ(e){return e==="light"?Ut.themeLight:e==="dark"?Ut.themeDark:Ut.themeSystem}function fJ(){const[e,t]=x.useState(zZ),[a,o]=x.useState(BZ),c=tt().workbuddyDesktop?.platform==="web";x.useEffect(()=>{const f=g=>t(String(g.detail||"system")),p=g=>o(Number(g.detail)||100);return window.addEventListener(vI,f),window.addEventListener(yI,p),()=>{window.removeEventListener(vI,f),window.removeEventListener(yI,p)}},[]);const d=a===100?r("100%(默认)"):`${a}%`;return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("显示模式"),tip:ss.displayTheme}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{children:s.jsx(In,{"aria-label":r("显示模式"),options:LZ,value:e,onValueChange:f=>tt().wbApp?.applyTheme?.(f)})}),s.jsx("div",{className:"settings-state",children:dJ(e)})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("界面缩放"),tip:ss.displayZoom}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"retention-list",children:s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"settings-zoom",children:r("缩放比例")}),s.jsx("span",{className:"prompt-input",children:s.jsxs(ft,{value:String(a),onValueChange:f=>tt().wbApp?.applyZoom?.(Number(f)),children:[s.jsx(mt,{id:"settings-zoom",className:"w-[140px]",disabled:c,"aria-label":r("界面缩放比例"),children:s.jsx(pt,{children:d})}),s.jsx(ht,{children:_Z.map(f=>s.jsx(qe,{value:String(f),children:f===100?r("100%(默认)"):`${f}%`},f))})]})}),s.jsx("div",{className:"hint",children:r("放大或缩小整个界面(文字与控件一起变),效果与浏览器 Ctrl +/- 相同:共 11 档,立即生效并记住。")})]})}),s.jsx("div",{className:"settings-state",children:c?Ut.zoomWeb:a===100?Ut.zoomDefault:r("当前按 {n}% 显示。",{n:a})})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("语言设置"),tip:ss.displayLanguage}),s.jsxs("div",{className:"panel-body",children:[s.jsx(pJ,{}),s.jsx("div",{className:"settings-state",children:Ut.languageHint})]})]})]})}function pJ(){const e=window.wbI18n,t=e?.rawLocale?.()??"auto",a=e?.LOCALES??[],o=c=>c==="auto"?r("跟随系统"):a.find(d=>d.code===c)?.label??c;return s.jsx("div",{className:"retention-list",children:s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"settings-language",children:r("界面语言")}),s.jsx("span",{className:"prompt-input",children:s.jsxs(ft,{value:t,onValueChange:c=>{c&&e?.setLocale(c)},children:[s.jsx(mt,{id:"settings-language",className:"w-[200px]","aria-label":r("界面语言"),children:s.jsx(pt,{children:o(t)})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"auto",children:r("跟随系统")}),a.map(c=>s.jsx(qe,{value:c.code,children:c.label},c.code))]})]})})]})})}function mJ({codes:e,status:t,busy:a}){const[o,c]=x.useState(""),d=x.useRef(null),f=t==="unavailable";return s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"settings-retry-no-codes-input",children:r("指定错误码直接换号")}),s.jsx("div",{className:"retention-input",children:s.jsxs("div",{className:f?"tag-input disabled":"tag-input",onClick:()=>d.current?.focus(),children:[(e||[]).map(p=>s.jsxs("span",{className:"tag-chip",children:[s.jsx("span",{className:"v",children:p}),s.jsx(se,{type:"button",variant:"ghost",size:"icon-2xs",className:"tag-x text-muted-foreground hover:bg-destructive-soft hover:text-destructive",title:r("删除 {code}",{code:p}),"aria-label":r("删除状态码 {code}",{code:p}),onClick:g=>{g.stopPropagation(),bW(p)},children:"✕"})]},p)),s.jsx($e,{ref:d,id:"settings-retry-no-codes-input",type:"text",className:"tag-input-field h-auto border-0 bg-transparent px-0 shadow-none focus:shadow-none",placeholder:f?"—":r("输入状态码,回车添加"),inputMode:"numeric",autoComplete:"off",value:o,disabled:f||a,onChange:p=>c(p.target.value),onKeyDown:p=>{if(p.key==="Enter"){p.preventDefault(),xW(o),c("");return}p.key==="Backspace"&&!o&&vW()}})]})}),s.jsx("div",{className:"hint",children:$n.retryCodes})]})}function hJ({prompt:e,locked:t,busy:a}){const[o,c]=x.useState(null);async function d(){const f=o;if(f!==null)try{await IW(f)}finally{c(null)}}return s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"settings-prompt-file",children:r("提示词文件")}),s.jsx("span",{className:"prompt-input",children:s.jsx($e,{id:"settings-prompt-file",type:"text",placeholder:r("留空 = 用内置默认提示词"),value:o!==null?o:e.file,disabled:t||a,onChange:f=>c(f.target.value),onFocus:()=>c(e.file),onBlur:()=>{d()},onKeyDown:f=>{f.key==="Enter"&&f.currentTarget.blur()}})}),s.jsx("div",{className:"hint",children:$n.promptFile})]})}function gJ(e){if(e.status==="loading")return Ut.appLoading;if(e.status==="unavailable")return Ut.promptUnavailable;const t=ZI(e.source),a=[];return e.mode==="passthrough"?a.push(r("客户端 system 原样出站(只靠指纹脱敏改写模板句)。")):a.push(r("{mode}生效:上游收到的 system 来自{source}{lines}。",{mode:e.mode==="custom"?r("替换"):r("追加"),source:t,lines:e.lines?r("({n} 行)",{n:e.lines}):""})),e.fileError&&a.push(`⚠️ ${e.fileError}`),a.join("")}function ZI(e){return e==="inline"?r("界面里编辑的正文"):e==="file"?r("提示词文件"):e==="builtin"?r("内置默认提示词"):""}function xJ(e){return r("已自动切换到最小中性提示词(撞了上游内容拦截,多半是 system 指纹误报),到 {until} 自动解除。",{until:e.degradeUntilText||Ut.degradeUntilFallback})+r("期间本模式自己的提示词不会发出;把提示词改好后可以立即解除。")}function bJ({item:e,label:t,locked:a,busy:o}){const[c,d]=x.useState(null);async function f(){const p=c;if(p!==null)try{p!==e.file&&await zW(e,p)}finally{d(null)}}return s.jsx("span",{className:"prompt-input",children:s.jsx($e,{id:`settings-prompt-file-${e.id}`,type:"text",placeholder:r("留空 = 用内置默认提示词"),"aria-label":r("{label} 提示词文件",{label:t}),value:c!==null?c:e.file,disabled:a||o,onChange:p=>d(p.target.value),onFocus:()=>d(e.file),onBlur:()=>{f()},onKeyDown:p=>{p.key==="Enter"&&p.currentTarget.blur()}})})}function vJ(e,t){if(!t)return r("未单独配置:模式、提示词文件与正文都跟随上面的全局配置(当前「{mode}」)。",{mode:zo.find(o=>o.value===e.mode)?.toastLabel??e.mode});if(e.mode==="passthrough")return r("客户端 system 原样出站。");const a=r("{mode}生效:上游收到的 system 来自{source}{lines}。",{mode:e.mode==="custom"?r("替换"):r("追加"),source:ZI(e.source),lines:e.lines?r("({n} 行)",{n:e.lines}):""});return e.fileError?`${a} ⚠️ ${e.fileError}`:a}function yJ({item:e,option:t,over:a,locked:o,busy:c}){const d=e.gateway,f=t.gatewayChars,p=f?r("约 {n} 字符",{n:f.toLocaleString("zh-CN")}):r("一段内置装配"),g=oJ(a);return s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{className:"prompt-gateway-label",children:r("网关自带")}),s.jsxs("span",{className:"prompt-input",children:[s.jsx(da,{id:`settings-prompt-gateway-${e.id}`,label:r("装上{size}的官方身份提示词",{size:p}),checked:d,disabled:o||c,onCheckedChange:v=>{UW(e.id,v)}}),s.jsx(lJ,{item:e,option:t,over:a,locked:o,busy:c})]}),s.jsxs("div",{className:d?"hint":"hint prompt-gateway-off",children:[d?t.gatewayNote:r("已关闭。{note}",{note:t.gatewayNote}),g?r(" 正文已改:{edited}(其余段用官方原文)。",{edited:g}):""]})]})}function jJ({prompt:e,locked:t,busy:a}){const o=e.options,c=new Map(e.providers.map(w=>[w.id,w])),d=[];for(const w of o)w.gatewayNote&&d.push(c.get(w.id)??{id:w.id,mode:e.mode,file:e.file,text:e.text,source:e.source,lines:e.lines,fileError:e.fileError,gateway:e.gateway[w.id]??!0,configured:!1});for(const w of e.providers)d.some(S=>S.id===w.id)||d.push({...w,gateway:e.gateway[w.id]??!0,configured:!0});const f=new Set(d.map(w=>w.id)),p=o.filter(w=>!w.gatewayNote&&!f.has(w.id)),[g,v]=x.useState(""),y=w=>o.find(S=>S.id===w)?.label||w,b=w=>o.find(S=>S.id===w),j=w=>b(w)?.gatewayNote||"";return s.jsxs(s.Fragment,{children:[d.map(w=>{const S=y(w.id),N=zo.find(D=>D.value===w.mode)?.optionLabel??w.mode,k=j(w.id),E=b(w.id);return s.jsxs(x.Fragment,{children:[s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:`settings-prompt-mode-${w.id}`,children:S}),s.jsxs("span",{className:"prompt-input",children:[s.jsxs(ft,{value:w.mode,onValueChange:D=>{D!=null&&String(D)&&LW(w,String(D))},children:[s.jsx(mt,{id:`settings-prompt-mode-${w.id}`,className:"w-[240px]",disabled:t||a,"aria-label":r("{label} 的提示词模式",{label:S}),children:s.jsx(pt,{children:N})}),s.jsx(ht,{children:zo.map(D=>s.jsx(qe,{value:D.value,children:D.optionLabel},D.value))})]}),s.jsx(bJ,{item:w,label:S,locked:t,busy:a}),s.jsx(rJ,{item:w,label:S,locked:t,busy:a}),w.configured?s.jsx(se,{variant:"outline",disabled:t||a,onClick:()=>{HW(w.id)},children:r("跟随默认")}):null]}),s.jsx("div",{className:"hint",children:vJ(w,w.configured)})]}),E&&k?s.jsx(yJ,{item:w,option:E,over:e.gatewayText[w.id],locked:t,busy:a}):null]},w.id)}),s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"settings-prompt-provider-add",children:r("添加提供商")}),s.jsx("span",{className:"prompt-input",children:s.jsxs(ft,{value:g,onValueChange:w=>{v("");const S=w==null?"":String(w);S&&_W(S)},children:[s.jsx(mt,{id:"settings-prompt-provider-add",className:"w-[240px]",disabled:t||a||p.length===0,"aria-label":r("添加要单独配置的提供商"),children:s.jsx(pt,{children:g?y(g):p.length?r("添加提供商…"):r("全部已配置")})}),s.jsx(ht,{children:p.map(w=>s.jsx(qe,{value:w.id,children:w.label},w.id))})]})}),s.jsx("div",{className:"hint",children:$n.promptProviders})]})]})}function wJ({snap:e}){const t=e.prompt,a=t.status!=="ready",o=e.busy==="prompt",c=zo.find(d=>d.value===t.mode)?.optionLabel??t.mode;return s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("系统提示词"),tip:ss.prompt,badge:t.status==="ready"?s.jsx(cn,{tone:"ok",children:t.mode==="passthrough"?r("透传"):r("已接管")}):t.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Br,{id:"btn-prompt-refresh",onClick:()=>{eJ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"retention-list",children:[s.jsxs("div",{className:"prompt-group",children:[r("全局配置"),s.jsx("span",{className:"note",children:r("所有未单独配置的提供商都用这一份")})]}),s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"settings-prompt-mode",children:r("模式")}),s.jsx("span",{className:"prompt-input",children:s.jsxs(ft,{value:t.mode,onValueChange:d=>{d!=null&&String(d)&&DW(String(d))},children:[s.jsx(mt,{id:"settings-prompt-mode",className:"w-[240px]",disabled:a||o,"aria-label":r("系统提示词模式"),children:s.jsx(pt,{children:c})}),s.jsx(ht,{children:zo.map(d=>s.jsx(qe,{value:d.value,children:d.optionLabel},d.value))})]})}),s.jsx("div",{className:"hint",children:$n.promptMode})]}),s.jsx(hJ,{prompt:t,locked:a,busy:o}),s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"btn-prompt-edit-body",children:r("提示词正文")}),s.jsx("span",{className:"prompt-input",children:s.jsx(sJ,{prompt:t,locked:a,busy:o})}),s.jsxs("div",{className:"hint",children:[$n.promptText,t.source==="inline"?r("(当前生效的就是这一份,{n} 行)",{n:t.lines}):t.text.trim()?r("(已存一份正文,{n} 行;切成「替换 / 追加」后生效)",{n:t.lines}):""]})]}),s.jsxs("div",{className:"prompt-group",children:[r("按提供商配置"),s.jsx("span",{className:"note",children:r("只列单独配置过的家,其余沿用上面的全局配置")})]}),s.jsx(jJ,{prompt:t,locked:a,busy:o}),t.status==="ready"&&t.degradeActive?s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{children:r("内容拦截降级")}),s.jsx("span",{className:"prompt-input",children:s.jsx(se,{id:"btn-prompt-clear-degrade",variant:"outline",disabled:o,onClick:()=>{FW()},children:r("立即解除")})}),s.jsx("div",{className:"hint",children:xJ(t)})]}):null]}),s.jsx("div",{className:"settings-state",children:gJ(t)}),s.jsx("div",{className:"hint retention-note",children:$n.prompt})]})]})}function SJ(e){if(e.status==="loading")return Ut.appLoading;if(e.status==="unavailable")return Ut.debugUnavailable;const t=e.count!==null&&e.limit!==null?r("已保存 {count} / {limit} 条报文(超出后丢弃最旧的)。",{count:e.count,limit:e.limit}):"";return e.on?`${Ut.debugOn}${t}${r("凭据类请求头已脱敏。")}`:Ut.debugOff}function NJ({snap:e}){return s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("请求超时"),tip:ss.timeouts,badge:Tp(e.timeouts),actions:s.jsx(Br,{id:"btn-timeouts-refresh",onClick:()=>{KW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"retention-list",children:SI.map(t=>s.jsx(Cp,{field:t,value:e.timeouts.values?.[t.key]??null,disabled:e.busy==="timeouts",onCommit:a=>yW(t,a)},t.key))}),s.jsx("div",{className:"hint retention-note",children:$n.timeouts})]})]})}function kJ({snap:e}){return s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("请求重试"),tip:ss.retry,badge:Tp(e.retry),actions:s.jsx(Br,{id:"btn-retry-refresh",onClick:()=>{GW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"retention-list",children:[wI.map(t=>s.jsx(Cp,{field:t,value:e.retry.values?.[t.key]??null,disabled:e.busy==="retry",onCommit:a=>gW(t,a)},t.key)),s.jsx(mJ,{codes:e.retryCodes,status:e.retry.status,busy:e.busy==="codes"||e.busy==="retry"})]}),s.jsx("div",{className:"hint retention-note",children:$n.retry})]})]})}const CJ={routingFailoverBackoff:"failoverBackoff",routingSink:"sink",routingBreakerEnabled:"breakerEnabled"};function TJ({snap:e}){const t=e.routing,a=e.busy==="routing"||t.status!=="ready",o=Cx.find(d=>d.value===t.strategy)?.value??"order",c=Tx.find(d=>d.value===t.sticky)?.value??"auto";return s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("账号路由"),tip:ss.routing,badge:t.status==="ready"?void 0:t.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Br,{id:"btn-routing-refresh",onClick:()=>{QW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"retention-list",children:[s.jsx("div",{className:"prompt-group",children:r("选路规则")}),s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{children:r("路由策略")}),s.jsxs("div",{className:"routing-row",children:[s.jsx("span",{className:"tip-q","data-tip":Cx.find(d=>d.value===o)?.tip}),s.jsx(In,{options:Cx.map(d=>({value:d.value,label:d.label})),value:o,disabled:a,"aria-label":r("路由策略"),onValueChange:d=>{cS({routingStrategy:String(d)})}})]})]}),s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{children:r("会话粘性")}),s.jsxs("div",{className:"routing-row",children:[s.jsx("span",{className:"tip-q","data-tip":Tx.find(d=>d.value===c)?.tip}),s.jsx(In,{options:Tx.map(d=>({value:d.value,label:d.label})),value:c,disabled:a,"aria-label":r("会话粘性"),onValueChange:d=>{cS({routingSticky:String(d)})}})]})]}),s.jsxs("div",{className:"prompt-group",children:[r("自愈保护"),s.jsx("span",{className:"note",children:r("默认值通常够用,出问题时才需要调")})]}),VZ.map(d=>{const f=`route-protection-${d.key}`;return s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:f,children:d.label}),s.jsxs("div",{className:"routing-row",children:[s.jsx("span",{className:"tip-q","data-tip":d.tip}),s.jsx(ms,{id:f,checked:t[CJ[d.key]],disabled:a,onCheckedChange:p=>{cS({[d.key]:p})}})]})]},d.key)})]}),s.jsx("div",{className:"hint retention-note",children:$n.routing})]})]})}function EJ({snap:e}){return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("排队等待"),tip:ss.queue,badge:Tp(e.queue),actions:s.jsx(Br,{id:"btn-queue-refresh",onClick:()=>{YW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"retention-list",children:NI.map(t=>s.jsx(Cp,{field:t,value:e.queue.values?.[t.key]??null,disabled:e.busy==="queue",onCommit:a=>cW(t,a)},t.key))}),s.jsx("div",{className:"hint retention-note",children:$n.queue})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("验证码令牌池"),tip:ss.captchaPool,badge:Tp(e.captchaPool),actions:s.jsx(Br,{id:"btn-captcha-pool-refresh",onClick:()=>{XW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"retention-list",children:RI.map(t=>s.jsx(Cp,{field:t,value:e.captchaPool.values?.[t.key]??null,disabled:e.busy==="captchaPool",onCommit:a=>uW(t,a)},t.key))}),s.jsx("div",{className:"hint retention-note",children:$n.captchaPool})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("models.dev 模型元数据"),tip:ss.modelsDev,badge:e.modelsDev.status==="ready"?s.jsx(cn,{tone:"ok",children:r("{count} 条",{count:Number(e.modelsDev.count).toLocaleString("zh-CN")})}):e.modelsDev.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Br,{id:"btn-modelsdev-refresh",onClick:()=>{TW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx(da,{id:"settings-modelsdev",label:r("用 models.dev 补齐上游没声明的模型能力与思考档位(联网刷新,内嵌快照始终生效)"),checked:e.modelsDev.enabled,disabled:e.modelsDev.status!=="ready"||e.busy==="modelsDev",onCheckedChange:t=>{CW(t)}}),s.jsx("div",{className:"settings-state",children:MZ(e.modelsDev)}),s.jsx("div",{className:"hint retention-note",children:$n.modelsDev})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("指纹脱敏"),tip:ss.sanitize,badge:e.sanitize.status==="ready"?s.jsx(cn,{tone:"ok",children:r("已生效")}):e.sanitize.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Br,{id:"btn-sanitize-refresh",onClick:()=>{WW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"settings-switches",children:s.jsx(da,{id:"settings-sanitize",label:r("剥离上游审核黑名单指纹(改写请求体里的模板句与表头)"),checked:e.sanitize.on,disabled:e.sanitize.status!=="ready"||e.busy==="sanitize",onCheckedChange:t=>{wW(t)}})}),s.jsx("div",{className:"settings-state",children:e.sanitize.status==="loading"?Ut.appLoading:e.sanitize.status==="unavailable"?Ut.sanitizeUnavailable:e.sanitize.on?Ut.sanitizeOn:Ut.sanitizeOff}),s.jsx("div",{className:"hint retention-note",children:$n.sanitize})]})]}),s.jsx(RJ,{snap:e}),s.jsx(wJ,{snap:e}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("调试模式"),tip:ss.debug,badge:e.debug.status==="ready"?s.jsx(cn,{tone:"ok",children:r("已生效")}):e.debug.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Br,{id:"btn-debug-refresh",onClick:()=>{ZW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"settings-switches",children:s.jsx(da,{id:"settings-debug-mode",label:r("保存上游原始报文(请求头、请求体、响应头、响应体)"),checked:e.debug.on,disabled:e.debug.status!=="ready"||e.busy==="debug",onCheckedChange:t=>{jW(t)}})}),s.jsx("div",{className:"settings-state",children:SJ(e.debug)}),s.jsx("div",{className:"hint retention-note",children:$n.debug})]})]})]})}function WI(e){const t=Object.entries(e.defaults).map(([a,o])=>({key:a,value:a in e.overrides?e.overrides[a]:o,isDefault:!0}));for(const[a,o]of Object.entries(e.overrides))a in e.defaults||t.push({key:a,value:o,isDefault:!1});return t}function AJ(e,t){const a=Object.keys(e);return a.length!==Object.keys(t).length?!1:a.every(o=>e[o]===t[o])}function RJ({snap:e}){const t=e.clineHeaders,[a,o]=x.useState(()=>WI(t));x.useEffect(()=>{o(WI(t))},[t]);const c=e.busy==="clineHeaders",d=t.status==="ready";function f(v,y){o(b=>b.map((j,w)=>w===v?{...j,...y}:j))}function p(){const v={};for(const y of a){const b=y.key.trim();b&&(y.isDefault?y.value!==(t.defaults[b]??"")&&(v[b]=y.value):y.value!==""&&(v[b]=y.value))}return v}const g=d&&!AJ(p(),t.overrides);return s.jsx(iJ,{title:r("Cline 伪装头"),tip:ss.clineHeaders,badge:t.status==="ready"?s.jsx(cn,{tone:"ok",children:r("已生效")}):t.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Br,{id:"btn-cline-headers-refresh",onClick:()=>{SW()}}),children:s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"retention-list",children:[d?a.map((v,y)=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx($e,{className:"w-[190px] shrink-0 font-mono text-[13px]",value:v.key,readOnly:v.isDefault,disabled:c,placeholder:"X-Custom-Header",onChange:b=>f(y,{key:b.target.value})}),s.jsx($e,{className:"flex-1 font-mono text-[13px]",value:v.value,disabled:c,placeholder:v.isDefault?r("值(留空 = 不发送)"):r("值"),onChange:b=>f(y,{value:b.target.value})}),s.jsx(se,{variant:"ghost",disabled:c,onClick:()=>{v.isDefault?f(y,{value:t.defaults[v.key]??""}):o(b=>b.filter((j,w)=>w!==y))},children:v.isDefault?r("还原"):r("删除")})]},String(y))):null,s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(se,{variant:"outline",disabled:c||!d,onClick:()=>o(v=>[...v,{key:"",value:"",isDefault:!1}]),children:r("添加自定义头")}),s.jsx("div",{className:"flex-1"}),s.jsx(se,{variant:"ghost",disabled:c||!d||Object.keys(t.overrides).length===0,onClick:()=>{GI({})},children:r("恢复默认")}),s.jsx(se,{disabled:c||!d||!g,onClick:()=>{GI(p())},children:r("保存")})]})]}),s.jsx("div",{className:"settings-state",children:t.status==="loading"?Ut.appLoading:t.status==="unavailable"?r("未能读取 Cline 伪装头设置,请稍后重试"):g?r("有未保存的修改"):r("{n} 个头将随每个 Cline 请求发送",{n:Object.keys(t.effective).length})+(Object.keys(t.overrides).length>0?r("({n} 项被覆盖)",{n:Object.keys(t.overrides).length}):r("(全部为默认值)"))}),s.jsx("div",{className:"hint retention-note",children:$n.clineHeaders})]})})}function OJ({snap:e}){const[t,a]=x.useState(!1);async function o(){a(!0),await $W()||a(!1)}return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("网关跨域访问(CORS)"),tip:ss.cors,badge:e.cors.status==="ready"?e.cors.on?s.jsx(cn,{tone:"bad",children:r("已开启")}):s.jsx(cn,{tone:"ok",children:r("已关闭")}):e.cors.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Br,{id:"btn-cors-refresh",onClick:()=>{JW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"settings-switches",children:s.jsx(da,{id:"settings-cors",label:r("允许浏览器里的页面跨来源调用网关(/v1/*)"),checked:e.cors.on,disabled:e.cors.status!=="ready"||e.busy==="cors",onCheckedChange:c=>{NW(c)}})}),s.jsx("div",{className:"settings-state",children:e.cors.status==="loading"?Ut.appLoading:e.cors.status==="unavailable"?Ut.corsUnavailable:e.cors.on?Ut.corsOn:Ut.corsOff}),s.jsx("div",{className:"hint retention-note",children:$n.cors})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("机器人校验")}),s.jsxs("div",{className:"panel-body",children:[s.jsx(da,{id:"settings-captcha",label:r("登录 / 注册需要通过 ALTCHA 人机验证(工作量证明)"),checked:e.captcha.enabled,disabled:!e.captcha.available||e.busy==="captcha",onCheckedChange:c=>{kW(c)}}),s.jsx("div",{className:"hint",children:$n.captcha})]})]}),e.panelLogin?s.jsxs("section",{className:"panel",id:"panel-login-section",children:[s.jsx(Qn,{title:r("面板登录")}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"hint",children:$n.panelLogin}),s.jsx("div",{className:"mt-2.5",children:s.jsx(se,{id:"btn-panel-logout",variant:"outline",disabled:t,onClick:()=>{o()},children:r("退出登录")})})]})]}):null]})}function Ep({label:e,value:t}){return s.jsxs("div",{className:"storage-count",children:[s.jsx("span",{className:"k",children:e}),s.jsx("span",{className:"v",children:t})]})}function MJ(e){return e.status==="loading"?s.jsx(cn,{tone:"idle",children:r("检测中…")}):e.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:e.available?"ok":"bad",children:e.available?r("已生效"):r("数据库不可用")})}function DJ({snap:e}){const t=e.busy,a=e.storage,o=tt().workbuddyDesktop?.platform==="web",c=a.status==="ready",d=c&&a.available,f=c&&a.file?a.file:"—",p=g=>d&&g!==null?UZ(g):"—";return s.jsxs(s.Fragment,{children:[!o&&s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("整库备份 / 恢复"),tip:ss.backup,actions:s.jsxs(s.Fragment,{children:[s.jsx(se,{id:"btn-settings-db-export",variant:"outline",disabled:t==="dbExport"||t==="dbImport",onClick:()=>{nW()},children:r(t==="dbExport"?"备份中…":"备份整库")}),s.jsx(se,{id:"btn-settings-db-restore",variant:"destructive",disabled:t==="dbExport"||t==="dbImport",onClick:()=>sW(),children:r(t==="dbImport"?"恢复中…":"恢复整库")})]})}),s.jsxs("div",{className:"panel-body",children:[e.dbWarning?s.jsxs("div",{className:"danger-zone",id:"settings-db-warning",children:[s.jsx("strong",{children:r("⚠️ 密钥警告")}),s.jsx("br",{}),e.dbWarning]}):null,s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"settings-db-include-logs",children:r("包含日志与调试报文")}),s.jsx(ms,{id:"settings-db-include-logs",checked:e.dbIncludeLogs,disabled:t!==null,onCheckedChange:tW}),s.jsx("div",{className:"hint",children:r("取消勾选后只备份业务数据(账号、配置与余额记录),文件显著变小;事件日志、请求统计与调试报文不会进备份文件。")})]}),s.jsx("div",{className:"danger-zone",children:s.jsx("strong",{children:$n.backupDanger})})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("账号导入 / 导出"),tip:ss.io,actions:s.jsxs(s.Fragment,{children:[s.jsx(se,{id:"btn-settings-export",variant:"outline",disabled:t==="export",onClick:()=>{JZ()},children:r(t==="export"?"导出中…":"导出账号")}),s.jsx(se,{id:"btn-settings-import",variant:"default",disabled:t==="import",onClick:()=>{eW()},children:r(t==="import"?"导入中…":"导入账号")})]})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"danger-zone",children:[s.jsx("strong",{children:r("导出文件内含 accessToken / refreshToken / apiKey 等凭证与自定义提供商定义")}),r(",可直接用于登录。请妥善保管,不要外传或上传到公共位置。")]}),e.ioFailure?s.jsx("div",{className:"io-result",children:s.jsxs("span",{className:"text-destructive",children:[r("失败 {n} 个:{detail}",{n:e.ioFailure.failed,detail:e.ioFailure.detail}),e.ioFailure.more?r(" 等"):""]})}):null]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("数据保留"),tip:ss.retention,badge:Tp(e.retention),actions:s.jsx(Br,{id:"btn-retention-refresh",onClick:()=>{qW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"retention-list",children:eS.map(g=>s.jsx(Cp,{field:g,value:e.retention.values?.[g.key]??null,disabled:e.busy==="retention",onCommit:v=>oW(g,v)},g.key))}),s.jsx("div",{className:"hint retention-note",children:$n.retention})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("数据存储"),tip:ss.storage,badge:MJ(a),actions:s.jsx(Br,{id:"btn-storage-refresh",onClick:()=>{tJ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"retention-list",children:[s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"storage-db-path",children:r("数据库文件")}),s.jsx("span",{className:"storage-line",children:s.jsx("span",{className:"storage-path",id:"storage-db-path",title:f,children:f})}),s.jsx("div",{className:"hint",children:$n.storageFile})]}),s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"storage-db-size",children:r("占用大小")}),s.jsx("span",{className:"storage-line",children:s.jsx("span",{className:"storage-path",id:"storage-db-size",children:d?AI(a.bytes):"—"})}),s.jsx("div",{className:"hint",children:$n.storageSize})]})]}),s.jsxs("div",{className:"retention-list storage-counts",children:[s.jsx(Ep,{label:r("账号"),value:p(a.accounts)}),s.jsx(Ep,{label:r("事件日志"),value:p(a.logs)}),s.jsx(Ep,{label:r("请求记录"),value:p(a.requests)}),s.jsx(Ep,{label:r("报表天数"),value:p(a.dailyDays)}),s.jsx(Ep,{label:r("调试报文"),value:p(a.debug)})]}),s.jsx("div",{className:"hint retention-note",children:$n.storage})]})]})]})}const IJ=[{title:r("问题反馈"),desc:r("遇到 Bug、报错或异常行为"),cta:r("去反馈"),url:"https://github.com/aimod-cc/agent2api/issues/new?template=bug_report.yml"},{title:r("功能建议"),desc:r("想要的新功能或改进想法"),cta:r("提建议"),url:"https://github.com/aimod-cc/agent2api/issues/new?template=feature_request.yml"},{title:r("请求提供商 / 模型支持"),desc:r("希望接入新的提供商或模型"),cta:r("去申请"),url:"https://github.com/aimod-cc/agent2api/issues/new?template=provider_request.yml"}];function PJ(){return s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("反馈与需求")}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"hint",children:r("点下面的入口会用系统默认浏览器打开 GitHub 的对应表单(需要 GitHub 账号,模板已预设好,填完直接提交即可)。")}),s.jsx("div",{className:"mt-3 flex flex-col gap-2",children:IJ.map(e=>s.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-hairline bg-surface-2 px-3 py-2.5",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12.5px] text-foreground",children:e.title}),s.jsx("div",{className:"mt-0.5 text-[12px] text-subtle",children:e.desc})]}),s.jsx(se,{variant:"outline",size:"sm",onClick:()=>{DZ(e.url)},children:e.cta})]},e.url))})]})]})}function _J({confirm:e}){const t=x.useRef(null);return s.jsx(Qt,{open:e!==null,onOpenChange:a=>{a||Mx(!1)},children:s.jsxs(Zt,{className:"w-[min(440px,calc(100vw-48px))]",initialFocus:t,children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("确认缩短保留天数")})}),s.jsx(Bt,{children:s.jsxs("div",{className:"danger-zone",children:[e?.head,s.jsx("br",{}),s.jsx("strong",{children:r("超出的历史数据会被立即删除,且不可恢复。")}),r("确定继续?")]})}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{ref:t,variant:"outline",onClick:()=>Mx(!1),children:r("取消")}),s.jsx(se,{variant:"destructive",onClick:()=>Mx(!0),children:r("继续并清理")})]})]})})}const wS={enable:{title:r("开启局域网访问"),body:()=>s.jsxs(s.Fragment,{children:[r("为了安全,开启前需要先注册一个"),s.jsx("b",{children:r("面板管理员账号")}),r("(已注册过会跳过这一步,直接生效)。"),s.jsx("br",{}),r("开启后网关将监听所有网卡,同一局域网内的设备即可把 API 地址指向本机 IP 一起使用;管理接口从此要求管理员会话或网关 Key,转发接口在没有一把启用的 Key 时也会拒绝服务(届时会自动创建一把名为「默认」的 Key)。"),s.jsx("br",{}),s.jsx("strong",{children:r("保存后应用将重启以生效。")}),r("确定继续?")]}),label:r("继续")},disable:{title:r("关闭局域网访问"),body:()=>s.jsxs(s.Fragment,{children:[r("关闭后网关回到只监听 127.0.0.1,局域网内的设备将无法继续访问;已配置的网关 Key 与账号都不受影响。"),s.jsx("br",{}),s.jsx("strong",{children:r("保存后应用将重启以生效。")}),r("确定继续?")]}),label:r("关闭并重启")},panel:{title:r("变更网页管理面板"),body:e=>e?s.jsxs(s.Fragment,{children:[r("开放后,局域网内其他设备的浏览器打开本机 IP 即可进入管理面板(需管理员账号登录)。"),s.jsx("br",{}),s.jsx("strong",{children:r("保存后应用将重启以生效。")}),r("确定继续?")]}):s.jsxs(s.Fragment,{children:[r("关闭后,管理界面不再从局域网提供,只有本机的桌面程序可以管理;已开启的 API 转发不受影响。"),s.jsx("br",{}),s.jsx("strong",{children:r("保存后应用将重启以生效。")}),r("确定继续?")]}),label:r("保存并重启")}};function LJ({confirm:e}){const t=x.useRef(null);return s.jsx(Qt,{open:e!==null,onOpenChange:a=>{a||iS(!1)},children:s.jsxs(Zt,{className:"w-[min(440px,calc(100vw-48px))]",initialFocus:t,children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("恢复整库备份")})}),s.jsx(Bt,{children:s.jsxs("div",{className:"danger-zone",children:[r("本机的全部数据(账号、网关配置、日志统计与桌面设置)将被所选备份文件"),s.jsx("strong",{children:r("整体替换")}),r(",包括恢复后需要重新登录管理面板。"),s.jsx("br",{}),s.jsx("strong",{children:r("替换前会自动把当前数据备份到配置目录的 backups/ 文件夹。")}),r("确定继续?")]})}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{ref:t,variant:"outline",onClick:()=>iS(!1),children:r("取消")}),s.jsx(se,{variant:"destructive",onClick:()=>iS(!0),children:r("选择备份文件并恢复")})]})]})})}function zJ({confirm:e,register:t}){const a=x.useRef(null),o=x.useRef(null),c=x.useRef(null),d=e!==null||t!==null,f=()=>{t!==null?PI():oS(!1)},p=()=>{WZ(o.current?.value??"",c.current?.value??"")};return s.jsx(Qt,{open:d,onOpenChange:g=>{g||f()},children:s.jsx(Zt,{className:"w-[min(480px,calc(100vw-48px))]",initialFocus:a,children:t!==null?s.jsxs(s.Fragment,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("注册管理员账号")})}),s.jsxs(Bt,{children:[s.jsx("div",{children:r("局域网开放后,管理接口要求登录。请设置管理员账号与密码,注册完成会直接继续开启流程。")}),s.jsxs("form",{onSubmit:g=>{g.preventDefault(),t.busy||p()},children:[s.jsx(Je,{htmlFor:"lan-admin-name",className:"mt-3.5 mb-[5px] block text-[12.5px]",children:r("账号")}),s.jsx($e,{ref:o,id:"lan-admin-name",autoComplete:"username",placeholder:r("管理员账号"),disabled:t.busy}),s.jsx(Je,{htmlFor:"lan-admin-password",className:"mt-3.5 mb-[5px] block text-[12.5px]",children:r("密码")}),s.jsx($e,{ref:c,id:"lan-admin-password",type:"password",autoComplete:"new-password",placeholder:r("至少 8 位"),disabled:t.busy})]}),s.jsx("div",{className:"mt-3 min-h-5 text-[13px] whitespace-pre-wrap text-destructive",children:t.error})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{ref:a,variant:"outline",onClick:PI,disabled:t.busy,children:r("取消")}),s.jsx(se,{onClick:p,disabled:t.busy,children:t.busy?r("正在注册…"):r("注册并开启")})]})]}):s.jsxs(s.Fragment,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:e?wS[e.mode].title:""})}),s.jsx(Bt,{children:s.jsx("div",{children:e?wS[e.mode].body(e.panel):null})}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{ref:a,variant:"outline",onClick:()=>oS(!1),children:r("取消")}),s.jsx(se,{onClick:()=>oS(!0),children:e?wS[e.mode].label:r("继续")})]})]})})})}function BJ(){const e=qZ(),t=x.useRef(null);x.useEffect(()=>{const o=t.current;o&&(o.scrollTop=0)},[e.scrollReset]);const a=o=>e.category===o?"settings-pane active":"settings-pane";return s.jsxs("div",{className:"settings-layout",children:[s.jsx("nav",{className:"settings-nav",id:"settings-nav",children:Nx.map(o=>s.jsxs("button",{type:"button",className:e.category===o.id?"settings-nav-item active":"settings-nav-item","data-cat":o.id,onClick:()=>GZ(o.id),children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:QI(o.icon,17)}}),o.label]},o.id))}),s.jsxs("div",{className:"settings-panes",ref:t,children:[s.jsx("div",{className:a("general"),"data-cat":"general",children:s.jsx(uJ,{snap:e})}),s.jsx("div",{className:a("display"),"data-cat":"display",children:s.jsx(fJ,{})}),s.jsx("div",{className:a("gateway"),"data-cat":"gateway",children:s.jsx(EJ,{snap:e})}),s.jsx("div",{className:a("routing"),"data-cat":"routing",children:s.jsx(TJ,{snap:e})}),s.jsx("div",{className:a("retry"),"data-cat":"retry",children:s.jsx(kJ,{snap:e})}),s.jsx("div",{className:a("timeout"),"data-cat":"timeout",children:s.jsx(NJ,{snap:e})}),s.jsx("div",{className:a("security"),"data-cat":"security",children:s.jsx(OJ,{snap:e})}),s.jsx("div",{className:a("data"),"data-cat":"data",children:s.jsx(DJ,{snap:e})}),s.jsx("div",{className:a("feedback"),"data-cat":"feedback",children:s.jsx(PJ,{})}),s.jsx("div",{className:a("about"),"data-cat":"about"})]}),s.jsx(_J,{confirm:e.retentionConfirm}),s.jsx(LJ,{confirm:e.dbBackupConfirm}),s.jsx(zJ,{confirm:e.lanConfirm,register:e.lanRegister})]})}const JI='.page[data-page="settings"]';let SS=null;function eP(){if(SS)return;const e=document.querySelector(JI);e&&(e.replaceChildren(),SS=vn.createRoot(e),ks.flushSync(()=>{SS?.render(s.jsx(BJ,{}))}))}MI(),document.querySelector(JI)?eP():document.addEventListener("DOMContentLoaded",eP,{once:!0}),window.wbSettingsPanel={load:jS,render:aS,renderRetention:Ax,renderRetry:hW,renderDebug:Px,renderSanitize:_x,renderPrompt:Gu,renderStorage:yS,showCategory:rS},tt().wbApp?.currentPage==="settings"&&jS();const tP="agent2api-col-config:",NS=[{value:"left",label:r("左")},{value:"center",label:r("中")},{value:"right",label:r("右")}],HJ=e=>NS.some(t=>t.value===e),UJ=NS.map(e=>`ta-${e.value}`),nP="colset-dragging",sP="open";let kS=null;const rP="grid grid-cols-[18px_minmax(78px,1fr)_44px_minmax(106px,auto)] items-center gap-2";function aP(){return window}const Bx=new Map;function CS(e){return e.columns.map(t=>({key:t.key,visible:t.visible!==!1,align:t.align||"left"}))}function VJ(e,t){const a=Array.isArray(t),o=!a&&t&&typeof t=="object"?t:null,c=a?t:Array.isArray(o?.items)?o.items:[],d=o?.defaults&&typeof o.defaults=="object"?o.defaults:null,f=new Map(e.columns.map(y=>[y.key,y])),p=new Map(CS(e).map(y=>[y.key,y])),g=[],v=new Set;for(const y of c){const b=y&&typeof y=="object"?y:{},j=String(b.key||"");if(!f.has(j)||v.has(j))continue;v.add(j);const w=f.get(j),S=w.align||"left",N=d?d[j]??S:w.legacyAlign??S,k=HJ(b.align)?b.align:null;g.push({key:j,visible:b.visible!==!1,align:k&&k!==N?k:S})}for(const y of e.columns)v.has(y.key)||FJ(g,e,{...p.get(y.key)});return g}function FJ(e,t,a){const o=t.columns.findIndex(c=>c.key===a.key);for(let c=o-1;c>=0;c-=1){const d=e.findIndex(f=>f.key===t.columns[c].key);if(d>=0){e.splice(d+1,0,a);return}}e.unshift(a)}function $J(e){try{const t=localStorage.getItem(tP+e.id);return VJ(e,t?JSON.parse(t):[])}catch{return CS(e)}}function qJ(e){try{const t={};for(const a of e.columns)t[a.key]=a.align||"left";localStorage.setItem(tP+e.id,JSON.stringify({v:2,defaults:t,items:e.config}))}catch{}}const GJ=e=>Bx.get(e)?.config||null,KJ=(e,t)=>e.columns.find(a=>a.key===t)?.label||t;function lP(e,t){const a=Bx.get(e);if(!a)return t;const o=new Map(t.map(c=>[c.key,c]));return a.config.filter(c=>c.visible&&o.has(c.key)).map(c=>({...o.get(c.key),align:c.align}))}function Ap(e,{silent:t=!1}={}){qJ(e),t||e.onChange?.(e.config),Il&&Il.id===e.id&&Il.repaint()}let Il=null;function Hx(){if(!Il)return;const e=Il;Il=null,e.destroy()}function YJ(e,t){Hx();const a=document.createElement("div");document.body.append(a);const o=vn.createRoot(a),c={current:null};Il={id:e.id,spec:e,repaint:()=>c.current?.(),destroy:()=>{o.unmount(),a.remove()}},o.render(s.jsx(JJ,{spec:e,anchor:t,repaintRef:c,onClose:Hx}))}function XJ(e,t){Il&&Il.id===e.id?Hx():YJ(e,t)}function QJ(e,t,a){const o=[...e],[c]=o.splice(t,1);return o.splice(a,0,c),o}function ZJ(e,t,a,o){const c=document.elementFromPoint(e,t)?.closest?.("[data-col-key]");if(!c||!a||!a.contains(c))return"";const d=c.getAttribute("data-col-key")||"";return o.some(f=>f.key===d)?d:""}const WJ=s.jsxs("svg",{viewBox:"0 0 24 24",width:13,height:13,fill:"currentColor","aria-hidden":"true",className:"block",children:[s.jsx("circle",{cx:"9",cy:"6",r:"1.6"}),s.jsx("circle",{cx:"15",cy:"6",r:"1.6"}),s.jsx("circle",{cx:"9",cy:"12",r:"1.6"}),s.jsx("circle",{cx:"15",cy:"12",r:"1.6"}),s.jsx("circle",{cx:"9",cy:"18",r:"1.6"}),s.jsx("circle",{cx:"15",cy:"18",r:"1.6"})]});function JJ({spec:e,anchor:t,repaintRef:a,onClose:o}){const c=t,d=x.useRef(null),[f,p]=x.useState(null),g=x.useRef(null),[,v]=x.useState(0),y=x.useCallback(()=>v(N=>N+1),[]);x.useLayoutEffect(()=>(a.current=y,()=>{a.current=null}),[y,a]),x.useEffect(()=>(c.classList.add(sP),c.setAttribute("aria-expanded","true"),()=>{c.classList.remove(sP),c.setAttribute("aria-expanded","false")}),[c]),x.useEffect(()=>{const N=()=>{const k=c.getBoundingClientRect();(!c.isConnected||!k.width||k.bottom<=0||k.top>=window.innerHeight)&&o()};return window.addEventListener("scroll",N,!0),window.addEventListener("resize",N),()=>{window.removeEventListener("scroll",N,!0),window.removeEventListener("resize",N)}},[c,o]),x.useEffect(()=>()=>{const N=g.current;N&&(N.teardown(),Ap(e))},[e]);function b(N,k){const E=e.config.find(D=>D.key===N);E&&(!k&&e.config.filter(D=>D.visible).length<=1||(E.visible=k,Ap(e)))}function j(N,k){const E=e.config.find(D=>D.key===N);!E||E.align===k||(E.align=k,Ap(e))}function w(){e.config=CS(e),Ap(e)}function S(N,k){k.preventDefault(),g.current?.teardown(),p(N),document.body.classList.add(nP);const E=d.current;function D(){window.removeEventListener("pointermove",C),window.removeEventListener("pointerup",A),document.body.classList.remove(nP),g.current=null,p(null)}function C(R){const I=ZJ(R.clientX,R.clientY,E,e.config);if(!I||I===N)return;const P=e.config.findIndex(_=>_.key===N),O=e.config.findIndex(_=>_.key===I);P<0||O<0||(e.config=QJ(e.config,P,O),y())}function A(){D(),Ap(e)}g.current={teardown:D},window.addEventListener("pointermove",C),window.addEventListener("pointerup",A)}return s.jsx(pf,{open:!0,modal:!1,onOpenChange:(N,k)=>{N||(k?.reason==="outside-press"&&(kS=k.event??null),o())},children:s.jsxs(mf,{anchor:c,side:"bottom",align:"end",sideOffset:6,collisionPadding:8,className:"w-[336px]","aria-label":r("{name}的列设置",{name:e.label||e.id}),children:[s.jsxs("div",{className:Ue(rP,"border-b border-hairline px-3 pt-[9px] pb-[7px]","text-[10.5px] font-semibold tracking-[.05em] text-muted-foreground"),children:[s.jsx("span",{}),s.jsx("span",{className:"text-center",children:r("列")}),s.jsx("span",{className:"text-center",children:r("显示")}),s.jsx("span",{className:"text-center",children:r("对齐")})]}),s.jsx("div",{ref:d,className:"min-h-0 flex-1 overflow-y-auto px-3 py-1",children:e.config.map(N=>{const k=KJ(e,N.key),E=f===N.key;return s.jsxs("div",{"data-col-key":N.key,className:Ue(rP,"rounded-sm py-[5px] hover:bg-nav-hover",E&&"opacity-50"),children:[s.jsx("span",{className:"flex cursor-grab items-center justify-center text-muted-foreground opacity-50 hover:opacity-100",title:r("按住拖动调整列顺序"),onPointerDown:D=>S(N.key,D),children:WJ}),s.jsx("span",{className:"min-w-0 truncate text-xs text-foreground",title:k,children:k}),s.jsx(ms,{className:"justify-self-center",checked:N.visible,onCheckedChange:D=>b(N.key,D),"aria-label":r("显示「{label}」列",{label:k}),title:N.visible?r("这一列正在显示"):r("这一列已隐藏")}),s.jsx(In,{className:"w-full justify-center",options:NS,value:N.align,onValueChange:D=>j(N.key,D),"aria-label":r("「{label}」列的对齐",{label:k})})]},N.key)})}),s.jsxs("div",{className:"flex items-center gap-2 border-t border-hairline px-3 pt-2 pb-[9px]",children:[s.jsx("span",{className:"flex-1 text-[11px] text-muted-foreground",children:r("拖动 ⋮⋮ 调整顺序")}),s.jsx(se,{variant:"outline",size:"sm",onClick:w,children:r("恢复默认")})]})]})})}function eee(e,t){e&&(e.classList.remove(...UJ),e.classList.add(`ta-${t}`))}const oP=new Map;function tee(e,t){const a=oP.get(e);if(a&&a.table===t&&a.row.isConnected)return a;const o=t?.querySelector("thead tr");if(!o)return null;const c=t?.querySelector("colgroup")??null,d={table:t,row:o,group:c,ths:new Map([...o.querySelectorAll("th[data-col]")].map(f=>[f.getAttribute("data-col")||"",f])),cols:new Map([...c?.querySelectorAll("col[data-col]")||[]].map(f=>[f.getAttribute("data-col")||"",f]))};return oP.set(e,d),d}function nee(e,t,a){const o=Bx.get(e);if(!o||!t)return;const c=tee(e,t);if(!c)return;const{row:d,group:f,ths:p,cols:g}=c;for(const v of o.config){const y=p.get(v.key);if(!y)continue;const b=g.get(v.key);if(!v.visible||a?.has(v.key)){y.remove(),b?.remove();continue}eee(y,v.align),d.appendChild(y),b&&f&&f.appendChild(b)}aP().wbTableColumns?.repaint?.(e)}function see(e){const t=document.createElement("button");return t.type="button",t.className=`sm colset-btn${e.buttonClass?` ${e.buttonClass}`:""}`,t.id=`btn-colset-${e.id}`,t.title=r("调整「{name}」的列:显示 / 隐藏、顺序、对齐",{name:e.label||e.id}),t.innerHTML=`${aP().wbIcons?.icon?.("settings",14)||""}${r("列设置")}`,t.setAttribute("aria-haspopup","dialog"),t.setAttribute("aria-expanded","false"),t.addEventListener("click",a=>{if(kS===a){kS=null;return}XJ(e,t)}),t}function ree(e){return(typeof e.mount=="function"?e.mount():e.mount?document.querySelector(e.mount):null)||null}function aee(e){const t={...e,config:$J(e)};Bx.set(e.id,t);const a=ree(e),o=see(t);return a&&(e.buttonPlacement==="last"?a.appendChild(o):a.insertBefore(o,a.firstChild)),{apply:c=>lP(e.id,c),config:()=>t.config}}window.wbColSettings={register:aee,apply:lP,configOf:GJ,syncStaticHead:nee,close:Hx};function sl(){return window}const lee=new Set(["updateCheck"]);function iP(e){return(Array.isArray(e?.tasks)?e.tasks:[]).filter(a=>!lee.has(a.id))}const oee=2e4,cP=1,iee=" · ";function Ku(e,t){sl().wbApp?.toast?.(e,t)}function Ux(e){return e instanceof Error?e.message:String(e)}function uP(e){return r(e==="seconds"?"秒":"分钟")}function dP(e){const t=Number(e)||0;return t?new Date(t).toLocaleTimeString("zh-CN",{hour12:!1}):""}function fP(e){const t=Number(e)||0;if(!t)return"";const a=t-Date.now();if(a<=0)return r("即将执行");const o=Math.round(a/1e3);if(o<60)return r("{n} 秒后",{n:o});const c=Math.round(o/60);if(c<60)return r("{n} 分钟后",{n:c});const d=Math.round(c/60);return d<24?r("{n} 小时后",{n:d}):r("{n} 天后",{n:Math.round(d/24)})}function cee(e){const t=e.runner==="backend",a=[];if(e.lastRunAt){const o=dP(e.lastRunAt);a.push(e.lastResult?r("上次执行 {time}({result})",{time:o,result:e.lastResult}):r("上次执行 {time}",{time:o}))}else a.push(r(t?"还没有执行记录":"由页面按间隔自动刷新"));return t&&e.enabled&&e.nextRunAt&&a.push(r("下次执行 {time}({relative})",{time:dP(e.nextRunAt),relative:fP(e.nextRunAt)})),t&&e.retryAt&&e.retryAt>Date.now()&&a.push(r("冷却中,{relative}重试",{relative:fP(e.retryAt)})),a.join(iee)}function uee(e,t){const a=String(t??"").trim(),o=uP(e.unit);if(!a)return{ok:!1,message:r("间隔不能为空(可填 {min}–{max} {unit})",{min:e.min,max:e.max,unit:o})};if(!/^\d+$/.test(a))return{ok:!1,message:r("间隔必须是整数")};const c=Number(a);return ce.max?{ok:!1,message:r("间隔必须在 {min}–{max} {unit} 之间(当前填的是 {value})",{min:e.min,max:e.max,unit:o,value:a})}:{ok:!0,value:c}}function dee(e){const t=sl();e.id==="logsAutoRefresh"?t.wbLogsPanel?.applyAutoRefresh?.(e):e.id==="requestsAutoRefresh"?t.wbRequestsPanel?.applyAutoRefresh?.(e):e.id==="reportAutoRefresh"&&t.wbReport?.applyAutoRefresh?.(e)}let lc=!1,Vx=null,TS=!1;async function pP(){if(!Vx){TS=!0;return}await Vx()}function fee(){const[e,t]=x.useState([]),[a,o]=x.useState(!1),[c,d]=x.useState(null),[f,p]=x.useState({});function g(I){p(P=>{if(!(I in P))return P;const O={...P};return delete O[I],O})}const v=x.useCallback(async()=>{const I=sl().workbuddyDesktop;try{if(!I)throw new Error(r("后端桥不可用"));const P=await I.getScheduledTasks();t(iP(P)),o(!0)}catch(P){console.warn("读取定时任务失败:",Ux(P)),t([]),o(!0)}},[]),y=x.useCallback(async()=>{if(lc||document.hidden||sl().wbApp?.currentPage!=="tasks")return;const I=sl().workbuddyDesktop;if(I)try{const P=await I.getScheduledTasks();t(iP(P))}catch(P){console.warn("同步定时任务状态失败:",Ux(P))}},[]);x.useEffect(()=>{const I=window.setInterval(()=>{y()},oee);return()=>{window.clearInterval(I)}},[y]),x.useEffect(()=>{sl().wbApp?.renderTopbarStatus?.()},[e,a]),x.useEffect(()=>(Vx=v,TS&&(TS=!1,v()),()=>{Vx=null}),[v]);async function b(I,P,O){if(lc)return;const _=sl().workbuddyDesktop;if(_){lc=!0;try{const L=await _.saveScheduledTask(I,P);t(H=>H.map(B=>B.id===I?L:B)),dee(L),Ku(r("✅ 已更新「{label}」",{label:O}))}catch(L){Ku(r("保存失败:{reason}",{reason:Ux(L)}),"err"),await v()}finally{lc=!1}}}async function j(I,P){const O=uee(I,P);if(!O.ok){Ku(O.message,"err"),g(I.id);return}if(O.value===I.interval){g(I.id);return}await b(I.id,{interval:O.value},r("{name}间隔",{name:r(I.label)})),g(I.id)}async function w(I){if(lc)return;const P=sl().workbuddyDesktop;if(P){lc=!0,d(I.id);try{const O=await P.runScheduledTask(I.id);if(O?.task){const _=O.task;t(L=>L.map(H=>H.id===I.id?_:H))}Ku(r("✅ {task}:{summary}",{task:r(I.label),summary:O?.summary||r("已执行")})),I.id==="credentialMaintenance"&&await sl().wbApp?.refresh?.()}catch(O){Ku(r("执行失败:{reason}",{reason:Ux(O)}),"err"),await v()}finally{lc=!1,d(null)}}}function S(I){const P=uP(I.unit),O=c===I.id;return s.jsxs("div",{className:"task-item","data-task":I.id,children:[s.jsxs("div",{className:"task-main",children:[s.jsxs("div",{className:"task-title",children:[s.jsxs("label",{className:"switch",children:[s.jsx(ms,{checked:I.enabled===!0,onCheckedChange:_=>{b(I.id,{enabled:_},r("{name}开关",{name:r(I.label)}))}}),s.jsx("span",{className:"task-name",children:r(I.label)})]}),s.jsx("span",{className:"tip-q","data-tip":r(I.description)}),s.jsx(ze,{className:"task-badge",variant:I.enabled?"success":"outline",children:I.enabled?r("已开启"):r("已关闭")}),I.running?s.jsx(ze,{className:"task-badge",variant:"warning",children:r("执行中…")}):null]}),s.jsx("div",{className:"task-state",children:cee(I)})]}),s.jsxs("div",{className:"task-actions",children:[s.jsxs("span",{className:"task-interval",children:[s.jsx("span",{className:"task-interval-label",children:r("每")}),s.jsx($e,{type:"number",inputMode:"numeric",min:I.min,max:I.max,step:1,className:"w-[74px] max-w-[74px] text-center tabular-nums",value:f[I.id]??String(I.interval),title:r("可填 {min}–{max} {unit}(默认 {def} {unit})",{min:I.min,max:I.max,unit:P,def:I.defaultInterval}),onChange:_=>{const L=_.currentTarget.value;p(H=>({...H,[I.id]:L}))},onBlur:_=>{j(I,_.currentTarget.value)},onKeyDown:_=>{_.key==="Enter"&&_.currentTarget.blur()}}),s.jsx("span",{className:"task-interval-unit",children:P})]}),I.canRun===!0?s.jsx(se,{size:"sm",variant:"outline",disabled:O||I.running===!0,onClick:()=>{w(I)},children:r(O?"执行中…":"立即执行")}):null]})]},I.id)}const N=e.length===0,k=e.filter(I=>I.enabled).length,E=N?a?r("不可用"):"—":r("{enabled} / {total} 个已开启",{enabled:k,total:e.length}),D=N?a?"destructive":"outline":k?"success":"outline",C=D==="destructive"?"bad":D==="success"?"ok":"",A=e.map(I=>S(I)),R=A.slice(cP);return s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("任务清单")}),s.jsx(ze,{id:"tasks-badge",variant:D,"data-tone":C,children:E}),s.jsx("span",{className:"panel-sub",children:r("状态每 20 秒自动同步")}),s.jsx("div",{className:"head-actions",children:s.jsx(se,{variant:"outline",onClick:()=>{v().then(()=>Ku(r("定时任务已刷新")))},children:r("刷新")})})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"task-list",children:N?s.jsx("div",{className:"log-empty",children:r(a?"没有可显示的定时任务。后端未返回任务清单,请确认网关正在运行。":"正在加载定时任务…")}):s.jsxs(s.Fragment,{children:[A.slice(0,cP),R.length?s.jsx("div",{className:"task-grid",children:R}):null]})})}),s.jsxs("div",{className:"panel-foot",children:[s.jsxs("span",{children:[r("任务配置保存在 "),s.jsx("code",{children:"~/.agent2api/config.json"}),r(" 的 "),s.jsx("code",{children:"scheduledTasks"}),r(" 字段")]}),s.jsx("span",{children:r("改动立即生效,不需要重启程序")})]})]})}const mP='.page[data-page="tasks"]';let hP=!1;function gP(){if(hP)return;const e=document.querySelector(mP);e&&(hP=!0,e.replaceChildren(),vn.createRoot(e).render(s.jsx(fee,{})))}document.querySelector(mP)?gP():document.addEventListener("DOMContentLoaded",gP,{once:!0}),window.wbTasksPanel={load:pP},sl().wbApp?.currentPage==="tasks"&&pP();const xP="workbuddy-desktop-update-skip";function pee(){try{return localStorage.getItem(xP)||""}catch{return""}}function mee(e){try{localStorage.setItem(xP,e)}catch{}}let bP="";function Fx(e,t){if(!e||e.hasUpdate!==!0||e.pendingRestart===!0)return;const a=String(e.latestVersion||"").trim();a&&Pn().wbApp?.currentPage!=="settings"&&(a===pee()||a===bP||(bP=a,vP(),Yu=document.createElement("div"),document.body.append(Yu),Rp=vn.createRoot(Yu),Rp.render(s.jsx(hee,{info:e,onGoUpdate:t,onClose:vP}))))}function hee({info:e,onGoUpdate:t,onClose:a}){const o=String(e.latestVersion||""),c=String(e.notes||"").trim(),d=c?q2(c):"";function f(){mee(o),a()}function p(){a();const g=Pn();g.wbApp?.showPage?.("settings"),g.wbSettingsPanel?.showCategory?.("about"),t(e)}return s.jsx(Qt,{open:!0,onOpenChange:g=>{g||a()},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("检测到更新")})}),s.jsxs(Bt,{children:[s.jsxs("p",{className:"text-[12.5px] leading-[1.6] text-subtle",children:[r("新版本 "),s.jsx("strong",{className:"text-foreground",children:o}),r(" 已发布(当前 {current}),更新日志如下:",{current:e.currentVersion||r("未知")})]}),s.jsx("div",{className:"max-h-[46vh] overflow-y-auto overscroll-contain pr-1.5",onClick:G2,children:d?s.jsx("div",{className:"md-body",dangerouslySetInnerHTML:{__html:d}}):s.jsx("div",{className:"md-body",children:s.jsx("p",{className:"md-body-empty",children:r("这个版本没有填写发布说明。")})})})]}),s.jsxs(nn,{children:[s.jsx(se,{variant:"outline",size:"sm",onClick:f,children:r("跳过此次更新")}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:a,children:r("取消")}),s.jsx(se,{variant:"default",onClick:p,children:r("去更新")})]})]})})}let Rp=null,Yu=null;function vP(){Rp&&(Rp.unmount(),Rp=null),Yu&&(Yu.remove(),Yu=null)}const yP="updateCheck",Xu=1,$x=1440,gee="https://github.com/settings/tokens/new?description="+encodeURIComponent("Agent2API 更新检查");function xee(e){return e?e.error?{badge:s.jsx(ze,{shape:"tag",variant:"destructive",title:e.error,children:r("无法解密")}),hint:r("重新粘贴保存一次即可自愈")}:e.filled&&e.origin==="stored"?{badge:s.jsx(ze,{shape:"tag",variant:"success",children:r("已填写")}),hint:r("已加密存储在本地,不显示具体值;粘贴新令牌可覆盖")}:e.filled?{badge:s.jsx(ze,{shape:"tag",variant:"secondary",children:r("环境变量")}),hint:r("已配置 GITHUB_TOKEN 环境变量,界面保存的令牌优先于它")}:{badge:s.jsx(ze,{shape:"tag",variant:"outline",children:r("未填写")}),hint:r("填写后检查限额 60 → 5000 次/小时(创建令牌无需勾选任何权限)")}:{badge:s.jsx(ze,{shape:"tag",variant:"outline",children:r("读取中")}),hint:""}}function bee({open:e,onClose:t}){const[a,o]=x.useState(K2),[c,d]=x.useState(null),[f,p]=x.useState(""),[g,v]=x.useState(!1),[y,b]=x.useState(null),[j,w]=x.useState(""),[S,N]=x.useState(!1),k=Y2(a);x.useEffect(()=>{e&&(p(""),PY().then(o),(async()=>{try{d(await Pn().workbuddyDesktop?.getUpdateToken()??null)}catch{}})(),(async()=>{try{const L=((await Pn().workbuddyDesktop?.getScheduledTasks?.())?.tasks??[]).find(z=>z.id===yP),H=L?.enabled===!0,B=Math.max(Xu,Math.round(Number(L?.interval)||0));b({enabled:H,interval:B}),w(String(B))}catch{}})())},[e]);async function E(_){if(!S){N(!0);try{const L=await Pn().workbuddyDesktop?.saveScheduledTask?.(yP,_),H=L?.enabled===!0,B=Math.max(Xu,Math.round(Number(L?.interval)||0));b({enabled:H,interval:B}),w(String(B)),nr(r("✅ 自动检查更新已保存"))}catch(L){nr(r("保存失败:{error}",{error:zr(L)}),"err")}finally{N(!1)}}}async function D(){const _=Math.round(Number(j));if(!Number.isFinite(_)||_$x){nr(r("检查间隔必须是 {min} ~ {max} 分钟",{min:Xu,max:$x}),"err");return}y&&_===y.interval||await E({interval:_})}async function C(_){const L=await _Y(_);L&&o(H=>({...H,proxyChoice:L.choice}))}async function A(){const _=f.trim();if(!_){nr(r("请先粘贴 GitHub 令牌"),"err");return}v(!0);try{const L=await Pn().workbuddyDesktop?.setUpdateToken({token:_});d(L??null),p(""),L?.saved===!1?nr(r("令牌已生效,但写入磁盘失败(重启后会丢失)"),"err"):nr(r("✅ GitHub 令牌已保存(加密存储,界面不再显示)"))}catch(L){nr(r("保存失败:{error}",{error:zr(L)}),"err")}finally{v(!1)}}async function R(){v(!0);try{const _=await Pn().workbuddyDesktop?.setUpdateToken({token:null});d(_??null),nr(r("✅ 已清除界面保存的 GitHub 令牌(环境变量若配置过则继续生效)"))}catch(_){nr(r("清除失败:{error}",{error:zr(_)}),"err")}finally{v(!1)}}const I=xee(c),P=!!c?.error||c?.origin==="stored",O=c?.filled&&c?.origin!=="env"?r("已填写(粘贴新令牌可覆盖)"):r("粘贴 GitHub 令牌(ghp_… / github_pat_…)");return s.jsx(Qt,{open:e,onOpenChange:_=>{_||t()},children:s.jsxs(Zt,{className:"w-[min(460px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("更新设置")})}),s.jsxs(Bt,{className:"gap-3.5",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:r("自动检查更新")}),s.jsx(ms,{checked:y?.enabled===!0,disabled:S||!y,onCheckedChange:_=>{E({enabled:_===!0})},"aria-label":r("自动检查更新")})]}),s.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[s.jsx($e,{type:"number",min:Xu,max:$x,step:1,className:"w-[110px]",disabled:S||!y||y.enabled!==!0,value:j,onChange:_=>w(_.currentTarget.value),onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),D())},"aria-label":r("检查间隔(分钟)")}),s.jsx("span",{className:"text-[12px] text-subtle",children:r("分钟({min} ~ {max})",{min:Xu,max:$x})}),s.jsx(se,{variant:"outline",size:"sm",disabled:S||!y||Math.round(Number(j))===y.interval,onClick:()=>{D()},children:r("保存")})]}),s.jsx("div",{className:"mt-1.5 text-[12px] text-subtle",children:r("到点自动向 GitHub 查询新版本,查到就走「检测到更新」弹窗;关闭后「检查更新」按钮仍可手动触发")})]}),s.jsx("div",{className:"h-px bg-hairline"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:r("出网代理")}),s.jsx("div",{className:"mt-1.5",children:s.jsxs(ft,{value:k.current,onValueChange:_=>{C(String(_))},children:[s.jsx(mt,{className:Ue("w-full",k.broken&&"border-destructive-bd"),title:k.title,"aria-label":r("更新出网代理"),children:s.jsx(pt,{className:"min-w-0 truncate",children:k.selected?.label||r("直连")})}),s.jsx(ht,{children:k.items.map(_=>s.jsx(qe,{value:_.value,disabled:_.disabled,children:_.label},_.value))})]})})]}),s.jsx("div",{className:"h-px bg-hairline"}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:r("GitHub 令牌")}),s.jsx(se,{variant:"outline",size:"xs",title:r("在默认浏览器中打开 GitHub 的令牌创建页(备注已预设,无需勾选任何权限,直接点 Generate token)"),onClick:()=>{$2(gee)},children:r("打开 GitHub 令牌页面")})]}),s.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[I.badge,s.jsx("span",{className:"text-[12px] text-subtle",children:I.hint})]}),s.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[s.jsx($e,{type:"password",className:"flex-1",placeholder:O,autoComplete:"new-password",spellCheck:!1,value:f,onChange:_=>p(_.currentTarget.value),onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),A())}}),s.jsx(se,{variant:"default",size:"sm",disabled:g||!f.trim(),onClick:()=>{A()},children:r("保存")}),P?s.jsx(se,{variant:"outline",size:"sm",disabled:g,onClick:()=>{R()},children:r("清除")}):null]})]})]})]})})}function vee({open:e,onClose:t}){return s.jsx(Qt,{open:e,onOpenChange:a=>{a||t()},children:s.jsxs(Zt,{className:"w-[min(320px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("加入 QQ 群")})}),s.jsxs(Bt,{className:"items-center gap-3 text-center",children:[s.jsx("img",{className:"qq-qr",src:IY,alt:r("QQ 群二维码")}),s.jsxs("div",{className:"qq-no",children:[s.jsx("span",{className:"k",children:r("群号")}),s.jsx("code",{children:Yg}),s.jsx(se,{type:"button",size:"sm",variant:"ghost","data-copy":Yg,children:r("复制")})]}),s.jsx("p",{className:"qq-hint",children:r("用手机 QQ 扫上面的二维码,或在 QQ 里搜索群号加入。")})]})]})})}const yee=1e3,jP=8,jee=10,wee=1e3,See={"":"outline",ok:"success",warn:"warning",bad:"destructive"},Nee={info:null,checkedAt:0,repository:"",badgeText:r("未检查"),badgeTone:"",stateText:r("点击「检查更新」查询最新发布版本。"),stateError:!1,percent:0,phase:"idle",readyPath:"",checking:!1,actionBusy:!1,restartSeconds:0};function Pl(e){return String(e).padStart(2,"0")}function kee(e){const t=new Date(String(e??""));return!e||Number.isNaN(t.getTime())?"":`${t.getFullYear()}-${Pl(t.getMonth()+1)}-${Pl(t.getDate())} ${Pl(t.getHours())}:${Pl(t.getMinutes())}`}function wP(e){const t=new Date(e);if(!e||Number.isNaN(t.getTime()))return"";const a=new Date,o=t.getFullYear()===a.getFullYear()&&t.getMonth()===a.getMonth()&&t.getDate()===a.getDate(),c=`${Pl(t.getHours())}:${Pl(t.getMinutes())}:${Pl(t.getSeconds())}`;return o?c:`${Pl(t.getMonth()+1)}-${Pl(t.getDate())} ${c}`}function qx(e){return e?.installerKind?e.installerKind==="dmg":/Mac|iPhone|iPad/.test(navigator.userAgent||"")}function Ma(e){return e?.selfUpdate===!0}function SP(e){return e?Ma(e)?e.serverAsset??null:e.asset??null:null}function Cee(e){return Ma(e)?r("正在下载服务端更新包…(下载完成后由面板完成替换,重启容器内的服务后生效)"):qx(e)?r("正在下载安装包…(下载完成后会挂载磁盘映像,把应用拖进「应用程序」即可完成安装)"):r("正在下载安装包…(下载完成后启动安装程序需要管理员权限,会弹出 UAC 确认框)")}function NP(e,t){return Ma(e)?r("更新包已就绪:{name}。点「安装并重启」后,面板会校验并替换容器内的程序与界面文件,然后重启服务(页面会自动刷新)。",{name:t}):qx(e)?r("安装包已就绪:{name}。点击「打开安装包」后会挂载磁盘映像,把应用拖进「应用程序」即可完成安装。",{name:t}):r("安装包已就绪:{name}。点击「安装并重启」后需要管理员权限,会弹出 UAC 确认框。",{name:t})}function Tee(e){return Ma(e)?r("安装并重启"):qx(e)?r("打开安装包"):r("安装并重启")}let fa=Nee;const ES=new Set;function AS(){return fa}function Eee(e){return ES.add(e),()=>{ES.delete(e)}}function zn(e){fa={...fa,...e};for(const t of ES)t()}let wr=!1,RS=null,Gx=null;function Qu(){Gx!==null&&(window.clearInterval(Gx),Gx=null)}function Ts(e,t=""){zn({badgeText:e,badgeTone:t})}function An(e,t=!1){zn({stateText:e,stateError:t})}function Kx(){const{info:e,checkedAt:t}=fa;if(!e)return;const a=t?r("(检查于 {time})",{time:wP(t)}):"";if(e.pendingRestart===!0){Ts(r("待重启"),"warn"),An(r("更新已应用到容器内,重启服务后生效。{at}",{at:a}));return}if(e.hasUpdate===!0){if(Ts(r("有新版本"),"warn"),Ma(e)&&!e.serverAsset){An(r("发现新版本 {latest}(当前 {current}),但该版本没有提供容器内更新包;请在宿主机执行 docker compose pull && docker compose up -d 升级。{at}",{latest:String(e.latestVersion||""),current:String(e.currentVersion||""),at:a}));return}An(r("发现新版本 {latest}(当前 {current})。{at}",{latest:String(e.latestVersion||""),current:String(e.currentVersion||""),at:a}))}else e.hasUpdate===!1?(Ts(r("已是最新"),"ok"),An(r("当前已是最新版本({current})。{at}",{current:String(e.currentVersion||""),at:a}))):(Ts(r("无法比较"),"warn"),An(e.latestVersion?r("最新发布版本为 {latest},但当前版本号「{current}」无法解析,未做新旧判断。{at}",{latest:e.latestVersion,current:e.currentVersion||r("未知"),at:a}):r("仓库暂无发布版本。{at}",{at:a})))}function kP(e){!e||e.checked===!1||(zn({info:e,checkedAt:Number(e.checkedAt)||0}),e.repository&&OS(e.repository),fa.phase==="idle"&&Kx())}function OS(e){const t=String(e||"").trim();/^[\w.-]+\/[\w.-]+$/.test(t)&&zn({repository:t})}function MS(e){if(!e)return!1;if(e.active){const t=Math.max(0,Math.min(100,Number(e.percent)||0)),a=(Number(e.received)||0)/1024/1024,o=(Number(e.total)||0)/1024/1024;return zn({phase:"downloading",percent:t}),Ts(r("下载中"),"warn"),An(r("正在下载 {name}:{percent}%({received} / {total} MB)",{name:e.filename||r("安装包"),percent:t,received:a.toFixed(1),total:o.toFixed(1)})),!0}if(Qu(),zn({percent:0}),e.error)return Ts(r("下载失败"),"bad"),An(r("下载失败:{error}",{error:e.error}),!0),zn({phase:"failed"}),!0;if(e.canceled)return Ts(r("已取消"),"warn"),An(Ma(fa.info)?r("下载已取消,可重新点击「下载并更新」。"):r("下载已取消,可重新点击「下载并安装」。")),zn({phase:"idle"}),!0;if(e.done&&e.path){const t=e.path,a=e.filename||t;return Ts(r("可安装"),"ok"),zn({phase:"ready",readyPath:t}),Ma(fa.info)?(An(NP(fa.info,a)),!0):(t!==RS?(RS=t,An(qx(fa.info)?r("安装包已下载完成,正在挂载磁盘映像…"):r("安装包已下载完成,正在启动安装程序(需要管理员权限,会弹出 UAC 确认框)…")),TP(t)):An(NP(fa.info,a)),!0)}return!1}async function Aee(){try{const e=await Pn().workbuddyDesktop?.updateProgress();if(!e){Qu();return}MS(e)}catch(e){Qu(),An(r("读取下载进度失败:{error}",{error:zr(e)}),!0)}}function CP(){Qu(),Gx=window.setInterval(()=>{Aee()},yee)}async function TP(e){const t=Pn().workbuddyDesktop;if(t)try{const o=(await t.runInstaller(e,!0))?.restart!==!1;An(r(o?"安装程序已启动,本程序将退出以便完成覆盖安装。安装程序需要管理员权限,会弹出 UAC 确认框,请选择「是」。":"安装包已挂载,请在弹出的窗口里把应用拖进「应用程序」完成安装。安装完成后重新打开本程序即可。"))}catch(a){Ts(r("启动失败"),"bad"),An(r("启动安装程序失败:{error}",{error:zr(a)}),!0)}}async function Ree(){const e=Pn().workbuddyDesktop;if(e?.installUpdate)try{Ts(r("安装中"),"warn"),An(r("正在校验并替换容器内的程序与界面文件…"));const t=await e.installUpdate(),a=String(t?.version||"").trim();An(a?r("已替换为 {version},正在重启服务…",{version:a}):r("替换完成,正在重启服务…")),await e.restartService?.().catch(()=>{}),DS(a)}catch(t){Ts(r("安装失败"),"bad"),An(r("安装失败:{error}",{error:zr(t)}),!0)}}async function Oee(){const e=Pn().workbuddyDesktop;if(!(!e?.rollbackUpdate||wr)){wr=!0,zn({actionBusy:!0});try{Ts(r("回滚中"),"warn"),An(r("正在回滚到上一版本…")),await e.rollbackUpdate(),An(r("已还原上一版本,正在重启服务…")),await e.restartService?.().catch(()=>{}),DS("")}catch(t){Ts(r("回滚失败"),"bad"),An(r("回滚失败:{error}",{error:zr(t)}),!0)}finally{wr=!1,zn({actionBusy:!1})}}}function DS(e){Qu(),zn({phase:"restarting",restartSeconds:jP,readyPath:""}),Ts(r("重启中"),"warn");let t=jP;const a=()=>{if(An(e?r("{version} 已就位,服务正在重启,页面会在恢复后自动刷新…({seconds}s)",{version:e,seconds:Math.max(0,t)}):r("服务正在重启,页面会在恢复后自动刷新…({seconds}s)",{seconds:Math.max(0,t)})),t<=0){window.clearInterval(o),Mee();return}t-=1,zn({restartSeconds:t})},o=window.setInterval(a,1e3);a()}async function Mee(){for(let e=0;e{window.setTimeout(t,wee)})}window.location.reload()}async function EP(){if(wr)return null;wr=!0,zn({checking:!0}),Ts(r("检查中"),"warn"),An(r("正在查询 GitHub 上的最新发布版本…"));let e=null;try{const t=Pn().workbuddyDesktop;if(!t)throw new Error(r("后端桥不可用"));e=await t.checkUpdate()??null,zn({info:e,checkedAt:Number(e?.checkedAt)||Date.now()}),e?.repository&&OS(e.repository),Kx()}catch(t){e=null,zn({info:null,checkedAt:0}),Ts(r("检查失败"),"bad"),An(r("检查更新失败:{error}",{error:zr(t)}),!0)}finally{wr=!1,zn({checking:!1})}return Pn().wbApp?.updateUpdateBadge?.(e),Fx(e,Op),e}async function AP(){let e=null;try{e=await Pn().workbuddyDesktop?.getUpdateStatus()??null}catch{}if(e&&e.checked!==!1){kP(e),Pn().wbApp?.updateUpdateBadge?.(e),Fx(e,Op);return}fa.info||(Ts(r("未检查")),An(r("点击「检查更新」查询 GitHub 上的最新发布版本。")))}async function IS(){if(wr)return;const e=AS();if(e.info?.pendingRestart===!0&&e.phase!=="downloading"){wr=!0,zn({actionBusy:!0});try{await Pn().workbuddyDesktop?.restartService?.().catch(()=>{}),DS("")}finally{wr=!1,zn({actionBusy:!1})}return}if(e.phase!=="downloading"&&e.readyPath){wr=!0,zn({actionBusy:!0});try{Ma(e.info)?await Ree():await TP(e.readyPath)}finally{wr=!1,zn({actionBusy:!1})}return}if(e.phase==="downloading"){try{await Pn().workbuddyDesktop?.cancelUpdate(),An(r("正在取消下载…"))}catch(a){nr(r("取消失败:{error}",{error:zr(a)}),"err")}return}const t=SP(e.info);if(!t?.url){nr(Ma(e.info)?r("这一版没有提供容器内更新包"):r("没有可下载的安装包"),"err");return}if(OP(e)){wr=!0,zn({actionBusy:!0});try{await Pn().workbuddyDesktop?.downloadUpdate({url:t.url,name:t.name}),RS=null,zn({phase:"downloading",readyPath:"",percent:0}),Ts(r("下载中"),"warn"),An(Cee(e.info)),CP()}catch(a){Ts(r("下载失败"),"bad"),An(r("下载失败:{error}",{error:zr(a)}),!0)}finally{wr=!1,zn({actionBusy:!1})}}}async function RP(){Kx(),await AP();try{const e=await Pn().workbuddyDesktop?.updateProgress();if(e?.active){MS(e),CP();return}if(e?.done&&e.path){MS(e);return}}catch{}}async function Op(e){if(e?.pendingRestart===!0){await IS();return}e?.hasUpdate===!0&&(zn({info:e,checkedAt:Number(e.checkedAt)||fa.checkedAt}),e.repository&&OS(e.repository),Kx(),Pn().wbApp?.updateUpdateBadge?.(e),Fx(e,Op)),await RP();const t=AS();if(!(t.phase==="downloading"||t.readyPath)&&t.info?.hasUpdate)for(let a=0;a<3;a+=1){if(wr){await new Promise(o=>{window.setTimeout(o,400)});continue}await IS();return}}function OP(e){return e.phase==="restarting"?null:e.info?.pendingRestart===!0&&e.phase==="idle"?{label:r("立即重启"),disabled:e.actionBusy}:!(e.info?.hasUpdate===!0&&!!SP(e.info)?.url)&&e.phase!=="downloading"&&e.phase!=="ready"?null:{label:e.phase==="downloading"?r("取消下载"):e.phase==="failed"?r("重试下载"):e.phase==="ready"?Tee(e.info):Ma(e.info)?r("下载并更新"):r("下载并安装"),disabled:e.actionBusy}}function Dee(e,t){const a=e.info,o=String(a?.notes||"").trim();if(!o)return s.jsx("div",{className:"update-log-hint",children:r(a?"这个版本没有填写发布说明。":"点击「检查更新」后,这里会显示最新版本的更新说明。")});const c=q2(o),d=F2(a?.pageUrl),f=kee(a?.publishedAt);return s.jsxs("div",{className:"rel-note",children:[s.jsxs("div",{className:"rel-note-head",children:[s.jsx("span",{className:"rel-tag",children:String(a?.latestVersion||r("最新版本"))}),a?.prerelease===!0?s.jsx(ze,{shape:"tag",variant:"warning",children:r("预发布")}):null,f?s.jsx("span",{className:"rel-date",children:f}):null]}),s.jsxs("div",{className:"rel-note-body",children:[c?s.jsx("div",{className:"md-body",dangerouslySetInnerHTML:{__html:c}}):s.jsx("div",{className:"md-body",children:s.jsx("p",{className:"md-body-empty",children:r("这个版本没有填写发布说明。")})}),s.jsxs("div",{className:"rel-foot",children:[d?s.jsx("a",{href:d,"data-external":d,target:"_blank",rel:"noopener",children:r("在 GitHub 查看完整说明")}):null,s.jsx(se,{type:"button",variant:"link",size:"sm",className:"h-auto border-0 px-0 text-[11.5px] font-semibold text-primary-fg underline-offset-auto",title:r("群号:{group}",{group:Yg}),onClick:t,children:r("加入 QQ 群")})]})]})]})}function Iee(){const e=x.useSyncExternalStore(Eee,AS),t=OP(e),[a,o]=x.useState(!1),[c,d]=x.useState(!1);x.useEffect(()=>()=>{Qu()},[]);const f=e.repository?`https://github.com/${e.repository}`:"",p=e.repository?`https://github.com/${e.repository.split("/")[0]}`:"",g=Ma(e.info),v=g&&e.info?.backupAvailable===!0&&e.phase!=="downloading"&&e.phase!=="ready"&&e.phase!=="restarting",y=e.info?.latestVersion?e.info.prerelease?r("{version}(预发布)",{version:e.info.latestVersion}):e.info.latestVersion:"—",b=String(e.info?.latestVersion||"").trim(),j=b?`${b}${e.checkedAt?r(" · 检查于 {time}",{time:wP(e.checkedAt)}):""}`:"";return s.jsxs("section",{className:"panel",onClick:G2,children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("软件更新")}),s.jsx("span",{className:"tip-q","data-tip":r(g?"容器内更新:更新包从 GitHub 发布页下载,校验 sha256 后由面板替换容器内的程序与界面文件,再重启服务(容器由 restart 策略拉起,页面会自动刷新)。更新的是容器里的文件,compose 里的镜像标签不变 —— 之后执行 docker compose pull && up -d 会回到镜像里的版本;更新失败可一键回滚到上一版本。检查更新与下载的出网线路、GitHub 令牌都在「更新设置」里。":"更新包从 GitHub 发布页下载,下载完成后可直接启动安装程序并自动重启本程序。安装包会先校验来源域名与文件完整性。检查更新与下载安装包的出网线路、GitHub 令牌都在「更新设置」里:线路默认直连(直连失败时自动借 Clash Verge 的混合端口重试一次),选定指定出口后只走该出口;填写 GitHub 令牌可把检查限额从 60 次/小时提高到 5000 次/小时。")}),s.jsx(ze,{id:"update-badge",variant:See[e.badgeTone],"data-tone":e.badgeTone,children:e.badgeText}),s.jsxs("div",{className:"head-actions",children:[s.jsx(se,{id:"btn-update-settings",variant:"outline",title:r("出网线路与 GitHub 令牌设置"),onClick:()=>o(!0),children:r("更新设置")}),s.jsx(se,{id:"btn-update-check",variant:"outline",disabled:e.checking||e.phase==="restarting",onClick:()=>{EP()},children:e.checking?r("检查中…"):r("检查更新")}),v?s.jsx(se,{id:"btn-update-rollback",variant:"outline",disabled:e.actionBusy,title:r("把容器内的程序与界面文件还原到更新前的版本,并重启服务"),onClick:()=>{Oee()},children:r("回滚到上一版本")}):null,t?s.jsx(se,{id:"btn-update-download",variant:"default",disabled:t.disabled,onClick:()=>{IS()},children:t.label}):null]})]}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"update-version",children:[s.jsxs("span",{className:"version-pill",children:[s.jsx("span",{className:"k",children:r("当前版本")}),s.jsx("span",{className:"v",id:"update-current",children:e.info?.currentVersion||"—"})]}),s.jsx("span",{className:"version-arrow",children:"→"}),s.jsxs("span",{className:"version-pill new",children:[s.jsx("span",{className:"k",children:r("最新版本")}),s.jsx("span",{className:"v",id:"update-latest",children:y})]})]}),s.jsx("div",{className:"detail",id:"update-state",style:e.stateError?{color:"var(--danger)"}:void 0,children:e.stateText}),e.phase==="downloading"&&e.percent>0&&e.percent<100?s.jsx(Jd,{value:e.percent}):null,p&&f?s.jsxs("div",{className:"update-author",id:"update-author",children:[s.jsxs("div",{className:"update-author-text",children:[s.jsx("strong",{children:r("关于作者")}),s.jsxs("span",{children:[r("本工具由")," ",s.jsx("a",{id:"update-author-link",href:p,"data-external":p,target:"_blank",rel:"noopener",children:e.repository.split("/")[0]})," ",r("个人开发并开源维护,免费使用、不带广告,也不会收集你的账号数据。如果它帮到了你,欢迎到项目仓库点个 Star 支持一下。")]})]}),s.jsx("div",{className:"update-author-actions",children:s.jsx(se,{id:"btn-update-favorite",type:"button",size:"sm",variant:"outline","data-external":f,title:r("在浏览器中打开项目仓库,点 Star 支持作者"),children:r("收藏项目")})})]}):null,s.jsxs("div",{className:"update-log",id:"update-notes",children:[s.jsxs("div",{className:"update-log-head",children:[s.jsx("span",{className:"update-log-title",children:r("更新日志")}),s.jsx("span",{className:"update-log-meta",id:"update-log-meta",children:j})]}),s.jsx("div",{className:"update-log-body",id:"update-log-body",children:Dee(e,()=>d(!0))})]})]}),a?s.jsx(bee,{open:!0,onClose:()=>o(!1)}):null,c?s.jsx(vee,{open:!0,onClose:()=>d(!1)}):null]})}const MP='.settings-pane[data-cat="about"]';let PS=null;function DP(){if(PS)return;const e=document.querySelector(MP);e&&(e.replaceChildren(),PS=vn.createRoot(e),PS.render(s.jsx(Iee,{})))}document.querySelector(MP)?DP():document.addEventListener("DOMContentLoaded",DP,{once:!0}),window.wbUpdatePanel={load:RP,check:EP,syncFromCache:AP,openAndDownload:Op,applyStatus:kP,showUpdateModal:e=>Fx(e,Op)};const Pee="zcode.z.ai/billing",_ee={active:"success",pending:"warning",expired:"ghost",unknown:"outline"};function Lee(e){const t=String(e||"").trim().toLowerCase();return t==="daily"?r("每日"):t==="weekly"?r("每周"):t==="monthly"?r("每月"):""}function zee(e){const t=Number(e);if(!Number.isFinite(t)||t<=0)return"";const a=window.wbUnits;return a?.formatTokens?a.formatTokens(t):String(t)}function oc(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"":Pe().wbApp?.formatTime?.(t*1e3)||new Date(t*1e3).toLocaleString()}function Bee(e){const t=zee(e.grantUnits),a=String(e.unitType||"").trim(),o=t?[t,a].filter(Boolean).join(" "):"",c=Lee(e.period),d=[String(e.showName||"").trim(),o].filter(Boolean).join(" ");return d?c?r("{body}({period})",{body:d,period:c}):d:""}function IP(e){return(e.entitlements||[]).map(Bee).filter(Boolean).join(r("、"))}function Hee(e){const t=oc(e.startsAt),a=oc(e.endsAt);return t&&a?`${t} → ${a}`:a?r("到期 {time}",{time:a}):t?r("开始 {time}",{time:t}):""}function Uee(e){const t=new Date(e*1e3);if(Number.isNaN(t.getTime()))return"";const a=`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`,o=d=>Math.floor(Date.UTC(d.getFullYear(),d.getMonth(),d.getDate())/864e5),c=o(t)-o(new Date);return c===0?r("今天 {time}",{time:a}):c===1?r("明天 {time}",{time:a}):oc(e)}function Vee(e){const t=[],a=Number(e.pendingUntil);if(Number.isFinite(a)&&a>0){const c=Uee(a);c&&t.push(r("待生效 {time}",{time:c}))}const o=oc(e.endsAt);if(o&&t.push(r("到期 {time}",{time:o})),t.length===0){const c=oc(e.startsAt);c&&t.push(r("开始 {time}",{time:c}))}return t.join(" · ")}function Fee({options:e,onClose:t}){const a=e.id,[,o]=x.useState(0);x.useEffect(()=>UA(()=>o(P=>P+1)),[]);const[c,d]=x.useState([]),[f,p]=x.useState({status:"loading"}),[g,v]=x.useState(""),y=Ea(a),b=String(y?.name||e.name||a),j=$h(y),w=[...new Set([...j,...c])],S=y?.claimPlans&&typeof y.claimPlans=="object"&&!Array.isArray(y.claimPlans)?y.claimPlans:{},N=y?Qa(y):void 0,k=N&&typeof N=="object"&&!Array.isArray(N)?N:null,E=k&&Array.isArray(k.plans)?k.plans:[],D=w.filter(P=>P&&!E.some(O=>String(O.planId||"")===P)),C=Zs().usageInflight.has(a),A=Pe().wbZcodeClaim,R=x.useCallback(async()=>{if(!A?.preview){p({status:"error",message:r("当前环境不支持领取(桥接方法缺失)")});return}p({status:"loading"});try{const P=await A.preview(a);p({status:"ready",result:P||{}})}catch(P){p({status:"error",message:ut(P)})}},[A,a]);x.useEffect(()=>{R();const P=Ea(a);P&&Qa(P)===void 0&&Wh(a)},[a,R]);async function I(P){if(!(!A?.claim||g)){v(P);try{const O=await A.claim(a,P);if(O?.ok||O?.failure==="already_claimed"){const _=O.planId||P;_&&d(L=>L.includes(_)?L:[...L,_]),Wh(a),Pe().wbApp?.refresh?.(),R()}}finally{v("")}}}return s.jsx(Qt,{open:!0,onOpenChange:(P,O)=>{if(!P){if(g){O.cancel();return}t()}},children:s.jsxs(Zt,{className:"w-[min(560px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("ZCode 套餐明细 — {name}",{name:b})})}),s.jsxs(Bt,{className:"space-y-4",children:[s.jsxs("section",{children:[s.jsxs("div",{className:"mb-1.5 flex items-center gap-2 text-[12px] font-semibold text-muted-foreground",children:[r("可领取的套餐"),s.jsx(ze,{variant:"outline",shape:"tag",children:r("官方限时活动")})]}),f.status==="loading"?s.jsxs("div",{className:"flex items-center gap-2 py-2 text-[12.5px] text-muted-foreground",children:[s.jsx(Wd,{className:"size-3"}),r("正在探测可领取的套餐…")]}):f.status==="error"?s.jsxs("div",{className:"py-1 text-[12.5px] text-destructive",children:[r("探测失败:{message}",{message:f.message}),s.jsx(se,{variant:"outline",size:"xs",className:"ml-2",onClick:()=>{R()},children:r("重试")})]}):f.result.deployed?(f.result.plans||[]).length===0?s.jsx("p",{className:"py-1 text-[12.5px] text-muted-foreground",children:r("当前没有可领取的套餐(活动期内每天发一份,明天可再领)")}):s.jsx("ul",{className:"m-0 list-none p-0",children:(f.result.plans||[]).map(P=>{const O=String(P.planId||""),_=w.includes(O),L=IP(P),H=Hee(P);return s.jsxs("li",{className:"flex items-start justify-between gap-3 border-b border-hairline py-2 last:border-b-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[13px] font-medium",children:[s.jsx("span",{className:"truncate",children:P.name||O||r("套餐")}),_?s.jsx(ze,{variant:"success",shape:"tag",children:r("今日已领")}):null]}),H?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:H}):null,L?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:L}):null,P.description?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:P.description}):null]}),s.jsx(se,{variant:"outline",size:"xs",className:"flex-none",title:_?r("这一份今天已经领过了(重复领取上游会回「已领取过」)"):void 0,disabled:g!=="",onClick:()=>{I(O)},children:r(g===O?"领取中…":_?"再领一次":"领取")})]},O||P.name)})}):s.jsx("p",{className:"py-1 text-[12.5px] text-muted-foreground",children:r("当前没有可领取的套餐(活动尚未开始)")}),s.jsx("p",{className:"mt-1.5 text-[11.5px] text-muted-foreground",children:r("活动期内每天发一份新套餐;同一份当天重复领取会提示「已领取过」,次日可再领。领取要走一次人机验证(滑块)。")}),f.status==="ready"&&f.result.activationError?s.jsx("p",{className:"text-[11.5px] text-muted-foreground",children:r("(激活事件补报失败,可能影响领取资格:{message})",{message:f.result.activationError})}):null]}),s.jsxs("section",{children:[s.jsxs("div",{className:"mb-1.5 flex items-center gap-2 text-[12px] font-semibold text-muted-foreground",children:[r("我的套餐"),Array.isArray(k?.wallets)&&k.wallets.length>0&&k.availableView?s.jsx(ze,{variant:"outline",shape:"tag",children:String(k.walletsFrom||"")==="monitor"?String(k.availableView):r("可用 {value}",{value:String(k.availableView)})}):null,s.jsx("div",{className:"ml-auto",children:s.jsx(se,{variant:"outline",size:"xs",disabled:C,title:r("重新读取该账号的余额与套餐(走余额查询那条链)"),onClick:()=>{Wh(a)},children:r(C?"查询中…":"查询余额")})})]}),E.length>0?s.jsx("ul",{className:"m-0 list-none p-0",children:E.map(P=>{const O=String(P.planId||""),_=String(P.state||"unknown"),L=IP(P),H=Vee(P),B=O&&y?.claimPlans&&Number(y.claimPlans[O])||0;return s.jsxs("li",{className:"flex items-start justify-between gap-3 border-b border-hairline py-2 last:border-b-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[13px] font-medium",children:[s.jsx("span",{className:"truncate",children:P.name||O||r("套餐")}),s.jsx(ze,{variant:_ee[_]||"outline",shape:"tag",children:AA(_)})]}),H?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:H}):null,L?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:L}):null]}),B>0?s.jsx("span",{className:"flex-none text-[11.5px] text-muted-foreground",children:r("本地领取于 {time}",{time:oc(B/1e3)})}):null]},O||P.name)})}):s.jsx("p",{className:"py-1 text-[12.5px] text-muted-foreground",children:N===void 0?r("还没有余额读数(已自动查询一次,稍候;也可以点右上角「查询余额」重读)"):k&&k.source&&k.source!==Pee?r("这个账号的余额走窗口限额通道(只配了编码套餐 API Key):只有每 N 小时的剩余比例,读不到套餐清单"):r("读数里没有套餐清单(免费账号、或套餐的上游状态还没刷新;可点右上角「查询余额」重读)")}),D.length>0?s.jsx("p",{className:"mt-1.5 text-[11.5px] text-muted-foreground",children:r("本地台账里今天还领过这些,但上面的读数里还没有:{plans}(读数刷新可能有延迟)",{plans:D.map(P=>{const O=Number(S[P])||0,_=O>0?oc(O/1e3):"";return _?r("{plan}({time} 领取)",{plan:P,time:_}):P}).join(r("、"))})}):null]})]}),s.jsxs(nn,{children:[s.jsx("span",{className:"min-w-0 text-[11.5px] text-muted-foreground",children:w.length>0?r("今天(北京时间)已领取 {n} 份:{plans}",{n:w.length,plans:w.join(r("、"))}):r("今天还没有领过:上面「可领取的套餐」里逐份点「领取」即可")}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("关闭")})]})]})})}let Mp=null,Zu=null;function PP(){Mp&&(Mp.unmount(),Mp=null),Zu&&(Zu.remove(),Zu=null)}function $ee(e){e?.id&&(PP(),Zu=document.createElement("div"),document.body.append(Zu),Mp=vn.createRoot(Zu),Mp.render(s.jsx(Fee,{options:e,onClose:PP})))}window.wbZcodePlans={open:$ee};const _P="w-auto flex-auto";function LP({onInput:e,domRef:t,icon:a,className:o,inputClassName:c,...d}){const f=g=>{t.current=g},p=g=>{e?.(g.currentTarget.value)};return a?s.jsxs(Ci,{className:Ue(_P,o),children:[s.jsx(Ei,{ref:f,className:c,onInput:p,...d}),s.jsx(Ti,{"aria-hidden":"true",children:a})]}):s.jsx($e,{ref:f,className:Ue(_P,c),onInput:p,...d})}function qee(e,t){const a=vn.createRoot(e),o={current:null};return a.render(s.jsx(LP,{domRef:o,defaultValue:t.value,placeholder:t.placeholder,type:t.type??"search",icon:t.icon,"aria-label":t.ariaLabel,onInput:t.onInput})),{setValue(c){const d=o.current;d&&d.value!==c&&(d.value=c)},getValue(){return o.current?.value??""},focus(){o.current?.focus()},unmount(){a.unmount()}}}const Gee=[["id","id"],["type","type"],["name","name"],["title","title"],["placeholder","placeholder"],["min","min"],["max","max"],["step","step"],["autocomplete","autoComplete"]];function Kee(e){const t={defaultValue:e.value||void 0,inputClassName:e.className||void 0};for(const[f,p]of Gee){const g=e.getAttribute(f);g!=null&&(t[p]=g)}const a=e.getAttribute("maxlength");a!=null&&(t.maxLength=Number(a));const o=e.getAttribute("inputmode");o!=null&&(t.inputMode=o),e.hasAttribute("spellcheck")&&(t.spellCheck=e.spellcheck),e.disabled&&(t.disabled=!0),e.readOnly&&(t.readOnly=!0),e.hidden&&(t.hidden=!0);const c=e.getAttribute("aria-label");c!=null&&(t["aria-label"]=c);for(const f of e.getAttributeNames())!f.startsWith("data-")||f.startsWith("data-island-")||(t[f]=e.getAttribute(f)??"");const d=e.getAttribute("data-island-icon");return d!=null&&(t.icon=d),t}function zP(e){if(e.dataset.islandUpgraded)return;e.dataset.islandUpgraded="1";const t=Kee(e),a=e.parentElement?.classList.contains("input-affix")?e.parentElement:null;let o;a?(a.className=a.className.replace(/\binput-affix\b/,"").trim(),a.style.display="flex",a.style.alignItems="center",o=a):(o=document.createElement("span"),o.style.display="contents",e.replaceWith(o));const c={current:null},d=vn.createRoot(o);ks.flushSync(()=>{d.render(s.jsx(LP,{...t,domRef:c}))})}function BP(e=document){if(e instanceof HTMLInputElement&&e.matches("[data-island-input]")){zP(e);return}e.querySelectorAll("input[data-island-input]").forEach(zP)}function Yee(){BP();const e=new MutationObserver(t=>{for(const a of t)for(const o of a.addedNodes)o instanceof Element&&BP(o)});return e.observe(document.body,{childList:!0,subtree:!0}),e}function Xee(e,t){const a=vn.createRoot(e);let o={options:t.options,value:t.value,ariaLabel:t.ariaLabel,className:t.className};const c=()=>{a.render(s.jsx(In,{options:o.options,value:o.value,onValueChange:t.onChange,"aria-label":o.ariaLabel,className:o.className}))};return c(),{setValue(d){d!==o.value&&(o={...o,value:d},c())},setOptions(d){o={...o,options:d},c()},unmount(){a.unmount()}}}window.wbSegmented={mount:Xee},window.wbInput={mount:qee},Yee()})(); +`)}}const y=[...p.entries()].sort((b,j)=>b[0]-j[0]).map(([,b])=>b);y.length&&e.onEvent({type:"toolCalls",calls:y}),e.onEvent({type:"done",finishReason:g})}function qj(e){const t=String(e||"").trim();if(!t)return{};try{const a=JSON.parse(t);return a&&typeof a=="object"&&!Array.isArray(a)?a:{}}catch{return{}}}function Ja(){const e=window.workbuddyDesktop;if(!e)throw new Error(r("桌面桥不可用(本页需要在 Agent2API 客户端里打开)"));return e}function wu(){window.wbApp?.refresh?.()}function at(e,t=256){return typeof e=="string"?e.trim().slice(0,t):""}function Ui(e){return typeof e=="boolean"?e:void 0}function Lf(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Su(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"):[]}function Nu(e){return(e instanceof Error?e.message:String(e)).replace(/^Error:\s*/,"")}async function xg(){const e=await Ja().getState?.();return(Array.isArray(e?.accounts)?e.accounts:[]).slice().sort((a,o)=>Number(a.priority??0)-Number(o.priority??0))}function zf(e){return at(e.name)||at(e.nickname)||at(e.id)||"(未命名账号)"}function Gj(e,t){const a=t.trim();if(!a)throw new Error(r("没给账号名"));const o=e.find(p=>at(p.id)===a);if(o)return o;const c=e.filter(p=>zf(p)===a);if(c.length===1)return c[0];const d=e.filter(p=>zf(p).includes(a));if(d.length===1)return d[0];const f=(c.length?c:d).map(zf).slice(0,6);throw f.length?new Error(r("「{name}」匹配到多个账号:{list},请用完整账号名重试",{name:a,list:f.join("、")})):new Error(r("没有找到账号「{name}」",{name:a}))}const gG={id:"list_models",label:r("获取模型列表"),kind:"read",desc:"读取各提供商的模型清单(模型 ID、所属提供商、是否启用、已挂的映射名)以及全部映射。回答「有哪些模型」「哪些模型在多家重复」「某个名字挂在哪」这类问题之前先调用它。",params:{type:"object",properties:{provider:{type:"string",description:"只看某一家(提供商 id,如 codearts / workbuddy);不填 = 全部"},keyword:{type:"string",description:"按模型 ID 或映射名做子串过滤;不填 = 不过滤"},enabledOnly:{type:"boolean",description:"true = 只看已启用的模型"}}},run:async e=>{const t=at(e.provider,64).toLowerCase(),a=at(e.keyword,128).toLowerCase(),o=Ui(e.enabledOnly)===!0,c=await Ja().getModelManage?.(),f=(Array.isArray(c?.models)?c.models:[]).filter(p=>!(t&&at(p.provider).toLowerCase()!==t||o&&p.enabled!==!0||a&&![at(p.id),at(p.name),...Array.isArray(p.aliases)?p.aliases.map(v=>at(v)):[]].join(" ").toLowerCase().includes(a))).map(p=>({provider:at(p.provider),id:at(p.id),enabled:p.enabled===!0,aliases:Array.isArray(p.aliases)?p.aliases.map(g=>at(g)):[]}));return{text:JSON.stringify({total:f.length,models:f.slice(0,400)}),summary:r("{n} 个模型",{n:f.length})}}},xG={id:"list_account_balance",label:r("查询账号余额"),kind:"read",desc:"查询各账号的余额 / 剩余额度(会向各上游发起真实的余额查询)。回答「还剩多少」「哪个账号快用完了」这类问题之前先调用它。",params:{type:"object",properties:{account:{type:"string",description:"只查某个账号(账号名或 id);不填 = 全部账号"}}},run:async e=>{const t=at(e.account,128),a=t?at(Gj(await xg(),t).id):"",o=await Ja().getAllBalances?.(a||void 0),c=Array.isArray(o?.results)?o.results:o,d=Array.isArray(c)?c:[];return{text:JSON.stringify({accounts:d.slice(0,60)}).slice(0,12e3),summary:r("{n} 个账号",{n:d.length})}}},bG={id:"set_model_enabled",label:r("启用 / 禁用模型"),kind:"write",desc:"开启或关闭某几个模型在网关上的可用性(粒度是「提供商 × 模型」)。禁用后下游请求不再路由到它。一次可以改多个。",params:{type:"object",properties:{items:{type:"array",description:"要改的模型列表",items:{type:"object",properties:{provider:{type:"string",description:"提供商 id"},id:{type:"string",description:"模型 ID"},enabled:{type:"boolean",description:"true = 启用,false = 禁用"}},required:["provider","id","enabled"]}}},required:["items"]},plan:e=>{const t=Su(e.items);return{lead:r("将修改 {n} 个模型的启停状态:",{n:t.length}),table:{head:[r("提供商"),r("模型"),r("改成")],rows:t.map(a=>[at(a.provider),at(a.id),Ui(a.enabled)===!1?r("禁用"):r("启用")])},note:r("改动立即生效;禁用后指向它的请求会落到下一个候选。")}},run:async e=>{const t=Ja(),a=Su(e.items),o=[];for(const c of a){const d=at(c.provider),f=at(c.id),p=Ui(c.enabled);if(!d||!f||p===void 0)throw new Error(r("参数不完整(需要 provider / id / enabled)"));await t.setModelState?.({provider:d,id:f,enabled:p}),o.push(`${p?"启用":"禁用"} ${d}/${f}`)}return wu(),{text:JSON.stringify({ok:!0,changed:o}),summary:r("已修改 {n} 个模型",{n:o.length})}}},vG={id:"set_model_mapping",label:r("设置模型映射 ID"),kind:"write",desc:"给模型新增或删除映射名(对外名)。同一对外名可以在多个提供商各挂一条:下游用同一个名字请求,网关按账号优先级主备切换;也可以给不同家的同名模型各加前缀(如 ca/claude-sonnet-4.5)来精确指定某一家。一次可以改多条。删掉的映射名只是不再对外可用,不删任何模型。",params:{type:"object",properties:{items:{type:"array",description:"要改的映射列表",items:{type:"object",properties:{provider:{type:"string",description:"提供商 id"},id:{type:"string",description:"上游模型 ID"},alias:{type:"string",description:"要新增 / 删除的映射名(对外名)"},action:{type:"string",enum:["add","remove"],description:"add = 新增映射,remove = 删除映射"}},required:["provider","id","alias","action"]}}},required:["items"]},plan:e=>{const t=Su(e.items),a=t.filter(d=>at(d.action)!=="remove").length,o=t.length-a,c=[];return a&&c.push(r("新增 {n} 条",{n:a})),o&&c.push(r("删除 {n} 条",{n:o})),{lead:r("将改动 {n} 条映射({parts}):",{n:t.length,parts:c.join("、")}),table:{head:[r("提供商"),r("上游模型"),r("操作"),r("映射名")],rows:t.map(d=>[at(d.provider),at(d.id),at(d.action)==="remove"?r("删除"):r("新增"),at(d.alias)])},note:r("只改映射名,不动上游模型 ID;映射立即生效(新对话即可用)。")}},run:async e=>{const t=Ja(),a=Su(e.items),o=[];for(const c of a){const d=at(c.provider),f=at(c.id),p=at(c.alias,128);if(!d||!f||!p)throw new Error(r("参数不完整(需要 provider / id / alias)"));at(c.action)==="remove"?(await t.removeModelMapping?.(p,f,d),o.push(`删除 ${p} → ${d}/${f}`)):(await t.addModelMapping?.(p,f,d),o.push(`新增 ${p} → ${d}/${f}`))}return wu(),{text:JSON.stringify({ok:!0,changed:o}),summary:r("已改动 {n} 条映射",{n:o.length})}}},kO=["maxInputTokens","maxOutputTokens","supportsToolCall","supportsImages","supportsVideo","supportsReasoning"],Kj={maxInputTokens:"上下文窗口",maxOutputTokens:"最大输出 Token",supportsToolCall:"工具调用",supportsImages:"图片识别",supportsVideo:"视频识别",supportsReasoning:"深度推理"},yG={id:"set_model_capability",label:r("修改模型能力"),kind:"write",desc:"修改某个模型对下游声明的能力位:上下文窗口、最大输出 Token、工具调用 / 图片 / 视频 / 深度推理四个布尔位。只传要改的键;布尔位给 null 表示恢复上游原值。",params:{type:"object",properties:{provider:{type:"string",description:"提供商 id"},id:{type:"string",description:"模型 ID"},capabilities:{type:"object",description:"要改的能力位(只写要改的键)",properties:{maxInputTokens:{type:["number","null"],description:"上下文窗口(token 数)"},maxOutputTokens:{type:["number","null"],description:"最大输出 token 数"},supportsToolCall:{type:["boolean","null"],description:"是否支持工具调用;null = 恢复上游原值"},supportsImages:{type:["boolean","null"],description:"是否支持图片识别;null = 恢复上游原值"},supportsVideo:{type:["boolean","null"],description:"是否支持视频识别;null = 恢复上游原值"},supportsReasoning:{type:["boolean","null"],description:"是否支持深度推理;null = 恢复上游原值"}}}},required:["provider","id","capabilities"]},plan:e=>{const t=e.capabilities&&typeof e.capabilities=="object"?e.capabilities:{},a=kO.filter(o=>o in t);return{lead:r("将修改 {model} 的 {n} 项能力:",{model:`${at(e.provider)} / ${at(e.id)}`,n:a.length}),table:{head:[r("能力"),r("改成")],rows:a.map(o=>{const c=t[o],d=c===null?r("恢复上游原值"):typeof c=="boolean"?r(c?"支持":"不支持"):String(c);return[Kj[o]||o,d]})},note:r("能力位决定下游看到的声明(能不能贴图、能塞多少上下文),不改上游的真实行为。")}},run:async e=>{const t=at(e.provider),a=at(e.id),o=e.capabilities&&typeof e.capabilities=="object"?e.capabilities:{},c={};for(const d of kO){if(!(d in o))continue;const f=o[d];if(f===null){c[d]=null;continue}if(d==="maxInputTokens"||d==="maxOutputTokens"){const p=Lf(f);if(p===void 0)throw new Error(r("{key} 需要数字",{key:Kj[d]}));c[d]=Math.round(p)}else{const p=Ui(f);if(p===void 0)throw new Error(r("{key} 需要 true / false / null",{key:Kj[d]}));c[d]=p}}if(!t||!a||!Object.keys(c).length)throw new Error(r("参数不完整(需要 provider / id / capabilities)"));return await Ja().setModelCapabilities?.(t,a,c),wu(),{text:JSON.stringify({ok:!0,provider:t,id:a,capabilities:c}),summary:r("已修改 {n} 项能力",{n:Object.keys(c).length})}}},jG={id:"test_model",label:r("发起模型测试"),kind:"run",desc:"对某个模型发一次真实的对话请求,回报连通性、耗时与首字延迟。会消耗该账号的额度。回答「这个模型通不通 / 快不快」时用它。",params:{type:"object",properties:{provider:{type:"string",description:"提供商 id"},id:{type:"string",description:"模型 ID"},prompt:{type:"string",description:"测试用的用户提示词;不填 = 默认一句问候(最小请求)"}},required:["provider","id"]},plan:e=>({lead:r("将对 {model} 发起一次真实请求:",{model:`${at(e.provider)} / ${at(e.id)}`}),table:{head:[r("项"),r("值")],rows:[[r("提示词"),at(e.prompt)||r("(默认问候)")],[r("代价"),r("消耗该账号额度")]]},note:r("这是真实的上游请求,与生产走同一条链路(会记账,报表排除)。")}),run:async e=>{const t={provider:at(e.provider),model:at(e.id)},a=at(e.prompt,4e3);a&&(t.prompt=a);const o=await Ja().testModel?.(t),c=String(o?.status??""),d=o?.success===!0,f={ok:d,status:c,error:o?.error??null,reply:String(o?.reply??"").slice(0,1500),duration_ms:o?.duration_ms??null,ttfb_ms:o?.ttfb_ms??null,account:o?.account_name??null};return{text:JSON.stringify(f).slice(0,6e3),summary:d?r("连通 · {ms}ms",{ms:String(f.duration_ms??"")}):r("失败 · {status}",{status:c||"—"})}}},wG={id:"set_provider_order",label:r("调整提供商顺位"),kind:"write",desc:"调整某个提供商在账号全局队列里的**整组顺位**(第几组),决定路由时先试哪一家。这一家的所有账号会作为一整块移动。位置从 1 开始数。",params:{type:"object",properties:{provider:{type:"string",description:"提供商 id"},position:{type:"number",description:"目标组顺位(1 = 最前)"}},required:["provider","position"]},plan:e=>({lead:r("将把「{provider}」整组移到第 {position} 顺位:",{provider:at(e.provider)||r("(未指定)"),position:String(Lf(e.position)??"?")}),note:r("队列是一次性整表提交(后端按新顺序重编优先级),移动会连带调整其它组的相对次序。")}),run:async e=>{const t=at(e.provider).toLowerCase(),a=Lf(e.position);if(!t||a===void 0)throw new Error(r("参数不完整(需要 provider / position)"));const o=await xg(),c=[];for(const g of o){const v=at(g.id),y=at(g.provider).toLowerCase();if(!v)continue;const b=c[c.length-1];b&&b.provider===y?b.ids.push(v):c.push({provider:y,ids:[v]})}const d=c.findIndex(g=>g.provider===t);if(d<0)throw new Error(r("没有找到提供商「{provider}」的账号",{provider:t}));const f=Math.max(0,Math.min(c.length-1,Math.round(a)-1)),[p]=c.splice(d,1);return c.splice(f,0,p),await Ja().reorderAccounts?.(c.flatMap(g=>g.ids)),wu(),{text:JSON.stringify({ok:!0,provider:t,from:d+1,to:f+1,moved:p.ids.length}),summary:r("已移到第 {n} 顺位",{n:f+1})}}},SG={id:"set_account_order",label:r("调整账号优先级"),kind:"write",desc:"把某个账号移动到账号全局队列的第 N 顺位(1 = 最前)。位置决定主备与切换顺序:越靠前越先被使用。",params:{type:"object",properties:{account:{type:"string",description:"账号名或账号 id"},position:{type:"number",description:"目标顺位(1 = 最前)"}},required:["account","position"]},plan:e=>({lead:r("将把账号「{account}」移到第 {position} 顺位:",{account:at(e.account)||r("(未指定)"),position:String(Lf(e.position)??"?")}),note:r("队列是一次性整表提交;位置越靠前,路由时越先被选中。")}),run:async e=>{const t=at(e.account,128),a=Lf(e.position);if(!t||a===void 0)throw new Error(r("参数不完整(需要 account / position)"));const o=await xg(),c=Gj(o,t),d=at(c.id),f=o.map(v=>at(v.id)).filter(Boolean),p=f.indexOf(d);if(p<0)throw new Error(r("账号不在当前队列里"));f.splice(p,1);const g=Math.max(0,Math.min(f.length,Math.round(a)-1));return f.splice(g,0,d),await Ja().reorderAccounts?.(f),wu(),{text:JSON.stringify({ok:!0,account:zf(c),from:p+1,to:g+1}),summary:r("已移到第 {n} 顺位",{n:g+1})}}},NG={id:"set_account_enabled",label:r("启用 / 禁用账号"),kind:"write",desc:"开启或关闭某几个账号的转发资格。禁用只是把它移出队列(余额仍可查),但**如果某条线路只剩它**,禁用会直接断供。一次可以改多个。",params:{type:"object",properties:{items:{type:"array",description:"要改的账号列表",items:{type:"object",properties:{account:{type:"string",description:"账号名或账号 id"},enabled:{type:"boolean",description:"true = 启用,false = 禁用"}},required:["account","enabled"]}}},required:["items"]},plan:e=>{const t=Su(e.items),a=t.filter(o=>Ui(o.enabled)===!1).length;return{lead:r("将修改 {n} 个账号的启用状态(其中禁用 {k} 个):",{n:t.length,k:a}),table:{head:[r("账号"),r("改成")],rows:t.map(o=>[at(o.account),Ui(o.enabled)===!1?r("禁用"):r("启用")])},note:r("禁用会把账号移出转发队列;若这条线路没有别的可用账号,请求会直接失败。")}},run:async e=>{const t=Ja(),a=Su(e.items),o=await xg(),c=[];for(const d of a){const f=Ui(d.enabled);if(f===void 0)throw new Error(r("参数不完整(需要 account / enabled)"));const p=Gj(o,at(d.account,128));await t.updateAccount?.(at(p.id),{enabled:f}),c.push(`${f?"启用":"禁用"} ${zf(p)}`)}return wu(),{text:JSON.stringify({ok:!0,changed:c}),summary:r("已修改 {n} 个账号",{n:c.length})}}},bg=[gG,xG,bG,vG,yG,jG,wG,SG,NG];function Yj(e){return bg.find(t=>t.id===e)}function kG(e){return bg.filter(t=>e[t.id]).map(t=>({type:"function",function:{name:t.id,description:t.desc,parameters:t.params}}))}r("获取模型列表"),r("读各提供商的模型清单、映射名与启用状态。"),r("查询账号余额"),r("读各账号的额度 / 剩余用量。"),r("启用 / 禁用模型"),r("开关模型的对外可用性,不改其它属性。"),r("设置模型映射 ID"),r("新增 / 删除映射名,支持批量加前缀与同名合并到多家。"),r("修改模型能力"),r("改上下文窗口 / 最大输出 Token / 工具调用等能力位。"),r("发起模型测试"),r("对指定模型发一次真实请求,回报连通性与耗时。"),r("调整提供商顺位"),r("改某一家的整组顺位(先试哪一家)。"),r("调整账号优先级"),r("改账号在全局队列里的名次,决定主备与切换顺序。"),r("启用 / 禁用账号"),r("禁用会把账号移出转发队列,线路可能因此断供。");const CO=12;function Bf(e,t){return window.wbIcons?.icon?.(e,t)||""}function CG(e){const t=window.wbMarkdown;return t?.render?t.render(e):e.replace(/[&<>]/g,a=>({"&":"&","<":"<",">":">"})[a]||a)}function TG({tone:e}){return e==="plain"?s.jsx("span",{className:"asst-tc-ico",dangerouslySetInnerHTML:{__html:Bf("spark",13)}}):s.jsx("span",{className:Ue("asst-tc-ico",e),children:e==="warn"?"!":"✕"})}function EG({item:e,onConfirm:t}){const a=Yj(e.call.name),o=a?.label||e.call.name,c=qj(e.call.arguments),d=Object.keys(c).length?JSON.stringify(c,null,2):"";return s.jsxs("div",{className:Ue("asst-tool-card",e.state==="confirm"&&"confirm",e.state==="confirm"&&a?.kind==="run"&&"danger",e.state==="failed"&&"failed",e.state==="running"&&"running"),children:[s.jsxs("div",{className:"asst-tc-head",children:[e.state==="running"?s.jsx("span",{className:"asst-tc-ico",children:s.jsx("span",{className:"spin"})}):s.jsx(TG,{tone:e.state==="failed"?"bad":e.state==="confirm"?"warn":"plain"}),s.jsx("span",{className:"asst-tc-name",children:o}),e.state==="confirm"&&s.jsx("span",{className:"badge tag warn",children:r("待确认")}),e.state==="done"&&s.jsxs("span",{className:"asst-tc-state",children:["✓ ",e.summary||r("完成")]}),e.state==="failed"&&s.jsx("span",{className:"asst-tc-state bad",children:r("失败")}),e.state==="cancelled"&&s.jsx("span",{className:"asst-tc-state plain",children:r("已取消")})]}),e.state==="confirm"&&e.plan&&s.jsxs("div",{className:"asst-tc-plan",children:[e.plan.lead,e.plan.table&&s.jsxs("table",{className:"asst-mini-table",children:[s.jsx("thead",{children:s.jsx("tr",{children:e.plan.table.head.map((f,p)=>s.jsx("th",{children:f},p))})}),s.jsx("tbody",{children:e.plan.table.rows.slice(0,20).map((f,p)=>s.jsx("tr",{children:f.map((g,v)=>s.jsx("td",{className:v===f.length-1?"mono hl":"",children:g},v))},p))})]}),e.plan.table&&e.plan.table.rows.length>20&&s.jsx("div",{className:"hint",children:r("(仅显示前 20 条,共 {n} 条)",{n:e.plan.table.rows.length})}),e.plan.note&&s.jsx("div",{className:"hint",children:e.plan.note})]}),e.state==="failed"&&e.error&&s.jsx("div",{className:"asst-tc-error",children:e.error}),e.state==="done"&&e.detail&&s.jsxs("details",{children:[s.jsx("summary",{className:"asst-tc-result",style:{cursor:"pointer"},children:r("查看结果")}),s.jsx("pre",{className:"asst-tc-json",children:e.detail})]}),e.state!=="confirm"&&d&&s.jsxs("details",{children:[s.jsx("summary",{className:"asst-tc-result",style:{cursor:"pointer"},children:r("查看参数")}),s.jsx("pre",{className:"asst-tc-json",children:d})]}),e.state==="confirm"&&s.jsxs("div",{className:"asst-tc-foot",children:[s.jsx("span",{className:Ue("hint",a?.kind==="run"&&"danger"),children:a?.kind==="run"?r("这会真实发起上游请求并消耗额度"):r("确认后立即生效")}),s.jsx(se,{size:"sm",variant:a?.kind==="run"?"destructive":"default",onClick:()=>t(!0),children:r("执行")}),s.jsx(se,{size:"sm",variant:"outline",onClick:()=>t(!1),children:r("取消")})]})]})}function AG(){const[e,t]=x.useState(null),[a,o]=x.useState([]),[c,d]=x.useState([]),[f,p]=x.useState(!1),[g,v]=x.useState(!1),[y,b]=x.useState(""),[j,w]=x.useState(""),[S,N]=x.useState(!1),k=x.useRef([]),E=x.useRef([]),D=x.useRef(null),C=x.useRef(null),A=x.useRef(null),R=x.useRef(!1),I=x.useRef(0),P=x.useRef(null),O=x.useRef(0),_=x.useCallback(()=>{d(k.current.slice())},[]);x.useEffect(()=>{const M=A.current;if(!M)return;M.scrollHeight-M.scrollTop-M.clientHeight<160&&(M.scrollTop=M.scrollHeight)},[c]);const L=x.useCallback(async()=>{if(!R.current){R.current=!0;try{const M=await fG();t(M),N(!1),I.current=0}catch(M){N(!0),w(r("加载助手设置失败:{message}",{message:Nu(M)})),I.current<3&&(I.current+=1,R.current=!1,setTimeout(()=>{L()},4e3))}try{o(await dG())}catch(M){w(U=>U||r("读取模型清单失败:{message}",{message:Nu(M)}))}}},[]);x.useEffect(()=>{const M=window;return M.wbAssistant={activate:()=>{L()}},L(),()=>{delete M.wbAssistant}},[L]);const H=x.useMemo(()=>{const M={};for(const U of bg)M[U.id]=e?.tools?.[U.id]??!1;return M},[e]),B=x.useMemo(()=>kG(H),[H]),z=Object.values(H).filter(Boolean).length,Q=e?.model??null,K=x.useCallback(async(M,U,Z)=>{for(let ae=U;ae{if(O.current>=CO){k.current.push({kind:"notice",text:r("这一轮来回已达 {n} 次上限,我先停下等你指示(可以换个说法,或拆成几步让我做)。",{n:CO}),bad:!0}),_();return}O.current+=1,p(!0),w("");const M=new AbortController;C.current=M;const U=k.current.push({kind:"bot",text:"",streaming:!0})-1;_();let Z=[],ae=!1;try{await hG({messages:E.current,tools:B,signal:M.signal,onEvent:ie=>{if(ie.type==="delta"){const ge=k.current[U];ge&&ge.kind==="bot"&&(k.current[U]={...ge,text:ge.text+ie.text},_())}ie.type==="toolCalls"&&(Z=ie.calls)}})}catch(ie){ae=!0;const ge=Nu(ie),ee=k.current[U],fe=ee&&ee.kind==="bot"?ee.text:"";fe?k.current[U]={kind:"bot",text:fe}:k.current.splice(U,1);const te=M.signal.aborted;k.current.push({kind:"notice",text:te?r("已停止这次回答。"):r("请求失败:{message}",{message:ge}),bad:!te}),_()}finally{C.current=null}if(ae){p(!1);return}const ce=k.current[U];ce&&ce.kind==="bot"&&(k.current[U]={...ce,streaming:!1});const J=ce&&ce.kind==="bot"?ce.text:"";if(E.current.push({role:"assistant",content:J,toolCalls:Z.length?Z:void 0}),_(),!Z.length){p(!1);return}await K(Z,0,[])},[B,K,_]);P.current=X;const q=x.useCallback(async M=>{const U=D.current;if(!U)return;D.current=null,v(!1);const Z=U.calls[U.index],ae=Yj(Z.name),ce=qj(Z.arguments);if(!M||!ae)k.current[U.cardIndex]={kind:"tool",call:Z,state:"cancelled"},U.collected.push({toolCallId:Z.id,content:"用户取消了这次操作,没有做任何改动。"}),_();else{k.current[U.cardIndex]={kind:"tool",call:Z,state:"running"},p(!0),_();try{const J=await ae.run(ce);k.current[U.cardIndex]={kind:"tool",call:Z,state:"done",summary:J.summary,detail:J.text},U.collected.push({toolCallId:Z.id,content:J.text})}catch(J){const ie=Nu(J);k.current[U.cardIndex]={kind:"tool",call:Z,state:"failed",error:ie},U.collected.push({toolCallId:Z.id,content:`工具执行失败:${ie}`})}_()}await K(U.calls,U.index+1,U.collected)},[K,_]),$=x.useCallback(async M=>{const U=M.trim();if(!(!U||f||g)){if(O.current=0,k.current.push({kind:"user",text:U}),E.current.push({role:"user",content:U}),b(""),_(),!e){k.current.push({kind:"notice",text:r("助手设置没读出来,现在还不能发消息 —— 看输入框下方的提示。"),bad:!0}),_();return}if(!e.model){k.current.push({kind:"notice",text:r("还没有选择对话模型:先在下方选一个(或去「设置 → AI 助手」里选)。"),bad:!0}),_();return}await X()}},[g,f,e,X,_]),Y=x.useCallback(()=>{C.current?.abort()},[]),F=x.useCallback(()=>{C.current?.abort(),D.current=null,k.current=[],E.current=[],v(!1),p(!1),w(""),_()},[_]),G=x.useCallback(async M=>{if(!M)return;if(!e){w(r("助手设置没读出来,暂时存不了对话模型 —— 看输入框下方的提示。"));return}const U={...e,model:M};t(U);try{await pG(U)}catch(Z){w(r("保存对话模型失败:{message}",{message:Nu(Z)}))}},[e]),W=f||g,le=x.useRef(null);return s.jsxs("div",{className:"asst-layout",children:[s.jsxs("div",{className:"asst-top",children:[s.jsxs(ft,{value:Q??"",onValueChange:M=>{G(String(M))},children:[s.jsx(mt,{className:"asst-model-pick","aria-label":r("对话模型"),children:s.jsx(pt,{children:Q?s.jsxs("span",{className:"flex items-center gap-2",children:[s.jsx("span",{className:Ue("dot","ok")}),s.jsx("span",{className:"mono",children:Q})]}):r("选择模型…")})}),s.jsxs(ht,{children:[a.length===0&&s.jsx(qe,{value:"none",disabled:!0,children:r("没有可用的模型")}),a.map(M=>s.jsx(qe,{value:M,children:M},M))]})]}),s.jsx("span",{className:"asst-top-hint",children:r("助手走本地网关,消耗所选账号的额度")}),s.jsx("span",{className:"spacer"}),s.jsx(se,{variant:"ghost",size:"sm",onClick:F,disabled:f||g||!c.length,children:r("新对话")})]}),s.jsxs("div",{className:"asst-scroll",ref:A,children:[c.length===0&&s.jsxs("div",{className:"asst-empty",children:[s.jsx("div",{className:"empty-logo",dangerouslySetInnerHTML:{__html:Bf("spark",26)||""}}),s.jsx("h3",{children:r("AI 助手")}),s.jsxs("p",{children:[r("用一句话让我查或改本机的模型转发配置。"),s.jsx("br",{}),r("我会在动手前把改动列给你确认。")]}),s.jsx("div",{className:"asst-suggests",children:[r("看看哪些模型在多家重复了"),r("测一下当前最快的模型通不通"),r("CodeArts 的账号余额还剩多少?"),r("把重复的模型加上家名前缀区分开")].map(M=>s.jsxs("button",{type:"button",onClick:()=>{$(M)},children:["“",M,"”"]},M))}),e!==null&&z===0&&s.jsx("div",{className:"asst-empty-warn",children:r("当前一个工具都没勾选,助手只能纯聊天。去「设置 → AI 助手 → 工具」里勾上需要的工具。")}),S&&s.jsx("div",{className:"asst-empty-warn bad",children:j||r("助手设置读取失败,工具可能已过时。")})]}),c.map((M,U)=>M.kind==="user"?s.jsx("div",{className:"asst-msg user",children:s.jsx("div",{className:"bubble",children:M.text})},U):M.kind==="bot"?!M.text&&M.streaming?s.jsxs("div",{className:"asst-msg bot",children:[s.jsxs("div",{className:"who",children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:Bf("spark",14)||""}})," ",r("助手")]}),s.jsx("div",{className:"body",children:s.jsx("span",{className:"spin"})})]},U):s.jsxs("div",{className:"asst-msg bot",children:[s.jsxs("div",{className:"who",children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:Bf("spark",14)||""}})," ",r("助手")]}),s.jsxs("div",{className:"body",children:[s.jsx("span",{dangerouslySetInnerHTML:{__html:CG(M.text)}}),M.streaming&&s.jsx("span",{className:"asst-caret"})]})]},U):M.kind==="notice"?s.jsx("div",{className:"asst-msg bot",children:s.jsx("div",{className:Ue("asst-empty-warn",M.bad&&"bad"),style:{margin:0},children:M.text})},U):s.jsx(EG,{item:M,onConfirm:Z=>{q(Z)}},U))]}),s.jsxs("div",{className:"asst-composer",children:[s.jsxs("div",{className:"asst-ta-wrap",children:[s.jsx(Zc,{ref:le,rows:1,value:y,placeholder:r(W?"等这一轮跑完…":"直接说要改什么 / 查什么…(Enter 发送,Shift+Enter 换行)"),disabled:W,onChange:M=>{b(M.currentTarget.value);const U=M.currentTarget;U.style.height="auto",U.style.height=`${Math.min(U.scrollHeight,132)}px`},onKeyDown:M=>{M.key==="Enter"&&!M.shiftKey&&!M.nativeEvent.isComposing&&(M.preventDefault(),$(y))}}),f?s.jsx("button",{type:"button",className:"asst-send stop",title:r("停止"),onClick:Y,children:"■"}):s.jsx("button",{type:"button",className:"asst-send",title:r("发送"),disabled:W||!y.trim(),onClick:()=>{$(y)},children:"➤"})]}),s.jsxs("div",{className:"asst-composer-foot",children:[s.jsxs("span",{className:"tools-state",children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:Bf("settings",12)||""}}),r("已注入 {n} / {total} 个工具 · 系统提示词:{state}",{n:z,total:bg.length,state:e?.systemPromptEnabled?r("开"):r("关")})]}),s.jsx("span",{className:"spacer"}),j?s.jsxs("span",{className:"hint",children:[j,S&&s.jsx("button",{type:"button",className:"asst-tc-more",onClick:()=>{L()},children:r("重试")})]}):Q?s.jsx("span",{className:"hint",children:r("回复由 {model} 生成 · 走本地网关",{model:Q})}):null]})]})]})}const TO='.page[data-page="assistant"]';let Xj=null;function EO(){if(Xj)return;const e=document.querySelector(TO);e&&(e.replaceChildren(),Xj=vn.createRoot(e),Xj.render(s.jsx(AG,{})))}document.querySelector(TO)?EO():document.addEventListener("DOMContentLoaded",EO,{once:!0}),$j().catch(()=>{});function Ir(){return Pe().workbuddyDesktop??{}}function AO(){return window}const RO="workbuddy-desktop-checkin-tab",RG=["center","schedule","records"];function OG(){try{const e=localStorage.getItem(RO);return RG.includes(e)?e:"center"}catch{return"center"}}function OO(e){if(e!==hs.tab){try{localStorage.setItem(RO,e)}catch{}Js({tab:e})}}async function vg(e){OO(e),hs.loaded||await Ol()}let hs={version:0,tab:OG(),snapshot:null,loaded:!1,loadError:"",expanded:new Set,runningAll:!1,autoSaving:!1,autoTimeDraft:null,keepaliveSaving:!1,keepaliveDraft:null,signing:new Set,onboarding:new Map,growth:new Map};const Qj=new Set;function MG(){for(const e of Qj)e()}function Js(e){hs={...hs,...e,version:hs.version+1},MG()}function ur(){return hs}function MO(e){return Qj.add(e),()=>Qj.delete(e)}function DG(e){const t=typeof e?.key=="string"?e.key:"";return t?{key:t,title:typeof e.title=="string"&&e.title?e.title:t,group:typeof e.group=="string"&&e.group?e.group:"",points:Number(e.points)||0,done:e.done===!0,blocked:e.blocked===!0}:null}function Zj(e){return(Array.isArray(e)?e:[]).map(DG).filter(a=>a!==null)}function cs(e){return Number(e)||0}async function Ol(){try{const e=await Ir().getCheckinCenter?.();if(!e)throw new Error(r("后端未返回签到中心数据"));Js({snapshot:e,loaded:!0,loadError:"",autoTimeDraft:null,keepaliveDraft:null}),IG(e.extras?.onboarding??[])}catch(e){Js({loaded:!0,loadError:ut(e)})}}function IG(e){for(const t of e){const a=t.settled;if(!a||typeof a!="object")continue;const o=hs.onboarding.get(t.id);if(o?.status==="loaded"&&o.unclaimed>0)continue;const c=Zj(a.tasks),d=cs(a.at);Co(t.id,{status:"loaded",error:void 0,checkedAt:void 0,settled:!0,settledAt:d>0?d:void 0,tasks:c,unclaimed:0,earned:cs(a.earned),total:cs(a.total)})}}function DO(e){const t=new Set(hs.expanded);t.has(e)?t.delete(e):t.add(e),Js({expanded:t})}function Wj(e){const t=`onb:${e}`,a=new Set(hs.expanded);a.has(t)?a.delete(t):a.add(t),Js({expanded:a})}function IO(e){return hs.expanded.has(`onb:${e}`)}async function PG(){if(!hs.runningAll){Js({runningAll:!0});try{const e=await Ir().runAutoCheckinNow?.();if(e){const t=cs(e.succeeded),a=cs(e.active),o=cs(e.total),c=cs(e.failedCount),d=a>0?r(",日活保活 {n} 个",{n:a}):"";c>0?Le(r("签到完成:{succeeded}/{total} 成功{active},{failed} 个失败",{succeeded:t,total:o,active:d,failed:c}),"err"):Le(r("✅ 签到完成:{succeeded}/{total} 个账号成功领取{active}",{succeeded:t,total:o,active:d})),AO().wbAccountsView?.refreshUsageAfterCheckin?.(null)}}catch(e){Le(r("签到失败:{error}",{error:ut(e)}),"err")}finally{Js({runningAll:!1}),await Ol(),PO(ur().snapshot?.extras.onboarding??[]),Pe().wbApp?.refresh?.()}}}async function yg(e,t="checkin"){const a=`${e}:${t}`;if(hs.signing.has(a))return;const o=new Set(hs.signing);o.add(a),Js({signing:o});try{let c;t==="checkin"?c=(await Ir().checkinAllAccounts?.(e))?.results?.[0]:c=await Ir().runCheckinActivity?.(e,t)??void 0;const d=c?.claim,f=c?.activity,p=f?.report?.succeeded===!0;c?.error?Le(r("签到失败:{error}",{error:String(c.error)}),"err"):t==="keepalive"?f?.pokeSucceeded===!0||p?Le(r("✅ {message}",{message:d?.msg||r("活跃保活完成")})):Le(d?.msg||r("活跃保活失败"),"err"):d?.success===!0?Le(r("✅ {message}",{message:d.msg||r("签到成功")})):d?.alreadyCompleted===!0?Le(d?.msg||r("今日已领取"),"err"):p?Le(r("✅ {message}",{message:d?.msg||r("活跃上报完成,但活动未开启")})):f?.pokeSucceeded===!0?Le(r("✅ {message}",{message:d?.msg||r("活跃保活完成,但活动未开启")})):Le(d?.msg||r("未领取"),"err"),AO().wbAccountsView?.refreshUsageAfterCheckin?.(e)}catch(c){Le(r("签到失败:{error}",{error:ut(c)}),"err")}finally{const c=new Set(ur().signing);c.delete(a),Js({signing:c}),await Ol();const d=(ur().snapshot?.extras.onboarding??[]).filter(f=>f.id===e);PO(d),Pe().wbApp?.refresh?.()}}function jg(e){Js({keepaliveDraft:e.map(t=>t.trim()).filter(Boolean)})}async function _G(e){const t=e.map(a=>a.trim()).filter(Boolean);if(!ur().keepaliveSaving){Js({keepaliveSaving:!0});try{const a=await Ir().saveCheckinKeepalive?.(t);if(a){const o=ur().snapshot;Js({snapshot:o&&{...o,keepalive:a},keepaliveDraft:null}),Le(r("已保存:保活模型链"))}}catch(a){Le(r("保存失败:{error}",{error:ut(a)}),"err")}finally{Js({keepaliveSaving:!1})}}}async function PO(e){for(const t of e)LG(t.id)||await Jj(t.id);for(const t of e){const a=ur().onboarding.get(t.id);a?.status!=="loaded"||a.claiming||a.settled||(t.provider==="officeace"||a.unclaimed>0)&&await _O(t.id)}}function LG(e){return hs.onboarding.get(e)?.settled===!0}function ku(e){return hs.onboarding.get(e)??{status:"idle",tasks:[],unclaimed:0,earned:0,total:0,claiming:!1}}function Co(e,t){const a=new Map(hs.onboarding);a.set(e,{...ku(e),...t}),Js({onboarding:a})}async function Jj(e,t){const a=ku(e);if(!(a.status==="loading"||a.claiming)){Co(e,{status:"loading",error:void 0,settled:!1});try{const o=await Ir().getOnboardingTasks?.(e,t?.refresh===!0),c=Zj(o?.tasks),d=o?.settled===!0;Co(e,{status:"loaded",checkedAt:Date.now(),tasks:c,unclaimed:c.filter(f=>!f.done&&!f.blocked).length,earned:cs(o?.earned),total:cs(o?.total),settled:d,settledAt:d&&cs(o?.settledAt)||void 0}),t?.expand===!0&&c.length>0&&!IO(e)&&Wj(e)}catch(o){Co(e,{status:"error",error:ut(o),settled:!1})}}}async function _O(e){const t=ku(e);if(!(t.claiming||t.status!=="loaded")){Co(e,{claiming:!0});try{Co(e,{tasks:ku(e).tasks.map(b=>b.done?b:{...b,claiming:!0,error:void 0})});const a=await Ir().claimOnboardingTasks?.(e),o=new Map,c=Array.isArray(a?.results)?a.results:[];for(const b of c){const j=typeof b?.key=="string"?b.key:"";j&&b?.ok!==!0&&o.set(j,String(b?.error||r("领取失败")))}const d=Zj(a?.tasks),f=(d.length?d:ku(e).tasks).map(b=>({...b,claiming:!1,error:o.get(b.key)})),p=f.filter(b=>b.done&&!o.has(b.key)).length,g=a?.settled===!0;Co(e,{claiming:!1,checkedAt:Date.now(),tasks:f,unclaimed:f.filter(b=>!b.done&&!b.blocked).length,earned:cs(a?.earned),total:cs(a?.total),settled:g,settledAt:g&&cs(a?.settledAt)||void 0});const v=f.filter(b=>b.error&&!b.done).length,y=typeof a?.message=="string"?a.message.trim():"";v?Le(r("新手福利有 {n} 项领取失败,可重试",{n:v}),"err"):y?Le(y,"ok"):p&&Le(r("✅ 新手福利领取完成,累计 {n} 积分",{n:cs(a?.earned)}))}catch(a){const o=ut(a);Co(e,{claiming:!1,tasks:ku(e).tasks.map(c=>({...c,claiming:!1,error:c.done?void 0:o}))}),Le(r("领取失败:{error}",{error:o}),"err")}finally{await Ol()}}}function LO(e){return(Array.isArray(e)?e:[]).map(a=>{const o=a??{},c=typeof o.code=="string"?o.code:"";return c?{code:c,title:typeof o.title=="string"&&o.title?o.title:c,description:typeof o.description=="string"?o.description:"",status:typeof o.status=="string"?o.status:"",current:cs(o.current),target:cs(o.target),locked:o.locked===!0,unlockAt:o.unlockAt,supported:o.supported===!0,unforgeable:o.unforgeable===!0,unforgeableReason:typeof o.unforgeableReason=="string"?o.unforgeableReason:"",kind:typeof o.kind=="string"?o.kind:"",source:typeof o.source=="string"?o.source:""}:null}).filter(a=>a!==null)}function zO(e){return(Array.isArray(e)?e:[]).map(a=>{const o=a??{},c=typeof o.code=="string"?o.code:"";return c?{code:c,outcome:typeof o.outcome=="string"?o.outcome:"failed",message:typeof o.message=="string"?o.message:"",credit:cs(o.credit),energy:cs(o.energy)}:null}).filter(a=>a!==null)}function Vi(e){return hs.growth.get(e)??{status:"idle",energy:null,streak:null,tasks:[],travel:null,school:null,running:!1,runningSchool:!1,runningTravel:!1}}function Pr(e,t){const a=new Map(hs.growth);a.set(e,{...Vi(e),...t}),Js({growth:a})}function zG(e){return hs.expanded.has(`growth:${e}`)}function BO(e){const t=`growth:${e}`,a=new Set(hs.expanded);a.has(t)?a.delete(t):a.add(t),Js({expanded:a})}async function wg(e){const t=Vi(e);if(!(t.status==="loading"||t.running)){Pr(e,{status:"loading",error:void 0});try{const a=await Ir().getGrowthStatus?.(e),o=a?.tasks??{},c=a?.travel??null,d=a?.school??null;Pr(e,{status:"loaded",checkedAt:Date.now(),energy:a?.energy===null||a?.energy===void 0?null:cs(a.energy),streak:a?.streak===null||a?.streak===void 0?null:cs(a.streak),tasks:LO(o.tasks),travel:c,school:d?{...d,tasks:LO(d.tasks)}:null,error:typeof o.error=="string"?o.error:void 0})}catch(a){Pr(e,{status:"error",error:ut(a)})}}}async function HO(e,t){const a=Vi(e);if(a.running)return;const o=(a.tasks??[]).filter(g=>!g.supported||g.unforgeable===!0||g.locked===!0?!1:t==="claim"?g.status==="completed"||g.current>=g.target&&g.status!=="claimed":g.status!=="claimed");if(o.length===0){Le(r("没有需要执行的任务"));return}Pr(e,{running:!0,results:[],error:void 0});let c=0,d=0,f=0,p=0;for(const g of o)try{const v=await Ir().runGrowthTask?.(e,g.code,t),y=zO([v])[0];y&&(Pr(e,{results:[...Vi(e).results??[],y]}),c+=y.credit??0,d+=y.energy??0,(y.outcome==="done"||y.outcome==="already")&&(f+=1),y.outcome==="failed"&&(p+=1))}catch(v){p+=1,Pr(e,{results:[...Vi(e).results??[],{code:g.code,outcome:"failed",message:ut(v),credit:0,energy:0}]})}Pr(e,{running:!1}),p>0?Le(r("成长任务完成({done} 项成功、{failed} 项失败),积分 +{credit} 能量 +{energy}",{done:f,failed:p,credit:c,energy:d}),"err"):Le(r("✅ 成长任务执行完成:积分 +{credit} 能量 +{energy}",{credit:c,energy:d})),await wg(e)}async function BG(e,t){if(!Vi(e).runningSchool){Pr(e,{runningSchool:!0,error:void 0});try{const o=await Ir().runGrowthSchool?.(e,t),c=zO(o?.results),d=o?.lottery??null;Pr(e,{runningSchool:!1,results:c,schoolText:c.length?c.map(f=>`${f.code}:${f.message}`).join(";"):void 0,lotteryText:d?String(d.message??r("已抽 {n} 次",{n:cs(d.drawn)})):void 0,checkedAt:Date.now()}),Le(d?r("开学季执行完成:{message}",{message:String(d.message??"")}):r("✅ 开学季任务执行完成")),await wg(e)}catch(o){Pr(e,{runningSchool:!1,error:ut(o)}),Le(r("开学季执行失败:{error}",{error:ut(o)}),"err")}}}async function HG(e){if(!Vi(e).runningTravel){Pr(e,{runningTravel:!0,error:void 0});try{const a=await Ir().runGrowthTravel?.(e),o=String(a?.message??""),c=String(a?.outcome??"");Pr(e,{runningTravel:!1,checkedAt:Date.now()}),c==="failed"?Le(r("猫猫旅行失败:{message}",{message:o}),"err"):Le(r("猫猫旅行:{message}",{message:o})),await wg(e)}catch(a){Pr(e,{runningTravel:!1,error:ut(a)}),Le(r("猫猫旅行失败:{error}",{error:ut(a)}),"err")}}}function UG(e){return e.totalCount?e.doneCount>=e.totalCount?"done":e.doneCount>0?"part":"todo":"none"}function VG(e){const a=(Array.isArray(e?.schedules)?e.schedules:[]).filter(o=>o.enabled===!0).map(o=>Number(o.nextRunAt)).filter(o=>Number.isFinite(o)&&o>0);return a.length?Math.min(...a):null}let To={version:0,data:null,loaded:!1,loadError:"",saving:!1,runningId:null,editingId:null};const ew=new Set;function FG(){for(const e of ew)e()}function _r(e){To={...To,...e,version:To.version+1},FG()}function UO(){return To}function $G(e){return ew.add(e),()=>ew.delete(e)}function Cu(){return Pe().workbuddyDesktop??{}}async function VO(){try{const e=await Cu().getCheckinSchedules?.();if(!e)throw new Error(r("后端未返回定时签到数据"));_r({data:e,loaded:!0,loadError:""})}catch(e){_r({loaded:!0,loadError:ut(e)})}}function Sg(e){e&&_r({data:e,loadError:""}),Ol()}async function qG(e){if(!To.saving){_r({saving:!0});try{const t=await Cu().saveAutoCheckin?.({enabled:e});Sg(t),Le(r(e?"✅ 定时签到已开启":"定时签到已关闭"))}catch(t){Le(r("保存失败:{error}",{error:ut(t)}),"err")}finally{_r({saving:!1})}}}async function FO(e){if(!To.saving){_r({saving:!0});try{const t=await Cu().saveCheckinSchedule?.(e);Sg(t),_r({editingId:null}),Le(r("已保存:定时条目"))}catch(t){Le(r("保存失败:{error}",{error:ut(t)}),"err")}finally{_r({saving:!1})}}}async function GG(e,t){await FO({id:e.id,label:e.label??"",enabled:t,time:e.time??"",providers:Array.isArray(e.providers)?e.providers:[]})}async function KG(e){if(!To.saving){_r({saving:!0});try{await Cu().deleteCheckinSchedule?.(e),Sg(await Cu().getCheckinSchedules?.()),Le(r("已删除定时条目"))}catch(t){Le(r("删除失败:{error}",{error:ut(t)}),"err")}finally{_r({saving:!1})}}}async function YG(e){if(!To.runningId){_r({runningId:e});try{const t=await Cu().runCheckinSchedule?.(e)??void 0,a=o=>Number(o)||0;if(t){const o=a(t.succeeded),c=a(t.active),d=a(t.total),f=a(t.failedCount),p=c>0?r(",日活保活 {n} 个",{n:c}):"";f>0?Le(r("签到完成:{succeeded}/{total} 成功{active},{failed} 个失败",{succeeded:o,total:d,active:p,failed:f}),"err"):Le(r("✅ 签到完成:{succeeded}/{total} 个账号成功领取{active}",{succeeded:o,total:d,active:p})),Sg(t)}}catch(t){Le(r("执行失败:{error}",{error:ut(t)}),"err")}finally{_r({runningId:null}),await Ol()}}}function tw(e){_r({editingId:e})}const XG=r("到点后自动签到勾选提供商的可用账号(WorkBuddy 国内版走每日签到接口,国际版走每日活跃任务:探测活动、领日活奖励、再用免费模型保活;小浣熊走桌面端每日积分链路;AutoClaw 走官方客户端的每日签到任务;Qoder 中国版走活动领取,没被下发活动的账号会得到中性提示;Qoder 国际版要先带设备风控身份(本机 Qoder 客户端 / qodercli 的 UMID 组件生成)才能看到「每日 100 Credits」活动,缺组件时会得到明确的说明而不是报错;Trae 领 SOLO 的每日签到积分(按自然日 0 点重置),上游没对该账号开活动、或凭据里没有设备号时得到的是「未领取 + 具体原因」而不是报错;Loomy 每天替账号打一次首次登录积分;KukuAI 领「免费领积分」的每日任务;CodeArts 领当日的运营福利(领取 → 确认 → 回读核实,自动执行受每天 6 次 / 间隔 10 分钟的写请求限流);OfficeAce 果办一次领当天全部奖励(每日签到 + 新人礼))。错过时点开机后会自动补签,不会因为当时没开机而漏掉。各家签到接口都是幂等的,重复执行不会重复领取。");function QG(){const[e,t]=x.useState(UO());return x.useEffect(()=>$G(()=>t(UO())),[]),e}function ZG(){const[e,t]=x.useState(ur());return x.useEffect(()=>MO(()=>t(ur())),[]),e}function $O(e,t){const a=Array.isArray(e.providers)?e.providers:[];return t.filter(o=>a.includes(o.id)).map(o=>o.label)}function WG(e,t){const a=$O(e,t);return a.length?t.length>0&&a.length>=t.length?r("全部 {n} 家",{n:t.length}):a.join(r("、")):r("未勾选提供商")}function JG(e,t){const a=$O(e,t);return a.length?a.join(r("、")):r("未勾选提供商")}function e7(e){const t=e.lastResult;if(!t)return r("还没执行过");const a=f=>Number(f)||0,o=[r("成功 {n}",{n:a(t.succeeded)})],c=a(t.active);c>0&&o.push(r("保活 {n}",{n:c}));const d=a(t.failedCount);return d>0&&o.push(r("失败 {n}",{n:d})),`${t.at?Vs(t.at):"—"}${t.reason?` · ${t.reason}`:""} —— ${o.join(r(" · "))}`}function qO({entry:e,store:t}){const a=Array.isArray(t.data?.providerOptions)?t.data.providerOptions:[],o=e===null,[c,d]=x.useState(e?.label??""),[f,p]=x.useState(e?.time??"00:01"),[g,v]=x.useState(new Set(o?a.map(S=>S.id):e?.providers??[]));x.useEffect(()=>{o&&a.length>0&&v(new Set(a.map(S=>S.id)))},[]);const y=f.trim()!==""&&g.size>0,b=()=>v(new Set(a.map(S=>S.id))),j=()=>v(new Set),w=async()=>{await FO({id:e?.id,label:c.trim(),enabled:e?.enabled??!0,time:f.trim(),providers:a.map(S=>S.id).filter(S=>g.has(S))})};return s.jsxs("div",{className:"ck-sched-editor",children:[s.jsxs("div",{className:"ck-set-line",children:[s.jsx("span",{className:"ck-set-k",children:r("名称")}),s.jsx("span",{className:"ck-set-v",children:s.jsx($e,{type:"text",className:"max-w-[220px]",placeholder:r("可选 · 缺省显示时刻"),value:c,disabled:t.saving,onChange:S=>d(S.currentTarget.value)})})]}),s.jsxs("div",{className:"ck-set-line",children:[s.jsx("span",{className:"ck-set-k",children:r("每天时刻")}),s.jsxs("span",{className:"ck-set-v flex items-center gap-2",children:[s.jsx($e,{type:"time",className:"w-[96px] max-w-[96px] font-mono tabular-nums",value:f,disabled:t.saving,onChange:S=>p(S.currentTarget.value)}),s.jsx("span",{className:"text-subtle text-xs",children:r("北京时间 · 错过时点开机后会自动补签")})]})]}),s.jsxs("div",{className:"ck-set-line ck-set-line-top",children:[s.jsx("span",{className:"ck-set-k",children:r("签到范围")}),s.jsxs("span",{className:"ck-set-v",children:[s.jsxs("div",{className:"ck-mini-row",children:[s.jsx("span",{className:"ck-mini-note",children:r("到点时逐个签到,已勾 {n} / {total} 家",{n:g.size,total:a.length})}),s.jsx("button",{type:"button",className:"ck-mini-btn",disabled:t.saving,onClick:b,children:r("全选")}),s.jsx("button",{type:"button",className:"ck-mini-btn",disabled:t.saving||g.size===0,onClick:j,children:r("清空")})]}),s.jsx("div",{className:"ck-range",children:a.map(S=>s.jsxs("label",{className:"ck-range-item",children:[s.jsx(Or,{checked:g.has(S.id),disabled:t.saving,onCheckedChange:N=>{const k=new Set(g);N===!0?k.add(S.id):k.delete(S.id),v(k)}}),s.jsx("span",{className:"ck-range-name",title:S.label,children:S.label})]},S.id))}),g.size===0?s.jsx("div",{className:"ck-mini-warn",children:r("至少勾一家才能保存(不勾等于这条条目不签到)")}):null]})]}),s.jsxs("div",{className:"ck-sched-actions",children:[s.jsx(se,{size:"sm",variant:"outline",disabled:t.saving,onClick:()=>tw(null),children:r("取消")}),s.jsx(se,{size:"sm",variant:"default",disabled:!y||t.saving,onClick:()=>{w()},children:t.saving?r("保存中…"):r("保存")})]})]})}function t7({store:e}){return s.jsxs("div",{className:"ck-sched-row open ck-sched-row-new",children:[s.jsxs("div",{className:"ck-sched-main",children:[s.jsx("span",{className:"ck-new-dot","aria-hidden":!0,children:"+"}),s.jsxs("div",{className:"ck-prov-info",children:[s.jsx("div",{className:"ck-prov-name",children:r("新建定时条目")}),s.jsx("div",{className:"ck-prov-desc",children:r("填好时刻与签到范围后点「保存」;名称可以留空(界面显示时刻)")})]})]}),s.jsx(qO,{entry:null,store:e})]})}function n7({entry:e,store:t}){const a=Array.isArray(t.data?.providerOptions)?t.data.providerOptions:[],o=t.editingId===e.id,c=t.runningId===e.id,d=t.data?.enabled===!0,f=Number(e.nextRunAt),p=async()=>{const g=Pe().wbConfirm?.ask;if(!g)return;const y=(e.displayLabel||e.time||e.id).replace(/&/g,"&").replace(//g,">");await g({title:r("删除定时条目"),html:r("确定删除「{name}」?删除后到点不再执行。",{name:y}),okText:r("删除"),okClass:"danger"})&&await KG(e.id)};return s.jsxs("div",{className:o?"ck-sched-row open":"ck-sched-row",children:[s.jsxs("div",{className:"ck-sched-main",children:[s.jsx(ms,{checked:e.enabled===!0,disabled:t.saving,onCheckedChange:g=>{GG(e,g===!0)}}),s.jsxs("div",{className:"ck-prov-info",children:[s.jsxs("div",{className:"ck-prov-name",children:[e.displayLabel||e.time||e.id,e.enabled===!0?null:s.jsx(ze,{variant:"outline",shape:"tag",children:r("已停用")})]}),s.jsx("div",{className:"ck-prov-desc ck-sched-scope",title:JG(e,a),children:r("每天 {time} · {scope}",{time:e.time??"—",scope:WG(e,a)})}),s.jsx("div",{className:"ck-prov-desc",children:r("上次执行:{line}",{line:e7(e)})})]}),s.jsxs("div",{className:"ck-prov-right",children:[s.jsx("span",{className:"ck-sched-next",children:d&&e.enabled===!0&&Number.isFinite(f)&&f>0?r("下次 {date}",{date:Vs(f)}):"—"}),s.jsx(se,{size:"sm",variant:"ghost",disabled:c||t.runningId!==null,onClick:()=>{YG(e.id)},children:r(c?"执行中…":"立即执行")}),s.jsx(se,{size:"sm",variant:"ghost",onClick:()=>tw(o?null:e.id),children:r(o?"收起":"编辑")}),s.jsx(se,{size:"sm",variant:"ghost",className:"text-destructive",disabled:t.saving,onClick:()=>{p()},children:r("删除")})]})]}),o?s.jsx(qO,{entry:e,store:t}):null]})}function s7(e,t){return e.length===t.length&&e.every((a,o)=>a===t[o])}let Hf=null;function r7(e,t){for(let a=0;ag!==t.row),d=r7(c,e.clientY);if(d===t.from)return;const f=[...t.list],[p]=f.splice(t.from,1);f.splice(d,0,p),t.list=f,t.from=d,t.onChange(f)}function Uf(){const e=Hf;Hf=null,window.removeEventListener("pointermove",GO),window.removeEventListener("pointerup",Uf),window.removeEventListener("pointercancel",Uf),document.body.classList.remove("ck-chain-dragging"),e?.row.classList.remove("dragging")}function a7(e,t,a,o){if(e.button!==0||Hf||a.length<2)return;const c=e.currentTarget.closest(".ck-chain-row");c&&(e.preventDefault(),Hf={list:[...a],from:t,row:c,onChange:o},c.classList.add("dragging"),document.body.classList.add("ck-chain-dragging"),window.addEventListener("pointermove",GO),window.addEventListener("pointerup",Uf),window.addEventListener("pointercancel",Uf))}function l7({models:e,defaultModels:t,dirty:a,saving:o}){const[c,d]=x.useState(""),f=()=>{const p=c.trim();if(p){if(e.includes(p)){Le(r("清单里已经有「{name}」",{name:p}),"err");return}jg([...e,p]),d("")}};return s.jsxs("section",{className:"panel ck-chain-panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("保活模型链")}),s.jsx("span",{className:"panel-sub",children:r("WorkBuddy 国际版日活任务的免费模型 · 全局一份,与条目无关")}),s.jsx(se,{size:"sm",variant:"default",className:"ml-auto",disabled:!a||o,onClick:()=>{_G(e)},children:r(o?"保存中…":"保存")})]}),s.jsxs("div",{className:"p-4",children:[s.jsxs("div",{className:"ck-set-line ck-set-line-top",children:[s.jsx("span",{className:"ck-set-k",children:r("模型清单")}),s.jsxs("span",{className:"ck-set-v",children:[s.jsxs("div",{className:"ck-mini-row",children:[s.jsx("span",{className:"ck-mini-note",children:r("按序逐个尝试,共 {n} 个",{n:e.length})}),s.jsx("button",{type:"button",className:"ck-mini-btn",disabled:o||t.length===0,title:r("把缺省链填进清单,再点「保存」生效"),onClick:()=>jg([...t]),children:r("填入缺省链")})]}),s.jsxs("div",{className:"ck-chain",children:[e.map((p,g)=>s.jsxs("div",{className:"ck-chain-row",children:[s.jsx("span",{className:"ck-chain-grip",role:"button",tabIndex:-1,"aria-label":r("按住拖动调整顺序"),title:r("按住拖动,调整这个模型在链里的顺序"),onPointerDown:v=>a7(v,g,e,jg),dangerouslySetInnerHTML:{__html:Pe().wbIcons?.icon?.("gripVertical",14)||""}}),s.jsx("span",{className:"ck-chain-name",title:p,children:p}),s.jsxs("span",{className:"ck-chain-index",children:["#",g+1]}),s.jsx("button",{type:"button",className:"ck-chain-del",disabled:o,"aria-label":r("移除 {name}",{name:p}),title:r("从清单里移除"),onClick:()=>jg(e.filter((v,y)=>y!==g)),children:"×"})]},p)),e.length===0?s.jsx("div",{className:"ck-chain-empty",children:r("清单为空 —— 保存后恢复缺省链")}):null]}),s.jsxs("div",{className:"ck-chain-add",children:[s.jsx($e,{type:"text",className:"max-w-[260px] font-mono text-xs",placeholder:r("WorkBuddy 国际版保活模型,按顺序回退"),value:c,disabled:o,onChange:p=>d(p.currentTarget.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),f())}}),s.jsx(se,{size:"sm",variant:"outline",disabled:o||c.trim()==="",onClick:f,children:r("添加模型")}),a?s.jsx("span",{className:"ck-chain-dirty",children:r("有未保存的改动")}):null]})]})]}),s.jsx("div",{className:"ck-note",children:r("「保活模型链」是 WorkBuddy 国际版领日活时用来保活的免费模型,按顺序逐个尝试、 第一个成功即止;清空清单并保存 = 恢复缺省链(当前缺省:{defaults})。 当天去重 + 幂等领取:重复执行只会拿到「已领取」,不会重复加分。",{defaults:t.join(r("、"))})})]})]})}function o7(){const e=QG(),t=ZG();if(x.useEffect(()=>{VO()},[]),!e.loaded)return s.jsxs("div",{className:"ck-loading",children:[s.jsx(Jd,{className:"size-5"}),s.jsx("span",{children:r("正在读取定时签到数据…")})]});const a=e.data,o=a?.enabled===!0,c=Array.isArray(a?.schedules)?a.schedules:[],d=t.snapshot?.keepalive,f=Array.isArray(d?.models)?d.models:[],p=Array.isArray(d?.defaultModels)?d.defaultModels:[],g=t.keepaliveDraft,v=g??f,y=g!==null&&!s7(g,f);return s.jsxs("div",{children:[e.loadError?s.jsxs("div",{className:"ck-page-error",children:[s.jsx("span",{children:r("读取定时签到数据失败:{error}",{error:e.loadError})}),s.jsx(se,{size:"sm",variant:"outline",onClick:()=>{VO()},children:r("重试")})]}):null,s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("定时签到")}),s.jsx("span",{className:"tip-q","data-tip":XG}),s.jsx("span",{className:"panel-sub",children:r("每条条目各有时刻与范围 · 各自当天去重 · 错过时点开机自动补签")}),s.jsx(se,{size:"sm",variant:"outline",className:"ml-auto flex-none",disabled:e.saving,onClick:()=>tw(e.editingId==="new"?null:"new"),children:e.editingId==="new"?r("收起新建"):r("添加条目")})]}),s.jsx("div",{className:"p-4",children:s.jsxs("div",{className:"ck-set-line",children:[s.jsx("span",{className:"ck-set-k",children:r("总开关")}),s.jsxs("span",{className:"ck-set-v flex items-center gap-2",children:[s.jsx(ms,{checked:o,disabled:e.saving,onCheckedChange:b=>{qG(b===!0)}}),s.jsx("span",{className:"text-subtle text-xs",children:r(o?"开着:启用的条目按各自时刻执行":"关着:所有条目都不执行")})]})]})}),s.jsxs("div",{children:[e.editingId==="new"?s.jsx(t7,{store:e}):null,c.map(b=>s.jsx(n7,{entry:b,store:e},b.id)),c.length===0?s.jsx("div",{className:"ck-empty",children:r("还没有定时条目 —— 点「添加条目」建一条,或到「签到中心」手动签到。")}):null]})]}),s.jsx(l7,{models:v,defaultModels:p,dirty:y,saving:t.keepaliveSaving})]})}const Ng="checkin-records",KO=["today","7","30","month","all"],Tu="all",i7=[{value:"today",label:r("今天")},{value:"7",label:r("7 天")},{value:"30",label:r("30 天")},{value:"month",label:r("本月")},{value:"all",label:r("全部")}],YO="workbuddy-desktop-checkin-records-range";function kg(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function XO(e){const t=new Date;switch(e){case"today":return kg(t);case"7":return kg(new Date(t.getFullYear(),t.getMonth(),t.getDate()-6));case"30":return kg(new Date(t.getFullYear(),t.getMonth(),t.getDate()-29));case"month":return kg(new Date(t.getFullYear(),t.getMonth(),1));default:return null}}function c7(){try{const e=localStorage.getItem(YO);return e!==null&&KO.includes(e)?e:Tu}catch{return Tu}}function QO(e){try{localStorage.setItem(YO,e)}catch{}}function ZO(e){return typeof e=="number"&&e>0?e:fu}const nw={success:{label:"成功领取",variant:"success"},already:{label:"今日已领",variant:"brand"},pending:{label:"等待窗口",variant:"warning"},failed:{label:"失败",variant:"destructive"}},u7={schedule:"定时",startup:"补签",manual:"手动",single:"单签",activity:"活动"},sw=[{key:"time",label:r("时间")},{key:"account",label:r("账号")},{key:"provider",label:r("提供商")},{key:"source",label:r("来源")},{key:"outcome",label:r("结果")},{key:"detail",label:r("说明")}];let rw=null;function WO(){return rw?rw.apply([...sw]):sw.map(e=>({...e,align:e.align??"left"}))}function JO(){window.wbTableColumns?.repaint?.(Ng)}function eM(e){return(ur().snapshot?.auto?.providerOptions??[]).find(a=>a.id===e)?.label??e}function d7(e,t){const a=`ck-col-${t.key} ta-${t.align}`;switch(t.key){case"time":return s.jsxs("td",{className:a,children:[e.ts?Vs(e.ts):"—",s.jsx("span",{className:"ck-record-date",children:e.date||""})]},t.key);case"account":return s.jsx("td",{className:a,children:e.accountName||e.accountId||"—"},t.key);case"provider":return s.jsx("td",{className:a,children:e.provider?eM(e.provider):"—"},t.key);case"source":return s.jsxs("td",{className:a,children:[s.jsx("span",{className:"ck-record-source",children:u7[e.source??""]??e.source??"—"}),e.reason?s.jsx("span",{className:"ck-record-reason",children:e.reason}):null]},t.key);case"outcome":{const o=nw[e.outcome??""]??{label:e.outcome||"—",variant:"outline"};return s.jsxs("td",{className:a,children:[s.jsx(ze,{variant:o.variant,shape:"tag",children:o.label}),e.keptActive?s.jsx(ze,{variant:"outline",shape:"tag",className:"ml-1",children:r("保活")}):null]},t.key)}case"detail":return s.jsx("td",{className:e.error?`${a} ck-record-detail-fail`:a,children:e.error||e.message||"—"},t.key);default:return null}}function f7(){const[e,t]=x.useState([]),[a,o]=x.useState(0),[c,d]=x.useState(1),[f,p]=x.useState(()=>c7()),[g,v]=x.useState(()=>ZO(sg(Ng,tg))),[y,b]=x.useState({outcome:"",provider:"",keyword:""}),[j,w]=x.useState(""),[S,N]=x.useState(!1),[k,E]=x.useState(""),[D,C]=x.useState(0),A=x.useRef(null),R=x.useRef(0),[,I]=x.useReducer(Y=>Y+1,0),P=ur().snapshot?.auto?.providerOptions??[],O=WO(),_=Math.max(1,Math.ceil(a/g)),L=Math.min(c,_),H=y.outcome!==""||y.provider!==""||y.keyword!==""||f!==Tu,B=a?{start:(L-1)*g+1,end:Math.min(a,L*g)}:null,z=x.useCallback(async Y=>{const F=R.current+1;R.current=F,N(!0),E("");try{const W=await Pe().workbuddyDesktop?.getCheckinRecords?.({limit:Y.size,offset:(Y.page-1)*Y.size,outcome:Y.filters.outcome,provider:Y.filters.provider,keyword:Y.filters.keyword,start:XO(Y.range)});if(F!==R.current)return;t(Array.isArray(W?.records)?W.records:[]),o(Number(W?.total)||0)}catch(G){if(F!==R.current)return;E(G instanceof Error?G.message:String(G))}finally{F===R.current&&N(!1)}},[]);x.useEffect(()=>{z({page:c,size:g,range:f,filters:y})},[z,c,g,f,y]),x.useEffect(()=>{c>_&&d(_)},[c,_]),x.useLayoutEffect(()=>{const Y=Pe().wbColSettings;if(!Y?.register){const F=window.setTimeout(()=>C(G=>G+1),50);return()=>window.clearTimeout(F)}rw=Y.register({id:Ng,label:r("签到记录表"),columns:sw.map(F=>({key:F.key,label:F.label,align:F.align??"left"})),mount:()=>A.current,onChange:()=>{ks.flushSync(()=>I()),JO()}}),I()},[D]),x.useLayoutEffect(()=>{JO()}),x.useEffect(()=>()=>{Pe().wbColSettings?.close()},[]);const Q=Y=>{b(Y),d(1)},K=Y=>{const F=KO.includes(Y)?Y:Tu;F!==f&&(QO(F),p(F),d(1))},X=Y=>{v(ZO(Y)),rg(Ng,Y),d(1)},q=()=>{w(""),QO(Tu),p(Tu),Q({outcome:"",provider:"",keyword:""})},$=async()=>{const Y=Pe().wbConfirm?.ask;if(!Y)return;const F=r(H?"确定清空当前筛选出的签到记录?清空后无法恢复。":"确定清空全部签到记录?清空后无法恢复。");if(await Y({title:r("清空签到记录"),html:F,okText:r("清空"),okClass:"danger"}))try{await Pe().workbuddyDesktop?.clearCheckinRecords?.(H?{outcome:y.outcome,provider:y.provider,keyword:y.keyword,start:XO(f)}:{all:"1"}),tM("签到记录已清空"),await z({page:1,size:g,range:f,filters:y}),d(1)}catch(G){tM(r("清空失败:{error}",{error:G instanceof Error?G.message:String(G)}),"err")}};return s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("签到记录")}),s.jsx("span",{className:"panel-sub",children:r("每执行一次签到 · 每个账号一条明细 · 结果与收益以后端落账为准")}),s.jsxs("div",{ref:A,className:"ml-auto flex items-center gap-2",children:[s.jsx(se,{size:"sm",variant:"outline",disabled:S,onClick:()=>{z({page:c,size:g,range:f,filters:y})},children:r(S?"刷新中…":"刷新")}),s.jsx(se,{size:"sm",variant:"ghost",className:"text-destructive",onClick:()=>{$()},children:r("清空")})]})]}),s.jsxs("div",{className:"ck-records-filters",children:[s.jsx(In,{options:i7,value:f,onValueChange:K,"aria-label":r("签到记录时间范围"),className:"shrink-0"}),s.jsxs(ft,{value:y.outcome,onValueChange:Y=>Q({...y,outcome:Y??""}),children:[s.jsx(mt,{className:"w-[128px] shrink-0","aria-label":r("按结果筛选"),children:s.jsx(pt,{children:y.outcome?nw[y.outcome]?.label??y.outcome:r("全部结果")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"",children:r("全部结果")}),Object.entries(nw).map(([Y,F])=>s.jsx(qe,{value:Y,children:F.label},Y))]})]}),s.jsxs(ft,{value:y.provider,onValueChange:Y=>Q({...y,provider:Y??""}),children:[s.jsx(mt,{className:"w-[148px] shrink-0","aria-label":r("按提供商筛选"),children:s.jsx(pt,{children:y.provider?eM(y.provider):r("全部提供商")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"",children:r("全部提供商")}),P.map(Y=>s.jsx(qe,{value:Y.id,children:Y.label},Y.id))]})]}),s.jsx("div",{className:"spacer"}),s.jsx($e,{type:"search",className:"ck-records-search w-[200px] basis-[200px] min-w-[150px] grow-0 shrink",placeholder:r("搜账号 / 收益 / 错误 / 触发原因"),value:j,onChange:Y=>w(Y.currentTarget.value),onBlur:()=>{j!==y.keyword&&Q({...y,keyword:j.trim()})},onKeyDown:Y=>{Y.key==="Enter"&&Y.currentTarget.blur(),Y.key==="Escape"&&(w(y.keyword),Y.currentTarget.blur())}}),H?s.jsx(se,{size:"sm",variant:"ghost",onClick:q,children:r("清除筛选")}):null,s.jsx("span",{className:"panel-sub",children:S?r("读取中…"):r("{n} 条",{n:a})})]}),k?s.jsxs("div",{className:"ck-page-error",children:[s.jsx("span",{children:r("读取签到记录失败:{error}",{error:k})}),s.jsx(se,{size:"sm",variant:"outline",onClick:()=>{z({page:c,size:g,range:f,filters:y})},children:r("重试")})]}):null,e.length===0&&!S?s.jsx("div",{className:"ck-empty",children:r(H?"没有符合筛选条件的签到记录":"还没有签到记录 —— 手动签到或等定时条目执行后,明细会出现在这里。")}):s.jsx("div",{className:"ck-records-scroll",children:s.jsxs("table",{className:"ck-table ck-records-table",children:[s.jsx("colgroup",{children:O.map(Y=>s.jsx("col",{"data-col":Y.key,className:`ck-col-${Y.key}`},Y.key))}),s.jsx("thead",{children:s.jsx("tr",{children:O.map(Y=>s.jsx("th",{"data-col":Y.key,className:`ck-col-${Y.key} ta-${Y.align}`,children:Y.label},Y.key))})}),s.jsx("tbody",{children:e.map(Y=>s.jsx("tr",{children:O.map(F=>d7(Y,F))},Y.rowId))})]})}),s.jsx(Li,{total:a,range:B,page:L,pageCount:_,size:g,sizes:tg,onSizeChange:X,onPageChange:d,disabled:S})]})}function tM(e,t){Pe().wbApp?.toast?.(e,t)}window.wbCheckinRecords={visibleColumns:()=>WO().map(e=>({key:e.key}))};const nM={workbuddy:r("腾讯每日签到接口 · 仅国内版"),"workbuddy-intl":r("每日活跃任务 · 领取才加积分,保活只维持活跃 · 两者可分开执行"),raccoon:r("桌面端每日积分链路"),autoclaw:r("官方客户端的每日签到任务"),"autoclaw-intl":r("与国内版同一套任务接口 · 站点不同"),qoder:r("活动(campaign)领取 · 每天 10:00 刷新"),"qoder-intl":r("带设备风控身份领取「每日 100 Credits」 · 需要 UMID 组件"),trae:r("SOLO 的 checkin_credits 领取 · 按自然日 0 点刷新"),loomy:r("无独立签到接口 · 每天替账号打一次首次登录积分"),kuku:r("「免费领积分」的每日任务 · 逐个领取"),officeace:r("一次领当天全部奖励(每日签到 + 新人礼) · 幂等由上游保证"),codearts:r("每日福利 · 领取 → 确认 → 回读核实 · 按北京时间自然日重置")},p7=[{value:"center",label:r("签到中心")},{value:"schedule",label:r("定时签到")},{value:"records",label:r("签到记录")}];function m7(e){return e==="raccoon"?"小浣熊":e==="loomy"?"Loomy":e==="codearts"?"CodeArts":e==="officeace"?"OfficeAce 果办":e}function h7(){const[e,t]=x.useState(ur());return x.useEffect(()=>MO(()=>t(ur())),[]),e}function g7({group:e}){const t=UG(e);return t==="none"?s.jsx(ze,{variant:"outline",shape:"tag",children:r("无账号")}):t==="done"?s.jsx(ze,{variant:"success",shape:"tag",children:r("已签")}):t==="part"?s.jsx(ze,{variant:"warning",shape:"tag",children:r("部分")}):s.jsx(ze,{variant:"brand",shape:"tag",children:r("待签")})}function Vf({id:e,label:t}){const a=ug[e==="workbuddy-intl"?"workbuddy":e];return s.jsx("span",{className:"ck-prov-logo",children:a?s.jsx("img",{src:a,alt:""}):t.slice(0,1)||"·"})}function x7({group:e}){const t=ur().signing,a=(o,c)=>t.has(`${o}:${c}`);return s.jsxs("table",{className:"ck-table",children:[s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:r("账号")}),s.jsx("th",{children:r("今日签到")}),s.jsx("th",{children:r("上次签到时间")}),s.jsx("th",{"aria-label":r("操作")})]})}),s.jsx("tbody",{children:e.accounts.map(o=>{const c=e.id==="workbuddy-intl";return s.jsxs("tr",{children:[s.jsx("td",{children:o.name||o.id}),s.jsx("td",{children:o.checkedInToday?s.jsx(ze,{variant:"success",shape:"tag",children:r("已签")}):s.jsx(ze,{variant:"brand",shape:"tag",children:r("待签")})}),s.jsx("td",{className:"text-subtle",children:o.checkinAt?Vs(o.checkinAt):"—"}),s.jsx("td",{className:"text-right",children:c?s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(se,{size:"sm",variant:"ghost",disabled:a(o.id,"keepalive"),title:r("用免费模型维持账号活跃 · 不领取奖励"),onClick:()=>{yg(o.id,"keepalive")},children:a(o.id,"keepalive")?r("保活中…"):r("保活")}),s.jsx(se,{size:"sm",variant:"ghost",disabled:a(o.id,"claim"),title:r("探测活动并领取日活奖励 · 不做保活"),onClick:()=>{yg(o.id,"claim")},children:a(o.id,"claim")?r("领取中…"):r("领取")}),s.jsx(se,{size:"sm",variant:"ghost",disabled:a(o.id,"full"),title:r("探测 + 领取 + 保活 · 与定时签到同一套组合"),onClick:()=>{yg(o.id,"full")},children:a(o.id,"full")?r("执行中…"):r("保活+领取")})]}):s.jsx(se,{size:"sm",variant:"ghost",disabled:a(o.id,"checkin"),onClick:()=>{yg(o.id)},children:a(o.id,"checkin")?r("签到中…"):o.checkedInToday?r("重签"):r("签到")})})]},o.id)})})]})}function b7({group:e,expanded:t}){const a=e.totalCount>0;return s.jsxs("div",{className:t?"ck-prov-row open":"ck-prov-row",children:[s.jsxs("div",{className:"ck-prov-main",onClick:()=>a&&DO(e.id),onKeyDown:o=>{a&&(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),DO(e.id))},role:a?"button":void 0,tabIndex:a?0:-1,"aria-expanded":a?t:void 0,children:[s.jsx(Vf,{id:e.id,label:e.label}),s.jsxs("div",{className:"ck-prov-info",children:[s.jsx("div",{className:"ck-prov-name",children:e.label}),s.jsx("div",{className:"ck-prov-desc",children:nM[e.id]??""})]}),s.jsxs("div",{className:"ck-prov-right",children:[s.jsx("span",{className:"ck-prov-count",children:a?r("{total} 账号 · {done} 已签",{total:e.totalCount,done:e.doneCount}):"—"}),s.jsx(g7,{group:e}),a?s.jsx("span",{className:"ck-chev","aria-hidden":!0,children:"›"}):null]})]}),e.id==="qoder-intl"?s.jsx(sM,{}):null,t?s.jsx("div",{className:"ck-prov-detail",children:s.jsx(x7,{group:e})}):null]})}function sM(){const[e,t]=x.useState(null),a=x.useCallback(async()=>{try{t(await Ir().getQoderUmid?.()??null)}catch{}},[]);x.useEffect(()=>{a()},[a]);const o=e?.installing===!0&&e.available!==!0;if(x.useEffect(()=>{if(!o)return;const d=window.setInterval(()=>{a()},3e3);return()=>{window.clearInterval(d)}},[o,a]),!e||e.available)return null;const c=async()=>{try{t(d=>d&&{...d,installing:!0}),await Ir().installQoderUmid?.(),Pe().wbApp?.toast?.(r("✅ UMID 组件已安装,下轮签到即可领取国际版积分"))}catch(d){Pe().wbApp?.toast?.(r("UMID 组件安装失败:{error}",{error:d instanceof Error?d.message:String(d)}),"err")}finally{a()}};return s.jsxs("div",{className:"flex flex-wrap items-center gap-2 pb-2.5 pl-[58px] pr-4 text-[12px] text-muted-foreground",children:[s.jsx("span",{children:r("国际版签到需要 UMID 组件生成设备风控身份(本机未检测到)。")}),e.installSupported?s.jsx(se,{variant:"outline",size:"sm",disabled:e.installing===!0,onClick:()=>{c()},children:e.installing?r("安装中…"):r("一键安装组件")}):s.jsx("span",{children:r("安装 Qoder 客户端或 qodercli 后即可(无需重启网关)。")})]})}function v7({row:e}){const t=e.provider??"loomy",a=ur().onboarding.get(e.id),o=a?.tasks??[],c=a?.unclaimed??0,d=a?.status==="loaded"&&o.length>0,f=d&&IO(e.id);return s.jsxs("div",{className:f?"ck-prov-row open":"ck-prov-row",children:[s.jsxs("div",{className:"ck-prov-main",onClick:d?()=>Wj(e.id):void 0,onKeyDown:p=>{d&&(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),Wj(e.id))},role:d?"button":void 0,tabIndex:d?0:-1,"aria-expanded":d?f:void 0,children:[s.jsx(Vf,{id:t,label:m7(t)}),s.jsxs("div",{className:"ck-prov-info",children:[s.jsx("div",{className:"ck-prov-name",children:e.name||e.id}),s.jsxs("div",{className:"ck-prov-desc",children:[a?.status==="loaded"?r("已领 {claimed}/{total} · 累计 {earned} 积分",{claimed:o.length-c,total:o.length,earned:a.total?`${a.earned} / ${a.total}`:a.earned}):r("尚未查询任务状态"),a?.settled&&a.settledAt?` · ${r("结算于 {time}",{time:Vs(a.settledAt)})}`:a?.checkedAt?` · ${r("查询于 {time}",{time:Vs(a.checkedAt)})}`:""]})]}),s.jsxs("div",{className:"ck-prov-right",onClick:p=>p.stopPropagation(),children:[a?.status==="loaded"&&c>0?s.jsx(ze,{variant:"warning",shape:"tag",children:r("{n} 项待领",{n:c})}):a?.status==="loaded"?s.jsx(ze,{variant:"success",shape:"tag",children:r("全部领取")}):a?.status==="error"?s.jsx(ze,{variant:"destructive",shape:"tag",children:r("查询失败")}):null,s.jsx(se,{size:"sm",variant:"outline",disabled:a?.status==="loading"||a?.claiming===!0,onClick:()=>{Jj(e.id,{expand:!0,refresh:!0})},children:a?.status==="loading"?r("查询中…"):r("查询任务")}),s.jsx(se,{size:"sm",variant:"outline",disabled:a?.status!=="loaded"||t!=="officeace"&&c===0||a?.claiming===!0,onClick:()=>{_O(e.id)},children:a?.claiming?r("领取中…"):c>0?r("一键领取({n})",{n:c}):r("领取")}),d?s.jsx("span",{className:"ck-chev","aria-hidden":!0,children:"›"}):null]})]}),a?.status==="error"?s.jsx("div",{className:"ck-fold-note",children:r("查询失败:{error}",{error:a.error??""})}):null,f?s.jsx("div",{className:"ck-prov-detail",children:o.map(p=>s.jsxs("div",{className:"ck-task-line",children:[s.jsx("span",{className:p.done?"ck-task-tick done":"ck-task-tick",children:p.done?"✓":"·"}),s.jsx("span",{children:p.title}),s.jsxs("span",{className:"ck-task-pts",children:["+",p.points]}),s.jsx("span",{className:"ck-task-st",children:p.claiming?s.jsx(ze,{variant:"warning",shape:"tag",children:r("领取中")}):p.done?s.jsx(ze,{variant:"success",shape:"tag",children:r("已领取")}):p.blocked?s.jsx(ze,{variant:"outline",shape:"tag",children:r("暂不可领")}):p.error?s.jsx(ze,{variant:"destructive",shape:"tag",children:p.error}):s.jsx(ze,{variant:"brand",shape:"tag",children:r("可领取")})})]},p.key))}):null]})}function y7({row:e}){const t=$h({claimPlans:e.claimPlans}),a=t.length>0;return s.jsxs("div",{className:"ck-welfare-row",children:[s.jsx(Vf,{id:"zcode",label:"ZCode"}),s.jsxs("div",{className:"ck-prov-info",children:[s.jsxs("div",{className:"ck-prov-name",children:[e.name||e.id,a?s.jsx(ze,{variant:"success",shape:"tag",title:r("本地台账里今天(北京时间)领过的套餐:{plans}",{plans:t.join(r("、"))}),children:r("今天已领 {n} 份",{n:t.length})}):s.jsx(ze,{variant:"outline",shape:"tag",title:r("本地台账里今天还没领过;活动期内每天发一份新套餐"),children:r("今天未领")})]}),s.jsx("div",{className:"ck-prov-desc",children:a?r("点「套餐明细」看领到了哪几份、什么时候生效;活动期内每天可再领"):e.claimAt?r("上次领取 {time} · 领取需通过滑块验证码",{time:Vs(e.claimAt)}):r("限时体验套餐(start-plan),活动期内每天一份 · 领取需滑块验证码")})]}),s.jsx("div",{className:"ck-prov-right",children:s.jsx(se,{size:"sm",variant:"outline",onClick:()=>mR(e.id,e.name),children:r(a?"套餐明细":"去领取")})})]})}function j7({row:e}){const t=ur().growth.get(e.id),a=t?.tasks??[],o=a.filter(b=>b.supported&&!b.unforgeable),c=o.filter(b=>b.status!=="claimed"&&b.current0,f=d&&zG(e.id),p=t?.travel,g=t?.school,v=t?.results??[],y=b=>v.find(j=>j.code===b);return s.jsxs("div",{className:f?"ck-prov-row open":"ck-prov-row",children:[s.jsxs("div",{className:"ck-prov-main",onClick:d?()=>BO(e.id):void 0,onKeyDown:b=>{d&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),BO(e.id))},role:d?"button":void 0,tabIndex:d?0:-1,"aria-expanded":d?f:void 0,children:[s.jsx(Vf,{id:"workbuddy",label:"WorkBuddy"}),s.jsxs("div",{className:"ck-prov-info",children:[s.jsx("div",{className:"ck-prov-name",children:e.name||e.id}),s.jsxs("div",{className:"ck-prov-desc",children:[t?.status==="loaded"?r("{total} 项任务 · {pending} 项可完成",{total:o.length,pending:c.length}):r("查询任务树并一键点亮 / 领奖(含开学季与猫猫旅行)"),t?.checkedAt?` · ${r("查询于 {time}",{time:Vs(t.checkedAt)})}`:""]})]}),s.jsxs("div",{className:"ck-prov-right",onClick:b=>b.stopPropagation(),children:[t?.status==="loaded"?c.length>0?s.jsx(ze,{variant:"warning",shape:"tag",children:r("{n} 项可完成",{n:c.length})}):s.jsx(ze,{variant:"success",shape:"tag",children:r("全部完成")}):t?.status==="error"?s.jsx(ze,{variant:"destructive",shape:"tag",children:r("查询失败")}):null,s.jsx(se,{size:"sm",variant:"outline",disabled:t?.status==="loading"||t?.running===!0,onClick:()=>{wg(e.id)},children:t?.status==="loading"?r("查询中…"):r("查询任务")}),s.jsx(se,{size:"sm",variant:"outline",disabled:t?.status!=="loaded"||t?.running===!0,title:r("接单 + 点亮 + 领奖(只处理已实测沉淀的任务)"),onClick:()=>{HO(e.id,"full")},children:t?.running?r("执行中…"):r("一键完成")}),s.jsx(se,{size:"sm",variant:"ghost",disabled:t?.status!=="loaded"||t?.running===!0,title:r("只领取已完成任务的奖励(幂等,重复点不会重复入账)"),onClick:()=>{HO(e.id,"claim")},children:r("领取")}),d?s.jsx("span",{className:"ck-chev","aria-hidden":!0,children:"›"}):null]})]}),t?.status==="error"?s.jsx("div",{className:"ck-fold-note",children:r("查询失败:{error}",{error:t.error??""})}):null,f?s.jsxs("div",{className:"ck-prov-detail",children:[s.jsxs("div",{className:"ck-fold-note",children:[t?.energy!==null&&t?.energy!==void 0?r("能量 {n}",{n:t.energy}):"",t?.streak!==null&&t?.streak!==void 0?` · ${r("连登 {n} 天",{n:t.streak})}`:"",t?.energy===null&&t?.streak===null?r("(能量 / 连登读数本次未取到)"):""]}),a.map(b=>{const j=y(b.code);return s.jsxs("div",{className:"ck-task-line",children:[s.jsx("span",{className:b.status==="claimed"?"ck-task-tick done":"ck-task-tick",children:b.status==="claimed"?"✓":"·"}),s.jsxs("span",{title:b.description||b.source||b.code,children:[b.title||b.code,b.target>1?` (${b.current}/${b.target})`:""]}),j?s.jsx("span",{className:"ck-task-pts",children:j.message}):null,s.jsx("span",{className:"ck-task-st",children:b.unforgeable?s.jsx(ze,{variant:"outline",shape:"tag",children:r("需真实操作")}):b.supported?b.status==="claimed"?s.jsx(ze,{variant:"success",shape:"tag",children:r("已领取")}):b.status==="completed"?s.jsx(ze,{variant:"brand",shape:"tag",children:r("可领取")}):b.locked?s.jsx(ze,{variant:"outline",shape:"tag",children:r("未解锁")}):s.jsx(ze,{variant:"warning",shape:"tag",children:r("可完成")}):s.jsx(ze,{variant:"outline",shape:"tag",children:r("暂不支持")})})]},b.code)}),s.jsxs("div",{className:"ck-task-line",children:[s.jsx("span",{className:"ck-task-tick",children:"🐾"}),s.jsxs("span",{children:[r("猫猫旅行"),p&&p.hasBuddy===!0?`:${p.buddyName||r("已领养")} · ${p.state==="traveling"?r("在途"):p.state==="arrived"?r("可领奖"):p.state==="idle"?p.dailyLimitReached?r("今日已派出"):r("可派出"):p.state??""}`:p&&p.hasBuddy===!1?`:${r("未领养(领养需先完成当日对话量)")}`:":"+(p?.error?String(p.error):r("尚未查询"))]}),s.jsx("span",{className:"ck-task-st",children:s.jsx(se,{size:"sm",variant:"ghost",disabled:t?.runningTravel===!0||t?.status!=="loaded",onClick:()=>{HG(e.id)},children:t?.runningTravel?r("执行中…"):r("巡检一次")})})]}),s.jsxs("div",{className:"ck-task-line",children:[s.jsx("span",{className:"ck-task-tick",children:"🎓"}),s.jsxs("span",{children:[r("开学季活动"),g&&g.inPeriod===!0?`:${r("进行中")}${g.lottery?.balance!==void 0&&g.lottery?.balance!==null?` · ${r("抽奖机会 {n} 次",{n:g.lottery.balance})}`:""}`:g&&g.inPeriod===!1?`:${r("非活动期")}`:":"+(g?.error?String(g.error):r("尚未查询"))]}),s.jsx("span",{className:"ck-task-st",children:s.jsx(se,{size:"sm",variant:"ghost",disabled:t?.runningSchool===!0||t?.status!=="loaded",title:r("执行开学季任务并抽空抽奖机会(分享 / 对话 / 专家事件)"),onClick:()=>{BG(e.id,!0)},children:t?.runningSchool?r("执行中…"):r("执行并抽奖")})})]}),t?.schoolText?s.jsx("div",{className:"ck-fold-note",children:t.schoolText}):null,t?.lotteryText?s.jsx("div",{className:"ck-fold-note",children:t.lotteryText}):null]}):null]})}function w7({group:e}){return s.jsxs("div",{className:"ck-prov-row",children:[s.jsxs("div",{className:"ck-prov-main",style:{cursor:"default"},children:[s.jsx(Vf,{id:e.id,label:e.label}),s.jsxs("div",{className:"ck-prov-info",children:[s.jsx("div",{className:"ck-prov-name",children:e.label}),s.jsx("div",{className:"ck-prov-desc",children:nM[e.id]??""})]}),s.jsx("div",{className:"ck-prov-right",children:s.jsx(ze,{variant:"outline",shape:"tag",children:r("无账号")})})]}),e.id==="qoder-intl"?s.jsx(sM,{}):null]})}function S7({store:e}){const t=e.snapshot,[a,o]=x.useState(null);x.useEffect(()=>{let N=!0;return(async()=>{try{const E=await Pe().workbuddyDesktop?.getCheckinRecords?.({limit:1});N&&o(Number(E?.total)||0)}catch{}})(),()=>{N=!1}},[e.version]);const c=t?.daily,d=t?.auto,f=(c?.outOfScope??[]).reduce((N,k)=>N+(Number(k.count)||0),0),p=t?.extras.onboarding??[],g=p.filter(N=>e.onboarding.get(N.id)?.status==="loaded"),v=p.reduce((N,k)=>N+(e.onboarding.get(k.id)?.unclaimed??0),0),y=t?.extras.plans??[],b=t?.extras.growth??[],j=Array.isArray(d?.schedules)?d.schedules:[],w=j.filter(N=>N.enabled===!0).length,S=VG(d);return s.jsxs("div",{children:[s.jsxs("div",{className:"ck-stats",children:[s.jsxs("div",{className:"ck-stat",children:[s.jsx("div",{className:"ck-stat-label",children:r("今日签到进度")}),s.jsx("div",{className:"ck-stat-value",children:c?s.jsxs(s.Fragment,{children:[" ",c.todayDone,s.jsxs("small",{children:[" / ",c.todayEligible]})]}):s.jsx("span",{className:"ck-pending",children:"—"})}),s.jsx(ef,{className:"ck-stat-bar",value:c&&c.todayEligible>0?c.todayDone/c.todayEligible*100:0}),s.jsx("div",{className:"ck-stat-foot",children:f>0?r("另有 {n} 个账号不参与每日签到",{n:f}):r("全部账号均可签到")})]}),s.jsxs("div",{className:"ck-stat ck-stat-link",onClick:()=>{vg("schedule")},role:"button",tabIndex:0,onKeyDown:N=>{N.key==="Enter"&&vg("schedule")},children:[s.jsx("div",{className:"ck-stat-label",children:r("定时签到")}),s.jsx("div",{className:"ck-stat-value",children:d?s.jsxs(s.Fragment,{children:[w,s.jsxs("small",{children:[" / ",j.length," ",r("条启用")]})]}):s.jsx("span",{className:"ck-pending",children:"—"})}),s.jsx("div",{className:"ck-stat-foot",children:d?.enabled!==!0?r("总开关已关闭 · 在「定时签到」页打开"):S?r("下次 {date} · 点此管理条目",{date:Vs(S)}):r("暂无启用的条目 · 点此添加")})]}),s.jsxs("div",{className:"ck-stat",children:[s.jsx("div",{className:"ck-stat-label",children:r("待领新手福利")}),s.jsx("div",{className:"ck-stat-value",children:p.length?s.jsxs(s.Fragment,{children:[v,s.jsxs("small",{children:[" ",r("项")]})]}):s.jsx("span",{className:"ck-pending",children:r("无")})}),s.jsx("div",{className:"ck-stat-foot",children:p.length?r("已有结果 {checked} / 共 {total} 个账号",{checked:g.length,total:p.length}):r("没有支持新手福利的账号")})]}),s.jsxs("div",{className:"ck-stat ck-stat-link",onClick:()=>{vg("records")},role:"button",tabIndex:0,onKeyDown:N=>{N.key==="Enter"&&vg("records")},children:[s.jsx("div",{className:"ck-stat-label",children:r("累计签到记录")}),s.jsx("div",{className:"ck-stat-value",children:a===null?s.jsx("span",{className:"ck-pending",children:"—"}):a}),s.jsx("div",{className:"ck-stat-foot",children:r("每账号一条明细 · 点此查看「签到记录」")})]})]}),s.jsxs("div",{className:"ck-main",children:[s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("每日签到")}),s.jsx("span",{className:"panel-sub",children:r("点击行展开账号明细 · 单账号签到不受范围限制")}),s.jsx(se,{size:"sm",variant:"default",className:"ml-auto",disabled:e.runningAll||d?.running===!0,onClick:()=>{PG()},children:e.runningAll||d?.running===!0?r("签到中…"):r("立即全部签到")})]}),s.jsxs("div",{children:[(c?.providers??[]).map(N=>N.totalCount>0?s.jsx(b7,{group:N,expanded:e.expanded.has(N.id)},N.id):s.jsx(w7,{group:N},N.id)),(c?.outOfScope??[]).length>0?s.jsx("div",{className:"ck-fold-note",children:r("不参与每日签到:{list}。CodeArts 的一次性奖励在下方「新手福利」,它的每日福利就在上方「每日签到」里;ZCode 的套餐领取见「活动福利」。",{list:c.outOfScope.map(N=>r("{label} ×{count}({reason})",{label:N.label,count:N.count,reason:N.reason})).join(r(";"))})}):null]})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("新手福利")}),s.jsx("span",{className:"panel-sub",children:r("一次性福利 · 签到后自动查询并领取,领完记在本机不再查上游 · 点击行展开任务清单")}),p.length>0?s.jsx(se,{size:"sm",variant:"outline",className:"ml-auto",onClick:()=>{for(const N of p)N.settled&&typeof N.settled=="object"||Jj(N.id)},children:r("全部查询")}):null]}),p.length?s.jsx("div",{children:p.map(N=>s.jsx(v7,{row:N},N.id))}):s.jsx("div",{className:"ck-empty",children:r("没有支持新手福利的账号 —— 目前有 Loomy、小浣熊、CodeArts 三家。")})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("活动福利")}),s.jsx("span",{className:"panel-sub",children:r("限时体验套餐 · 领取需滑块验证码 · 逐份查看与领取")})]}),y.length>0?s.jsx("div",{children:y.map(N=>s.jsx(y7,{row:N},N.id))}):s.jsx("div",{className:"ck-empty",children:r("没有可领套餐的账号(ZCode 未添加)。")})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("成长任务")}),s.jsx("span",{className:"panel-sub",children:r("WorkBuddy 国内版 · 查询任务树后一键点亮 / 领奖 · 含开学季与猫猫旅行 · 点击行展开明细")})]}),b.length>0?s.jsx("div",{children:b.map(N=>s.jsx(j7,{row:N},N.id))}):s.jsx("div",{className:"ck-empty",children:r("没有支持成长任务的账号(需要 WorkBuddy 国内版)。")})]})]})]})}function N7(){const e=h7(),t=e.snapshot;if(x.useEffect(()=>{Ol()},[]),x.useEffect(()=>{window.wbApp?.renderTopbarStatus?.()},[e.version]),!e.loaded)return s.jsxs("div",{className:"ck-loading",children:[s.jsx(Jd,{className:"size-5"}),s.jsx("span",{children:r("正在读取签到数据…")})]});const a=t?.auto,o=a?.enabled===!0;return s.jsxs("div",{children:[e.loadError?s.jsxs("div",{className:"ck-page-error",children:[s.jsx("span",{children:r("读取签到数据失败:{error}",{error:e.loadError})}),s.jsx(se,{size:"sm",variant:"outline",onClick:()=>{Ol()},children:r("重试")})]}):null,s.jsxs("div",{className:"ck-tabs",children:[s.jsx(In,{options:p7,value:e.tab,onValueChange:c=>OO(c),"aria-label":r("签到中心分区")}),s.jsx(ze,{id:"checkin-badge",className:"ml-auto",variant:a?o?"success":"outline":"destructive","data-tone":a?o?"ok":"":"bad",children:a?o?a?.lastFiredToday?r("今日已执行"):r("已开启"):r("已关闭"):r("不可用")})]}),e.tab==="center"?s.jsx(S7,{store:e}):null,e.tab==="schedule"?s.jsx(o7,{}):null,e.tab==="records"?s.jsx(f7,{}):null]})}const rM='.page[data-page="checkin"]';let aM=!1;function lM(){if(aM)return;const e=document.querySelector(rM);e&&(aM=!0,e.replaceChildren(),vn.createRoot(e).render(s.jsx(N7,{})))}const oM=()=>Ol();window.wbCheckinPanel={load:oM},document.querySelector(rM)?lM():document.addEventListener("DOMContentLoaded",lM,{once:!0}),Pe().wbApp?.currentPage==="checkin"&&oM();function k7(e){return String(e??"").replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}function C7({options:e,onSettle:t}){const{title:a="确认操作",html:o="",text:c="",okText:d="确定",okClass:f="primary",bodyClass:p="danger-zone",cancelText:g="取消"}=e,v=x.useRef(null);return x.useEffect(()=>{function y(b){b.key==="Escape"&&t(!1)}return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[t]),x.useEffect(()=>{function y(b){b.target?.dataset.slot==="alert-dialog-overlay"&&t(!1)}return document.addEventListener("click",y),()=>document.removeEventListener("click",y)},[t]),s.jsx(xV,{open:!0,onOpenChange:y=>{y||t(!1)},children:s.jsxs(jV,{initialFocus:v,showCloseButton:!0,children:[s.jsx(wV,{className:"pr-10",children:s.jsx(vV,{children:a})}),s.jsx(SV,{children:s.jsx(kV,{tone:p==="danger-zone"?"danger":"neutral",dangerouslySetInnerHTML:{__html:o||k7(c).replace(/\n/g,"
")}})}),s.jsxs(NV,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{ref:v,variant:"outline",onClick:()=>t(!1),children:g}),s.jsx(se,{variant:f==="danger"?"destructive":"default",onClick:()=>t(!0),children:d})]})]})})}let Ff=null,Eu=null,Cg=null;function T7(){Ff&&(Ff.unmount(),Ff=null),Eu&&(Eu.remove(),Eu=null)}function iM(e){const t=Cg;Cg=null,T7(),t?.(e)}function E7(e={}){return new Promise(t=>{Cg&&iM(!1),Cg=t,Eu=document.createElement("div"),document.body.append(Eu),Ff=vn.createRoot(Eu),Ff.render(s.jsx(C7,{options:e,onSettle:iM}))})}window.wbConfirm={ask:E7};const A7=r("Base URL 填进客户端的「API 地址 / Base URL」栏;对话协议按客户端支持的类型三选一(Chat Completions / Responses / Anthropic Messages),三者共用同一套模型与账号池,可随时切换;鉴权用「网关 Key」页里任一启用 Key。");function $f({id:e,name:t,note:a}){return s.jsxs("div",{className:"ep-row",children:[s.jsxs("div",{className:"ep-head",children:[s.jsx("span",{className:"ep-name",children:t}),s.jsx("span",{className:"ep-note",children:a})]}),s.jsxs("div",{className:"ep-line",children:[s.jsx("code",{className:"ep-value",id:e,children:"—"}),s.jsx(se,{variant:"ghost",size:"icon-xs",className:"copy-btn size-[21px] rounded-[var(--r-xs)]","data-copy-from":e,title:r("复制地址"),children:"⧉"})]})]})}function R7(){return s.jsxs("section",{className:"panel ep-panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("接口地址")}),s.jsx("span",{className:"tip-q","data-tip":A7})]}),s.jsxs("div",{className:"ep-list",children:[s.jsx($f,{id:"api-base",name:"Base URL",note:r("填进客户端的「API 地址 / Base URL」")}),s.jsx("div",{className:"ep-group",children:r("对话协议(按客户端支持的类型选一行)")}),s.jsx($f,{id:"api-chat",name:"OpenAI Chat Completions",note:r("多数 OpenAI 兼容客户端的默认协议")}),s.jsx($f,{id:"api-responses",name:"OpenAI Responses",note:r("OpenAI 新协议(Codex、新版 SDK)")}),s.jsx($f,{id:"api-messages",name:"Anthropic Messages",note:r("Claude Code / Anthropic SDK(token 计数:/v1/messages/count_tokens)")}),s.jsx("div",{className:"ep-group",children:r("模型清单")}),s.jsx($f,{id:"api-models",name:r("模型列表"),note:r("客户端自动拉取可用模型;不受鉴权限制,配 Key 之前就能拉")})]}),s.jsx("div",{className:"panel-foot",children:s.jsxs("span",{children:[r("鉴权用「网关 Key」页里任一"),s.jsx("b",{children:r("启用")}),r("的 Key:请求带 "),s.jsx("code",{children:"Authorization: Bearer "}),r(" 或 "),s.jsx("code",{children:"x-api-key: "}),r("。一把启用的 Key 都没有时不鉴权(默认网关只监听 127.0.0.1;在设置页开启「局域网访问」后监听所有网卡,鉴权与安全闸门随之启用)。")]})})]})}const cM='.page[data-page="docs"]';let uM=!1;function dM(){if(uM)return;const e=document.querySelector(cM);e&&(uM=!0,e.replaceChildren(),vn.createRoot(e).render(s.jsx(R7,{})))}document.querySelector(cM)?dM():document.addEventListener("DOMContentLoaded",dM,{once:!0});function ia(){return window}function aw(e){return e instanceof Error?e.message:String(e)}function qf(e,t){ia().wbApp?.toast?.(e,t)}function O7(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}const lw=[{key:"name",label:r("名称")},{key:"key",label:"Key"},{key:"time",label:r("创建时间")},{key:"state",label:r("启用")},{key:"act",label:r("操作"),align:"right"}],M7={name:"cell-name",key:"cell-key",time:"cell-time",state:"cell-state state",act:"cell-act r"},fM='.page[data-page="keys"]';let Tg=null,ow=null;function pM(){return Tg?Tg.apply([...lw]):lw.map(e=>({...e,align:e.align??"left"}))}function mM(){ia().wbColSettings?.syncStaticHead?.("keys",document.querySelector("table.keys-table"))}function D7(){if(Tg)return;const e=ia().wbColSettings?.register({id:"keys",label:r("网关 Key 表"),columns:lw,mount:()=>document.querySelector('.page[data-page="keys"] .panel-head .head-actions'),onChange:()=>{mM(),ow?.()}});e&&(Tg=e,mM())}function I7(e){return Array.isArray(e?.keys)?e.keys:[]}function P7(e){return Array.isArray(e?.providers)?e.providers:[]}function _7(e){const t=e?.modelsByProvider;return t&&typeof t=="object"?t:{}}function iw(e){return ia().wbProviders?.labelOf?.(e)||e}function L7(e,t,a){const o=new Map,c=f=>{const p=String(f??"").trim();if(!p)return;const g=p.toLowerCase();o.has(g)||o.set(g,p)};t.forEach(f=>{const p=e[f]??e[String(f).toLowerCase()];Array.isArray(p)&&p.forEach(c)}),a.forEach(c);const d=[...o.values()].map(f=>({value:f,label:r(f)}));return d.sort((f,p)=>f.value.toLowerCase()String(t)):[]}function gM(e,t){const a=new Map(t.map(c=>[c.value.toLowerCase(),c.value])),o=new Set;return e.forEach(c=>{const d=a.get(String(c).toLowerCase());d&&o.add(d)}),t.filter(c=>o.has(c.value)).map(c=>c.value)}function U7({target:e,providers:t,modelsByProvider:a,onClose:o,onSaved:c}){const d=e?.id??null,f=!!d,[p,g]=x.useState(e?.name??""),[v,y]=x.useState(""),[b,j]=x.useState(""),[w,S]=x.useState(!1),N=x.useRef(!1),[k,E]=x.useState(()=>hM(e?.allowedProviders)),[D,C]=x.useState(()=>hM(e?.allowedModels)),A=x.useMemo(()=>t.map(H=>({value:String(H.id),label:r(String(H.label??H.id))})),[t]),R=x.useMemo(()=>gM(k,A),[k,A]),I=x.useMemo(()=>L7(a,R,D),[a,R,D]),P=x.useMemo(()=>gM(D,I),[D,I]),O=I.length?r("没有匹配的选项"):R.length?r("这几家当前没有可用模型(账号未登录或清单为空)"):r("请先在上面选择可用提供商");function _(){N.current=!1,S(!1)}async function L(){if(!N.current){N.current=!0,S(!0),j(r("保存中…"));try{const H=ia().workbuddyDesktop;if(!H)throw new Error(r("后端桥不可用"));if(d){const Q=await H.updateKey(d,{allowedProviders:R,allowedModels:P});_(),c(Q),o(),qf(r("✅ 可用范围已保存"));return}const B=v.trim();if(B&&B.length<8){j(r("Key 至少需要 8 个字符"));return}const z=await H.createKey({name:p.trim(),key:B||void 0,allowedProviders:R,allowedModels:P});_(),c(z,z?.created?.id),o(),qf(r("✅ Key 已创建,记得复制给客户端"))}catch(H){j(r("保存失败:{reason}",{reason:aw(H)}))}finally{_()}}}return s.jsx(Qt,{open:!0,onOpenChange:(H,B)=>{if(!H){if(N.current){B.cancel();return}o()}},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:f?r("可用范围 · {name}",{name:e?.name||r("未命名")}):r("新建 API Key")})}),s.jsxs(Bt,{children:[s.jsxs(Vn,{children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(Je,{htmlFor:"key-name",className:"text-[12.5px] whitespace-nowrap text-subtle",children:r("名称")}),s.jsx($e,{id:"key-name",type:"text",maxLength:60,placeholder:r("例如 Cursor / 公司电脑"),autoComplete:"off",value:p,disabled:f,onChange:H=>g(H.currentTarget.value)})]}),!f&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(Je,{htmlFor:"key-value",className:"text-[12.5px] whitespace-nowrap text-subtle",children:"Key"}),s.jsx($e,{id:"key-value",type:"text",placeholder:r("留空自动生成;手填至少 8 个字符"),autoComplete:"off",spellCheck:!1,value:v,onChange:H=>y(H.currentTarget.value),onKeyDown:H=>{H.key==="Enter"&&L()}})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(Je,{className:"text-[12.5px] whitespace-nowrap text-subtle",children:r("可用提供商")}),s.jsx(_h,{value:R,onValueChange:E,options:A,placeholder:r("留空 = 不限制"),searchPlaceholder:r("搜索提供商…"),"aria-label":r("可用提供商"),className:"flex-auto min-w-[180px] max-w-[260px]"})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(Je,{className:"text-[12.5px] whitespace-nowrap text-subtle",children:r("可用模型")}),s.jsx(_h,{value:P,onValueChange:C,options:I,placeholder:r("留空 = 不限制"),emptyHint:O,searchPlaceholder:r("搜索模型…"),"aria-label":r("可用模型"),className:"flex-auto min-w-[180px] max-w-[260px]"})]}),s.jsx("p",{children:r("留空表示不限制;同时设置时请求需同时满足两个条件(模型在白名单内且路由到允许的提供商)。 「可用模型」的候选跟着上面勾选的提供商走:没勾提供商时它是空的(还没有约束范围), 勾了几家就列出这几家能收的全部对外名。")}),s.jsx("p",{id:"key-restrict-summary",children:H7(R,P)})]}),s.jsx("div",{className:"min-h-[18px] text-[11.5px] text-muted-foreground",children:b})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:o,disabled:w,children:r("取消")}),s.jsx(se,{variant:"default",disabled:w,onClick:()=>{L()},children:r(f?"保存范围":"创建")})]})]})})}let Eg=null;async function V7(){await Eg?.load()}function F7(){Eg?.render()}function $7(){const[e,t]=x.useState(null),[a,o]=x.useState(()=>new Set),[c,d]=x.useState(()=>new Set),[f,p]=x.useState(null),[,g]=x.useState(0),v=x.useRef(new Set),y=x.useRef(!1),b=x.useCallback(L=>{t(L)},[]),j=x.useCallback(L=>{L&&Array.isArray(L.keys)&&b(L)},[b]),w=x.useCallback(async()=>{if(!y.current){y.current=!0;try{const L=ia().workbuddyDesktop;if(!L)throw new Error(r("后端桥不可用"));b(await L.getKeys()??null)}catch(L){qf(r("读取 Key 列表失败:{reason}",{reason:aw(L)}),"err")}finally{y.current=!1}}},[b]);async function S(L,H,B){if(!v.current.has(L)){v.current.add(L),d(new Set(v.current));try{j(await H()),B&&qf(B)}catch(z){qf(r("操作失败:{reason}",{reason:aw(z)}),"err")}finally{v.current.delete(L),d(new Set(v.current))}}}function N(L){o(H=>{const B=new Set(H);return B.has(L)?B.delete(L):B.add(L),B})}async function k(L){const H=ia().workbuddyDesktop,B=ia().wbConfirm?.ask;if(!H||!B)return;const z=O7(L.name||L.masked||L.id);await B({title:r("删除网关 Key"),html:r("确定删除 Key「{name}」?使用它的客户端会立刻无法访问。",{name:z}),okText:r("删除"),okClass:"danger"})&&S(L.id,()=>H.deleteKey(L.id),r("Key 已删除"))}function E(L,H){const B=ia().workbuddyDesktop;B&&S(L.id,()=>B.updateKey(L.id,{enabled:H}),r(H?"Key 已启用":"Key 已停用"))}x.useLayoutEffect(()=>(Eg={load:w,render:()=>g(L=>L+1)},ow=()=>g(L=>L+1),D7(),g(L=>L+1),()=>{Eg=null,ow=null}),[w]),x.useEffect(()=>{ia().wbApp?.currentPage==="keys"&&w()},[w]),x.useEffect(()=>{ia().wbApp?.renderTopbarStatus?.()},[e]);const D=I7(e),C=ag(D.length,"keys"),A=C.paged?C.slice(D):D,R=pM(),I=e?.authRequired===!0,P=A.filter(L=>L.enabled).length,O=I?r("已启用鉴权 · {n} 把 Key 生效",{n:P}):r("未启用鉴权");function _(L,H,B){switch(L){case"name":return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mid",children:s.jsx("span",{className:"t",children:H.name||r("未命名")})}),s.jsx("div",{className:"mname",title:B7(H),children:z7(H)})]});case"key":{const z=a.has(H.id);return s.jsxs("div",{className:"keycell",children:[s.jsx("code",{className:"kv",children:z?H.key:H.masked}),s.jsx(se,{size:"sm",variant:"ghost",onClick:()=>N(H.id),children:r(z?"隐藏":"显示")}),s.jsx(se,{size:"sm",variant:"ghost","data-copy":H.key,title:r("复制 Key"),children:r("复制")})]})}case"time":return s.jsx("span",{className:"muted",children:H.createdAt?ia().wbApp?.formatTime?.(H.createdAt):"—"});case"state":return s.jsx(ms,{checked:H.enabled===!0,disabled:B,"aria-label":r("启用「{name}」",{name:H.name||r("未命名")}),onCheckedChange:z=>E(H,z)});case"act":return s.jsxs("div",{className:"row-actions",children:[s.jsx(se,{size:"sm",variant:"ghost",disabled:B,onClick:()=>p({key:H}),children:r("可用范围")}),s.jsx(se,{size:"sm",variant:"destructive",disabled:B,onClick:()=>{k(H)},children:r("删除")})]});default:return null}}return s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("API Key 列表")}),s.jsx(ze,{id:"keys-status",variant:I?"success":"warning","data-tone":I?"ok":"warn",children:O}),s.jsx("div",{className:"head-actions",children:s.jsx(se,{variant:"default",onClick:()=>p({key:null}),children:r("+ 新建 Key")})})]}),s.jsx("div",{className:"models-table-wrap",children:s.jsxs("table",{className:"models-table keys-table",children:[s.jsxs("colgroup",{children:[s.jsx("col",{className:"k-name","data-col":"name"}),s.jsx("col",{className:"k-key","data-col":"key"}),s.jsx("col",{className:"k-time","data-col":"time"}),s.jsx("col",{className:"k-state","data-col":"state"}),s.jsx("col",{className:"k-act","data-col":"act"})]}),s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"data-col":"name",children:r("名称")}),s.jsx("th",{"data-col":"key",children:"Key"}),s.jsx("th",{"data-col":"time",children:r("创建时间")}),s.jsx("th",{"data-col":"state",children:r("启用")}),s.jsx("th",{className:"r","data-col":"act",children:r("操作")})]})}),s.jsx("tbody",{children:A.length?A.map(L=>{const H=c.has(L.id);return s.jsx("tr",{className:L.enabled?"":"off","data-id":L.id,children:R.map(B=>s.jsx("td",{className:`${M7[B.key]??""} ta-${B.align}`,children:_(B.key,L,H)},B.key))},L.id)}):s.jsx("tr",{children:s.jsx("td",{colSpan:R.length,className:"empty",children:r(e?"还没有 Key,当前不鉴权":"加载中…")})})})]})}),s.jsx(Li,{leading:s.jsxs("span",{children:[r("客户端请求需带 "),s.jsx("code",{children:"Authorization: Bearer "}),r(" 或 "),s.jsx("code",{children:"x-api-key: "}),r("; 修改后立即生效,本程序自身会自动使用第一把启用的 Key。每把 Key 可单独限制"),s.jsx("b",{children:r("可用提供商")}),r("与"),s.jsx("b",{children:r("可用模型")}),r("(行内「可用范围」):留空 = 不限制,两个都设时 按交集生效 —— 被限制的模型对这把 Key 表现为「不存在」(拉 /v1/models 也看不到它), 提供它的家不在可用列表里时请求同样被拒。")]}),total:D.length,range:C.paged?{start:C.rangeStart,end:C.rangeEnd}:null,page:C.page,pageCount:C.pageCount,size:C.size,onSizeChange:C.setSize,onPageChange:C.goto}),f?s.jsx(U7,{target:f.key,providers:P7(e),modelsByProvider:_7(e),onClose:()=>p(null),onSaved:(L,H)=>{H&&o(B=>new Set(B).add(H)),j(L)}}):null]})}let xM=!1;function bM(){if(xM)return;const e=document.querySelector(fM);e&&(xM=!0,e.replaceChildren(),vn.createRoot(e).render(s.jsx($7,{})))}document.querySelector(fM)?bM():document.addEventListener("DOMContentLoaded",bM,{once:!0}),window.wbKeysPanel={load:V7,render:F7,visibleColumns:pM};const q7="login-app",G7=x.createElement("panel-captcha",{id:"captcha"});function K7(){return s.jsxs("div",{className:"w-[min(400px,100%)] rounded-lg border border-border bg-card p-[36px_34px_30px] shadow-3",children:[s.jsxs("div",{className:"mb-[26px] flex flex-col items-center gap-3 text-center",children:[s.jsxs("svg",{viewBox:"0 0 24 24",role:"img","aria-label":"Agent2API",className:"size-[52px] rounded-[12px] shadow-[0_6px_18px_rgba(0,122,255,0.35)]",children:[s.jsx("rect",{width:"24",height:"24",rx:"5.4",fill:"#007AFF"}),s.jsxs("g",{fill:"none",stroke:"#fff",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M5.23 9.24h10.71"}),s.jsx("path",{d:"M15.94 6.72 18.77 9.24 15.94 11.76"}),s.jsx("path",{d:"M18.77 14.76H8.06"}),s.jsx("path",{d:"M8.06 12.24 5.23 14.76 8.06 17.28"})]})]}),s.jsxs("div",{children:[s.jsx("h1",{className:"m-0 text-[21px] font-bold tracking-[0.2px]",children:"Agent2API"}),s.jsx("div",{className:"text-[12.5px] text-muted-foreground",children:r("OpenAI 兼容网关 · 管理面板")})]})]}),s.jsx("div",{id:"mode-tip",className:"mb-[18px] text-center text-[13px] text-muted-foreground"}),s.jsxs("form",{id:"form",autoComplete:"on",children:[s.jsx(Je,{htmlFor:"username",className:"mt-3.5 mb-[5px] text-[12.5px]",children:r("账号")}),s.jsx($e,{id:"username",autoComplete:"username",placeholder:r("管理员账号")}),s.jsx(Je,{htmlFor:"password",className:"mt-3.5 mb-[5px] text-[12.5px]",children:r("密码")}),s.jsx($e,{id:"password",type:"password",autoComplete:"new-password",placeholder:r("至少 8 位")}),G7,s.jsx(se,{id:"submit",type:"submit",size:"lg",className:"w-full",children:r("继续")}),s.jsx("div",{id:"error",className:"mt-3 min-h-5 text-center text-[13px] whitespace-pre-wrap text-destructive"})]}),s.jsx("div",{className:"mt-[22px] text-center text-[12px] text-muted-foreground",children:r("登录后可在「网关 Key」页为 API 客户端创建密钥")})]})}function Y7(){const e=document.getElementById(q7);e&&ks.flushSync(()=>{vn.createRoot(e).render(s.jsx(K7,{}))})}Y7();function Lr(){return window}function cw(e){return e instanceof Error?e.message:String(e)}function Ag(e,t){Lr().wbApp?.toast?.(e,t)}const vM=1e3,X7=ng,Q7=500,yM="workbuddy-desktop-logs-range",uw="workbuddy-desktop-logs-filters",Z7=300,W7="~/.agent2api/logs.jsonl",dw=["today","7","30","month","all"],fw="all",J7={today:r("今天"),7:r("7 天"),30:r("30 天"),month:r("本月"),all:r("全部")},e9=dw.map(e=>({value:e,label:J7[e]})),pw=[{value:"",label:r("全部级别")},{value:"debug",label:r("debug 及以上")},{value:"info",label:r("info 及以上")},{value:"warn",label:r("warn 及以上")},{value:"error",label:r("仅 error")}],t9=r("全部级别"),jM=r("全部分类"),n9={debug:r("调试"),info:r("信息"),warn:r("警告"),error:r("错误")};let Rg=vM,Og=!0,mw=!1,hw=!1,gw=!1,xw=null,Eo=null,bw=null,Mg=null,vw=!1,yw=!1;const jw={level:"",category:"",keyword:""};function s9(){const e=Lr().wbFilterMemory;if(!e)return{...jw};vw=!0;const t=e.load(uw,{...jw});return{level:pw.some(a=>a.value===t.level)?t.level:"",category:t.category,keyword:t.keyword}}function Dg(e){Lr().wbFilterMemory?.save(uw,{level:e.level||"",category:e.category||"",keyword:e.keyword.trim()||""})}function r9(){try{const e=localStorage.getItem(yM);return e!==null&&dw.includes(e)?e:fw}catch{return fw}}function a9(e){try{localStorage.setItem(yM,e)}catch{}}function Ig(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function l9(e){const t=new Date;switch(e){case"today":return Ig(t);case"7":return Ig(new Date(t.getFullYear(),t.getMonth(),t.getDate()-6));case"30":return Ig(new Date(t.getFullYear(),t.getMonth(),t.getDate()-29));case"month":return Ig(new Date(t.getFullYear(),t.getMonth(),1));default:return null}}function o9(e){if(!e)return"—";const t=new Date(e),a=d=>String(d).padStart(2,"0"),o=`${a(t.getHours())}:${a(t.getMinutes())}:${a(t.getSeconds())}`,c=`${a(t.getMonth()+1)}-${a(t.getDate())}`;return t.getFullYear()===new Date().getFullYear()?`${c} ${o}`:`${t.getFullYear()}-${c} ${o}`}function i9(e){const t=e.data;if(!t)return"";const a=[];return(t.from||t.to)&&a.push([t.from,t.to].filter(Boolean).join(" → ")),t.model&&a.push(r("模型 {model}",{model:t.model})),t.resetAtText?a.push(r("{time} 恢复",{time:t.resetAtText})):t.status&&!t.from&&!t.to&&a.push(`HTTP ${t.status}`),a.length?a.join(" · "):""}function ww(e){return Array.isArray(e?.entries)?e.entries:[]}function Pg(e,t,a){const o=Math.max(1,a==="all"?1:Math.ceil(t.length/a));return Math.min(Math.max(1,e),o)}function Sw(e,t){return Object.hasOwn(e,t)}function c9(e){const t={};if(e&&typeof e=="object")for(const[a,o]of Object.entries(e))typeof o=="string"&&(t[a]=o);return t}function wM(e,t){const a=new URLSearchParams,o=e.keyword.trim(),c=l9(t);return e.level&&a.set("level",e.level),e.category&&a.set("category",e.category),o&&a.set("keyword",o),c!==null&&a.set("start",String(c)),a}function u9(e,t){const a=wM(e,t);return a.set("limit",String(Q7)),a.toString()}function d9(e,t){return wM(e,t).toString()}function f9(e){xw=e||null,Lr().wbApp?.updateLogsBadge?.(xw)}async function p9(){if(!mw)try{const e=await Lr().workbuddyDesktop?.getScheduledTasks(),t=(e?.tasks||[]).find(a=>a.id==="logsAutoRefresh");Nw(t||null),mw=Array.isArray(e?.tasks)}catch(e){console.warn("读取日志自动刷新间隔失败,按默认 10 秒:",cw(e)),Nw(null)}}function Nw(e){mw=!0;const t=Number(e?.interval);!!e&&typeof e=="object"&&Number.isFinite(t)&&t>0&&(e.unit==="seconds"||e.unit==="minutes")?(Og=e.enabled!==!1,Rg=e.unit==="minutes"?t*6e4:t*1e3):(Og=!0,Rg=vM),Eo?.applyAutoConfig(Rg,Og)}async function m9(e={}){await Eo?.load(e)}function h9(e){if(!Eo){Mg={data:e??null};return}Eo.render(e)}function g9(){return xw}async function x9(e){if(!Eo){bw=e;return}await Eo.showCategory(e)}const b9={entries:[],total:0,matched:0,file:W7,categories:{},loaded:!1};function kw(e,t){return{entries:ww(e),total:Number(e?.total)||0,matched:Number(e?.matched)||0,file:e?.file||t.file,categories:Object.keys(t.categories).length?t.categories:c9(e?.categories),loaded:!0}}function v9(e){return e.loaded?e.total?r("没有符合筛选条件的日志"):r("暂无日志"):r("正在加载日志…")}function y9(){const[e,t]=x.useState(b9),[a,o]=x.useState(s9),[c,d]=x.useState(r9),[f,p]=x.useState(1),[g,v]=x.useState(()=>sg("logs")),[y,b]=x.useState(null),[j,w]=x.useState(()=>({ms:Rg,enabled:Og})),S=x.useRef(null),N=x.useRef(null),k=x.useRef(null),E=x.useRef(null),D=x.useRef(a),C=x.useRef(c),A=x.useRef(f),R=x.useRef(g),I=x.useRef(e),P=x.useCallback(re=>{const de={...D.current,...re};return D.current=de,o(de),de},[]),O=x.useCallback(re=>{C.current=re,d(re)},[]),_=x.useCallback(re=>{A.current=re,p(re)},[]),L=x.useCallback(re=>{R.current=re,v(re),rg("logs",re)},[]),H=x.useCallback(re=>{I.current=re,t(re)},[]),B=x.useCallback(()=>{if(vw)return;const re=Lr().wbFilterMemory;if(!re||(vw=!0,yw))return;const de=re.load(uw,{...jw});P({level:de.level,category:de.category,keyword:de.keyword})},[P]),z=x.useCallback(async(re={})=>{const{silent:de=!1,resetPage:ke=!1}=re;ke&&_(1),p9(),B();const Ee=u9(D.current,C.current),ve=A.current;try{const he=Lr().workbuddyDesktop;if(!he)throw new Error(r("后端桥不可用"));const[ye,we]=await Promise.all([he.getLogs(Ee),he.getLogStats()]),xe=ke?0:S.current?.scrollTop??0,Te=kw(ye,I.current);H(Te),_(Pg(A.current,ww(ye),R.current)),N.current=A.current===ve?xe:0,f9(we),Object.keys(Te.categories).length&&D.current.category&&!Sw(Te.categories,D.current.category)&&(Dg(P({category:""})),z({resetPage:!0}))}catch(he){de||(console.warn("读取运行日志失败:",cw(he)),H(kw(null,I.current)),_(Pg(A.current,[],R.current)))}},[H,_,B]),Q=x.useCallback(re=>{re!==void 0&&(H(kw(re,I.current)),_(Pg(A.current,ww(re),R.current)))},[H,_]),K=x.useCallback(async re=>{if(Sw(I.current.categories,re)||await z({silent:!0}),!Sw(I.current.categories,re))return;const de=P({category:re});Dg(de),_(1),await z({resetPage:!0}),Lr().wbApp?.showPage?.("logs",{persist:!0})},[P,_,z]);x.useEffect(()=>{if(Eo={load:z,render:Q,showCategory:K,applyAutoConfig:(de,ke)=>w({ms:de,enabled:ke})},Mg){const de=Mg;Mg=null,Q(de.data)}const re=bw;return re!==null?(bw=null,K(re)):z({silent:!0}),()=>{Eo=null,k.current!==null&&window.clearTimeout(k.current),k.current=null}},[z,Q,K]),x.useEffect(()=>{if(!j.enabled||j.ms<=0)return;const re=window.setInterval(()=>{document.hidden||Lr().wbApp?.currentPage!=="logs"||hw||(hw=!0,z({silent:!0}).finally(()=>{hw=!1}))},j.ms);return()=>{window.clearInterval(re)}},[j,z]),x.useLayoutEffect(()=>{const re=N.current;if(re===null)return;N.current=null;const de=S.current;de&&(de.scrollTop=re)});async function X(re,de,ke){if(!gw){gw=!0,b({which:re,label:de});try{await ke()}catch(Ee){Ag(r("操作失败:{error}",{error:cw(Ee)}),"err")}finally{gw=!1,b(null)}}}async function q(){const re=d9(D.current,C.current),de=re.length>0,ke=de?r("确定清空当前筛选出的 {count} 条日志?清空后无法恢复。",{count:Number(I.current.matched)||0}):r("确定清空全部运行日志?清空后无法恢复。"),Ee=Lr().wbConfirm?.ask;Ee&&await Ee({title:r("清空运行日志"),html:ke,okText:r("清空"),okClass:"danger"})&&await X("clear",r("清空中…"),async()=>{const ve=Lr().workbuddyDesktop;if(!ve)throw new Error(r("后端桥不可用"));await ve.clearLogs(de?re:"all=1"),await z({resetPage:!0}),Ag(r("运行日志已清空"))})}async function $(){await X("export",r("导出中…"),async()=>{const re=Lr().workbuddyDesktop;if(!re)throw new Error(r("后端桥不可用"));const de=await re.exportLogs();if(!(!de||de.canceled)){if(de.count===0){Ag(r("暂无日志可导出"),"err");return}Ag(r("✅ 已导出 {count} 条日志到 {file}",{count:String(de.count),file:String(de.file)}))}})}function Y(re){const de=Pg(re,I.current.entries,R.current);de!==A.current&&(_(de),N.current=0)}function F(re){if(re===R.current)return;const de=I.current.entries.length,ke=de?(A.current-1)*(R.current==="all"?de:R.current):0;L(re),_(re==="all"?1:Math.floor(ke/re)+1),N.current=0}function G(re){yw=!0,Dg(P(re)),z({resetPage:!0})}function W(re){yw=!0,P({keyword:re}),k.current!==null&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{k.current=null,Dg(D.current),z({resetPage:!0})},Z7)}function le(re){const de=dw.includes(re)?re:fw;de!==C.current&&(O(de),a9(de),z({resetPage:!0}))}const M=e.entries,U=g!=="all",Z=Math.max(1,U?Math.ceil(M.length/g):1),ae=Math.min(Math.max(1,f),Z),ce=U?M.slice((ae-1)*g,ae*g):M,J=M.length?U?(ae-1)*g+1:1:0,ie=M.length?U?J+ce.length-1:M.length:0,ge=e.categories,ee=e.matched===e.total?r("{n} 条",{n:e.total}):r("{matched} / {total} 条",{matched:e.matched,total:e.total});x.useEffect(()=>{const re=e.loaded?ee:"—";E.current!==re&&(E.current=re,Lr().wbApp?.renderTopbarStatus?.())},[e.loaded,ee]);function fe(re,de){const ke=re.level||"",Ee=i9(re);return s.jsxs("div",{className:`log-row ${ke}`,children:[s.jsx("span",{className:"log-rail",children:s.jsx("span",{className:`log-dot ${ke}`})}),s.jsxs("div",{className:"log-main",children:[s.jsxs("div",{className:"log-line",children:[s.jsx("span",{className:"log-cat",children:ge[re.category||""]||re.category}),s.jsx("span",{className:`log-lvl ${ke}`,children:n9[ke]||re.level}),s.jsx("span",{className:"msg",children:re.message})]}),Ee?s.jsx("div",{className:"log-extra-wrap",children:s.jsx("span",{className:"extra",children:Ee})}):null]}),s.jsx("span",{className:"time",children:o9(re.ts)})]},re.id??de)}const te=y?.which==="export",Ce=y?.which==="clear";return s.jsxs("section",{className:"panel",id:"logs-panel-events",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("系统事件")}),s.jsx(ze,{id:"logs-badge",variant:"outline","data-tone":"",children:e.loaded?ee:"—"}),s.jsxs("div",{className:"head-actions",children:[s.jsx(se,{id:"btn-logs-export",variant:"outline",disabled:y!==null,onClick:()=>{$()},children:te?y?.label:r("导出")}),s.jsx(se,{id:"btn-logs-clear",variant:"destructive",disabled:y!==null,onClick:()=>{q()},children:Ce?y?.label:r("清空")})]})]}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"log-filters",children:[s.jsx(In,{options:e9,value:c,onValueChange:le,"aria-label":r("事件日志时间范围"),className:"shrink-0"}),s.jsxs(ft,{value:a.level,onValueChange:re=>G({level:String(re??"")}),children:[s.jsx(mt,{id:"logs-level",className:"min-w-[120px]",title:r("按最低级别筛选"),"aria-label":r("按最低级别筛选"),children:s.jsx(pt,{children:pw.find(re=>re.value===a.level)?.label??t9})}),s.jsx(ht,{children:pw.map(re=>s.jsx(qe,{value:re.value,children:re.label},re.value))})]}),s.jsxs(ft,{value:a.category,onValueChange:re=>G({category:String(re??"")}),children:[s.jsx(mt,{id:"logs-category",className:"min-w-[120px]",title:r("按分类筛选"),"aria-label":r("按分类筛选"),children:s.jsx(pt,{children:a.category?ge[a.category]||a.category:jM})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"",children:jM}),Object.entries(ge).map(([re,de])=>s.jsx(qe,{value:re,children:de},re))]})]}),s.jsxs(Ci,{className:"w-auto flex-auto",children:[s.jsx(Ei,{id:"logs-keyword",type:"search",placeholder:r("搜索消息关键词…"),autoComplete:"off","aria-label":r("搜索消息关键词"),value:a.keyword,onChange:re=>W(re.currentTarget.value)}),s.jsx(Ti,{"aria-hidden":"true",children:"⌕"})]})]}),s.jsx("div",{className:"log-list",id:"log-list",ref:S,children:ce.length?ce.map((re,de)=>fe(re,de)):s.jsx("div",{className:"log-empty",children:v9(e)})})]}),s.jsx(Li,{total:M.length,range:U?{start:J,end:ie}:null,page:ae,pageCount:Z,size:g,sizes:X7,onSizeChange:F,onPageChange:Y})]})}const SM='.page[data-page="logs"]';let NM=!1;function kM(){if(NM)return;const e=document.querySelector(SM);e&&(NM=!0,e.replaceChildren(),vn.createRoot(e).render(s.jsx(y9,{})))}document.querySelector(SM)?kM():document.addEventListener("DOMContentLoaded",kM,{once:!0}),window.wbLogsPanel={load:m9,render:h9,lastStats:g9,applyAutoRefresh:Nw,showCategory:x9};const Au=["maxInputTokens","maxOutputTokens","supportsToolCall","supportsImages","supportsVideo","supportsReasoning"],Gf=["maxInputTokens","maxOutputTokens"],CM=["supportsToolCall","supportsImages","supportsVideo","supportsReasoning"],Ru={maxInputTokens:r("上下文窗口"),maxOutputTokens:r("最大输出 Token"),supportsToolCall:r("工具调用"),supportsImages:r("图片识别"),supportsVideo:r("视频识别"),supportsReasoning:r("支持思考")};r("工具"),r("图片"),r("视频"),r("思考");const j9=1e8;function Cw(e){return Gf.includes(e)}function Tw(e,t){if(Cw(e)){const a=typeof t=="number"?t:Number(t);return!Number.isFinite(a)||a<1||a>j9?null:Math.trunc(a)}return typeof t=="boolean"?t:null}function TM(e){const t={};if(!e||typeof e!="object")return t;const a=e;for(const o of Au){const c=Tw(o,a[o]);c!==null&&(t[o]=c)}return t}function Ew(e){return Array.isArray(e)?Au.filter(t=>e.some(a=>a===t)):[]}function Aw(e){return TM(e?.capabilities)}function EM(e){const t=Number(e);if(!Number.isFinite(t)||t<=0)return"—";const a=o=>o.toFixed(1).replace(/\.0$/,"");return t>=1e6?`${a(t/1e6)}M`:t>=1e3?`${a(t/1e3)}K`:String(Math.round(t))}function Kf(e){const t=Number(e);return!Number.isFinite(t)||t<=0?r("未声明"):Math.round(t).toLocaleString("en-US")}function Rw(e){return e===!0?"on":e===!1?"off":"unset"}function w9(e){const t=e?.reasoningLevels;if(!Array.isArray(t))return null;const a=t.filter(c=>typeof c=="string"&&c.trim()!=="");if(!a.length)return null;const o=e?.reasoningDefaultLevel;return{levels:a,defaultLevel:typeof o=="string"?o.trim():""}}function S9(e,t,a,o=""){const c=Ru[e],d=a?r("(已被手动覆盖,弹窗里可恢复继承)"):"",f=N9(o);if(Cw(e))return t==null?r("{label}:上游未声明{suffix}",{label:c,suffix:d}):r("{label}:{value}(对下游声明的精确值){origin}{suffix}",{label:c,value:Kf(t),origin:f,suffix:d});const p=Rw(t);return p==="on"?r("{label}:支持{origin}{suffix}",{label:c,origin:f,suffix:d}):p==="off"?r("{label}:不支持{origin}{suffix}",{label:c,origin:f,suffix:d}):r("{label}:上游未声明(下游会按不支持处理){suffix}",{label:c,suffix:d})}function Ou(e,t){const a=e?.capSources?.[t];return a==="upstream"||a==="modelsdev"||a==="user"?a:""}function N9(e){return e==="modelsdev"?r("(由 models.dev 补齐)"):e==="user"?r("(手动设定)"):""}function k9(e){const t={};for(const a of Au){const o=e[a];Cw(a)?t[a]=Tw(a,o.trim()):t[a]=o==="on"?!0:o==="off"?!1:null}return t}function Yf(){return window}const AM=e=>String(e??"").trim().toLowerCase(),Fs=(e,t)=>AM(e)===AM(t);function Jn(e){return typeof e=="string"&&e.startsWith("custom-")}function Fi(){return(Yf().wbProviders?.customList?.()||[]).filter(e=>Jn(e?.id))}function RM(){return Yf().wbProviders?.customList?.()||[]}function Ao(e){return Fi().find(t=>t.id===e)||null}function C9(e){const t=TM(e),a={};for(const o of Au){const c=t[o];(typeof c=="number"||typeof c=="boolean")&&(a[o]=c)}return Object.keys(a).length?a:void 0}function OM(e){const t=(Array.isArray(e?.models)?e.models:[]).map(c=>{const d={id:String(c?.id??"").trim(),enabled:c?.enabled!==!1,reasoning:typeof c?.reasoning=="string"?c.reasoning:""};return d.capabilities=C9(c?.capabilities),d}).filter(c=>c.id),a=(Array.isArray(e?.mappings)?e.mappings:[]).map(c=>({alias:String(c?.alias??"").trim(),target:String(c?.target??"").trim(),enabled:c?.enabled!==!1,reasoning:typeof c?.reasoning=="string"?c.reasoning:""})).filter(c=>c.alias&&c.target);for(const c of t){const d=a.find(f=>Fs(f.alias,c.id)&&Fs(f.target,c.id));d&&(c.enabled=c.enabled&&d.enabled,c.reasoning=d.reasoning||c.reasoning)}const o=a.filter(c=>!(Fs(c.alias,c.target)&&t.some(d=>Fs(d.id,c.target))));return{models:t,mappings:o}}function MM(e){const t=Ao(e);if(!t)return null;const a=OM(t),o=t.name||e,c=[],d=[];for(const f of a.models)c.push({id:f.id,name:"",provider:e,providerLabel:o,source:"",enabled:f.enabled,aliases:[],capabilities:f.capabilities||{},capOverrides:[]}),d.push({alias:f.id,target:f.id,provider:e,enabled:f.enabled,reasoning:f.reasoning,isDefault:!0,dangling:!1,carried:!0});for(const f of a.mappings){const p=c.find(g=>Fs(g.id,f.target));d.push({alias:f.alias,target:f.target,provider:e,enabled:f.enabled,reasoning:f.reasoning,isDefault:!1,dangling:!p,carried:!!p}),p&&p.aliases.push(f.alias)}return{models:c,mappings:d}}async function $i(e,t){const a=Yf().wbProviders;if(!a?.customRequest)throw new Error(r("目录模块未就绪"));const o=Ao(e);if(!o)throw new Error(r("该自定义提供商已不存在(可能已被删除),请刷新后重试"));const c=OM(o),d=t(c);return await a.customRequest("POST","/api/custom-providers/models",{providerId:e,models:c.models,mappings:c.mappings}),await a.refreshCustom?.(),d}async function DM(e,t,a,o={}){const{enabled:c,reasoning:d}=o;await $i(e,f=>{if(Fs(t,a)){const g=f.models.find(v=>Fs(v.id,a));if(!g)throw new Error(r("该提供商的清单里没有模型「{name}」",{name:a}));return c!==void 0&&(g.enabled=!!c),d!==void 0&&(g.reasoning=String(d??"")),null}const p=f.mappings.find(g=>Fs(g.alias,t)&&Fs(g.target,a));if(p)return c!==void 0&&(p.enabled=!!c),d!==void 0&&(p.reasoning=String(d??"")),null;if(c===!1)throw new Error(r("映射「{alias} → {target}」不存在",{alias:t,target:a}));return f.mappings.push({alias:t,target:a,enabled:c??!0,reasoning:String(d??"")}),null})}async function IM(e,t,a){await $i(e,o=>{const c=o.mappings.length;if(o.mappings=o.mappings.filter(d=>!(Fs(d.alias,t)&&Fs(d.target,a))),o.mappings.length===c)throw new Error(r("映射「{alias} → {target}」不存在",{alias:t,target:a}));return null})}async function PM(e,t){const a=String(t??"").trim();if(!a)throw new Error(r("请填写模型 ID"));await $i(e,o=>{if(o.models.some(c=>Fs(c.id,a)))throw new Error(r("模型「{name}」已存在(忽略大小写判重)",{name:a}));return o.models.push({id:a,enabled:!0,reasoning:""}),null})}async function T9(e,t){const a=(Array.isArray(t)?t:[]).map(o=>String(o??"").trim()).filter(Boolean);if(!a.length)throw new Error(r("没有选中任何模型"));return $i(e,o=>{let c=0;for(const d of a)o.models.some(f=>Fs(f.id,d))||(o.models.push({id:d,enabled:!0,reasoning:""}),c++);return c})}async function _M(e,t,a){await $i(e,o=>{const c=o.models.find(f=>Fs(f.id,t));if(!c)throw new Error(r("该提供商的清单里没有模型「{name}」",{name:t}));const d={...c.capabilities||{}};for(const[f,p]of Object.entries(a))p==null?delete d[f]:d[f]=p;return c.capabilities=Object.keys(d).length?d:void 0,null})}async function LM(e,t){return $i(e,a=>{const o=a.mappings.length;a.mappings=a.mappings.filter(d=>!Fs(d.target,t));const c=o-a.mappings.length;return a.models=a.models.filter(d=>!Fs(d.id,t)),{removedMappings:c}})}async function E9(e){const t=Yf().wbProviders;if(!t?.customRequest)throw new Error(r("目录模块未就绪"));const a=await t.customRequest("POST","/api/custom-providers/fetch-models",{providerId:e}),o=(Array.isArray(a?.models)?a.models:[]).map(d=>String(d??"").trim()).filter(Boolean),c=await $i(e,d=>{let f=0;for(const p of o)d.models.some(g=>Fs(g.id,p))||(d.models.push({id:p,enabled:!0,reasoning:""}),f++);return f});return{total:o.length,added:Number(c)||0}}Yf().wbModelsCustom={isCustom:Jn,list:Fi,listSource:RM,record:Ao,buildView:MM,setBinding:DM,removeMapping:IM,addModel:PM,addModels:T9,removeModel:LM,setCapabilities:_M,fetchModels:E9};const ca="__custom__",A9=["off","none","minimal","low","medium","high","xhigh","max"];function Xf(e,t){const a=zM(t);if(a.length)return a;const o=e?.reasoningLevels;return Array.isArray(o)&&o.length?o.filter(c=>typeof c=="string"):[...A9]}function zM(e){const t=e?.reasoningLevels;return Array.isArray(t)?t.filter(a=>typeof a=="string"&&a.trim()!==""):[]}function R9(e,t){const a=t.map(zM).filter(f=>f.length>0);if(!a.length||a.length!==t.length)return Xf(e);const[o,...c]=a,d=o.filter(f=>c.every(p=>p.includes(f)));return d.length?d:Xf(e)}function BM(e,t,a){return`${String(e??"").trim().toLowerCase()}${String(t??"").trim().toLowerCase()}${String(a??"").trim().toLowerCase()}`}function O9(e){const t=new Map;for(const a of Array.isArray(e)?e:[]){const o=typeof a?.reasoning=="string"?a.reasoning.trim():"";o&&t.set(BM(a.alias,a.target,a.provider),o)}return(a,o,c)=>t.get(BM(a,o,c))||""}function Wt(){return window}function Ro(e){return e instanceof Error?e.message:String(e)}function yr(e,t){Wt().wbApp?.toast?.(e,t)}function Ow(e){const t=Wt().wbApp?.esc;return t?t(e):String(e??"").replace(/[&<>"']/g,a=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[a]||a)}function M9(e){const t=Wt().formatTime??Wt().wbApp?.formatTime;return String(t?.(e)??"")}const HM=e=>String(e??"").trim().toLowerCase(),Oo=(e,t)=>HM(e)===HM(t),UM=8,VM="workbuddy-desktop-models-filters",Mw=["all","enabled","disabled","mapped"],D9={all:r("全部"),enabled:r("已启用"),disabled:r("已禁用"),mapped:r("有映射")},I9=Mw.map(e=>({value:e,label:D9[e]})),Dw=["default","rate-asc","rate-desc"],P9={default:r("默认"),"rate-asc":r("倍率升序"),"rate-desc":r("倍率降序")},_9=Dw.map(e=>({value:e,label:P9[e]})),Iw=[{key:"check",label:r("选择"),align:"center"},{key:"model",label:r("上游模型")},{key:"rate",label:r("倍率")},{key:"source",label:r("来源")},{key:"budget",label:r("上下文 / 输出")},{key:"caps",label:r("能力")},{key:"alias",label:r("模型映射")},{key:"act",label:r("操作"),align:"right"}],FM=new Set(["rate","source"]),qi="custom-all",Pw={models:[],mappings:[]},$M={provider:"all",state:"all",search:"",sort:"default"};function qM(){const e=Wt().wbFilterMemory;if(!e)return{...$M};const t=e.load(VM,{...$M});return{provider:String(t.provider||"all"),state:Mw.includes(t.state)?t.state:"all",search:String(t.search||""),sort:Dw.includes(t.sort)?t.sort:"default"}}const _g=qM();let GM=!!Wt().wbFilterMemory,Lg=!1,es={provider:_g.provider,stateFilter:_g.state,search:_g.search,sort:_g.sort,data:null,expanded:new Set,pending:new Set,mapping:null,customModel:null,capability:null};const _w=new Set;function Qf(){return es}function L9(e){return _w.add(e),()=>{_w.delete(e)}}function Is(e){const t={...es,...e},a=Bg(t),o=Bg(es)!==a;es=a===t.provider?t:{...t,provider:a},B9(),o&&Hg();for(const c of _w)c()}function zg(e){Wt().wbFilterMemory?.save(VM,e)}function KM(){if(GM||Lg||!Wt().wbFilterMemory)return;GM=!0;const e=qM();(e.provider!==es.provider||e.state!==es.stateFilter||e.search!==es.search||e.sort!==es.sort)&&Is(e)}function Bg(e){const t=e.provider;return t==="all"||t===qi||Fi().some(a=>a.id===t)||Array.isArray(e.data?.models)&&e.data.models.some(a=>(a.provider||"")===t)||!e.data||!Lw()?t:"all"}function Mu(){return Bg(es)}function Lw(){return!!Wt().wbProviders}function Du(){return Mu()===qi}function YM(){return Du()||Jn(Mu())}let Zf=null;function zw(e){const t=Ao(e);return(!Zf||Zf.id!==e||Zf.record!==t)&&(Zf={id:e,record:t,view:MM(e)||Pw}),Zf.view}let Wf=null;function z9(){const e=RM();if(Wf&&Wf.directory===e)return Wf.view;const t=[],a=[];for(const o of Fi()){const c=zw(String(o.id||""));t.push(...c.models||[]),a.push(...c.mappings||[])}return Wf={directory:e,view:t.length||a.length?{models:t,mappings:a}:Pw},Wf.view}function Bw(){const e=Mu();return e===qi?z9():Jn(e)?zw(e):es.data||Pw}function Jf(){const e=Bw();return Array.isArray(e.models)?e.models:[]}function XM(){const e=Bw();return Array.isArray(e.mappings)?e.mappings:[]}let QM=(e,t,a)=>"";function B9(){QM=O9(XM())}function Hw(){const e=new Map,t=Array.isArray(es.data?.models)?es.data.models:[];for(const a of t){const o=a.provider||"";if(!o)continue;const c=e.get(o)||{label:a.providerLabel||o,n:0};c.n++,e.set(o,c)}return e}function H9(){const e=new Map;for(const t of Fi()){const a=String(t.id||"");if(!a)continue;const o=zw(a);e.set(a,{label:String(t.name||a),n:(o.models||[]).length})}return e}function U9(){return[...Hw().keys()]}function V9(e){const a=(Array.isArray(es.data?.models)?es.data.models:[]).find(o=>o.provider===e);return Number(a?.refreshedAt)||0}function Uw(){const e=new Map;for(const t of Jf()){const a=t.provider||"";a&&!e.has(a)&&e.set(a,t.providerLabel||a)}return[...e].map(([t,a])=>({id:t,label:a}))}function ZM(e){return e?Jf().filter(t=>(t.provider||"")===e).sort((t,a)=>+(t.enabled===!1)-+(a.enabled===!1)).map(t=>({id:t.id,label:t.name&&t.name!==t.id?r("{id}({name})",{id:t.id,name:t.name}):t.id,off:t.enabled===!1})):[]}function F9(){const e=[],t=Wt().wbProviders?.all?.();if(Array.isArray(t))for(const a of t){const o=String(a?.id||"");o&&e.push({id:o,label:String(a?.label||o)})}for(const a of Fi()){const o=String(a.id||"");o&&e.push({id:o,label:String(a.name||o)})}return e.length?e:Uw()}let ep=null,Vw=null;function WM(){const e=ep?ep.apply(Iw):Iw;return YM()?e.filter(t=>!FM.has(t.key)):e}function Hg(){Wt().wbColSettings?.syncStaticHead("models",Vw,YM()?FM:null)}function $9(){if(ep)return;ep=Wt().wbColSettings?.register({id:"models",label:r("模型管理表"),columns:Iw,mount:()=>document.querySelector('.page[data-page="gateway"] .panel-head .head-actions'),buttonPlacement:"last",onChange:()=>{Hg(),Gi()}})||null,ep&&Gi()}let Ug=0,Fw=!1;async function Vg({force:e=!1}={}){if(Fw&&!e)return;const t=++Ug;Fw=!0,KM();try{const a=await Wt().workbuddyDesktop?.getModelManage();if(t!==Ug)return;Is({data:a&&Array.isArray(a.models)?a:null})}catch(a){if(t!==Ug)return;Gi(),yr(r("读取模型清单失败:{message}",{message:Ro(a)}),"err")}finally{t===Ug&&(Fw=!1)}}async function JM(){try{await Wt().wbProviders?.refreshCustom?.()}catch{}await Vg({force:!0})}function Gi(){Is({})}function Ki(e){const t=e;if(t&&Array.isArray(t.models)){Is({data:t});return}Gi()}async function Fg(e,t,a,o){if(Jn(e))return DM(e,t,a,o);const c=Wt().workbuddyDesktop;if(!c)throw new Error(r("后端桥不可用"));return c.addModelMapping(t,a,e,o.reasoning,o.enabled)}async function q9(e,t,a){if(Jn(e))return IM(e,t,a);const o=Wt().workbuddyDesktop;if(!o)throw new Error(r("后端桥不可用"));return o.removeModelMapping(t,a,e)}async function G9(e,t){if(Jn(e))return PM(e,t);const a=Wt().workbuddyDesktop;if(!a)throw new Error(r("后端桥不可用"));return a.addCustomModel(e,t)}async function e2(e,t){if(Jn(e))return LM(e,t);const a=Wt().workbuddyDesktop;if(!a)throw new Error(r("后端桥不可用"));return a.removeCustomModel(e,t)}async function K9(e,t,a){if(Jn(e))return _M(e,t,a);const o=Wt().workbuddyDesktop;if(!o)throw new Error(r("后端桥不可用"));return o.setModelCapabilities(e,t,a)}async function $w(e,t,a){if(!es.pending.has(e)){Is({pending:new Set(es.pending).add(e)});try{Ki(await t()),a&&yr(a)}catch(o){yr(r("操作失败:{message}",{message:Ro(o)}),"err")}finally{const o=new Set(es.pending);o.delete(e),Is({pending:o})}}}function tp(e){return Iu(e).some(t=>t.enabled!==!1)}function Iu(e){const t=e.provider||"",a=XM().filter(p=>Oo(p.target,e.id)&&(!p.provider||Oo(p.provider,t))),o=new Map;for(const p of a){const g=String(p.alias).toLowerCase();(!o.has(g)||p.provider)&&o.set(g,p)}const c=String(e.id).toLowerCase(),d=o.get(c);o.delete(c);const f=[{alias:e.id,target:e.id,provider:t,enabled:e.enabled!==!1&&d?.enabled!==!1,isDefault:!0}];return f.push(...o.values()),f}const Yi=e=>`${e.provider||""}:${e.id}`,qw=(e,t,a)=>`${e}:${t}:${a||""}`;function Y9(e){Is({expanded:new Set(es.expanded).add(e)})}function X9(e){const t=new Set(es.expanded);t.delete(e),Is({expanded:t})}function Q9(e){const t=Mw.includes(e)?e:"all";t!==es.stateFilter&&(Lg=!0,Is({stateFilter:t}),zg({state:t}))}function Z9(e){const t=Dw.includes(e)?e:"default";t!==es.sort&&(Lg=!0,Is({sort:t}),zg({sort:t}))}function W9(e){Lg=!0,Is({search:e}),zg({search:e})}function np(e){Is({provider:String(e??"").trim()||"all"}),zg({provider:es.provider}),Hg()}async function J9(e){const t=Wt().wbCustomProvidersUi;if(!t?.remove){yr(r("删除入口未就绪,请重试或重启应用"),"err");return}await t.remove(e)&&await Vg({force:!0})}function eK(){Wt().wbAccountAddForms?.openNewCustomForm?.()}function t2(e){Is({mapping:e})}function tK(){Is({mapping:null})}function nK(){const e=Mu(),t=e!==qi&&Jn(e);Is({customModel:{provider:t||e!=="all"&&e!==qi?e:"",locked:t}})}function sK(){Is({customModel:null})}function n2(e,t){Is({capability:{provider:e,id:t}})}function rK(){Is({capability:null})}function s2(e,t){return Jf().find(a=>(a.provider||"")===e&&Oo(a.id,t))||null}function Gw(e){if(Jn(e)){const t=Ao(e)?.name;return typeof t=="string"&&t||e}return Wt().wbProviders?.labelOf?.(e)||e}function r2(){const e=Mu(),t=e!==qi&&Jn(e),a=t?Ao(e)?.name||e:r("内置提供商");Wt().wbModelsFetchModal?.open({providerId:e===qi?"all":e,custom:t,name:a,onDone:()=>Gi(),onRefreshed:()=>{Vg({force:!0})}})}window.wbModelsPanel={render:Gi,load:Vg,refreshAll:JM,refreshModels:r2,visibleColumns:WM,selectProvider:np,builtinProviders:U9,providerRefreshedAt:V9};function Kw(e,t,a){return QM(e,t,a)}function aK(e){Vw=e}function lK(){const e=Vw;if(!e)return;const t=o=>Object.keys(o).some(c=>c.startsWith("__reactFiber$")||c.startsWith("__reactInternalInstance$"));for(const o of[...e.children])o.tagName==="TBODY"?o.id!=="models"&&o.remove():o.tagName==="TR"&&!t(o)&&o.remove();const a=e.querySelector("tbody#models");if(a)for(const o of[...a.children])t(o)||o.remove()}const oK=e=>[{value:"inherit",label:e},{value:"on",label:r("支持")},{value:"off",label:r("不支持")}];function iK(e){const t=Rw(e);return r(t==="on"?"支持":t==="off"?"不支持":"未声明")}function a2(e,t,a,o,c=""){const d=t!=null,f=Gf.includes(e)?Kf(t):iK(t);return a?o?r("已填写:对下游声明 {value}",{value:f}):r("已覆盖:对下游声明 {value}",{value:f}):o?r("未填写(下游按未声明处理)"):d?c==="modelsdev"?r("models.dev 补齐:对下游声明 {value}",{value:f}):r("继承上游:{value}",{value:f}):r("上游未声明(下游会按不支持处理)")}function cK(e,t,a){return a?Au.filter(o=>{const c=e[o];return c!=null}):t}function uK(e,t){const a={};for(const o of Au){const c=t.includes(o),d=e[o];Gf.includes(o)?a[o]=c&&typeof d=="number"?String(d):"":a[o]=c?d===!0?"on":"off":"inherit"}return a}function dK({context:e,onClose:t}){const a=Jn(e.provider),o=s2(e.provider,e.id),c=w9(o),d=Aw(o),f=cK(d,Ew(o?.capOverrides),a),[p,g]=x.useState(()=>uK(d,f)),[v,y]=x.useState(""),[b,j]=x.useState(!1);if(!o)return s.jsx(Qt,{open:!0,onOpenChange:R=>{R||t()},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("模型能力")})}),s.jsx(Bt,{children:s.jsx("p",{className:"text-sm leading-[1.7] text-subtle",children:r("这一行已不在当前清单里(模型被移除、或目录刷新后上游不再提供它)。关闭后刷新列表再试。")})}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("关闭")})]})]})});const w=o.id,S=o.providerLabel||Gw(e.provider),N=r(a?"未声明":"继承上游"),k=r(a?"清除":"恢复继承");function E(R){const I=d[R];return D(R)?"":a?r("未填写"):typeof I=="number"?r("继承上游 {value}",{value:Kf(I)}):r("上游未声明")}function D(R){return f.includes(R)}function C(R,I){g(P=>({...P,[R]:I}))}async function A(){if(!b){for(const R of Gf){const I=p[R].trim();if(I&&Tw(R,I)===null){y(r("{label}要填 1 ~ 1 亿之间的整数(留空 = {inherit})",{label:Ru[R],inherit:N}));return}}j(!0),y(r("保存中…"));try{Ki(await K9(e.provider,e.id,k9(p))),t(),yr(r("✅ 已保存 {id} 的能力位({provider})",{id:w,provider:S}))}catch(R){y(r("保存失败:{message}",{message:Ro(R)})),j(!1)}}}return s.jsx(Qt,{open:!0,onOpenChange:(R,I)=>{if(!R){if(b){I.cancel();return}t()}},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("模型能力")})}),s.jsxs(Bt,{children:[s.jsxs("div",{className:"rounded-md border border-border bg-surface-inset px-3 py-2.5 font-mono text-[12px] text-subtle",children:[s.jsx("b",{className:"text-primary-fg",children:o.id}),r("({provider})",{provider:S})]}),Gf.map(R=>s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-[7px]",children:[s.jsx(Je,{htmlFor:`cap-${R}`,children:Ru[R]}),D(R)?s.jsx(se,{variant:"ghost",size:"2xs",disabled:b,title:r(a?"清除这一项(回到未声明)":"清除覆盖,回到上游声明值"),onClick:()=>C(R,""),children:k}):null]}),s.jsx($e,{id:`cap-${R}`,inputMode:"numeric",autoComplete:"off",spellCheck:!1,placeholder:E(R),disabled:b,value:p[R],onChange:I=>C(R,I.currentTarget.value),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),A())}}),s.jsx("p",{className:"text-xs leading-[1.6] text-subtle",children:a2(R,d[R]??null,D(R),a,Ou(o,R))})]},R)),CM.map(R=>s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{children:Ru[R]}),s.jsx(In,{options:oK(N),value:p[R],"aria-label":Ru[R],className:"self-start",onValueChange:I=>C(R,String(I))}),s.jsx("p",{className:"text-xs leading-[1.6] text-subtle",children:a2(R,d[R]??null,D(R),a,Ou(o,R))})]},R)),c?s.jsxs("div",{className:"rounded-md border border-border bg-surface-inset px-3 py-2.5 text-xs leading-[1.7] text-subtle",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[s.jsx("span",{children:r("可配思考档位")}),s.jsx("span",{className:"font-mono text-[12px] text-primary-fg",children:c.levels.join(" / ")}),c.defaultLevel?s.jsxs("span",{children:[r("(默认 "),s.jsx("span",{className:"font-mono text-[12px] text-primary-fg",children:c.defaultLevel}),r(")")]}):null]}),s.jsx("div",{className:"mt-1",children:r("这是模型自己能配的档位(来自上游目录),只读;要改某一档请到映射弹窗里选。")})]}):null,s.jsxs("p",{className:"text-xs leading-[1.65] text-subtle",children:[r("这几项是给"),s.jsx("b",{children:r("下游客户端")}),r("看的能力声明("),s.jsx("code",{children:"/v1/models"}),r(" 里的 "),s.jsx("code",{children:"max_input_tokens"})," / ",s.jsx("code",{children:"supports_*"}),r(" 与 "),s.jsx("code",{children:"input_modalities"}),r("),下游按它们决定发不发图片、按多大的窗口堆历史。"),s.jsx("b",{children:r("不影响网关的转发与路由")}),r("。上游清单给的值不准时,在这里改;"),r(a?"这家的清单是你自己登记的,不填的项下游按未声明处理。":"「恢复继承」会把这一项交还给上游清单的值。")]}),s.jsx("div",{className:"min-h-[18px] text-xs text-subtle",children:v})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:b,onClick:t,children:r("取消")}),s.jsx(se,{variant:"default",disabled:b,onClick:()=>{A()},children:r("保存")})]})]})})}function sp(){return window}const fK="你好",l2=4e3,pK=[{value:"chat_completions",label:"OpenAI - Chat Completions"},{value:"responses",label:"OpenAI - Responses"},{value:"anthropic",label:"Anthropic - Messages"}],mK={chat_completions:"Chat Completions",responses:"Responses",anthropic:"Anthropic Messages"},hK="direct",gK={remote:r("远程目录"),builtin:r("内置清单"),manual:r("手动登记")},xK=[{test:e=>e===429,hint:r("该账号对这个模型正在限额冷却,等一会儿自己会好;也可以先测别的账号。")},{test:e=>e===401||e===403,hint:r("上游拒绝了这条登录态:重新登录一次,或把这条账号删掉。")},{test:e=>e===404,hint:r("上游不认识这个模型名:先点「获取模型」刷新清单,或核对默认绑定指向的上游模型。")},{test:e=>e===504,hint:r("上游没在预算内给完回答。可以只勾一个账号再测一次,看是普遍慢还是某一个账号慢。")},{test:e=>e>=500,hint:r("多半是上游自己的问题,过一会儿再试。同一个错误出现在所有账号上时,先查模型目录与映射。")}];function o2(){return sp().wbApp?.getState?.()?.accounts?.accounts||[]}function i2(e){return o2().filter(t=>(t.provider||iu)===e&&t.available!==!1&&t.enabled!==!1).sort(Vh)}function c2(e){const t=String(e.email||"").trim();return t&&ir(e.provider).emailAsName?t:uu(e)||t||r("未命名账号")}function bK(){const e=globalThis.crypto?.randomUUID?.();if(e)return e;const t=a=>Array.from({length:a},()=>Math.floor(Math.random()*16).toString(16)).join("");return`${t(8)}-${t(4)}-4${t(3)}-a${t(3)}-${t(12)}`}function Yw(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"—":t<1e3?`${Math.round(t)} ms`:`${(t/1e3).toFixed(t<1e4?2:1)} s`}function vK(e,t){return i2(e).length?"":r("该提供商没有可用账号(要在账号页启用一个、且凭证完整),一行都发不出去")}function u2({children:e,plain:t=!1}){return s.jsxs("p",{className:t?"flex items-center gap-2 text-xs leading-[1.6] text-subtle":"flex gap-2 rounded-md border border-border bg-surface-2 px-3 py-2.5 text-xs leading-[1.65] text-subtle",children:[s.jsx("span",{"aria-hidden":"true",className:t?"size-4 flex-none rounded-full border border-border-strong text-center text-[10px] leading-[14px]":"mt-px size-4 flex-none rounded-full border border-border-strong text-center text-[10px] leading-[14px]",children:"i"}),s.jsx("span",{children:e})]})}function yK({open:e,label:t,text:a,onToggle:o}){return s.jsxs("div",{className:"overflow-hidden rounded-sm border border-border",children:[s.jsxs(se,{variant:"ghost",size:"xs",className:"w-full","aria-expanded":e,onClick:o,children:[s.jsx("span",{className:"truncate",children:t}),s.jsx("span",{"aria-hidden":"true",className:"ml-auto text-[10px]",children:e?"▴":"▾"})]}),e?s.jsx("div",{className:"border-t border-hairline bg-surface px-2.5 py-2",children:s.jsx("pre",{className:"whitespace-pre-wrap font-mono text-[11.5px] leading-[1.65] text-subtle",children:a})}):null]})}function jK(e){const[t,a]=x.useState(()=>Date.now());return x.useEffect(()=>{if(!e)return;a(Date.now());const o=window.setInterval(()=>a(Date.now()),400);return()=>window.clearInterval(o)},[e]),t}function d2(e){if(e.transport||!e.result||e.result.error)return!1;const t=Number(e.result.status)||0;return t>=200&&t<300}function wK({target:e,onClose:t}){const a=e.provider,o=s2(a,e.id),c=i2(a),d=cj(o2()),[f,p]=x.useState(""),[g,v]=x.useState(fK),[y,b]=x.useState("chat_completions"),[j,w]=x.useState(""),[S,N]=x.useState(null),[k,E]=x.useState(""),[D,C]=x.useState(""),[A,R]=x.useState(!0),[I,P]=x.useState(()=>{const te=c.find(Ce=>!bf(Ce,e.id))||c[0];return te?[te.id]:[]}),[O,_]=x.useState([]),[L,H]=x.useState(()=>new Set),B=x.useRef(0),z=x.useRef([]);z.current=O;const Q=O.some(te=>te.state==="running"),K=jK(Q);x.useEffect(()=>{let te=!0;return(async()=>{try{const Ce=sp().workbuddyDesktop?.getProxyPool;if(typeof Ce!="function")throw new Error(r("当前环境不支持代理池"));const re=await Ce();if(!te)return;if(!re||typeof re!="object"||!Array.isArray(re.items))throw new Error(r("代理池响应异常"));N(re.items),E("")}catch(Ce){if(!te)return;N([]),E(Ro(Ce))}})(),()=>{te=!1}},[]);const X=x.useCallback((te=!1)=>{const Ce=z.current.filter(re=>re.state==="running");B.current+=1;for(const re of Ce)sp().workbuddyDesktop?.terminateStatsRequest?.(re.testId)?.catch(()=>{});_([]),Ce.length&&!te&&yr(r("已中止在途测试({n} 个账号)",{n:Ce.length}))},[]);x.useEffect(()=>()=>{X(!0)},[X]);async function q(te,Ce){const re={provider:a,model:e.id,account_id:te.accountId,prompt:g.trim(),system_prompt:f.trim(),reasoning:D,stream:A,protocol:y,...j?{proxy:j}:{},test_id:te.testId},de=ke=>{B.current===Ce&&_(Ee=>Ee.map(ve=>ve.testId===te.testId?{...ve,...ke}:ve))};try{const ke=await sp().workbuddyDesktop?.testModel(re);if(!ke){de({state:"done",transport:r("桥接调用返回空(本机网关没有响应这次测试)")});return}de({state:"done",result:ke})}catch(ke){de({state:"done",transport:Ro(ke)})}}function $(){const te=c.filter(ke=>I.includes(ke.id));if(!te.length){yr(r("至少选一个测试账号"),"err");return}const Ce=B.current+1;B.current=Ce;const re=Date.now(),de=te.map(ke=>({accountId:ke.id,label:c2(ke),position:d.get(ke.id)?.position||0,testId:bK(),startedAt:re,state:"running"}));H(new Set),_(de);for(const ke of de)q(ke,Ce)}function Y(){Q?X():_([])}const F=s.jsx("span",{className:"ml-2 font-mono text-[12px] font-normal text-subtle",children:e.id});if(!o)return s.jsx(Qt,{open:!0,onOpenChange:te=>{te||t()},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("测试模型")})}),s.jsx(Bt,{children:s.jsx("p",{className:"text-sm leading-[1.7] text-subtle",children:r("这一行已不在当前清单里(模型被移除、或目录刷新后上游不再提供它)。关闭后刷新列表再试。")})}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("关闭")})]})]})});const G=Iu(o).find(te=>te.isDefault)?.enabled===!1,W=Kw(o.id,o.id,a),le=Iu(o).filter(te=>!te.isDefault).map(te=>te.alias),M=Xf(Qf().data,o).filter(te=>te!=="off"&&te!=="none"),U=G?r("跟随映射(该行未启用,本次不注入)"):W?r("跟随映射(当前 {level})",{level:W}):r("跟随映射(未绑定等级)"),Z=[r("以模型本名直发"),le.length?r("另有 {n} 条别名映射({aliases}),别名不参与本次",{n:le.length,aliases:le.join(r("、"))}):"",G?r("该行当前未启用:测试照常按本名直发(「先测通、再决定要不要启用」正是这颗按钮的用法),但本行的思考等级绑定不参与本次,生产路由也要等绑定打开后才会放行"):W?r("映射上绑定的思考等级是 {level},「跟随映射」按它注入",{level:W}):r("映射上未绑定思考等级,「跟随映射」等于这次不注入")].filter(Boolean).join(r(";"))+r("。"),ae=sp().wbProviders?.PROTOCOL_OPTIONS||pK,ce=ae.find(te=>te.value===y)?.label||y,J=[{value:"",label:r("跟随账号配置")},{value:hK,label:r("直连(不使用代理)")},...(S??[]).map(te=>({value:`${Ya}${te.id}`,label:lu(te)}))];S===null?J.push({value:"__hint_pool__",label:r("正在读取代理列表…"),disabled:!0}):S.length||J.push({value:"__hint_pool__",label:r(k?"代理列表读取失败":"还没有代理(去「网络代理」页添加)"),disabled:!0});const ie=J.find(te=>te.value===j)?.label||r("跟随账号配置"),ge=c.map(te=>({value:te.id,label:`#${d.get(te.id)?.position||0} ${c2(te)}`+(bf(te,e.id)?r(" · 限额中"):"")}));function ee(te){const Ce=(he,ye)=>s.jsxs("div",{className:"flex items-center gap-2.5 border-b border-hairline px-3 py-2",children:[he,s.jsx("b",{className:"min-w-0 truncate text-[12.5px] text-foreground",title:te.label,children:te.label}),te.position?s.jsxs("span",{className:"flex-none text-xs text-subtle",children:["#",te.position]}):null,s.jsx("span",{className:"ml-auto flex-none font-mono text-[11.5px] tabular-nums text-subtle",children:ye})]},"head");if(te.state==="running"){const he=(K-te.startedAt)/1e3;return s.jsxs("div",{className:"flex items-center gap-2.5 rounded-md border border-border bg-surface-2 px-3 py-2.5 text-xs text-subtle",children:[s.jsx(Jd,{className:"flex-none"}),s.jsxs("span",{className:"min-w-0 truncate",children:[r("账号 "),s.jsx("b",{className:"text-foreground",children:te.label}),r(" 已发出,等待上游首帧…")]}),s.jsx("span",{className:"ml-auto flex-none font-mono tabular-nums",children:r("已等待 {seconds}s",{seconds:he.toFixed(1)})})]},te.testId)}const re=te.result;if(!d2(te)){const he=Number(re?.status)||0,ye=xK.find(we=>we.test(he))?.hint??(te.transport?r("确认桌面端还在运行,再重试一次。"):"");return s.jsxs("div",{className:"rounded-md border border-border bg-surface-2",children:[Ce(s.jsx(ze,{shape:"tag",variant:"destructive",className:"flex-none",children:he||r("失败")}),r("用时 {time}",{time:Yw(re?.duration_ms)})),s.jsxs("div",{className:"flex flex-col gap-1.5 px-3 py-2.5",children:[s.jsxs("div",{className:"text-[12.5px] leading-[1.7]",children:[te.transport?s.jsxs(s.Fragment,{children:[s.jsx("b",{className:"text-destructive",children:r("本机网关没有返回结论")}),r(":"),te.transport]}):s.jsxs(s.Fragment,{children:[s.jsx("b",{className:"text-destructive",children:r("测试未通过")}),r(":"),re?.error||r("上游没有给出可读的错误说明")]}),Number(re?.attempts)>1?r("(中间共尝试 {n} 次)",{n:Number(re?.attempts)}):""]}),ye?s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:ye}):null]})]},te.testId)}const de=String(re?.reply??""),ke=String(re?.reasoning??""),Ee=`think-${te.testId}`,ve=[re?.upstream_model&&re.upstream_model!==e.id?r("上游 {model}",{model:re.upstream_model}):"",re?.upstream_reasoning?r("思考等级 {level}",{level:re.upstream_reasoning}):"",re?.protocol&&re.protocol!=="chat_completions"?mK[re.protocol]||re.protocol:"",re?.proxy?r("节点 {proxy}",{proxy:re.proxy}):"",Number(re?.attempts)>1?r("尝试 {n} 次",{n:Number(re?.attempts)}):""].filter(Boolean).join(" · ");return s.jsxs("div",{className:"rounded-md border border-border bg-surface-2",children:[Ce(s.jsx(ze,{shape:"tag",variant:"success",className:"flex-none",children:Number(re?.status)||200}),r("用时 {time} · 首字 {ttfb}",{time:Yw(re?.duration_ms),ttfb:Yw(re?.ttfb_ms)})),s.jsxs("div",{className:"flex flex-col gap-2 px-3 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[11.5px] text-subtle",children:[s.jsx("span",{className:"flex-none",children:r("回复")}),ve?s.jsx("span",{className:"min-w-0 truncate",title:ve,children:ve}):null,s.jsx(se,{variant:"ghost",size:"2xs",className:"ml-auto flex-none","data-copy":de,children:r("复制")})]}),s.jsx("div",{className:"max-h-[220px] overflow-y-auto whitespace-pre-wrap rounded-sm border border-border bg-surface px-3 py-2 text-[12.5px] leading-[1.7]",children:de||s.jsx("span",{className:"text-subtle",children:r("(上游这一次返回了空正文)")})}),ke?s.jsx(yK,{open:L.has(Ee),label:r("思考过程({n} 字)",{n:ke.length}),text:ke,onToggle:()=>H(he=>{const ye=new Set(he);return ye.has(Ee)?ye.delete(Ee):ye.add(Ee),ye})}):null]})]},te.testId)}function fe(){if(Q){const Ce=O.length-O.filter(re=>re.state==="running").length;return s.jsxs(s.Fragment,{children:[O.length>1?s.jsxs("p",{className:"text-xs text-subtle",children:[r("正在测 "),s.jsx("b",{className:"text-foreground",children:O.length}),r(" 个账号"),Ce?s.jsxs(s.Fragment,{children:[r(",已完成 "),s.jsx("b",{className:"text-foreground",children:Ce})]}):null,r("。")]}):null,O.map(re=>ee(re))]})}const te=O.filter(d2).length;return s.jsxs(s.Fragment,{children:[O.length>1?s.jsxs("p",{className:"text-xs text-subtle",children:[s.jsx("b",{className:te?"text-success":"text-foreground",children:te}),r(" 成功 ·"),s.jsxs("b",{className:O.length-te?"text-destructive":"text-foreground",children:[" ",O.length-te]}),r(" 失败")]}):null,O.map(Ce=>ee(Ce)),te===0?s.jsxs(u2,{children:[r("两边原因不一样时各自处理。如果"),s.jsx("b",{className:"text-foreground",children:r("同一条错误出现在所有账号上")}),r(",通常就不是账号问题了:先确认这个模型还在上游目录里(「获取模型」刷一次),再看默认绑定指向的上游模型对不对。")]}):null]})}return s.jsx(Qt,{open:!0,onOpenChange:te=>{te||t()},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsxs(Gt,{children:[r("测试模型"),F]})}),s.jsxs(Bt,{children:[s.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border bg-surface-inset px-3 py-2.5",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate font-mono text-[12.5px] font-semibold text-primary-fg",title:o.id,children:o.id}),s.jsx(ze,{shape:"tag",variant:"brand",children:Gw(a)}),s.jsx(ze,{shape:"tag",variant:"outline",children:Jn(a)?r("自定义家"):gK[o.source]||r("来源未知")}),s.jsxs(Ii,{children:[s.jsx(Pi,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("本次测试的发送口径")}),children:"?"}),s.jsx(_i,{children:Z})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"model-test-system",children:r("系统提示词")}),s.jsx(Zc,{id:"model-test-system",rows:2,maxLength:l2,placeholder:r("留空则不携带;设置页的提示词模式照常生效"),value:f,onChange:te=>p(te.currentTarget.value)})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"model-test-prompt",children:r("用户提示词")}),s.jsx(Zc,{id:"model-test-prompt",rows:2,maxLength:l2,placeholder:r("留空用默认问候「你好」"),value:g,onChange:te=>v(te.currentTarget.value)})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(Je,{htmlFor:"model-test-protocol",children:r("对话协议")}),s.jsxs(Ii,{children:[s.jsx(Pi,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("对话协议的说明")}),children:"?"}),s.jsx(_i,{children:r("按所选网关对话协议组装请求并校验响应转换(Chat Completions / Responses / Anthropic Messages)。")})]})]}),s.jsxs(ft,{value:y,onValueChange:te=>b(String(te)),children:[s.jsx(mt,{id:"model-test-protocol",className:"w-full",children:s.jsx(pt,{className:"min-w-0 truncate",children:ce})}),s.jsx(ht,{children:ae.map(te=>s.jsx(qe,{value:te.value,children:te.label},te.value))})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(Je,{htmlFor:"model-test-proxy",children:r("测试节点")}),s.jsxs(Ii,{children:[s.jsx(Pi,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("测试节点的说明")}),children:"?"}),s.jsx(_i,{children:r("仅本次测试临时生效,不修改账号保存的代理配置。可选「网络代理」页里的节点或强制直连。")})]})]}),s.jsxs(ft,{value:j,onValueChange:te=>w(String(te)),children:[s.jsx(mt,{id:"model-test-proxy",className:"w-full",children:s.jsx(pt,{className:"min-w-0 truncate",children:ie})}),s.jsx(ht,{children:J.map(te=>s.jsx(qe,{value:te.value,disabled:te.disabled,children:te.label},te.value))})]})]})]}),s.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"model-test-reasoning",children:r("思考等级")}),s.jsxs(ft,{value:D,onValueChange:te=>C(String(te)),children:[s.jsx(mt,{id:"model-test-reasoning",className:"w-full",children:s.jsx(pt,{children:D?r("{level}(本次指定)",{level:D}):U})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"",children:U}),M.map(te=>s.jsx(qe,{value:te,children:r("{level}(本次指定)",{level:te})},te))]})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(Je,{htmlFor:"model-test-stream",children:r("流式请求")}),s.jsxs(Ii,{children:[s.jsx(Pi,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("流式请求的说明")}),children:"?"}),s.jsx(_i,{children:r("默认开,与真实请求一致:可同时验证 SSE 链路与首字延迟。")})]})]}),s.jsx(ms,{id:"model-test-stream",checked:A,onCheckedChange:te=>R(!!te)})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Je,{htmlFor:"model-test-accounts",children:r("测试账号")}),s.jsxs(Ii,{children:[s.jsx(Pi,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("测试账号的说明")}),children:"?"}),s.jsx(_i,{children:r("勾几个就并行测几次;默认选队列里最靠前的一个。")})]}),s.jsx(se,{variant:"ghost",size:"xs",className:"ml-auto",disabled:!c.length||I.length===c.length,onClick:()=>P(c.map(te=>te.id)),children:r("全选({n})",{n:c.length})})]}),s.jsx(_h,{id:"model-test-accounts",value:I,onValueChange:P,options:ge,placeholder:r("选一个账号(至少一个)"),searchPlaceholder:r("搜索账号…"),emptyHint:r("这家没有可用账号(要在账号页启用一个、且凭证完整)")})]}),s.jsx(u2,{plain:!0,children:r("真实链路 · 消耗少量额度 · 日志带「测试」标记,不计报表")})]}),s.jsxs(nn,{className:"justify-end",children:[s.jsx(se,{variant:"outline",onClick:t,children:r("关闭")}),s.jsx(se,{variant:"default",disabled:!I.length||!c.length,onClick:$,children:r("开始测试")})]}),s.jsx(Qt,{open:O.length>0,onOpenChange:te=>{te||Y()},children:s.jsxs(Zt,{overlayForceRender:!0,className:"w-[min(680px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsxs(Gt,{children:[r(Q?"测试中…":"测试结果"),F]})}),s.jsx(Bt,{children:fe()}),s.jsx(nn,{className:"justify-end",children:Q?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mr-auto text-xs text-subtle",children:r("关闭即中止")}),s.jsx(se,{variant:"outline",onClick:()=>X(),children:r("中止测试")}),s.jsx(se,{variant:"default",disabled:!0,children:r("测试中…")})]}):s.jsxs(s.Fragment,{children:[s.jsx(se,{variant:"outline",onClick:Y,children:r("关闭")}),s.jsx(se,{variant:"default",onClick:$,children:r("再测一次")})]})})]})})]})})}const f2=[{value:"enable",label:r("启用")},{value:"disable",label:r("禁用")},{value:"reasoning",label:r("设置思考等级")},{value:"delete",label:r("删除")}];function p2(e){return e.source==="manual"||Jn(e.provider)}function SK(e){return(e.name&&e.name!==e.id?r("{name}({id})",{name:e.name,id:e.id}):e.id)||e.id}function NK({models:e,onClose:t,onDone:a}){const[o,c]=x.useState("enable"),d=R9(Qf().data,e),[f,p]=x.useState(()=>({select:d[0]||"",custom:""})),[g,v]=x.useState(!1),[y,b]=x.useState(""),j=f.select===ca?f.custom.trim():f.select,w=e.filter(p2).length,S=f2.find(E=>E.value===o)?.label||r("操作");async function N(E){return Promise.resolve(Wt().wbConfirm?.ask?.({title:r("删除选中的模型"),html:r("确定删除选中的 {count} 个模型登记?删除后 /v1/models 不再广告它们、请求也会被拒。",{count:E})+(e.length>E?"
"+r("另有 {n} 个非手动登记的模型将被跳过。",{n:e.length-E}):""),okText:r("删除"),okClass:"danger"})??!1)}async function k(){if(g)return;if(!e.length){yr(r("没有选中的模型"),"err");return}if(o==="reasoning"&&f.select===ca&&!j){b(s.jsx("span",{className:"text-destructive",children:r("请填写自定义思考等级,或改选候选档 / 「清除」")}));return}if(o==="delete"){if(w===0){b(s.jsx("span",{className:"text-destructive",children:r("选中的模型都不是手动登记,无法删除(开关映射才是它们的手段)")}));return}if(!await N(w))return}v(!0),b("");let E=0,D=0,C=0,A="";for(const R of e){const I=R.provider||"";try{if(o==="delete"){if(!p2(R)){D+=1;continue}Ki(await e2(I,R.id))}else if(o==="enable"||o==="disable"){const P=o==="enable";for(const O of Iu(R))Ki(await Fg(I,O.alias,R.id,{enabled:P}))}else for(const P of Iu(R))Ki(await Fg(I,P.alias,R.id,{reasoning:j}));E+=1}catch(P){C+=1,A||(A=Ro(P)),b(s.jsx("span",{className:"text-destructive",children:r("失败 {n} 个 · 首个失败:{error}",{n:C,error:A})}))}}C===0?(yr(D?r("✅ 批量{action}完成:共 {n} 个模型(跳过不可删除的 {skipped} 个)",{action:S,n:E,skipped:D}):r("✅ 批量{action}完成:共 {n} 个模型",{action:S,n:E})),a()):(yr(r("批量{action}完成:成功 {ok} 个,失败 {failed} 个",{action:S,ok:E,failed:C}),"err"),b(s.jsxs("span",{className:"text-destructive",children:[r("成功 {ok} 个,失败 {failed} 个",{ok:E,failed:C}),D?r(",跳过 {n} 个",{n:D}):"",A?r(";首个失败:{error}",{error:A}):""]}))),v(!1)}return s.jsx(Qt,{open:!0,onOpenChange:E=>{E||g||t()},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("批量操作 · 已选 {n} 个模型",{n:e.length})})}),s.jsxs(Bt,{children:[s.jsxs(Vn,{children:[s.jsx("h3",{children:r("将作用于以下模型")}),s.jsx("p",{style:{maxHeight:84,overflowY:"auto"},children:e.map(SK).join(r("、"))})]}),s.jsxs(Vn,{children:[s.jsx("h3",{children:r("操作")}),s.jsx(kh,{value:o,onValueChange:E=>c(E),className:"flex-row flex-wrap items-center gap-5","aria-label":r("批量动作"),children:f2.map(E=>s.jsxs(Je,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(bo,{value:E.value}),E.label]},E.value))}),o==="reasoning"?s.jsxs("div",{className:"mt-2.5",children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:"batch-model-reasoning",children:r("思考等级")}),s.jsxs(ft,{value:f.select,onValueChange:E=>p(D=>({...D,select:String(E)})),children:[s.jsx(mt,{id:"batch-model-reasoning",className:"min-w-[220px]",children:s.jsx(pt,{children:f.select===ca?r("自定义等级…"):f.select||r("清除(不覆盖)")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"",children:r("清除(不覆盖)")}),d.map(E=>s.jsx(qe,{value:E,children:E},E)),s.jsx(qe,{value:ca,children:r("自定义等级…")})]})]})]}),f.select===ca?s.jsxs("div",{className:"field-row mt-2",children:[s.jsx("label",{htmlFor:"batch-model-reasoning-custom",children:r("自定义等级")}),s.jsx($e,{id:"batch-model-reasoning-custom",maxLength:32,value:f.custom,onChange:E=>p(D=>({...D,custom:E.currentTarget.value}))})]}):null,s.jsxs("p",{className:"detail mt-1.5",children:[r("设置 / 清除会应用到选中模型的"),s.jsx("b",{children:r("全部映射")}),r("(默认绑定与别名 chips);「清除」= 不给这些映射指定等级(选「不覆盖」的口径与映射弹窗一致)")]})]}):null,o==="delete"?s.jsx("p",{className:"detail mt-2",children:w===0?r("选中的都不是手动登记的模型,删除不可用(上游目录带回来的行由清单决定存在性)"):r("可删除 {n} 个(手动登记 / 自定义家);",{n:w})+(e.length>w?r("其余 {n} 个会被跳过。",{n:e.length-w}):"")}):null]}),s.jsx("div",{className:"detail",style:{minHeight:18},children:y})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:g,onClick:t,children:r("关闭")}),s.jsx(se,{variant:o==="delete"?"destructive":"default",disabled:g,onClick:()=>{k()},children:g?r("执行中…"):r("执行{action}",{action:S})})]})]})})}function er(){return window}const m2={intl:"fm-table-intl",custom:"fm-table-custom"},h2={intl:"fetch-models",custom:"fetch-models-custom"},Xw=["provider","source","state","count","note","updated","op"],Qw=["pick","model","state"],kK={provider:"w-[13%]",source:"w-[21%]",state:"w-[9%]",count:"w-[6%]",note:"w-[20%]",updated:"w-[16%]",op:"w-[15%]"},CK={pick:"w-[8%]",model:"w-[74%]",state:"w-[18%]"},TK={pick:"",provider:r("提供商"),source:r("模型来源"),state:r("状态"),count:r("模型数"),note:r("说明"),updated:r("更新日期"),model:r("上游模型"),op:r("操作")},EK={refreshed:{variant:"brand",label:r("已刷新")},failed:{variant:"destructive",label:r("失败")},skipped:{variant:"outline",label:r("跳过")}},g2=new Set(["cline-free","cline-pass"]),x2="workbuddy-desktop-fetch-model-source";function rp(e){return String(e??"").trim().toLowerCase()}function Zw(e,t){er().wbApp?.toast?.(e,t)}function Ww(e){return e instanceof Error?e.message:String(e)}function b2(e){const t=er().formatTime??er().wbApp?.formatTime;return String(t?.(e)??"")}function v2(){return er().wbApp?.getState?.()?.accounts?.accounts||[]}function AK(e){const a=(er().wbProviders?.customList?.()||[]).find(o=>o.id===e)?.models;return new Set((Array.isArray(a)?a:[]).map(o=>rp(o?.id)).filter(Boolean))}function y2(e){if(e?.nameCustom===!0&&e?.name)return e.name;const t=String(e?.email||"").trim();return er().wbAccountsModel?.providerFeatures?.(e?.provider)?.emailAsName&&t?t:String(e?.nickname||e?.name||t||e?.id||"").trim()||r("未命名账号")}function RK(e){if(g2.has(e))return[];const t=er().wbAccountsModel?.byPriorityOrder,a=v2().filter(o=>(o?.provider||"workbuddy")===e&&o?.available!==!1&&o?.enabled!==!1);return t?a.sort(t):a}function j2(){const e=new Set(er().wbModelsPanel?.builtinProviders?.()||[]);for(const t of v2())t?.available===!1||t?.enabled===!1||e.add(t?.provider||"workbuddy");return[...e]}function OK(){const e=new Set(j2());return(er().wbProviders?.all?.()||[]).filter(t=>e.has(t?.id??""))}function MK(e){return b2(Number(e.refreshedAt)||0)||"—"}function DK(e){return EK[String(e.status)]??{variant:"outline",label:String(e.status||r("未知"))}}function IK(){try{const e=JSON.parse(localStorage.getItem(x2)||"{}");if(!e||typeof e!="object")return{};const t={};for(const[a,o]of Object.entries(e))typeof o=="string"&&o&&(t[a]=o);return t}catch{return{}}}function PK(e){er().wbFilterMemory?.save?.(x2,e)}function _K({options:e,onClose:t}){const a=e.providerId,o=!!e.custom,c=e.name||a,{onDone:d,onRefreshed:f}=e,[p,g]=x.useState("idle"),[v,y]=x.useState(""),[b,j]=x.useState(""),[w,S]=x.useState(null),[N,k]=x.useState(""),E=w!==null,[D,C]=x.useState(!1),[A,R]=x.useState([]),[I,P]=x.useState(()=>new Set),[O,_]=x.useState(()=>new Set),[L,H]=x.useState([]),[B,z]=x.useState(""),[Q,K]=x.useState(IK);x.useEffect(()=>{er().wbTableColumns?.repaint?.(o?h2.custom:h2.intl)},[o]);const X=o?[]:OK(),q=o?[]:G(),$=B.trim().toLowerCase(),Y=A.filter(ve=>!$||ve.toLowerCase().includes($)),F=o?D?r("已选 {picked} 个 · 上游共 {upstream} 个 · 清单已有 {managed} 个",{picked:O.size,upstream:A.length,managed:I.size}):r("尚未获取"):W(q);function G(){const ve=new Map(L.map(we=>[String(we.provider||""),we])),he=X.map(we=>{const xe=String(we.id||"");return{provider:xe,label:String(we.label||xe),item:ve.get(xe)}}),ye=new Set(he.map(we=>we.provider));for(const we of L){const xe=String(we.provider||"");ye.has(xe)||he.push({provider:xe,label:String(we.providerLabel||xe),item:we})}return he}function W(ve){if(p==="loading")return r("正在刷新…");if(p==="error")return"";const he=ve.map(xe=>xe.item).filter(xe=>!!xe);if(!he.length)return D?r("刷新完成,但没有得到任何结果"):ve.length?r("共 {n} 家 · 点「获取模型」开始",{n:ve.length}):r("0 家");const ye=he.filter(xe=>xe.status==="refreshed").length,we=he.filter(xe=>xe.status==="failed").length;return we?r("{total} 家 · 成功 {done} · 失败 {failed}",{total:ve.length,done:ye,failed:we}):r("{total} 家 · 成功 {done}",{total:ve.length,done:ye})}function le(ve,he){const ye=RK(ve);if(!ye.length)return{list:ye,selected:""};const we=String(Q[ve]||""),xe=String(he||""),Te=Oe=>ye.some(Ne=>String(Ne.id)===Oe);return{list:ye,selected:Te(we)?we:Te(xe)?xe:String(ye[0].id)}}function M(ve){const he={};for(const[ye,we]of Object.entries(Q))we&&(he[ye]=we);for(const ye of ve){const{selected:we}=le(ye.provider,ye.reported);we&&(he[ye.provider]=we)}return he}const U=q.map(ve=>({provider:ve.provider,reported:ve.item?.accountId}));function Z(ve,he){K(ye=>({...ye,[ve]:he})),PK({[ve]:he})}async function ae(){if(!E){S("load"),j(""),y(""),g("loading");try{if(o){const he=await er().wbProviders?.customRequest?.("POST","/api/custom-providers/fetch-models",{providerId:a}),ye=new Set,we=(Array.isArray(he?.models)?he.models:[]).map(Te=>String(Te??"").trim()).filter(Te=>{const Oe=rp(Te);return!Te||ye.has(Oe)?!1:(ye.add(Oe),!0)}),xe=AK(a);R(we),P(xe),_(new Set(we.filter(Te=>!xe.has(rp(Te))))),C(!0),g("ready");return}const ve=await er().workbuddyDesktop?.refreshModels({accounts:M(U),providers:j2()});H(Array.isArray(ve?.results)?ve.results:[]),C(!0),g("ready"),Number(ve?.refreshed)>0&&f?.()}catch(ve){const he=Ww(ve);y(he),g("error"),j(he)}finally{S(null)}}}async function ce(ve){if(!(E||!ve.provider)){S("row"),k(ve.provider),j("");try{const he=await er().workbuddyDesktop?.refreshModels({accounts:M([{provider:ve.provider,reported:ve.item?.accountId}]),providers:[ve.provider]});H(ye=>J(ye,Array.isArray(he?.results)?he.results:[])),C(!0),g("ready"),Number(he?.refreshed)>0&&f?.()}catch(he){const ye=Ww(he);j(ye),Zw(r("获取失败:{message}",{message:ye}),"err")}finally{S(null),k("")}}}function J(ve,he){const ye=new Map(he.map(Te=>[String(Te.provider||""),Te])),we=ve.map(Te=>ye.get(String(Te.provider||""))??Te),xe=new Set(we.map(Te=>String(Te.provider||"")));for(const Te of he)xe.has(String(Te.provider||""))||we.push(Te);return we}async function ie(){if(!o||E||!O.size)return;const ve=[...O];S("import"),j("");try{const he=Number(await er().wbModelsCustom?.addModels?.(a,ve))||0;Zw(r("✅ 已导入 {added} 个模型({skipped} 个已存在,跳过)",{added:he,skipped:ve.length-he})),S(null),t(),d?.()}catch(he){const ye=Ww(he);Zw(r("导入失败:{message}",{message:ye}),"err"),j(ye),S(null)}}function ge(){E||t()}function ee(){const ve=new Set(O);for(const he of A)I.has(rp(he))||ve.add(he);_(ve)}function fe(ve){return s.jsx(kl,{children:s.jsx(Nn,{colSpan:o?Qw.length:Xw.length,className:"py-[26px] text-center text-muted-foreground",children:ve})})}function te(ve){return s.jsx("span",{className:"font-mono text-[11.5px] tabular-nums text-muted-foreground",children:ve})}function Ce(ve){return s.jsx("div",{className:"truncate font-mono text-[12px] font-semibold",children:ve})}function re(ve,he){const{list:ye,selected:we}=le(ve,he);if(!ye.length){const Te=g2.has(ve)?r("这家的模型清单是全局的,不跟账号走"):r("这家还没有可用账号,刷新会使用默认登录态");return s.jsx("span",{className:"text-[11.5px] text-muted-foreground",title:Te,children:"—"})}const xe=ye.find(Te=>String(Te.id)===we);return s.jsxs(ft,{value:we,onValueChange:Te=>Z(ve,String(Te)),children:[s.jsx(mt,{className:"w-full",title:r("用哪个账号去拉这家的模型清单"),"aria-label":r("模型来源"),children:s.jsx(pt,{children:xe?y2(xe):"—"})}),s.jsx(ht,{children:ye.map(Te=>s.jsx(qe,{value:String(Te.id),children:y2(Te)},String(Te.id)))})]})}function de(){return p==="idle"?fe(r("点右侧「获取模型」从上游拉取这家的模型清单")):p==="loading"?fe(r("正在获取…")):p==="error"?fe(r("获取失败:{message}",{message:v})):Y.length?Y.map(ve=>{const he=I.has(rp(ve));return s.jsxs(kl,{className:he?"opacity-50":void 0,children:[s.jsx(Nn,{children:s.jsx(Or,{checked:O.has(ve),disabled:he,"aria-label":ve,onCheckedChange:ye=>_(we=>{const xe=new Set(we);return ye?xe.add(ve):xe.delete(ve),xe})})}),s.jsx(Nn,{children:Ce(ve)}),s.jsx(Nn,{children:he?s.jsx(ze,{variant:"brand",title:r("这个模型已经在这家的清单里,不重复导入"),children:r("已添加")}):s.jsx(ze,{variant:"outline",title:r("勾上它,导入后即进入这家的清单"),children:r("未添加")})})]},ve)}):fe(A.length?r("没有匹配「{keyword}」的模型",{keyword:$}):r("上游没有返回任何模型"))}function ke(ve){const he=w==="row"&&N===ve.provider;return s.jsx(se,{variant:"outline",size:"sm",className:"w-full",disabled:E,title:r("只刷新这一家的模型清单"),onClick:()=>{ce(ve)},children:he?r("获取中…"):ve.item?r("重新获取"):r("获取")})}function Ee(){return p==="loading"?fe(r("正在获取…")):p==="error"?fe(r("获取失败:{message}",{message:v})):q.length?q.map(ve=>{const he=ve.item;if(!he){const Te=b2(Number(er().wbModelsPanel?.providerRefreshedAt?.(ve.provider))||0);return s.jsxs(kl,{children:[s.jsx(Nn,{children:Ce(ve.label)}),s.jsx(Nn,{children:re(ve.provider)}),s.jsx(Nn,{children:s.jsx(ze,{variant:"outline",children:r("待获取")})}),s.jsx(Nn,{children:te("—")}),s.jsx(Nn,{children:te("—")}),s.jsx(Nn,{children:te(Te||"—")}),s.jsx(Nn,{children:ke(ve)})]},ve.provider)}const ye=DK(he),we=Number(he.count),xe=he.status==="refreshed"?r("远程目录已更新,「来源」列会显示为「远程」"):he.message||(he.fixed?r("这家用固定模型清单,无可刷新"):r("本次没有取到新内容"));return s.jsxs(kl,{children:[s.jsx(Nn,{children:Ce(ve.label)}),s.jsx(Nn,{children:re(ve.provider,he.accountId)}),s.jsx(Nn,{children:s.jsx(ze,{variant:ye.variant,children:ye.label})}),s.jsx(Nn,{children:te(we?r("{n} 个",{n:we}):"—")}),s.jsx(Nn,{children:s.jsx("span",{className:"text-[11.5px] leading-[1.5] text-muted-foreground",children:xe})}),s.jsx(Nn,{children:te(MK(he))}),s.jsx(Nn,{children:ke(ve)})]},ve.provider)}):fe(r("还没有可刷新的提供商:先在账号页添加一个账号"))}return s.jsx(Qt,{open:!0,onOpenChange:(ve,he)=>{if(!ve){if(E){he.cancel();return}t()}},children:s.jsxs(Zt,{className:o?"w-[min(552px,calc(100vw-48px))]":"w-[min(920px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("获取模型 — {name}",{name:c})})}),s.jsxs(Bt,{children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx("span",{className:"text-[11.5px] text-muted-foreground",children:F}),o&&s.jsxs(Ci,{className:"w-[240px] flex-none",children:[s.jsx(Ei,{type:"search",placeholder:r("搜索模型 ID…"),autoComplete:"off",value:B,onChange:ve=>z(ve.currentTarget.value)}),s.jsx(Ti,{"aria-hidden":"true",children:"⌕"})]}),s.jsx("div",{className:"mr-auto"}),o&&s.jsxs(s.Fragment,{children:[s.jsx(se,{variant:"ghost",size:"sm",onClick:ee,children:r("全选未添加")}),s.jsx(se,{variant:"ghost",size:"sm",onClick:()=>_(new Set),children:r("清空")})]}),s.jsx(se,{variant:"outline",size:"sm",title:r("刷新全部家(逐家打上游)"),disabled:E,onClick:()=>{ae()},children:r(w==="load"?"获取中…":D?"重新获取":"获取模型")})]}),s.jsxs(Vy,{id:o?m2.custom:m2.intl,className:"table-fixed",containerClassName:"max-h-[min(48vh,460px)]",children:[s.jsx("colgroup",{children:(o?Qw:Xw).map(ve=>s.jsx("col",{"data-col":ve,className:o?CK[ve]:kK[ve]},ve))}),s.jsx(pE,{children:s.jsx(kl,{children:(o?Qw:Xw).map(ve=>s.jsx(mE,{"data-col":ve,children:TK[ve]},ve))})}),s.jsx(Fy,{className:"[&_tr:last-child>td]:border-b-0",children:o?de():Ee()})]})]}),s.jsxs(nn,{children:[s.jsx("span",{className:"min-w-0 text-[11.5px] text-muted-foreground",children:b}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:ge,children:r(o?"取消":"完成")}),o&&s.jsx(se,{variant:"default",disabled:!O.size||E,onClick:()=>{ie()},children:w==="import"?r("导入中…"):O.size?r("导入选中的 {n} 个模型",{n:O.size}):r("导入")})]})]})})}let ap=null,Pu=null;function w2(){ap&&(ap.unmount(),ap=null),Pu&&(Pu.remove(),Pu=null)}function LK(e){e?.providerId&&(w2(),Pu=document.createElement("div"),document.body.append(Pu),ap=vn.createRoot(Pu),ap.render(s.jsx(_K,{options:e,onClose:w2})))}window.wbModelsFetchModal={open:LK};const Mo=(e,t)=>t?`${e} ta-${t}`:e;function S2(e,t){const a=(t||"").trim();if(a)return Jf().find(o=>Oo(o.provider,e)&&Oo(o.id,a))}const zK="[.pv-row:hover_&_[data-slot=nav-item-count]]:invisible";function BK(e){const t=/x\s*([\d.]+)/i.exec(String(e||""));return t?`${t[1]}x`:String(e||"")}function N2(e){const t=/x\s*([\d.]+)/i.exec(String(e||""));if(!t)return null;const a=Number(t[1]);return Number.isFinite(a)?a:null}const HK={workbuddy:250,"workbuddy-intl":295,raccoon:60,catpaw:85,autoclaw:250,"autoclaw-intl":295,qoder:330,"qoder-intl":350,"cline-free":200,"cline-pass":200,codearts:210,loomy:155,kuku:15,accio:320,"accio-intl":335,trae:170,zcode:285};function UK(e){const t=HK[e];if(t!==void 0)return t;let a=0;for(let o=0;o>>0;return a%360}function VK(e){const t=String(e||"").trim();if(!t)return"?";const a=t.match(/[A-Za-z]/);return(a?a[0]:t[t.length-1]).toUpperCase()}const FK=e=>({"--av-h":String(UK(e))}),Jw=s.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:s.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{x:"3.5",y:"3.5",width:"7",height:"7",rx:"1.5"}),s.jsx("rect",{x:"13.5",y:"3.5",width:"7",height:"7",rx:"1.5"}),s.jsx("rect",{x:"13.5",y:"13.5",width:"7",height:"7",rx:"1.5"}),s.jsx("rect",{x:"3.5",y:"13.5",width:"7",height:"7",rx:"1.5"})]})});function $K(e){if(!e)return"";const t=Wt().wbPresetProviders?.list;if(!Array.isArray(t))return"";const a=t.find(o=>o.name===e);return a&&Wt().wbPresetProviders?.iconOf?.(String(a.key||""))||""}function qK(e,t){return Jn(e)?$K(t):ug[e==="workbuddy-intl"?"workbuddy":e]||""}function _u(e,t,a){const o=a?"":qK(e,t),c=e==="all"||e==="custom-all";return s.jsx("span",{className:Ue("pv-ico",c&&"mute",o&&"img"),style:o?void 0:FK(e),"aria-hidden":"true",children:o?s.jsx("img",{src:o,alt:""}):a??VK(t)})}const GK={supportsToolCall:s.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:s.jsx("path",{fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"})}),supportsImages:s.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:s.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2.5"}),s.jsx("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),s.jsx("path",{d:"M21 15l-5-5L5 21"})]})}),supportsVideo:s.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:s.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M10 8.5l6 3.5-6 3.5z"})]})}),supportsReasoning:s.jsx("svg",{viewBox:"0 0 24 24","aria-hidden":"true",children:s.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5"}),s.jsx("path",{d:"M9 18h6M10 22h4"})]})})};function KK(e,t,a,o){return o==="enabled"&&!tp(e)||o==="disabled"&&tp(e)||o==="mapped"&&!(e.aliases||[]).length||a!=="all"&&a!=="custom-all"&&(e.provider||"")!==a?!1:t?[e.id,e.name,...e.aliases||[]].join(" ").toLowerCase().includes(t):!0}function YK(){const e=x.useSyncExternalStore(L9,Qf),t=Bg(e),a=Jn(t)||t==="custom-all",[o,c]=x.useState(null),[d,f]=x.useState(!1),[p,g]=x.useState(new Set),v=a&&!Du()&&Lw()&&!Ao(t);x.useEffect(()=>{$9(),Hg(),KM(),Wt().wbApp?.currentPage==="gateway"&&JM().then(()=>Wt().wbProviders?.refreshCustom?.()).then(()=>{Gi()})},[]),x.useEffect(()=>{lK()});const y=Bw(),b=Array.isArray(y.models)?y.models:[],j=e.search.trim().toLowerCase(),w=b.filter(G=>KK(G,j,t,e.stateFilter)),S=e.sort,N=WM(),k=N.length,E=t==="all"?r("全部"):t==="custom-all"?r("自定义 · 全部"):a?String(Ao(t)?.name||t):Hw().get(t)?.label||Gw(t),D=b.filter(tp).length,C=b.filter(G=>(G.aliases||[]).length>0).length,A=ag(w.length,"models"),R=b.filter(G=>p.has(Yi(G))),I=(G,W)=>{const le=new Set(p);W?le.add(G):le.delete(G),g(le)},P=w.map(Yi),O=P.length>0&&P.every(G=>p.has(G)),_=P.some(G=>p.has(G)),L=s.jsx(Or,{checked:O,indeterminate:!O&&_,disabled:!P.length,"aria-label":r("全选当前筛选结果"),title:r("全选当前筛选出的模型(跨分页);再点取消"),onCheckedChange:G=>{const W=new Set(p);for(const le of P)G===!0?W.add(le):W.delete(le);g(W)}});function H(){const G=Hw(),W=Fi(),le=H9(),M=[...G.values()].reduce((ce,J)=>ce+J.n,0),U=r("全部({n} 家)",{n:G.size}),Z=[...le.values()].reduce((ce,J)=>ce+J.n,0),ae=r("全部({n} 家)",{n:[...le.values()].filter(ce=>ce.n>0).length});return s.jsxs("aside",{className:"prov-rail",id:"prov-rail","aria-label":r("按提供商选择"),children:[s.jsxs("div",{className:"rail-scroll",children:[s.jsx("div",{className:"rail-label",children:r("内置提供商")}),s.jsx(au,{active:t==="all","data-provider":"all",title:U,count:M,icon:_u("all","",Jw),className:"shadow-none",onClick:()=>np("all"),children:U}),[...G].map(([ce,J])=>s.jsx(au,{active:t===ce,"data-provider":ce,title:J.label,count:J.n,icon:_u(ce,J.label),className:"shadow-none",onClick:()=>np(ce),children:J.label},ce)),s.jsx("div",{className:"rail-label",children:r("自定义提供商")}),W.length?[...Z>0?[s.jsx(au,{active:Du(),"data-provider":"custom-all",title:ae,count:Z,icon:_u("custom-all","",Jw),className:"shadow-none",onClick:()=>np("custom-all"),children:ae},"custom-all")]:[],...W.map(ce=>{const J=String(ce.id||""),ie=String(ce.name||J);return s.jsxs("div",{className:"pv-row",children:[s.jsx(au,{active:t===J,"data-provider":J,title:ie,count:le.get(J)?.n??0,icon:_u(J,ie),className:Ue("shadow-none",zK),onClick:()=>np(J),children:ie}),s.jsx("button",{type:"button",className:"pv-del","aria-label":r("删除自定义提供商"),title:r("删除这个自定义提供商(连同名下账号)"),onClick:()=>{J9(J)},children:"×"})]},J)})]:s.jsx("div",{className:"rail-empty",children:r("还没有自定义提供商")})]}),s.jsx("div",{className:"rail-foot",children:s.jsx(au,{variant:"add",id:"rail-add-custom",title:r("新建一个自定义提供商(同时创建它的第一个账号)"),onClick:()=>eK(),children:r("+ 新建自定义提供商")})})]})}function B(G,W,le,M){const U=Kw(G,W,le);return s.jsx(se,{variant:U?"secondary":"dashed",size:"2xs",disabled:M,className:"font-mono font-bold shadow-none",title:U?r("思考等级 {level}(点击修改)",{level:U}):r("设置思考等级(当前未绑定)"),onClick:()=>t2({alias:G,target:W,provider:le}),children:U||r("+等级")})}function z(G){const W=G.provider||"",le=Iu(G),[M,...U]=le;async function Z(ce){await Wt().wbConfirm?.ask?.({title:r("删除映射"),html:r("确定删除映射「{alias} → {target}」?",{alias:Ow(ce),target:Ow(G.id)}),okText:r("删除"),okClass:"danger"})&&$w(qw(ce,G.id,W),()=>q9(W,ce,G.id),r("映射已删除"))}const ae=ce=>{const J=ce.alias,ie=ce.enabled!==!1,ge=e.pending.has(qw(J,G.id,W));return s.jsxs("span",{className:Ue("alias",!ie&&"map-off"),children:[s.jsx(ms,{size:"sm",checked:ie,disabled:ge,title:r(ie?"映射已启用,点击关闭":"映射已关闭,点击启用"),"aria-label":r("{action}映射 {alias}",{action:r(ie?"关闭":"启用"),alias:J}),onCheckedChange:ee=>{$w(qw(J,G.id,W),()=>Fg(W,J,G.id,{enabled:ee}),r(ee?"映射已启用":"映射已关闭"))}}),s.jsx("span",{className:"t","data-copy":J,title:r("点击复制:{name}",{name:J}),children:J}),ce.isDefault?s.jsx("span",{className:"binding-default",children:r("默认")}):null,B(J,G.id,W,ge),ce.isDefault?null:s.jsx(se,{variant:"ghost",size:"icon-2xs",className:"text-[12px] leading-none",disabled:ge,title:r("删除映射 {alias}",{alias:J}),onClick:()=>{Z(J)},children:"×"})]},`${J}${ce.isDefault?"d":"m"}`)};return s.jsxs("div",{className:"aliases",children:[s.jsxs("div",{className:"alias-row",children:[M?ae(M):null,s.jsx(se,{variant:"dashed",size:"xs",onClick:()=>t2({target:G.id,provider:W}),children:r("+ 映射")})]}),U.map(ae)]})}function Q(G){if(G.source==="manual")return s.jsxs("span",{className:"src manual",title:r("手动登记的上游模型;移除它会直接删掉这条登记"),children:[s.jsx("i",{"aria-hidden":"true"}),r("手动")]});if(!G.source&&Jn(G.provider))return s.jsxs("span",{className:"src manual",title:r("用户登记的自定义模型;整份清单只属于这一家"),children:[s.jsx("i",{"aria-hidden":"true"}),r("自定义")]});if(G.source!=="remote"&&G.source!=="builtin")return s.jsx("span",{className:"rate",children:"—"});const W=G.source==="remote",le=M9(Number(G.refreshedAt)||0),M=W?le?r("来自上游目录接口,清单拉取于 {at};刷新失败时保留上一份成功结果",{at:le}):r("来自上游目录接口;刷新失败时保留上一份成功结果"):r("上游目录尚未拉到,用的是内置静态清单;点「刷新模型清单」可重试");return s.jsxs("span",{className:Ue("src",W?"remote":"builtin"),title:M,children:[s.jsx("i",{"aria-hidden":"true"}),r(W?"远程":"内置")]})}function K(G){const W=Aw(G),le=Ew(G.capOverrides),M=typeof W.maxInputTokens=="number"?W.maxInputTokens:null,U=typeof W.maxOutputTokens=="number"?W.maxOutputTokens:null,Z=r("上下文窗口 {input} / 最大输出 Token {output} —— 点击修改模型能力",{input:Kf(M),output:Kf(U)})+X(G);return s.jsxs("button",{type:"button",className:"caps-open",title:Z,onClick:()=>n2(G.provider||"",G.id),children:[s.jsxs("span",{className:Ue("cap-num",M===null&&"unset",Ou(G,"maxInputTokens")==="modelsdev"&&"filled"),children:[EM(M),le.includes("maxInputTokens")?s.jsx("i",{className:"cap-mark",title:r("已覆盖上游值")}):null]}),s.jsx("span",{className:"cap-sep",children:"/"}),s.jsxs("span",{className:Ue("cap-num",U===null&&"unset",Ou(G,"maxOutputTokens")==="modelsdev"&&"filled"),children:[EM(U),le.includes("maxOutputTokens")?s.jsx("i",{className:"cap-mark",title:r("已覆盖上游值")}):null]})]})}function X(G){const W=["maxInputTokens","maxOutputTokens"].filter(le=>Ou(G,le)==="modelsdev").map(le=>Ru[le]);return W.length?r(";其中 {keys} 由 models.dev 补齐",{keys:W.join(r("、"))}):""}function q(G){const W=Aw(G),le=Ew(G.capOverrides);return s.jsx("button",{type:"button",className:"caps-open caps-badges",title:r("对下游声明的能力(工具调用 / 图片识别 / 视频识别 / 支持思考)—— 点击修改"),onClick:()=>n2(G.provider||"",G.id),children:CM.map(M=>{const U=W[M]??null,Z=Rw(U),ae=le.includes(M),ce=Ou(G,M);return s.jsxs("span",{className:Ue("cap-dot",Z,ce==="modelsdev"&&"filled",ae&&"marked"),title:S9(M,U,ae,ce),children:[GK[M],ae?s.jsx("i",{className:"cap-mark"}):null]},M)})})}function $(G,W,le){async function M(){await Wt().wbConfirm?.ask?.({title:r("移除自定义模型"),html:r("确定移除自定义模型「{id}」?这条登记会被直接移除,之后 /v1/models 不再广告它、请求它也会被拒。",{id:Ow(W.id)}),okText:r("移除"),okClass:"danger"})&&$w(Yi(W),()=>e2(W.provider||"",W.id),Jn(W.provider||"")?r("模型已移除"):r("自定义模型已移除"))}switch(G.key){case"check":return s.jsx("td",{className:Mo("cell-check",G.align),children:s.jsx(Or,{checked:p.has(Yi(W)),title:r("勾选后可批量操作"),"aria-label":r("勾选后可批量操作"),onCheckedChange:U=>I(Yi(W),U===!0)})});case"model":return s.jsxs("td",{className:Mo("cell-model",G.align),children:[s.jsx("div",{className:"mid",children:s.jsx("span",{className:"t","data-copy":W.id,title:r("点击复制:{name}",{name:W.id}),children:W.id})}),W.name&&W.name!==W.id?s.jsx("div",{className:"mname",children:W.name}):null]});case"rate":return s.jsx("td",{className:Mo("cell-rate",G.align),children:s.jsx("span",{className:"rate",children:W.credits?BK(W.credits):"—"})});case"source":return s.jsx("td",{className:Mo("cell-source",G.align),children:Q(W)});case"budget":return s.jsx("td",{className:Mo("cell-budget",G.align),children:K(W)});case"caps":return s.jsx("td",{className:Mo("cell-caps",G.align),children:q(W)});case"alias":return s.jsx("td",{className:Mo("cell-alias",G.align),children:z(W)});case"act":{const U=vK(W.provider||""),Z=W.source==="manual"||Jn(W.provider||"");return s.jsx("td",{className:Mo("cell-act r",G.align),children:s.jsxs("div",{className:"row-actions",children:[s.jsx(se,{variant:"ghost",size:"sm",disabled:!!U,title:U||r("以这个上游模型发一次最小请求,走真实转发链路"),onClick:()=>c({provider:W.provider||"",id:W.id}),children:r("测试")}),Z?s.jsx(se,{variant:"ghost",size:"sm",className:"text-destructive",disabled:le,onClick:()=>{M()},children:r("移除")}):null]})})}default:return null}}function Y(G){const W=e.pending.has(Yi(G)),le=p.has(Yi(G));return s.jsx("tr",{className:Ue(le&&"sel"),children:N.map(M=>s.jsx(x.Fragment,{children:$(M,G,W)},M.key))},`${G.provider||""}${G.id}`)}function F(){if(!b.length){const Z=a?Lw()?Du()?r("自定义提供商还没有模型:先在左栏选一家,点「添加模型」登记,或「获取上游模型」从上游拉取"):r(v?"该提供商已不存在(可能已被删除),请刷新列表":"这家还没有模型:点「添加模型」登记,或「获取上游模型」从上游拉取"):r("加载中…"):e.data?r("暂无模型(请先添加账号)"):r("加载中…");return s.jsx("tr",{children:s.jsx("td",{colSpan:k,className:"empty",children:Z})})}if(!w.length)return s.jsx("tr",{children:s.jsx("td",{colSpan:k,className:"empty",children:j?r("没有匹配「{keyword}」的模型",{keyword:j}):r("没有匹配当前筛选的模型")})});const G=t==="all"||Du(),W=G&&!j&&e.stateFilter==="all"&&!A.paged,le=new Map;for(const Z of w){const ae=Z.provider||"";le.has(ae)||le.set(ae,{label:Z.providerLabel||ae||r("未知"),items:[]}),le.get(ae)?.items.push(Z)}const M=[];let U=0;for(const[Z,ae]of le){ae.items.sort((te,Ce)=>{const re=+!tp(te)-+!tp(Ce);if(re!==0||S==="default")return re;const de=N2(te.credits),ke=N2(Ce.credits);return de===null||ke===null?de===ke?0:de===null?1:-1:S==="rate-asc"?de-ke:ke-de});const ce=e.expanded.has(Z)||!W,J=ce?ae.items:ae.items.slice(0,UM),ie=ae.items.length-J.length,ge=A.paged?Math.max(0,A.rangeStart-1-U):0,ee=A.paged?Math.min(J.length,A.rangeEnd-U):J.length,fe=ge0?r("(续)"):"",r("{n} 个模型",{n:ae.items.length})]})},`group:${Z}`));for(const te of fe)M.push(Y(te));U+=J.length,ie>0?M.push(s.jsx("tr",{className:"tr-more",children:s.jsx("td",{colSpan:k,children:s.jsx(se,{variant:"ghost",size:"sm",onClick:()=>Y9(Z),children:r("展开其余 {n} 个模型 ▾",{n:ie})})})},`more:${Z}`)):ce&&W&&ae.items.length>UM&&M.push(s.jsx("tr",{className:"tr-more",children:s.jsx("td",{colSpan:k,children:s.jsx(se,{variant:"ghost",size:"sm",onClick:()=>X9(Z),children:r("收起 ▴")})})},`collapse:${Z}`))}return M}return s.jsxs(s.Fragment,{children:[s.jsx("section",{className:"panel",children:s.jsxs("div",{className:"mm",children:[H(),s.jsxs("div",{className:"mm-main",children:[s.jsxs("div",{className:"panel-head",children:[s.jsxs("div",{className:"mm-titlebar",children:[s.jsxs("div",{className:"mm-title",children:[t==="all"||t==="custom-all"?_u(t,"",Jw):_u(t,E),s.jsx("h2",{children:E}),s.jsxs("span",{className:"mm-meta",children:[s.jsx("b",{children:b.length}),r(" 个模型 · 已启用 "),s.jsx("b",{children:D}),r(" · 有映射 "),s.jsx("b",{children:C})]})]}),s.jsxs("div",{className:"head-actions",children:[s.jsx(se,{id:"btn-refresh-models",title:Jn(t)?r("从这一家的上游拉一份模型清单,勾选要哪些再导入(已添加的不会重复导入)"):r("刷新模型管理页里各提供商的远程模型目录,逐家结果列在弹窗里"),onClick:()=>r2(),children:r("获取模型")}),s.jsx(se,{id:"btn-add-custom-model",variant:"outline",size:"sm",onClick:()=>nK(),children:r("+ 添加模型")})]})]}),s.jsxs("div",{className:"mm-filters",children:[s.jsx(In,{options:I9,value:e.stateFilter,onValueChange:Q9,"aria-label":r("按状态筛选"),className:"shrink-0"}),s.jsx(In,{options:_9,value:e.sort,onValueChange:Z9,"aria-label":r("按倍率排序"),className:"shrink-0"}),s.jsxs(Ci,{className:"w-full min-[768px]:w-[240px] flex-none min-[768px]:flex-none",id:"models-search",children:[s.jsx(Ei,{type:"search",placeholder:r("搜索模型 ID / 名称 / 映射名…"),"aria-label":r("搜索模型"),autoComplete:"off",value:e.search,onChange:G=>W9(G.currentTarget.value)}),s.jsx(Ti,{"aria-hidden":"true",children:"⌕"})]}),R.length>0?s.jsxs("span",{className:"batch-chip",children:[r("已选 "),s.jsx("b",{children:R.length}),r(" 个"),s.jsx(se,{id:"btn-batch-models",variant:"outline",size:"xs",title:r("对选中的 {n} 个模型执行批量操作",{n:R.length}),onClick:()=>f(!0),children:r("批量操作")})]}):null]})]}),s.jsx("div",{className:"models-table-wrap",children:s.jsxs("table",{className:"models-table",ref:G=>aK(G),children:[s.jsxs("colgroup",{children:[s.jsx("col",{className:"c-check","data-col":"check"}),s.jsx("col",{className:"c-model","data-col":"model"}),s.jsx("col",{className:"c-rate","data-col":"rate"}),s.jsx("col",{className:"c-source","data-col":"source"}),s.jsx("col",{className:"c-budget","data-col":"budget"}),s.jsx("col",{className:"c-caps","data-col":"caps"}),s.jsx("col",{className:"c-alias","data-col":"alias"}),s.jsx("col",{className:"c-act","data-col":"act"})]}),s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{"data-col":"check",children:L}),s.jsx("th",{"data-col":"model",children:r("上游模型")}),s.jsx("th",{"data-col":"rate",children:r("倍率")}),s.jsx("th",{"data-col":"source",children:r("来源")}),s.jsxs("th",{"data-col":"budget",children:[r("上下文 / 输出"),s.jsx("span",{className:"th-help","aria-hidden":"true",title:r("数字带虚线底 = 由 models.dev 补齐;右上角小点 = 你手动覆盖过;— = 未声明。点任意一格可改。"),children:s.jsx("svg",{viewBox:"0 0 24 24",children:s.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M12 16v-4"}),s.jsx("path",{d:"M12 8h.01"})]})})})]}),s.jsxs("th",{"data-col":"caps",children:[r("能力"),s.jsx("span",{className:"th-help","aria-hidden":"true",title:r("圆点带内侧描边 = 由 models.dev 补齐;右上角小点 = 你手动覆盖过;虚线圈 = 未声明。悬停某一枚可看逐项出处。"),children:s.jsx("svg",{viewBox:"0 0 24 24",children:s.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M12 16v-4"}),s.jsx("path",{d:"M12 8h.01"})]})})})]}),s.jsxs("th",{"data-col":"alias",children:[r("模型映射"),s.jsx("span",{className:"th-help","aria-hidden":"true",title:r("每条映射 = 对外名 → 上游模型;原始 ID 与别名有独立开关,默认绑定永远存在(没有映射时是合成的那条)。"),children:s.jsx("svg",{viewBox:"0 0 24 24",children:s.jsxs("g",{fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[s.jsx("circle",{cx:"12",cy:"12",r:"9"}),s.jsx("path",{d:"M12 16v-4"}),s.jsx("path",{d:"M12 8h.01"})]})})})]}),s.jsx("th",{className:"r","data-col":"act",children:r("操作")})]})}),s.jsx("tbody",{id:"models",children:F()})]})}),s.jsx(Li,{className:"models-panel-foot",leading:Du()?s.jsxs(s.Fragment,{children:[r("这里是"),s.jsx("b",{children:r("全部自定义提供商")}),r("的模型合集:每家的清单互相独立,别名也只在自己那家内生效;要改名称 / 协议 / Base URL,到账号页该家账号的「设置」→ 提供商一栏。")]}):a?s.jsxs(s.Fragment,{children:[r("自定义提供商的清单"),s.jsx("b",{children:r("只属于这一家")}),r(":这里的模型不会出现在其他家,别名也只在这一家内生效。改名称 / 协议 / Base URL 在账号页该家账号的「设置」→ 提供商一栏;整家不要了,鼠标移到左栏这家上点 × 删除(连同名下账号)。")]}):void 0,total:w.length,range:A.paged?{start:A.rangeStart,end:A.rangeEnd}:null,page:A.page,pageCount:A.pageCount,size:A.size,onSizeChange:A.setSize,onPageChange:A.goto})]})]})}),e.mapping?s.jsx(QK,{context:e.mapping,onClose:tK}):null,e.customModel?s.jsx(ZK,{initial:e.customModel,onClose:sK}):null,e.capability?s.jsx(dK,{context:e.capability,onClose:rK}):null,o?s.jsx(wK,{target:o,onClose:()=>c(null)}):null,d?s.jsx(NK,{models:R,onClose:()=>f(!1),onDone:()=>{g(new Set),f(!1)}}):null]})}const XK=r("绑定在「对外名 → 上游模型」这一条映射上的思考等级(列表照抄 OmniProxy 的手动绑定),选「不覆盖」表示不给这条映射指定等级。它会跟着这条映射注入转发,由承载的那家翻译成自己的档位字段(CatPaw 归并成 low/high/max,Qoder 按模型声明的档位归一)。以下几种情况故意不注入:① off / none(关闭思考)—— 本项目没有安全的表达方式;② 表外的自定义等级(各家能力范围不同,无法判断上游收不收);③ 客户端请求体里已经自己指定了档位(那是更明确的意图,绑定不覆盖);④ 这家上游不认识档位字段(如 WorkBuddy / 小浣熊 / AutoClaw / Cline)。注入与跳过都会写进详细日志。");function k2(e,t,a){const o=ZM(e),c=(t||"").trim(),d=o.find(f=>f.id.toLowerCase()===c.toLowerCase());return d?d.id:c||o[0]?.id||""}function QK({context:e,onClose:t}){const a=!!e.alias,[o,c]=x.useState(()=>e.provider||Uw()[0]?.id||""),[d,f]=x.useState(e.alias||""),[p,g]=x.useState(()=>k2(o,e.target)),[v,y]=x.useState(""),[b,j]=x.useState(!1),[w,S]=x.useState(()=>{const _=Xf(Qf().data,S2(o,p)),L=a?Kw(e.alias,e.target,e.provider):"";return L&&_.includes(L)?{select:L,custom:""}:{select:L?ca:"",custom:L}}),N=Xf(Qf().data,S2(o,p)),k=(()=>{const _=Uw();for(const L of[e.provider,o])L&&!_.some(H=>H.id===L)&&_.push({id:L,label:Wt().wbProviders?.labelOf?.(L)||L});return _})(),E=(()=>{const _=ZM(o),L=(p||"").trim();return L&&!_.some(H=>H.id.toLowerCase()===L.toLowerCase())&&_.unshift({id:L,label:r("{name}(不在该家当前清单里)",{name:L}),off:!0}),_})(),D=k.find(_=>_.id===o)?.label||o||r("(全局)"),C=w.select&&w.select!==ca&&!N.includes(w.select)?{select:ca,custom:w.custom||w.select}:w,A=C.select===ca?C.custom.trim():C.select,R=C.select===ca;function I(_){c(_),g(k2(_,p))}async function P(){if(b)return;const _=a?e.alias||"":d.trim(),L=p;if(!_){y(r("请填写对外映射名"));return}if(!L){y(r("该提供商当前没有可选的上游模型"));return}if(!o){y(r("请选择提供商"));return}if(!a&&Oo(_,L)&&Jf().some(H=>Oo(H.id,L)&&Oo(H.provider,o))){y(r("原始 ID 已作为默认绑定,请直接使用该绑定的开关或等级按钮"));return}j(!0),y(r("保存中…"));try{Ki(await Fg(o,_,L,{reasoning:A})),j(!1),t();const H=A?r(" · 思考等级 {level}",{level:A}):"",B=Wt().wbProviders?.labelOf?.(o)||o;yr(a?r("✅ 已更新 {name} 的思考等级",{name:_}):r("✅ 已添加映射 {name} → {target}({label}){suffix}",{name:_,target:L,label:B,suffix:H}))}catch(H){y(r("保存失败:{message}",{message:Ro(H)})),j(!1)}}const O=_=>{_.key==="Enter"&&(_.preventDefault(),P())};return s.jsx(Qt,{open:!0,onOpenChange:(_,L)=>{if(!_){if(b){L.cancel();return}t()}},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r(a?"设置思考等级":"添加模型映射")})}),s.jsxs(Bt,{children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"mapping-provider",children:r("提供商")}),s.jsxs(ft,{value:o,disabled:!0,onValueChange:_=>I(String(_)),children:[s.jsx(mt,{id:"mapping-provider",className:"w-full",children:s.jsx(pt,{children:k.find(_=>_.id===o)?.label||o})}),s.jsx(ht,{children:k.map(_=>s.jsx(qe,{value:_.id,children:_.label},_.id))})]})]}),s.jsxs("div",{className:"grid grid-cols-[1fr_24px_1fr] items-end gap-2.5",children:[s.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"mapping-alias",children:r("对外映射名(下游请求时用)")}),s.jsx($e,{id:"mapping-alias",maxLength:128,placeholder:r("例如 gpt-4o"),autoComplete:"off",autoFocus:!a,value:d,disabled:a,onChange:_=>f(_.currentTarget.value),onKeyDown:O})]}),s.jsx("div",{className:"pb-2 text-center text-muted-foreground",children:"→"}),s.jsxs("div",{className:"flex min-w-0 flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"mapping-upstream",children:r("转发到上游模型")}),s.jsxs(ft,{value:p,disabled:!0,onValueChange:_=>g(String(_)),children:[s.jsx(mt,{id:"mapping-upstream",className:"w-full",children:s.jsx(pt,{children:E.find(_=>_.id===p)?.label||p})}),s.jsx(ht,{children:E.map(_=>s.jsxs(qe,{value:_.id,children:[_.label,_.off?r("(已禁用)"):""]},_.id))})]})]})]}),s.jsxs("div",{className:"rounded-md border border-border bg-surface-inset px-3 py-2.5 font-mono text-[12px] text-subtle",children:[r("下游请求 "),s.jsx("b",{className:"text-primary-fg",children:d.trim()||r("<对外名>")}),r(" → 转发")," ",s.jsx("b",{className:"text-primary-fg",children:p||r("<上游模型>")}),r("({label})",{label:D}),A?s.jsxs(s.Fragment,{children:[r(" · 思考等级 "),s.jsx("b",{className:"text-primary-fg",children:A})]}):null]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-[7px]",children:[s.jsx(Je,{htmlFor:"mapping-reasoning",children:r("思考等级")}),s.jsxs(Ii,{children:[s.jsx(Pi,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("思考等级的注入规则")}),children:"?"}),s.jsx(_i,{children:XK})]})]}),s.jsxs(ft,{value:C.select,onValueChange:_=>{const L=String(_);S(H=>({...H,select:L}))},children:[s.jsx(mt,{id:"mapping-reasoning",className:"w-full",autoFocus:a,children:s.jsx(pt,{children:C.select===ca?r("自定义等级…"):C.select||r("不覆盖")})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"",children:r("不覆盖")}),N.map(_=>s.jsx(qe,{value:_,children:_},_)),s.jsx(qe,{value:ca,children:r("自定义等级…")})]})]}),R?s.jsx($e,{id:"mapping-reasoning-custom",maxLength:32,autoFocus:!0,placeholder:r("自定义等级(例如 custom-high)"),autoComplete:"off",disabled:b,value:C.custom,onChange:_=>S(L=>({...L,custom:_.currentTarget.value})),onKeyDown:O}):null]}),s.jsxs("p",{className:"text-xs leading-[1.65] text-subtle",children:[r("对外名可自由命名,允许与上游模型 ID 同名(同名时该上游的原生路由优先,映射作兜底); 支持字母、数字与 "),s.jsx("code",{children:"- _ . / :"}),r("。同一对外名可在多个提供商各添加一条: 下游用同一个名字请求,网关按账号优先级主备切换,失败自动落到下一个提供商。")]}),s.jsx("div",{className:"min-h-[18px] text-xs text-subtle",children:v})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("取消")}),s.jsx(se,{variant:"default",disabled:b,onClick:()=>{P()},children:r(a?"保存等级":"保存映射")})]})]})})}function ZK({initial:e,onClose:t}){const[a,o]=x.useState(e.provider),[c,d]=x.useState(""),[f,p]=x.useState(""),[g,v]=x.useState(!1),y=(()=>{const N=F9();return a&&!N.some(k=>k.id===a)&&N.push({id:a,label:Wt().wbProviders?.labelOf?.(a)||a}),N})(),b=y.some(N=>N.id===a)?a:y[0]?.id||"",j=y.find(N=>N.id===b)?.label||b||r("(未选)");async function w(){if(g)return;const N=c.trim();if(!b){p(r("请选择提供商"));return}if(!N){p(r("请填写上游模型 ID"));return}v(!0),p(r("保存中…"));try{const k=await G9(b,N);Ki(k),v(!1),t();const E=y.find(D=>D.id===b)?.label||b;if(Jn(Mu()))yr(r("✅ 已登记模型 {name}({label})",{name:N,label:E}));else{const D=k;Array.isArray(D?.models)&&D.models.some(A=>A.id===N&&(A.provider||"")===b)?yr(r("✅ 已登记自定义模型 {name}({label})",{name:N,label:E})):yr(r("✅ 已登记 {name}({label}),但该提供商还没有可用账号,这一行要加上账号后才会显示",{name:N,label:E}),"err")}}catch(k){p(r("保存失败:{message}",{message:Ro(k)})),v(!1)}}const S=N=>{N.key==="Enter"&&(N.preventDefault(),w())};return s.jsx(Qt,{open:!0,onOpenChange:(N,k)=>{if(!N){if(g){k.cancel();return}t()}},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("添加自定义模型")})}),s.jsxs(Bt,{children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"custom-model-provider",children:r("提供商")}),s.jsxs(ft,{value:b,disabled:e.locked,onValueChange:N=>o(String(N)),children:[s.jsx(mt,{id:"custom-model-provider",className:"w-full",children:s.jsx(pt,{children:j})}),s.jsx(ht,{children:y.map(N=>s.jsx(qe,{value:N.id,children:N.label},N.id))})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"custom-model-id",children:r("上游模型 ID")}),s.jsx($e,{id:"custom-model-id",maxLength:128,placeholder:r("例如 gpt-5.5-preview"),autoComplete:"off",spellCheck:!1,autoFocus:!0,value:c,onChange:N=>d(N.currentTarget.value),onKeyDown:S})]}),s.jsxs("div",{className:"rounded-md border border-border bg-surface-inset px-3 py-2.5 font-mono text-[12px] text-subtle",children:[r("在 "),s.jsx("b",{className:"text-primary-fg",children:j}),r(" 上登记上游模型")," ",s.jsx("b",{className:"text-primary-fg",children:c.trim()||r("<上游模型 ID>")}),r("(登记后即可用这个名字请求)")]}),s.jsxs("p",{className:"text-xs leading-[1.65] text-subtle",children:[r("填上游真正认识的那个模型 ID(不是给下游用的名字)。登记后它会进入该家的模型清单: 表格里出现这一行、"),s.jsx("code",{children:"/v1/models"}),r(" 会广告它、请求它也会被转发到这家。 支持字母、数字与 "),s.jsx("code",{children:"- _ . / :"}),r("。")]}),s.jsxs("p",{className:"text-xs leading-[1.65] text-subtle",children:[r("「来源」列会标成"),s.jsx("b",{children:r("手动")}),r(",与远程目录 / 内置清单区分开。删除自定义模型是"),s.jsx("b",{children:r("直接移除")}),r("这条登记(不像内置模型那样只是隐藏),因为它的存在完全由这次登记决定。")]}),s.jsx("div",{className:"min-h-[18px] text-xs text-subtle",children:f})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("取消")}),s.jsx(se,{variant:"default",disabled:g,onClick:()=>{w()},children:r("保存")})]})]})})}const C2='.page[data-page="gateway"]';let e0=null;function T2(){if(e0)return;const e=document.querySelector(C2);e&&(e.replaceChildren(),e0=vn.createRoot(e),e0.render(s.jsx(YK,{})))}document.querySelector(C2)?T2():document.addEventListener("DOMContentLoaded",T2,{once:!0});const E2=3065;function WK(){if(el().workbuddyDesktop?.platform!=="web")return null;const e=typeof window>"u"?"":window.location?.origin;return e&&e!=="null"?e:null}function A2(e,t){return WK()??(e?`http://127.0.0.1:${e}`:t)}function el(){return window}function $g(e){return e instanceof Error?e.message:String(e)}function Lu(e,t){el().wbApp?.toast?.(e,t)}let lp={backend:null,gatewayBase:A2(0,`http://127.0.0.1:${E2}`)};const t0=new Set;function n0(){return lp}function JK(e){return t0.add(e),()=>{t0.delete(e)}}function eY(e){lp=e;for(const t of t0)t()}function R2(){return lp.gatewayBase.replace(/^https?:\/\//,"")}function tY(){return lp.backend?.ready===!0}function O2(e){const t=(a,o)=>{const c=document.getElementById(a);c&&(c.textContent=o)};t("api-base",`${e}/v1`),t("api-chat",`POST ${e}/v1/chat/completions`),t("api-responses",`POST ${e}/v1/responses`),t("api-messages",`POST ${e}/v1/messages`),t("api-models",`GET ${e}/v1/models`)}let s0=!1;async function zu(){if(!s0){s0=!0;try{const e=el().workbuddyDesktop;if(!e)throw new Error("后端桥不可用");const t=await e.getBackendStatus(),a=Number(t?.port)||0,o=n0(),c={backend:t??null,gatewayBase:A2(a,o.gatewayBase)};c.gatewayBase!==o.gatewayBase&&O2(c.gatewayBase),eY(c),el().wbApp?.renderTopbarStatus?.()}catch(e){console.warn("读取后端状态失败:",$g(e))}finally{s0=!1}}}function nY(){O2(lp.gatewayBase),zu()}async function M2(e){Lu(e||r("正在重启…"));try{await el().workbuddyDesktop?.restartApp()}catch(t){Lu(r("重启失败:{reason}",{reason:$g(t)}),"err")}}const sY={idle:r("结束占用进程"),querying:r("查询中…"),ending:r("结束中…")};function rY({container:e}){const{backend:t,gatewayBase:a}=x.useSyncExternalStore(JK,n0),[o,c]=x.useState("idle"),d=t?.failure||null,f=R2(),p=t?.ready;let g="live off",v=r("正在检查… · {port}",{port:f});p===!0?(g="live pulse",v=r("网关运行中 · {port}",{port:f})):d?(g="live bad",v=r("{label} · {port}",{label:d.label||r("网关启动失败"),port:f})):p===!1&&(v=r("网关启动中… · {port}",{port:f}));const y=d?d.message??"":p===!0?r("本地网关正在监听 {url},可直接调用 OpenAI 兼容接口",{url:a}):r("正在确认网关是否已就绪");x.useEffect(()=>{zu()},[]),x.useEffect(()=>{const j=el().workbuddyDesktop?.onBackendError?.(()=>{zu()});return typeof j=="function"?j:void 0},[]),x.useEffect(()=>{e.title=y},[e,y]);async function b(){if(o!=="idle")return;const j=el().workbuddyDesktop;if(j){c("querying");try{const w=await j.getPortOccupant(),S=w?.occupant;if(!S){Lu(r("端口 {port} 上没有查到监听进程,请改用「更换端口」",{port:w?.port??""}),"err");return}const N=[r("即将结束以下进程:"),"",r("进程名:{name}",{name:String(S.name)}),r("PID:{pid}",{pid:String(S.pid)}),r("路径:{path}",{path:S.path||r("(未知)")}),"",r("结束它会强制退出该程序未保存的数据。确认继续?")],k=el().wbConfirm?.ask;if(!k||!await k({title:r("结束占用端口的进程"),text:N.join(` +`),okText:r("结束进程"),okClass:"danger"}))return;c("ending"),(await j.endPortOccupant())?.released?(Lu(r("已结束进程 {name}(PID {pid}),端口已释放",{name:String(S.name),pid:String(S.pid)})),await k({title:r("重启程序"),text:r("端口已释放。现在重启程序让网关用这个端口启动?"),okText:r("重启")})?await M2(r("重启中…")):await zu()):(Lu(r("进程已结束,但端口仍被占用,建议改用「更换端口」"),"err"),await zu())}catch(w){Lu(r("结束失败:{reason}",{reason:$g(w)}),"err")}finally{c("idle")}}}return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"status-line",children:[s.jsx("span",{className:g}),s.jsx("span",{className:"txt",children:v})]}),d?.conflict?s.jsxs("div",{className:"status-actions",children:[d.canEndOccupant===!0?s.jsx(se,{size:"sm",disabled:o!=="idle",onClick:()=>{b()},children:sY[o]}):null,s.jsx(se,{size:"sm",onClick:()=>{oY()},children:r("更换端口")})]}):null]})}let r0=null;function D2(){if(r0)return;const e=document.getElementById("sidebar-status");e&&(e.replaceChildren(),r0=vn.createRoot(e),r0.render(s.jsx(rY,{container:e})))}const aY={idle:r("保存并重启"),checking:r("校验中…"),saving:r("保存中…")};function lY({status:e,onClose:t}){const a=Number(e?.port)||E2,[o,c]=x.useState(()=>a<65535?String(a+1):String(a-1)),[d,f]=x.useState("idle"),[p,g]=x.useState(""),[v,y]=x.useState(""),b=x.useRef(!0),j=Number(o)||0,w=e?.failure?.message||r("当前端口 {port},网关运行正常。",{port:a});async function S(){if(d!=="idle")return;const N=el().workbuddyDesktop;if(!N)return;const k=Number(o)||0;if(!k||k<1024||k>65535){y(r("端口需在 1024-65535 之间"));return}f("checking"),y(""),g("");try{const E=await N.checkPort(k);if(!E?.ok){g(E?.message||r("该端口不可用"));return}if(E.same){g(E.message??"");return}if(f("saving"),(await N.changePort(k))?.changed===!1){g(r("与当前端口相同,无需重启"));return}t(),await M2(r("端口已改为 {port},正在重启…",{port:k}))}catch(E){y($g(E))}finally{f("idle")}}return s.jsx(Qt,{open:!0,onOpenChange:N=>{N||t()},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("更换网关端口")})}),s.jsxs(Bt,{children:[s.jsxs(Vn,{children:[s.jsx("h3",{children:r("当前状态")}),s.jsx("p",{children:w})]}),s.jsxs(Vn,{children:[s.jsx("h3",{children:r("新端口")}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(Je,{htmlFor:"port-input",className:"text-[12.5px] whitespace-nowrap text-subtle",children:r("端口号")}),s.jsx($e,{id:"port-input",type:"number",min:1024,max:65535,step:1,placeholder:r("例如 3066"),autoComplete:"off",className:"max-w-[130px]",value:o,onChange:N=>{c(N.currentTarget.value)},onKeyDown:N=>{N.key==="Enter"&&S()},autoFocus:!0,onFocus:N=>{b.current&&(b.current=!1,N.currentTarget.select())}})]}),p?s.jsx("p",{children:p}):null,s.jsx("p",{children:r("端口需在 1024-65535 之间。1023 及以下是系统保留范围,普通程序无法监听。")})]}),s.jsxs(Vn,{children:[s.jsx("h3",{children:r("换端口后要改的地方")}),s.jsxs("p",{children:[r("网关地址会变成 "),s.jsx("code",{children:`http://127.0.0.1:${j||"—"}`}),r("。已经把这个地址填进其它工具(Claude Code、Cherry Studio 等)的,需要一并改成新地址,否则那些工具会连不上。")]})]}),s.jsx("p",{className:"min-h-[18px] text-[11.5px] text-muted-foreground",children:v})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("取消")}),s.jsx(se,{variant:"default",disabled:d!=="idle",onClick:()=>{S()},children:aY[d]})]})]})})}let op=null,Bu=null;function I2(){op&&(op.unmount(),op=null),Bu&&(Bu.remove(),Bu=null)}async function oY(){let e=n0().backend;e||(e=await el().workbuddyDesktop?.getBackendStatus().catch(()=>null)??null),I2(),Bu=document.createElement("div"),document.body.append(Bu),op=vn.createRoot(Bu),op.render(s.jsx(lY,{status:e,onClose:I2}))}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",D2,{once:!0}):D2(),window.wbPortPanel={render:nY,sync:zu,portLabel:R2,isReady:tY};function iY(e){return e.source==="subscription"&&(e.port===null||e.port===void 0)}function tr(){return window}function Fn(e,t){tr().wbApp?.toast?.(e,t)}function Aa(e){return e instanceof Error?e.message:String(e)}function P2(e){return tr().wbApp?.formatTime?.(e)||""}function a0(e){const t=Number(e);return!Number.isFinite(t)||t<0?"":t<1e3?`${Math.round(t)}ms`:`${(t/1e3).toFixed(1)}s`}function l0(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]||t)}function Hu(e){return String(e?.name||e?.id||"")}function _2(e){return e.source==="clash"}function ip(e){return e.source==="subscription"}function qg(e){return _2(e)||ip(e)}function cY(e){return e.localDisabled===!0||e.enabled===!1}function L2(e){return qg(e)&&e.enabled===!1&&e.localDisabled!==!0}function uY(e){return ip(e)&&cY(e)}function Gg(e){return ip(e)&&e.orphan===!0}function z2(e){return!qg(e)||Gg(e)}const dY=r("来自 Clash Verge 同步(名称、端口跟随 Clash),请到 Clash Verge 中修改;启用可在本页关闭"),fY=r("该节点来自订阅(名称、端口跟随订阅与内核),请在「订阅管理」里修改;启用可在本页关闭"),B2=r("该节点所属订阅已删除,不会再被同步更新,可手动删除清理");function H2(e){return Gg(e)?B2:ip(e)?fY:dY}const pY=r("禁用后本端不再用它(引用它的账号回退直连);端口在 Clash Verge 侧,不受影响"),mY=r("禁用后本端不再用它(引用它的账号回退直连),并会关掉它的本地监听端口"),hY=r("已在本页禁用(打开开关即恢复)"),gY=r("这条在 Clash Verge 里是停用的,本页启用不生效 —— 到 Clash Verge 里打开它");function xY(e){if(Gg(e))return B2;if(e.localDisabled===!0)return hY;if(L2(e))return gY;if(ip(e))return mY;if(_2(e))return pY}let gs={data:null,loading:!1,error:"",testing:null,pending:new Set,syncing:!1,batchBusy:!1,batchProgress:null,selected:new Set};const o0=new Set;function bY(e){return o0.add(e),()=>{o0.delete(e)}}function vY(){return gs}function ts(e){gs={...gs,...e},o0.forEach(t=>t())}function Kg(){return gs.data?.items??[]}function yY(e){return gs.selected.has(e)}function jY(e,t){const a=new Set(gs.selected);t?a.add(e):a.delete(e),ts({selected:a})}function wY(e,t){const a=new Set(gs.selected);for(const o of e)t?a.add(o):a.delete(o);ts({selected:a})}function SY(){ts({selected:new Set})}function Do(e){if(!e||typeof e!="object"||!Array.isArray(e.items))return;const t=new Set(e.items.map(o=>o.id)),a=new Set([...gs.selected].filter(o=>t.has(o)));ts({data:e,error:"",selected:a})}async function cp(e=!1){const t=tr().workbuddyDesktop;if(typeof t?.getProxyPool!="function"){ts({error:r("当前环境不支持代理池(桥接方法缺失)")});return}e||ts({loading:!0});try{Do(await t.getProxyPool())}catch(a){ts({error:Aa(a)}),e||Fn(r("代理列表加载失败:{reason}",{reason:Aa(a)}),"err")}finally{ts({loading:!1})}}async function NY(){const e=tr().workbuddyDesktop;if(typeof e?.syncClashToProxyPool!="function"){Fn(r("当前环境不支持同步(桥接方法缺失)"),"err");return}if(!gs.syncing){ts({syncing:!0});try{const t=await e.syncClashToProxyPool();Do(t),t?.syncError?Fn(r("没能同步:{reason}",{reason:t.syncError}),"err"):t?.changes?Fn(r("✅ 已同步 Clash Verge 出口({n} 项变更)",{n:t.changes})):Fn(r("已是最新,没有需要同步的变更"))}catch(t){Fn(r("同步失败:{reason}",{reason:Aa(t)}),"err")}finally{ts({syncing:!1})}}}async function kY(e){const t=tr().workbuddyDesktop;if(typeof t?.testProxyPoolItem!="function"){Fn(r("当前环境不支持代理测试(桥接方法缺失)"),"err");return}if(!gs.testing){ts({testing:e.id});try{const a=await t.testProxyPoolItem(e.id);if(a?.items&&Do({items:a.items}),a?.success){const o=a0(a.durationMs);Fn(r("✅ 「{name}」出口可用{ip}{took}",{name:Hu(e),ip:a.ip?r(" 出口 IP {ip}",{ip:a.ip}):"",took:o?` ${o}`:""}))}else Fn(r("❌ 「{name}」{error}",{name:Hu(e),error:a?.error||r("连接失败")}),"err");a?.saveError&&Fn(r("测试结果没能记下:{reason}",{reason:a.saveError}),"err")}catch(a){Fn(r("测试失败:{reason}",{reason:Aa(a)}),"err")}finally{ts({testing:null})}}}async function CY(e,t){const a=tr().workbuddyDesktop;if(typeof a?.setProxyPoolItemEnabled!="function"){Fn(r("当前环境不支持启停(桥接方法缺失)"),"err");return}const o=new Set(gs.pending);o.add(e.id),ts({pending:o});try{const c=await a.setProxyPoolItemEnabled({id:e.id,enabled:t});Do(c);const d=Hu(e),f=c?.listener??"none";Fn(t?f==="opening"?r("已启用「{name}」,正在补建监听端口(内核重建中)",{name:d}):r("已启用「{name}」",{name:d}):f==="closing"?r("已禁用「{name}」,监听端口正在关闭(内核重建中)",{name:d}):r("已禁用「{name}」",{name:d})),(f==="closing"||f==="opening")&&TY(e.id,f)}catch(c){Fn(r("保存失败:{reason}",{reason:Aa(c)}),"err")}finally{const c=new Set(gs.pending);c.delete(e.id),ts({pending:c})}}async function TY(e,t){for(let a=0;a<12;a+=1){await new Promise(d=>setTimeout(d,1500)),await cp(!0);const o=Kg().find(d=>d.id===e);if(!o)return;const c=o.port!==null&&o.port!==void 0;if(t==="closing"?!c:c)return}}async function U2(e){const t=tr().workbuddyDesktop;if(typeof t?.removeProxyPoolItem!="function")return;if(!z2(e)){Fn(H2(e),"err");return}const a=e.usedBy||[],o=a.length?`

${r("有 {n} 个账号正在使用它({names})—— 删除后这些账号会回退直连。",{n:a.length,names:a.map(f=>l0(String(f.name||f.id||""))).join(r("、"))})}

`:"";if(!await tr().wbConfirm?.ask?.({title:r("删除代理"),html:r("确定删除「{name}」?{used}",{name:l0(Hu(e)),used:o}),okText:r("删除"),okClass:"danger"}))return;const d=new Set(gs.pending);d.add(e.id),ts({pending:d});try{const f=await t.removeProxyPoolItem(e.id);Do(f),Fn(r("已删除「{name}」",{name:Hu(e)}))}catch(f){Fn(r("删除失败:{reason}",{reason:Aa(f)}),"err")}finally{const f=new Set(gs.pending);f.delete(e.id),ts({pending:f})}}async function EY(){const e=tr().workbuddyDesktop;if(typeof e?.testProxyPoolItem!="function"){Fn(r("当前环境不支持代理测试(桥接方法缺失)"),"err");return}if(gs.batchBusy||gs.testing)return;const t=Kg().filter(f=>gs.selected.has(f.id));if(!t.length)return;ts({batchBusy:!0,batchProgress:{done:0,total:t.length}});let a=0,o=0,c="";for(const[f,p]of t.entries()){ts({testing:p.id,batchProgress:{done:f,total:t.length}});try{const g=await e.testProxyPoolItem(p.id);g?.items&&Do({items:g.items}),g?.success?a+=1:o+=1,g?.saveError&&!c&&(c=g.saveError)}catch{o+=1}}ts({testing:null,batchBusy:!1,batchProgress:null});const d=o?r("批量测试完成:{ok} 个可用、{failed} 个失败(共 {total} 个)",{ok:a,failed:o,total:t.length}):r("批量测试完成:{ok} 个可用(共 {total} 个)",{ok:a,total:t.length});Fn(o?d:`✅ ${d}`,o?"err":"ok"),c&&Fn(r("部分测试结果没能记下:{reason}",{reason:c}),"err")}async function AY(){const e=tr().workbuddyDesktop;if(typeof e?.removeProxyPoolItem!="function"||gs.batchBusy||gs.testing)return;const t=Kg().filter(S=>gs.selected.has(S.id)),a=t.filter(S=>z2(S)),o=t.length-a.length;if(!a.length){Fn(o?r("选中的 {n} 条都是同步来的只读条目(Clash / 订阅),不能删除",{n:o}):r("没有可删除的条目"),"err");return}const c=a.slice(0,8).map(S=>l0(Hu(S))).join(r("、")),d=a.length>8?r("{names} 等 {n} 条",{names:c,n:a.length}):c,f=a.filter(S=>(S.usedBy||[]).length).length,p=f?`

${r("其中 {n} 条正被账号使用 —— 删除后那些账号会回退直连。",{n:f})}

`:"",g=o?`

${r("另有 {n} 条是同步来的只读条目(Clash / 订阅),将跳过。",{n:o})}

`:"";if(!await tr().wbConfirm?.ask?.({title:r("批量删除代理"),html:`${r("确定删除选中的 {n} 个代理?",{n:a.length})}

${d}

${p}${g}`,okText:r("删除"),okClass:"danger"}))return;ts({batchBusy:!0,batchProgress:{done:0,total:a.length}});let y=0,b=0,j="";for(const[S,N]of a.entries()){ts({batchProgress:{done:S,total:a.length}});try{const k=await e.removeProxyPoolItem(N.id);Do(k),y+=1}catch(k){b+=1,j||(j=Aa(k))}}ts({batchBusy:!1,batchProgress:null});const w=[r("已删除 {n} 个代理",{n:y})];o&&w.push(r("跳过 {n} 个(同步只读条目)",{n:o})),b&&w.push(r("失败 {n} 个({reason})",{n:b,reason:j})),Fn(b?w.join(r(",")):`✅ ${w.join(r(","))}`,b?"err":"ok")}async function RY(e,t){const a=tr().workbuddyDesktop,o=e?{...t,id:e.id}:t,c=e?await a?.updateProxyPoolItem?.(o):await a?.createProxyPoolItem?.(o);return Do(c),c}async function V2(){const e=tr().workbuddyDesktop;if(typeof e?.getProxySettings!="function")throw new Error(r("当前环境不支持代理设置(桥接方法缺失)"));const t=await e.getProxySettings();if(!t||typeof t!="object")throw new Error(r("代理设置响应异常"));return t}async function OY(e){const t=tr().workbuddyDesktop;if(typeof t?.saveProxySettings!="function")throw new Error(r("当前环境不支持代理设置(桥接方法缺失)"));const a=await t.saveProxySettings(e);if(!a||typeof a!="object")throw new Error(r("代理设置响应异常"));return a}function MY({item:e,onClose:t}){const a=e!==null,[o,c]=x.useState(e?.name||""),[d,f]=x.useState(e?.protocol==="socks5"?"socks5":"http"),[p,g]=x.useState(e?.host||""),[v,y]=x.useState(e?.port?String(e.port):""),[b,j]=x.useState(e?.username||""),[w,S]=x.useState(e?.password||""),[N,k]=x.useState(e?e.enabled:!0),[E,D]=x.useState(!1),[C,A]=x.useState(!1),[R,I]=x.useState(null);function P(){const L=o.trim();if(!L)return{error:r("请填写代理名称")};const H=p.trim();if(!H)return{error:r("请填写代理主机地址")};const B=Number(v);return!Number.isInteger(B)||B<1||B>65535?{error:r("代理端口必须是 1-65535 的整数")}:{payload:{name:L,source:"manual",protocol:d,host:H,port:B,username:b.trim(),password:w,enabled:N}}}async function O(){if(C)return;const L=P();if("error"in L){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",L.error]}));return}const H=L.payload,B={source:"custom",protocol:H.protocol,host:H.host,port:H.port,username:H.username,password:H.password};A(!0),I(r("正在连接上游…"));try{const z=await tr().workbuddyDesktop?.testProxy?.({proxy:B});if(z?.success){const Q=a0(z.durationMs);I(s.jsxs("span",{className:"text-success",children:[r("✅ 出口可用"),z.ip?r(" 出口 IP {ip}",{ip:z.ip}):"",Q?` ${Q}`:""]}))}else I(s.jsxs("span",{className:"text-destructive",children:["❌ ",z?.error||r("连接失败")]}))}catch(z){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",Aa(z)]}))}finally{A(!1)}}async function _(){if(E)return;const L=P();if("error"in L){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",L.error]}));return}D(!0),I(null);try{await RY(e,L.payload),Fn(a?r("已保存「{name}」",{name:o.trim()}):r("已新增「{name}」",{name:o.trim()})),t()}catch(H){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",Aa(H)]})),D(!1)}}return s.jsx(Qt,{open:!0,onOpenChange:L=>{!L&&!E&&t()},children:s.jsxs(Zt,{className:"max-w-[560px]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r(a?"编辑代理":"新增代理")})}),s.jsxs(Bt,{className:"flex flex-col gap-3.5",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-name",children:r("名称")}),s.jsx($e,{id:"proxy-name",maxLength:60,autoComplete:"off",spellCheck:!1,placeholder:r("例如:香港 HTTP 出口"),value:o,onChange:L=>c(L.currentTarget.value)})]}),s.jsxs("div",{className:"flex flex-row items-end gap-2.5",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-protocol",children:r("协议")}),s.jsxs(ft,{value:d,onValueChange:L=>f(L),children:[s.jsx(mt,{id:"proxy-protocol",className:"min-w-[110px]",children:s.jsx(pt,{children:d==="socks5"?"SOCKS5":"HTTP"})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"http",children:"HTTP"}),s.jsx(qe,{value:"socks5",children:"SOCKS5"})]})]})]}),s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-host",children:r("主机")}),s.jsx($e,{id:"proxy-host",placeholder:"127.0.0.1",autoComplete:"off",spellCheck:!1,value:p,onChange:L=>g(L.currentTarget.value)})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-port",children:r("端口")}),s.jsx($e,{id:"proxy-port",type:"number",min:1,max:65535,className:"max-w-[110px]",placeholder:"7890",value:v,onChange:L=>y(L.currentTarget.value)})]})]}),s.jsxs("div",{className:"flex flex-row items-end gap-2.5",children:[s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-user",children:r("用户名")}),s.jsx($e,{id:"proxy-user",placeholder:r("可选"),autoComplete:"off",value:b,onChange:L=>j(L.currentTarget.value)})]}),s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-pass",children:r("密码")}),s.jsx($e,{id:"proxy-pass",placeholder:r("可选"),autoComplete:"off",value:w,onChange:L=>S(L.currentTarget.value)})]})]}),s.jsxs("div",{className:"flex flex-row items-center gap-2.5",children:[s.jsx(ms,{checked:N,onCheckedChange:k,"aria-label":r("启用这条代理")}),s.jsx("span",{className:"text-[12.5px]",children:r("启用(禁用的条目不会被账号使用,被引用时账号回退直连;仍可测试)")})]}),s.jsxs("p",{className:"text-xs leading-[1.65] text-subtle",children:[r("想要 Clash Verge 的出口?那类条目由工具条的"),s.jsx("b",{children:r("「同步 Clash Verge」")}),r("整体 镜像进来(进本页时也会自动同步一次),名称与端口跟随 Clash、因此是只读的 —— 不必(也不能)在这里手工填。")]}),s.jsx("div",{className:"min-h-[18px] text-xs text-subtle",children:R})]}),s.jsxs(nn,{children:[s.jsx(se,{variant:"outline",disabled:C||E,onClick:()=>{O()},children:r(C?"测试中…":"测试出口")}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:E,onClick:t,children:r("取消")}),s.jsx(se,{variant:"default",disabled:E,onClick:()=>{_()},children:r(E?"保存中…":"保存")})]})]})})}function DY({onClose:e}){const[t,a]=x.useState(!0),[o,c]=x.useState(!1),[d,f]=x.useState(""),[p,g]=x.useState(""),[v,y]=x.useState(""),[b,j]=x.useState({}),[w,S]=x.useState(""),[N,k]=x.useState(!1);x.useEffect(()=>{let A=!0;return(async()=>{try{const R=await V2();if(!A||R===null)return;f(String(R.listenerPortBase??"")),g(String(R.listenerPortEnd??"")),y(String(R.testUrl??"")),j(R.defaults??{}),a(!1)}catch(R){if(!A)return;S(Aa(R)),a(!1)}})(),()=>{A=!1}},[]);function E(){const A=Number(d),R=Number(p);if(!Number.isInteger(A)||A<1||A>65535||!Number.isInteger(R)||R<1||R>65535)return S(r("端口范围必须是 1-65535 的整数")),null;if(A>R)return S(r("起始端口不能大于结束端口")),null;const I=v.trim();return I&&!I.startsWith("http://")&&!I.startsWith("https://")?(S(r("测试网址要以 http:// 或 https:// 开头")),null):(S(""),{listenerPortBase:A,listenerPortEnd:R,testUrl:I})}async function D(){if(o||t)return;const A=E();if(A){c(!0);try{await OY(A),k(!0)}catch(R){S(Aa(R))}finally{c(!1)}}}function C(){f(String(b.listenerPortBase??"")),g(String(b.listenerPortEnd??"")),y(String(b.testUrl??"")),k(!1),S("")}return s.jsx(Qt,{open:!0,onOpenChange:A=>{!A&&!o&&e()},children:s.jsxs(Zt,{className:"max-w-[560px]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("代理设置")})}),s.jsx(Bt,{className:"flex flex-col gap-3.5",children:t?s.jsx("p",{className:"text-xs text-subtle",children:r("加载中…")}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-row items-end gap-2.5",children:[s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-settings-base",children:r("节点端口范围(起始)")}),s.jsx($e,{id:"proxy-settings-base",type:"number",min:1,max:65535,placeholder:String(b.listenerPortBase??""),autoComplete:"off",value:d,onChange:A=>{f(A.currentTarget.value),k(!1)}})]}),s.jsx("span",{"aria-hidden":"true",className:"flex-none pb-[7px] text-subtle",children:"—"}),s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-settings-end",children:r("节点端口范围(结束)")}),s.jsx($e,{id:"proxy-settings-end",type:"number",min:1,max:65535,placeholder:String(b.listenerPortEnd??""),autoComplete:"off",value:p,onChange:A=>{g(A.currentTarget.value),k(!1)}})]})]}),s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:r("订阅节点会在本机各占一个监听端口,从该范围里挑空闲的分配;节点多的大订阅把默认范围({base}-{end})用尽时会报「没有可用的节点端口」,这时把范围调大再重启内核。已分配出去的端口不会因改范围而失效。",{base:b.listenerPortBase??"",end:b.listenerPortEnd??""})}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"proxy-settings-url",children:r("出口测试网址")}),s.jsx($e,{id:"proxy-settings-url",placeholder:b.testUrl||"",autoComplete:"off",spellCheck:!1,className:"font-mono text-[12px]",value:v,onChange:A=>{y(A.currentTarget.value),k(!1)}})]}),s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:r("「测试」与「批量测试」访问的目标;留空用默认(打 WorkBuddy 上游)。判据是能否拿到 HTTP 响应,不用考虑该网址返回什么内容。")}),s.jsxs("div",{className:"min-h-[18px] text-xs",children:[w?s.jsxs("span",{className:"text-destructive",children:["❌ ",w]}):null,!w&&N?s.jsxs("span",{className:"text-success",children:["✅ ",r("已保存。重启内核后,新分配的节点端口才会按新范围来。")]}):null]})]})}),s.jsxs(nn,{children:[s.jsx(se,{variant:"ghost",disabled:t||o,onClick:C,children:r("恢复默认")}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:o,onClick:e,children:r("关闭")}),s.jsx(se,{variant:"default",disabled:t||o,onClick:()=>{D()},children:r(o?"保存中…":"保存")})]})]})})}function Pn(){return window}function nr(e,t){Pn().wbApp?.toast?.(e,t)}function zr(e){return e instanceof Error?e.message:String(e)}function F2(e){const t=String(e||"").trim();return/^https?:\/\//i.test(t)?t:""}async function $2(e){const t=F2(e);if(!t){nr(r("链接地址不受支持"),"err");return}try{await Pn().workbuddyDesktop?.openReleasePage(t)}catch(a){nr(r("打开链接失败:{error}",{error:zr(a)}),"err")}}const Yg="1127656296",IY=`assets/qq-group/${Yg}.jpg`;function q2(e){return Pn().wbMarkdown?.render?.(e)||""}function G2(e){const a=e.target?.closest?.("[data-external]");a&&(e.preventDefault(),$2(a.dataset.external||""))}const up="__proxy_other__",K2={proxyChoice:null,pool:null,poolError:""};async function PY(){const e=Pn().workbuddyDesktop,t={...K2};if(!e?.getUpdateProxy)return t;try{t.proxyChoice=(await e.getUpdateProxy())?.proxy??null}catch{}try{if(typeof e.getProxyPool!="function")throw new Error("桥未提供代理池方法");const a=(await e.getProxyPool())?.items;if(!Array.isArray(a))throw new Error("代理池响应异常");t.pool=a}catch(a){t.pool=[],t.poolError=zr(a)}return t}async function _Y(e){if(e===up)return null;const t=Pn().workbuddyDesktop;if(!t?.setUpdateProxy)return null;const a=e===""?null:{source:"pool",proxyId:e.slice(Ya.length)};try{const o=await t.setUpdateProxy({proxy:a}),c=o?.proxy??null,d=o?.saved!==!1;return d?nr(c?r("✅ 更新出网已切换为 {label}",{label:c.label||r("指定代理")}):r("✅ 更新出网已切换为直连")):nr(r("出网线路已切换,但写入磁盘失败(重启后会恢复原线路)"),"err"),{choice:c,saved:d}}catch(o){return nr(r("保存失败:{error}",{error:zr(o)}),"err"),null}}function Y2(e){const t=e.proxyChoice,a=t?.config?.source||t?.source,o=t?.label||r(a==="custom"?"自定义代理":"已设置"),c=!!t?.error,d=Array.isArray(e.pool)?e.pool:[];let f="";a==="pool"&&t?.config?.proxyId?f=`${Ya}${t.config.proxyId}`:t&&(f=up);const p=[{value:"",label:r("直连")}];for(const g of d)p.push({value:`${Ya}${g.id}`,label:lu(g)});if(e.pool===null?p.push({value:"__hint_pool__",label:r("正在读取代理列表…"),disabled:!0}):d.length||p.push({value:"__hint_pool__",label:e.poolError?r("代理列表读取失败"):r("还没有代理(去「网络代理」页添加)"),disabled:!0}),f===up){const g=a==="clash"?r("Clash 出口:"):a==="custom"?r("自定义:"):"";p.push({value:up,label:`${g}${o}${c?r("(不可用)"):""}`})}else a==="pool"&&!d.some(g=>`${Ya}${g.id}`===f)&&p.push({value:f,label:`${o}${c?r("(不可用)"):""}`});return{current:f,items:p,selected:p.find(g=>g.value===f),broken:c,title:c?r("当前线路不可用:{error};请重新选择代理或切回直连",{error:String(t?.error||"")}):r("检查更新与下载安装包走哪条线路(当前:{current});选择即保存。选项来自「网络代理」页;直连失败时会自动借 Clash 混合端口重试一次,选定指定代理后只走它",{current:t?o:r("直连")})}}function sr(){return window}function sn(e,t){sr().wbApp?.toast?.(e,t)}function jr(e){return e instanceof Error?e.message:String(e)}let Ht={data:null,loading:!1,error:"",pending:!1,refreshing:null};const i0=new Set;function Xg(e){return i0.add(e),()=>{i0.delete(e)}}function Qg(){return Ht}function yn(e){Ht={...Ht,...e},i0.forEach(t=>t())}function LY(){return Ht.data?.items??[]}function Uu(){return Ht.data?.kernel??null}function Xi(e){!e||typeof e!="object"||!Array.isArray(e.items)||yn({data:e,error:""})}function Io(){cp(!0)}async function Ml(e=!1){const t=sr().workbuddyDesktop;if(typeof t?.getSubscriptions!="function"){yn({error:r("当前环境不支持订阅(桥接方法缺失)")});return}e||yn({loading:!0});try{Xi(await t.getSubscriptions())}catch(a){yn({error:jr(a)})}finally{e||yn({loading:!1})}}const zY=20;function BY(e){const t=e.kernel;if(!t||t.download.state==="downloading")return!1;if(!t.installed||t.lastError&&!t.running)return!0;const a=t.providerSync??{};return(e.items??[]).filter(o=>o.enabled!==!1).every(o=>!!a[o.id])}async function Qi(){const e=sr().workbuddyDesktop;if(typeof e?.getSubscriptions=="function")for(let t=0;tsetTimeout(o,1500)),Io();let a;try{a=await e.getSubscriptions()}catch{return}if(Xi(a),t>=1&&a&&Array.isArray(a.items)&&BY(a))return}}async function X2(e){const a=await sr().workbuddyDesktop?.addSubscription?.({enabled:!0,kind:"url",url:"",...e});return Xi(a),sn(r("已新增订阅「{name}」,内核正在同步节点…",{name:e.name.trim()})),Io(),Qi(),a??null}async function Q2(e,t){const o=await sr().workbuddyDesktop?.saveSubscription?.({id:e.id,...t});Xi(o),sn(r("已保存「{name}」",{name:t.name.trim()})),Io(),Qi()}async function HY(e,t){const a=sr().workbuddyDesktop;if(!Ht.pending){yn({pending:!0});try{const o=await a?.saveSubscription?.({id:e.id,name:e.name,url:e.url,kind:e.kind,enabled:t});Xi(o),sn(t?r("已启用「{name}」",{name:e.name}):r("已禁用「{name}」",{name:e.name})),Io(),Qi()}catch(o){sn(r("保存失败:{reason}",{reason:jr(o)}),"err")}finally{yn({pending:!1})}}}async function UY(e){const t=sr().workbuddyDesktop;if(!(Ht.refreshing||Ht.pending)){yn({refreshing:e.id});try{const a=await t?.refreshSubscription?.(e.id);Xi(a),sn(r("已刷新「{name}」,正在同步节点…",{name:e.name})),Io(),Qi()}catch(a){sn(r("刷新失败:{reason}",{reason:jr(a)}),"err")}finally{yn({refreshing:null})}}}async function VY(e){const t=sr().workbuddyDesktop;if(await window.wbConfirm?.ask?.({title:r("删除订阅"),html:r("确定删除「{name}」?它在代理池里的节点会一并移除,引用这些节点的账号会回退直连。",{name:e.name||e.id}),okText:r("删除"),okClass:"danger"})&&!Ht.pending){yn({pending:!0});try{const o=await t?.removeSubscription?.(e.id);Xi(o),sn(r("已删除「{name}」",{name:e.name||e.id})),Io(),Qi()}catch(o){sn(r("删除失败:{reason}",{reason:jr(o)}),"err")}finally{yn({pending:!1})}}}async function FY(e){const t=sr().workbuddyDesktop;if(typeof t?.downloadKernel!="function"){sn(r("当前环境不支持订阅(桥接方法缺失)"),"err");return}if(!Ht.pending){yn({pending:!0});try{const a=await t.downloadKernel(e);a&&Ht.data&&yn({data:{...Ht.data,kernel:a}}),a?.saved===!1&&sn(r("下载线路 / 存放目录没能写进配置(本次下载已按新设置走,重启后会恢复原值)"),"err");for(let c=0;c<300;c+=1){await new Promise(f=>setTimeout(f,1e3));const d=await t.getKernelStatus?.();if(d&&Ht.data&&yn({data:{...Ht.data,kernel:d}}),!d||d.download.state!=="downloading")break}const o=Ht.data?.kernel;o?.download.state==="error"?sn(r("内核下载失败:{reason}",{reason:o.download.error||r("未知错误")}),"err"):o?.download.state==="canceled"?sn(r("已停止下载内核(未下载完的临时文件已删除)")):o?.download.state==="done"&&(sn(r("✅ 内核下载完成,正在启动…")),Qi())}catch(a){sn(r("内核下载失败:{reason}",{reason:jr(a)}),"err")}finally{yn({pending:!1})}}}async function $Y(){const e=sr().workbuddyDesktop;if(typeof e?.cancelKernelDownload!="function")return"none";try{const t=await e.cancelKernelDownload();if(t&&Ht.data&&yn({data:{...Ht.data,kernel:t}}),t?.canceled===!1)return"none";for(let o=0;o<20;o+=1){const c=await e.getKernelStatus?.();if(c&&Ht.data&&yn({data:{...Ht.data,kernel:c}}),c&&c.download.state!=="downloading")break;await new Promise(d=>setTimeout(d,250))}const a=Ht.data?.kernel?.download.state;return a==="canceled"?"canceled":a==="done"?"done":"stalled"}catch(t){return sn(r("停止下载失败:{reason}",{reason:jr(t)}),"err"),"none"}}async function qY(){const e=sr().workbuddyDesktop;if(!Ht.pending){yn({pending:!0});try{const t=await e?.restartKernel?.();t&&Ht.data&&yn({data:{...Ht.data,kernel:t}}),sn(r("内核正在启动…")),Io(),Qi()}catch(t){sn(r("内核启动失败:{reason}",{reason:jr(t)}),"err")}finally{yn({pending:!1})}}}async function GY(){const e=sr().workbuddyDesktop;if(typeof e?.stopKernel!="function"){sn(r("当前环境不支持订阅(桥接方法缺失)"),"err");return}if(!Ht.pending){yn({pending:!0});try{const t=await e.stopKernel();t&&Ht.data&&yn({data:{...Ht.data,kernel:t}});for(let o=0;o<10;o+=1){const c=await e.getKernelStatus?.();if(c&&Ht.data&&yn({data:{...Ht.data,kernel:c}}),c&&c.running===!1)break;await new Promise(d=>setTimeout(d,500))}const a=Ht.data?.kernel;if(a?.running===!1)sn(r("内核已关闭(订阅与端口注册表保留,「启动内核」后原位恢复)"));else{const o=a?.lastError||r("内核没有在超时内停下来");sn(r("关闭内核失败:{reason}",{reason:o}),"err")}Ml(!0)}catch(t){sn(r("关闭内核失败:{reason}",{reason:jr(t)}),"err"),Ml(!0)}finally{yn({pending:!1})}}}async function KY(){const e=sr().workbuddyDesktop;if(typeof e?.removeKernel!="function"){sn(r("当前环境不支持订阅(桥接方法缺失)"),"err");return}const t=Uu()?.version;if(!await window.wbConfirm?.ask?.({title:r("删除内核"),html:r("确定删除已下载的内核{version}?内核文件与端口映射会被移除,订阅节点会变成「未分配端口」,引用它们的账号会暂时回退直连;订阅本身保留,重新下载内核后会重新分配端口。",{version:t?`(${t})`:""}),okText:r("删除内核"),okClass:"danger"})||Ht.pending)return;yn({pending:!0});const o=Uu()?.lastError||"";try{const c=await e.removeKernel();c&&Ht.data&&yn({data:{...Ht.data,kernel:c}});for(let f=0;f<20;f+=1){const p=await e.getKernelStatus?.();if(p&&Ht.data&&yn({data:{...Ht.data,kernel:p}}),p&&p.installed===!1||p?.lastError&&p.lastError!==o)break;await new Promise(g=>setTimeout(g,500))}const d=Ht.data?.kernel;if(d?.installed===!1)sn(r("已删除内核(订阅与账号引用保留,重新下载后会重新分配端口)")),Io();else{const f=d?.lastError&&d.lastError!==o?d.lastError:r("内核目录没能删掉(可能仍被进程占用),稍后重试一次");sn(r("删除内核失败:{reason}",{reason:f}),"err")}Ml(!0)}catch(c){sn(r("删除内核失败:{reason}",{reason:jr(c)}),"err"),Ml(!0)}finally{yn({pending:!1})}}async function YY(e){const t=sr().workbuddyDesktop;if(typeof t?.decodeQrImage!="function")throw new Error(r("当前环境不支持订阅(桥接方法缺失)"));const a=await new Promise((d,f)=>{const p=new FileReader;p.onload=()=>d(String(p.result||"")),p.onerror=()=>f(new Error(r("图片读取失败"))),p.readAsDataURL(e)}),c=(await t.decodeQrImage({imageBase64:a}))?.url;if(!c)throw new Error(r("二维码里没有订阅链接"));return c}function XY(e){return new Promise((t,a)=>{const o=new FileReader;o.onload=()=>t(String(o.result||"")),o.onerror=()=>a(new Error(r("文件读取失败"))),o.readAsDataURL(e)})}function Z2(e){return(Math.max(0,Number(e)||0)/1024/1024).toFixed(1)}function QY(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")||e.startsWith("/")}function ZY({onClose:e}){const t=x.useSyncExternalStore(Xg,Qg),a=Uu(),o=a?.download,c=o?.state==="downloading",d=c&&o&&o.total>0?Math.round(o.received/o.total*100):null,[f,p]=x.useState(null),[g,v]=x.useState(""),[y,b]=x.useState(null),[j,w]=x.useState(a?.kernelDir||""),[S,N]=x.useState(!1),[k,E]=x.useState(!1),[D,C]=x.useState("");x.useEffect(()=>{let H=!0;return(async()=>{try{const B=(await sr().workbuddyDesktop?.getProxyPool?.())?.items;if(!Array.isArray(B))throw new Error(r("代理池响应异常"));H&&p(B)}catch(B){if(!H)return;p([]),v(jr(B))}})(),()=>{H=!1}},[]),x.useEffect(()=>{a?.installed&&e()},[a?.installed]);const A=Y2({proxyChoice:a?.downloadProxy??null,pool:f,poolError:g}),R=y??A.current,I=A.items.find(H=>H.value===R)??A.selected,P=a?.kernelDirDefault||"";async function O(){if(S)return;const H=j.trim();if(H&&!QY(H)){C(r("存放位置要填绝对路径,例如 D:\\proxy-kernel"));return}C(""),N(!0);try{const B={dir:H};R!==up&&(B.proxy=R===""?null:{source:"pool",proxyId:R.slice(Ya.length)}),FY(B)}finally{N(!1)}}async function _(){if(!k){E(!0);try{const H=await $Y();H==="done"?sn(r("下载已经完成,停止没赶上(内核已安装)")):H==="none"?sn(r("当前没有正在进行的下载"),"err"):H==="stalled"&&sn(r("停止请求已发出,但下载还没收手,稍后再看一次进度"),"err")}finally{E(!1)}}}async function L(){const H=sr().workbuddyDesktop;if(typeof H?.pickFolder!="function"){sn(r("当前环境不支持选择文件夹,直接填写绝对路径即可"),"err");return}try{const B=await H.pickFolder(j.trim()||P||null);if(B?.unsupported){sn(r("当前环境不支持选择文件夹,直接填写绝对路径即可"),"err");return}if(B?.canceled||!B?.path)return;w(B.path)}catch(B){sn(r("打开文件夹选择框失败:{reason}",{reason:jr(B)}),"err")}}return s.jsx(Qt,{open:!0,onOpenChange:H=>{H||e()},children:s.jsxs(Zt,{className:"w-[min(520px,calc(100vw-48px))]",children:[s.jsxs(Kt,{children:[s.jsx(Gt,{children:r(c?"正在下载内核":"下载内核")}),s.jsx("span",{className:"text-[11.5px] text-subtle",children:r("内核 {version}({asset})",{version:a?.version||"—",asset:a?.asset||"—"})})]}),c?s.jsxs(Bt,{className:"flex flex-col gap-3",children:[s.jsx(ef,{value:d??null}),s.jsxs("div",{className:"flex items-center justify-between text-[12px]",children:[s.jsx("span",{className:"text-text-2",children:d!==null?r("{percent}%({received} / {total} MB)",{percent:d,received:Z2(o?.received),total:Z2(o?.total)}):r("正在连接 GitHub…")}),s.jsx("span",{className:"text-subtle",children:r("存放位置 {dir}",{dir:a?.kernelDir||"—"})})]}),s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:r("关掉这个窗口不会中断下载(它在后台继续跑)—— 要停下就点下面的「停止下载」,未下载完的临时文件会被删除。")})]}):s.jsxs(Bt,{className:"flex flex-col gap-3.5",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"kernel-proxy",children:r("下载线路")}),s.jsxs(ft,{value:R,onValueChange:H=>b(String(H)),children:[s.jsx(mt,{id:"kernel-proxy",className:Ue("w-full",A.broken&&"border-destructive-bd"),children:s.jsx(pt,{className:"min-w-0 truncate",children:I?.label||r("直连")})}),s.jsx(ht,{children:A.items.map(H=>s.jsx(qe,{value:H.value,disabled:H.disabled,children:H.label},H.value))})]}),s.jsx("div",{className:"text-[12px] text-subtle",children:A.broken?r("当前线路不可用:{error};重新选一条或切回直连",{error:String(a?.downloadProxy?.error||"")}):r("选项来自「网络代理」页(Clash Verge 同步的出口在这里可用;订阅节点要等内核起来才有端口)。选「直连」时连不上会自动借 Clash 混合端口重试一次;选定某条线路后只走它。")})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"kernel-dir",children:r("存放位置")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx($e,{id:"kernel-dir",className:"min-w-0 flex-1 font-mono text-[12px]",autoComplete:"off",spellCheck:!1,value:j,placeholder:P,onChange:H=>w(H.currentTarget.value)}),s.jsx(se,{variant:"outline",size:"sm",className:"flex-none",onClick:()=>{L()},children:r("选择目录…")}),P&&j.trim()!==P?s.jsx(se,{variant:"ghost",size:"sm",className:"flex-none",title:P,onClick:()=>w(P),children:r("恢复默认")}):null]}),s.jsx("div",{className:"text-[12px] text-subtle",children:r("内核二进制 / 配置 / 端口映射都会放在这里,默认 {dir};目录不存在会在下载开始时自动创建。",{dir:P||"—"})})]}),o?.state==="error"&&o.error?s.jsx("span",{className:"text-[12px] text-destructive",children:r("上次下载失败:{reason}",{reason:o.error})}):null,o?.state==="canceled"?s.jsx("span",{className:"text-[12px] text-subtle",children:r("上次下载已停止,未下载完的临时文件已删除")}):null,D?s.jsx("span",{className:"text-[12px] text-destructive",children:D}):null]}),s.jsx(nn,{children:c?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:e,children:r("后台继续")}),s.jsx(se,{variant:"destructive",disabled:k,onClick:()=>{_()},children:r(k?"正在停止…":"停止下载")})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:e,children:r("取消")}),s.jsx(se,{variant:"default",disabled:S||t.pending,onClick:()=>{O()},children:r(S?"正在开始…":"下载")})]})})]})})}function W2({showPortRange:e=!1}){const t=x.useSyncExternalStore(Xg,Qg),a=Uu(),[o,c]=x.useState(null),[d,f]=x.useState(!1);x.useEffect(()=>{let v=!0;return(async()=>{try{const y=await V2();if(!v||!y)return;const b=Number(y.listenerPortBase),j=Number(y.listenerPortEnd);Number.isFinite(b)&&Number.isFinite(j)&&b>0&&j>0&&c({base:b,end:j})}catch{}})(),()=>{v=!1}},[]);const p=a?.download.state==="downloading",g=p&&a.download.total>0?Math.round(a.download.received/a.download.total*100):null;return s.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border bg-surface-2 px-3 py-2",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx(ze,{variant:a?.running?"default":"secondary",children:a?.running?r("内核运行中"):a?.installed?r("内核已停止"):r("内核未安装")}),s.jsxs("span",{className:"text-[12.5px] text-text-2",children:[a?.installed?r("内核 {version}",{version:a.version})+" · ":"",a?.running?r("控制端口 {port} · {n} 个节点监听器",{port:a?.controllerPort??"—",n:a?.listenerCount??0}):a?.installed?r("内核已停止,点「启动内核」拉起"):r("按需下载(约 20-40MB)")]}),e&&o?s.jsx("span",{className:"text-[11.5px] text-subtle",children:r("节点端口范围 {base}–{end}",{base:o.base,end:o.end})}):null,s.jsx("div",{className:"ml-auto flex items-center gap-2",children:a?.installed?s.jsxs(s.Fragment,{children:[s.jsx(se,{size:"sm",variant:"outline",disabled:t.pending||p,onClick:()=>{qY()},children:a?.running?r("重启内核"):r("启动内核")}),a?.running?s.jsx(se,{size:"sm",variant:"outline",disabled:t.pending||p,onClick:()=>{GY()},children:r("关闭内核")}):null,s.jsx(se,{size:"sm",variant:"destructive",disabled:t.pending||p,onClick:()=>{KY()},children:r("删除内核")})]}):s.jsx(se,{size:"sm",variant:"outline",disabled:t.pending&&!p,onClick:()=>f(!0),children:r(p?"下载中…":"下载内核")})})]}),p?s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(ef,{className:"min-w-[200px] flex-1",value:g??null}),s.jsx("span",{className:"text-[11px] text-subtle",children:g!==null?r("{percent}%({received} / {total} MB)",{percent:g,received:J2(a.download.received),total:J2(a.download.total)}):r("下载中…")})]}):null,a?.lastError?s.jsx("span",{className:"text-[12px] text-destructive",children:a.lastError}):null,d?s.jsx(ZY,{onClose:()=>f(!1)}):null]})}function WY({onClose:e}){const t=x.useSyncExternalStore(Xg,Qg),a=LY(),o=t.data!==null,[c,d]=x.useState(null);return x.useEffect(()=>{Ml()},[]),s.jsxs(Qt,{open:!0,onOpenChange:f=>{f||e()},children:[s.jsxs(Zt,{className:"w-[min(880px,calc(100vw-48px))]",children:[s.jsxs(Kt,{children:[s.jsx(Gt,{children:r("订阅管理")}),s.jsxs("span",{className:"text-[11.5px] text-subtle",children:[o?r("{n} 条订阅",{n:a.length}):r("加载中…")," · ",r("节点由内核起成本地监听器,镜像进代理池")]})]}),s.jsxs(Bt,{className:"flex flex-col gap-3",children:[s.jsx(W2,{}),s.jsx("div",{className:"models-table-wrap",children:s.jsxs("table",{className:"models-table",children:[s.jsxs("colgroup",{children:[s.jsx("col",{className:"w-[18%]"}),s.jsx("col",{className:"w-[31%]"}),s.jsx("col",{className:"w-[9%]"}),s.jsx("col",{className:"w-[14%]"}),s.jsx("col",{className:"w-[8%]"}),s.jsx("col",{className:"w-[20%]"})]}),s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{children:r("名称")}),s.jsx("th",{children:r("订阅来源")}),s.jsx("th",{className:"ta-center",children:r("节点")}),s.jsx("th",{children:r("上次同步")}),s.jsx("th",{className:"ta-center",children:r("启用")}),s.jsx("th",{className:"ta-right",children:r("操作")})]})}),s.jsx("tbody",{children:a.length?a.map(f=>{const p=Uu()?.providerSync?.[f.id];return s.jsxs("tr",{className:f.enabled?"":"off",children:[s.jsx("td",{children:s.jsx("b",{children:f.name||r("未命名")})}),s.jsx("td",{className:"group",children:s.jsx("div",{className:"flex min-w-0 items-center gap-1",children:f.kind==="local"?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"min-w-0 truncate font-mono text-[12px] text-text-2",title:f.fileName,children:f.fileName||r("本地 YAML 文件")}),s.jsx(ze,{variant:"secondary",children:r("本地文件")})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"min-w-0 truncate font-mono text-[12px] text-text-2",title:f.url,children:JY(f.url)}),s.jsx(se,{variant:"ghost",size:"icon-xs",className:"copy-btn size-[21px] rounded-[var(--r-xs)] opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100","data-copy":f.url,title:r("复制订阅链接"),children:"⧉"})]})})}),s.jsx("td",{className:"ta-center",children:eD(p,f)>0?s.jsx(ze,{variant:"secondary",children:r("{n} 个",{n:eD(p,f)})}):s.jsx("span",{className:"text-subtle",children:r("—")})}),s.jsx("td",{children:p?.at?s.jsx("span",{className:"text-[12px] text-text-2",children:P2(p.at)}):s.jsx("span",{className:"text-subtle",children:r("未同步")})}),s.jsx("td",{className:"ta-center",children:s.jsx(ms,{checked:f.enabled,disabled:t.pending,"aria-label":r("启用订阅「{name}」",{name:f.name||r("未命名")}),onCheckedChange:g=>{HY(f,g)}})}),s.jsx("td",{children:s.jsxs("div",{className:"row-actions",children:[s.jsx(se,{size:"sm",variant:"ghost",disabled:t.pending||t.refreshing!==null||f.kind==="local",title:f.kind==="local"?r("本地文件订阅无需更新(要换内容请编辑后重新选择文件)"):void 0,onClick:()=>{UY(f)},children:t.refreshing===f.id?r("更新中…"):r("立即更新")}),s.jsx(se,{size:"sm",variant:"ghost",disabled:t.pending,onClick:()=>d({item:f}),children:r("编辑")}),s.jsx(se,{size:"sm",variant:"destructive",disabled:t.pending,onClick:()=>{VY(f)},children:r("删除")})]})})]},f.id)}):s.jsx("tr",{children:s.jsx("td",{colSpan:6,className:"empty",children:o?s.jsxs("div",{className:"flex flex-col items-center gap-2 py-3",children:[s.jsx("span",{children:r("还没有订阅:粘贴订阅链接、导入本地 YAML 文件,或从图片识别二维码。")}),s.jsx(se,{size:"sm",variant:"outline",disabled:t.pending,onClick:()=>d({item:null}),children:r("+ 新增订阅")}),s.jsx("span",{className:"text-[11px] text-subtle",children:r("订阅里的节点会自动同步进代理池,账号即可引用。")})]}):r("加载中…")})})})]})}),s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:r("订阅里的节点会被内核起成本地监听器,镜像到代理池(账号按 id 引用,与本页其它出口同一用法)。内核只在用到订阅时按需下载(约 20-40MB),不随安装包分发。")}),t.error?s.jsx("span",{className:"text-destructive",children:r("读取失败:{reason}",{reason:t.error})}):null]}),s.jsxs(nn,{children:[s.jsx(se,{variant:"default",disabled:t.pending,onClick:()=>d({item:null}),children:r("+ 新增订阅")}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:e,children:r("完成")})]})]}),c?s.jsx(eX,{item:c.item,onClose:()=>d(null)}):null]})}function J2(e){return!Number.isFinite(e)||e<=0?"—":(e/1e3/1e3).toFixed(1)}function JY(e){try{const t=new URL(e);return t.host+(t.pathname!=="/"?"/…":"")}catch{return e.slice(0,60)}}function eD(e,t){return e?.count??t.nodeCount}function eX({item:e,onClose:t}){const a=e!==null,[o,c]=x.useState(e?.kind==="local"?"local":"url"),[d,f]=x.useState(e?.name||""),[p,g]=x.useState(e?.url||""),[v,y]=x.useState(e?.fileName||""),[b,j]=x.useState(""),[w,S]=x.useState(e?e.enabled:!0),[N,k]=x.useState(!1),[E,D]=x.useState(!1),[C,A]=x.useState(!1),[R,I]=x.useState(null),P=x.useRef(null);async function O(){if(N)return;const z=d.trim();if(!z){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",r("请填写订阅名称")]}));return}const Q=p.trim();if(o==="url"&&!(Q.startsWith("http://")||Q.startsWith("https://"))){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",r("订阅链接必须是 http:// 或 https:// 开头")]}));return}if(!a&&o==="local"&&!b){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",r("请选择要导入的 YAML 文件")]}));return}k(!0);try{a&&o==="local"?await Q2(e,{name:z,enabled:w,kind:"local",fileName:v||void 0,...b?{contentB64:b}:{}}):a?await Q2(e,{name:z,url:Q,enabled:w,kind:"url"}):o==="local"?await X2({name:z,kind:"local",fileName:v||void 0,contentB64:b}):await X2({name:z,kind:"url",url:Q}),t()}catch(K){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",jr(K)]})),k(!1)}}async function _(z){if(!E){D(!0),I(r("正在识别二维码…"));try{const Q=await YY(z);g(Q),I(s.jsxs("span",{className:"text-success",children:["✅ ",r("已识别订阅链接")]}))}catch(Q){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",jr(Q)]}))}finally{D(!1)}}}async function L(z){if(!C){A(!0),I(null);try{const Q=await XY(z);j(Q),y(z.name),I(s.jsxs("span",{className:"text-success",children:["✅ ",r("已选择「{name}」,保存后导入",{name:z.name})]}))}catch(Q){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",jr(Q)]}))}finally{A(!1)}}}function H(z){if(o!=="url")return;const K=Array.from(z.clipboardData?.files||[]).find(X=>X.type.startsWith("image/"));K&&(z.preventDefault(),_(K))}function B(z){z!==o&&(c(z),I(null))}return s.jsx(Qt,{open:!0,onOpenChange:z=>{!z&&!N&&t()},children:s.jsxs(Zt,{className:"max-w-[560px]",overlayForceRender:!0,onPaste:H,children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r(a?"编辑订阅":"新增订阅")})}),s.jsxs(Bt,{className:"flex flex-col gap-3.5",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"sub-name",children:r("名称")}),s.jsx($e,{id:"sub-name",maxLength:60,autoComplete:"off",spellCheck:!1,placeholder:r("例如:我的机场"),value:d,onChange:z=>f(z.currentTarget.value)})]}),a?null:s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{children:r("订阅来源")}),s.jsx(In,{options:[{value:"url",label:r("订阅链接")},{value:"local",label:r("本地 YAML 文件")}],value:o,onValueChange:B,"aria-label":r("订阅来源")})]}),o==="url"?s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"sub-url",children:r("订阅链接")}),s.jsx($e,{id:"sub-url",autoComplete:"off",spellCheck:!1,placeholder:"https://…",value:p,onChange:z=>g(z.currentTarget.value)}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(se,{size:"sm",variant:"outline",disabled:E,onClick:()=>P.current?.click(),children:r(E?"识别中…":"从图片识别二维码")}),s.jsx("span",{className:"text-[11px] text-subtle",children:r("也可以把二维码截图直接粘贴到弹窗里(Ctrl+V)")}),s.jsx("input",{ref:P,type:"file",accept:"image/*",className:"hidden",onChange:z=>{const Q=z.currentTarget.files?.[0];Q&&_(Q),z.currentTarget.value=""}})]})]}):s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"sub-file",children:r("YAML 文件")}),s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[s.jsx(se,{size:"sm",variant:"outline",disabled:C,className:"shrink-0",onClick:()=>P.current?.click(),children:r(C?"读取中…":a?"重新选择文件…":"选择 YAML 文件…")}),s.jsx("span",{className:"min-w-0 truncate font-mono text-[12px] text-text-2",title:v||void 0,children:v||r(a?"保持原文件":"未选择文件")})]}),a?s.jsx("span",{className:"text-[11px] text-subtle",children:r("本地文件不会自动更新:要更新节点,重新选择文件后保存;不重选则内容保持不变。")}):null,s.jsx("input",{ref:P,type:"file",accept:".yaml,.yml,text/yaml,application/yaml,text/plain",className:"hidden",onChange:z=>{const Q=z.currentTarget.files?.[0];Q&&L(Q),z.currentTarget.value=""}})]}),s.jsxs("div",{className:"flex flex-row items-center gap-2.5",children:[s.jsx(ms,{checked:w,onCheckedChange:S,"aria-label":r("启用这条订阅")}),s.jsx("span",{className:"text-[12.5px]",children:r("启用(禁用的订阅不参与内核同步,它的节点会从代理池移除)")})]}),s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:r(o==="url"?"订阅内容由内核定时刷新(每 24 小时);节点数与同步状态在保存后由轮询刷新,稍等几秒。":"本地文件订阅的内容在导入时固定:节点会由内核起成本地监听器并镜像进代理池,节点数稍等几秒由轮询刷新。")}),s.jsx("div",{className:"min-h-[18px] text-xs text-subtle",children:R})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:N,onClick:t,children:r("取消")}),s.jsx(se,{variant:"default",disabled:N||E||C,onClick:()=>{O()},children:r(N?"保存中…":"保存")})]})]})})}const c0=[{key:"pick",label:r("选择"),align:"center"},{key:"name",label:r("节点")},{key:"addr",label:r("地址")},{key:"state",label:r("启用"),align:"center"},{key:"test",label:r("连通性")},{key:"act",label:r("操作"),align:"right"}],tX={pick:"p-pick",name:"",addr:"p-addr",state:"p-state",test:"p-test",act:"p-act"},tD="proxies";function u0(){return window}let Zg=null,nD=null;function sD(){return Zg?Zg.apply([...c0]):c0.map(e=>({...e,align:e.align??"left"}))}function nX(){u0().wbTableColumns?.repaint?.(tD)}function sX(e){if(nD=e,Zg)return!0;const t=u0().wbColSettings;return t?.register?(Zg=t.register({id:tD,label:r("代理池表"),columns:c0.map(a=>({key:a.key,label:a.label,align:a.align??"left"})),mount:()=>document.querySelector('.page[data-page="proxies"] .panel-head .head-actions'),onChange:()=>nD?.()}),!0):!1}function rX(){u0().wbColSettings?.close?.()}function aX(){const e=x.useSyncExternalStore(bY,vY),t=x.useSyncExternalStore(Xg,Qg).data?.items??[],[a,o]=x.useState(null),[c,d]=x.useState(!1),[f,p]=x.useState(!1),[g,v]=x.useState(""),[y,b]=x.useState("all"),[j,w]=x.useState("all"),[S,N]=x.useState("all"),[k,E]=x.useState(0),[,D]=x.useReducer(J=>J+1,0),C=Kg(),A=e.data!==null,R=e.selected.size,I=C.filter(J=>e.selected.has(J.id)&&qg(J)).length,P=e.batchProgress;x.useEffect(()=>{Ml()},[]),x.useLayoutEffect(()=>{if(!sX(()=>D())){const J=window.setTimeout(()=>E(ie=>ie+1),50);return()=>window.clearTimeout(J)}D()},[k]),x.useLayoutEffect(()=>{nX()}),x.useEffect(()=>()=>{rX()},[]);const O=g.trim().toLowerCase(),_=iX(C,t);function L(J){return j==="all"?!0:j==="manual"||j==="clash"||j==="subscription"?tl(J)===j:j===lD?!!J.orphan:J.source==="subscription"&&!J.orphan&&J.providerId===j}function H(J){return!(y!=="all"&&tl(J)!==y||!L(J)||S!=="all"&&aD(J)!==S||O&&![J.name,zh(J),J.host,J.protocol,String(J.port??"")].join(" ").toLowerCase().includes(O))}function B(J){const ie=J??"all";w(ie),b(ie==="all"?"all":ie==="manual"||ie==="clash"?ie:"subscription")}function z(J){b(J),w("all")}const Q=C.filter(H),K=Q.map(J=>J.id),X=K.length>0&&K.every(J=>e.selected.has(J)),q=K.some(J=>e.selected.has(J))&&!X,$=sD(),Y=[];for(const J of rD())Y.push(...Q.filter(ie=>tl(ie)===J.key));const F=ag(Q.length,"proxies"),G=F.paged?F.slice(Y):Y,W=new Map;for(const J of Q)W.set(tl(J),(W.get(tl(J))??0)+1);x.useEffect(()=>{F.goto(1)},[O,y,j,S]);function le(J){const ie=J.lastTest;if(!ie||!ie.at)return s.jsx("span",{className:"text-subtle",children:r("未测试")});const ge=a0(ie.durationMs);return s.jsxs("div",{className:"flex flex-col gap-0.5 leading-[1.5] min-w-0",children:[s.jsxs("span",{className:ie.success?"text-success":"text-destructive",children:[ie.success?r("✅ {ip}",{ip:ie.ip||r("连接成功")}):r("❌ 连接失败"),ge?` ${ge}`:"",s.jsxs("span",{className:"text-[11px] text-subtle",children:[" ",P2(ie.at)]})]}),ie.success?null:s.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-[11px] text-subtle",title:String(ie.error||r("连接失败")),children:String(ie.error||r("连接失败"))})]})}function M(J){const ie=J.usedBy||[],ge=[];return J.protocol&&ge.push(J.protocol),ie.length&&ge.push(s.jsx("span",{className:"text-warn",title:ie.map(ee=>String(ee.name||ee.id||"")).join(r("、")),children:r("{n} 个账号在用",{n:ie.length})})),ge.length?s.jsx("span",{className:"text-[11px] text-subtle",children:ge.map((ee,fe)=>s.jsxs(x.Fragment,{children:[fe?" · ":"",ee]},fe))}):null}function U(J){if(uY(J)&&(J.port===null||J.port===void 0))return s.jsx("span",{className:"text-subtle",children:r("已禁用(未开监听端口)")});if(J.resolveError){const ge=J.source==="subscription"&&(J.port===null||J.port===void 0);return s.jsx("span",{className:ge?"text-subtle":"text-destructive",title:J.resolveError,children:r(ge?"未分配端口":"解析失败")})}if(iY(J)){const ge=Uu()?.installed===!1;return s.jsx("span",{className:"text-subtle",title:r(ge?"代理内核未安装(在「订阅管理」里下载内核后,节点会自动分配监听端口)":"还没有监听端口(还没有账号引用它 —— 在账号里选它并保存后,内核会自动开端口)"),children:zh(J)||r("未分配端口")})}const ie=zh(J);return s.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[s.jsx("span",{className:"min-w-0 flex-1 font-mono text-[12px] leading-[1.45] text-text-2 break-all",title:ie||void 0,children:ie||"—"}),ie?s.jsx(se,{variant:"ghost",size:"icon-xs",className:"copy-btn flex-none","data-copy":ie,title:r("复制地址"),children:"⧉"}):null]})}function Z(J,ie,ge,ee){const fe=ge||e.batchBusy;switch(J){case"pick":return s.jsx(Or,{checked:ee,title:r("勾选后可批量操作"),"aria-label":r("勾选「{name}」",{name:ie.name||r("未命名")}),onCheckedChange:te=>jY(ie.id,te)});case"name":return s.jsxs("div",{className:"flex flex-col gap-0.5 leading-[1.5] min-w-0",children:[s.jsx("b",{children:ie.name||r("未命名")}),M(ie)]});case"addr":return U(ie);case"state":{const te=L2(ie);return s.jsx(ms,{checked:ie.enabled!==!1,disabled:fe||te,"aria-label":r("启用「{name}」",{name:ie.name||r("未命名")}),title:xY(ie),onCheckedChange:Ce=>{CY(ie,Ce)}})}case"test":return le(ie);case"act":{const te=Gg(ie);qg(ie);const Ce=H2(ie),re=e.testing===ie.id;return s.jsxs("div",{className:"row-actions",children:[s.jsx(se,{size:"sm",variant:"ghost",disabled:fe||e.testing!==null,onClick:()=>{kY(ie)},children:r(re?"测试中…":"测试")}),ie.source!=="clash"&&ie.source!=="subscription"?s.jsxs(s.Fragment,{children:[s.jsx(se,{size:"sm",variant:"ghost",disabled:fe,onClick:()=>o({item:ie}),children:r("编辑")}),s.jsx(se,{size:"sm",variant:"destructive",disabled:fe,onClick:()=>{U2(ie)},children:r("删除")})]}):null,te?s.jsx(se,{size:"sm",variant:"destructive",disabled:fe,title:Ce,onClick:()=>{U2(ie)},children:r("删除")}):null]})}default:return null}}function ae(J){const ie=e.pending.has(J.id),ge=yY(J.id);return s.jsx("tr",{className:Ue(J.enabled?"":"off",ge&&"bg-primary-soft"),"data-id":J.id,children:$.map(ee=>s.jsx("td",{className:`ta-${ee.align}`,children:Z(ee.key,J,ie,ge)},ee.key))},J.id)}function ce(){if(!C.length)return s.jsx("tr",{children:s.jsx("td",{colSpan:$.length,className:"empty",children:r(A?"还没有代理。点右上角「+ 新增代理」手填一个,点「同步 Clash Verge」把 Clash 的出口导进来,或在「订阅管理」里导入订阅节点。":"加载中…")})});if(!Q.length)return s.jsx("tr",{children:s.jsx("td",{colSpan:$.length,className:"empty",children:O?r("没有匹配「{kw}」的出口",{kw:g.trim()}):r("没有匹配当前筛选的出口")})});const J=[];let ie="";for(const ge of G){const ee=tl(ge);if(ee!==ie){ie=ee;const fe=rD().find(te=>te.key===ee);J.push(s.jsx("tr",{className:"tr-group",children:s.jsxs("td",{colSpan:$.length,children:[s.jsx("span",{className:"prov-tag",children:fe?.label??ee}),r("{n} 个",{n:W.get(ee)??0}),fe?.note?s.jsxs("span",{className:"font-normal",children:[" · ",fe.note]}):null]})},`group:${ee}:${J.length}`))}J.push(ae(ge))}return s.jsx(s.Fragment,{children:J})}return s.jsx(s.Fragment,{children:s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("代理池")}),s.jsx("span",{className:"panel-sub",children:A?r("{n} 个出口",{n:C.length}):r("加载中…")}),s.jsx("span",{className:"text-[11px] text-subtle",children:r("订阅与 Clash 的出口自动镜像进来")}),s.jsxs("div",{className:"head-actions",children:[s.jsx(se,{variant:"outline",disabled:e.batchBusy,onClick:()=>d(!0),children:r("设置")}),s.jsx(se,{variant:"outline",disabled:e.batchBusy,onClick:()=>p(!0),children:t.length?r("订阅管理({n})",{n:t.length}):r("订阅管理")}),s.jsx(se,{variant:"outline",disabled:e.syncing||e.batchBusy,onClick:()=>{NY()},children:e.syncing?r("同步中…"):r("同步 Clash Verge")}),s.jsx(se,{variant:"outline",disabled:e.loading||e.batchBusy,onClick:()=>{cp(),Ml()},children:e.loading?r("刷新中…"):r("刷新")}),s.jsx(se,{variant:"default",disabled:e.batchBusy,onClick:()=>o({item:null}),children:r("+ 新增代理")})]})]}),s.jsx("div",{className:"px-3 pt-3",children:s.jsx(W2,{showPortRange:!0})}),R>0?s.jsxs("div",{className:"batch-bar active",children:[s.jsxs("span",{className:"batch-count",children:[r("已选")," ",s.jsx("b",{children:R})," ",r("个 · 共")," ",s.jsx("b",{children:Q.length})," ",r("个")]}),I?s.jsx("span",{className:"batch-hidden",children:r("其中 {n} 条是同步来的只读条目(Clash / 订阅):可参与批量测试,删除会跳过",{n:I})}):null,s.jsxs("div",{className:"batch-actions",children:[s.jsx(se,{variant:"outline",disabled:e.batchBusy,onClick:()=>{EY()},children:P?r("测试中 {done}/{total}",{done:P.done,total:P.total}):r("批量测试")}),s.jsx(se,{variant:"destructive",disabled:e.batchBusy,onClick:()=>{AY()},children:r("批量删除")}),s.jsx(se,{variant:"outline",disabled:e.batchBusy,onClick:()=>SY(),children:r("取消选择")})]})]}):s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5 border-b border-border px-4 py-[10px]",children:[s.jsxs(Ci,{className:"w-[clamp(150px,22vw,220px)]",children:[s.jsx(Ei,{type:"search",value:g,"aria-label":r("搜索节点"),placeholder:r("搜索名称 / 地址 / 端口"),onChange:J=>v(J.currentTarget.value)}),s.jsx(Ti,{align:"inline-start","aria-hidden":"true",children:s.jsx(cX,{})})]}),s.jsxs(ft,{value:j,onValueChange:B,children:[s.jsx(mt,{className:"w-[clamp(150px,18vw,210px)]","aria-label":r("按提供方筛选"),children:s.jsx(pt,{children:_.find(J=>J.value===j)?.label??r("全部提供方")})}),s.jsx(ht,{children:_.map(J=>s.jsx(qe,{value:J.value,children:s.jsxs("span",{className:"flex w-full items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate"+(J.count?"":" text-subtle"),children:J.label}),s.jsx("span",{className:"flex-none text-[11px] text-subtle",children:J.count})]})},J.value))})]}),s.jsx(In,{options:lX(C),value:y,onValueChange:z,"aria-label":r("按来源筛选")}),s.jsx(In,{options:oX(C),value:S,onValueChange:N,"aria-label":r("按状态筛选")}),s.jsx("span",{className:"ml-auto text-[11px] text-subtle",children:r("显示 {n} / 共 {total} 个出口",{n:Q.length,total:C.length})})]}),s.jsx("div",{className:"models-table-wrap",children:s.jsxs("table",{className:"models-table proxies-table",children:[s.jsx("colgroup",{children:$.map(J=>s.jsx("col",{"data-col":J.key,className:tX[J.key]||void 0},J.key))}),s.jsx("thead",{children:s.jsx("tr",{children:$.map(J=>s.jsx("th",{"data-col":J.key,className:`ta-${J.align}`,children:J.key==="pick"?s.jsx(Or,{checked:X,indeterminate:q,disabled:!K.length,title:r("全选当前筛选出的出口"),"aria-label":r("全选当前筛选出的出口"),onCheckedChange:ie=>wY(K,ie)}):J.label},J.key))})}),s.jsx("tbody",{children:ce()})]})}),s.jsx(Li,{leading:s.jsxs(s.Fragment,{children:[e.data?.clash&&e.data.clash.available===!1?s.jsx("span",{className:"text-subtle",children:e.data.clash.error?r("未检测到 Clash Verge:{reason}",{reason:e.data.clash.error}):r("未检测到 Clash Verge")}):null,e.error?s.jsx("span",{className:"text-destructive",children:r("读取失败:{reason}",{reason:e.error})}):null]}),total:Q.length,page:F.page,pageCount:F.pageCount,size:F.size,onSizeChange:F.setSize,onPageChange:F.goto,range:F.paged?{start:F.rangeStart,end:F.rangeEnd}:null}),a?s.jsx(MY,{item:a.item,onClose:()=>o(null)}):null,c?s.jsx(DY,{onClose:()=>d(!1)}):null,f?s.jsx(WY,{onClose:()=>p(!1)}):null]})})}function tl(e){return e.source==="clash"?"clash":e.source==="subscription"?"subscription":"manual"}function rD(){return[{key:"manual",label:r("手动"),note:r("本页可编辑、可删除")},{key:"clash",label:"Clash Verge",note:r("名字与端口在 Clash Verge 里改;启用可在本页关闭")},{key:"subscription",label:r("订阅"),note:r("名字与端口跟随订阅与内核;启用可在本页关闭")}]}function lX(e){const t=a=>e.filter(o=>tl(o)===a).length;return[{value:"all",label:r("全部"),count:e.length},{value:"manual",label:r("手动"),count:t("manual")},{value:"clash",label:"Clash",count:t("clash")},{value:"subscription",label:r("订阅"),count:t("subscription")}]}function aD(e){return e.enabled===!1?"off":e.port===null||e.port===void 0?"wait":e.lastTest?.at?e.lastTest.success?"ok":"fail":"none"}function oX(e){const t=a=>e.filter(o=>aD(o)===a).length;return[{value:"all",label:r("全部状态"),count:e.length},{value:"ok",label:r("可用"),count:t("ok")},{value:"fail",label:r("失败"),count:t("fail")},{value:"wait",label:r("未就绪"),count:t("wait")},{value:"off",label:r("已禁用"),count:t("off")}]}const lD="__orphan";function iX(e,t){const a=e.filter(d=>tl(d)==="subscription"),o=t.map(d=>({value:d.id,label:d.name||d.id,count:a.filter(f=>!f.orphan&&f.providerId===d.id).length})).sort((d,f)=>f.count-d.count||d.label.localeCompare(f.label)),c=a.filter(d=>d.orphan).length;return[{value:"all",label:r("全部提供方"),count:e.length},{value:"manual",label:r("手动"),count:e.filter(d=>tl(d)==="manual").length},{value:"clash",label:"Clash Verge",count:e.filter(d=>tl(d)==="clash").length},{value:"subscription",label:r("全部订阅"),count:a.length},...o,...c?[{value:lD,label:r("已移除的订阅"),count:c}]:[]]}function cX(){return s.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[s.jsx("circle",{cx:"11",cy:"11",r:"8"}),s.jsx("path",{d:"m21 21-4.3-4.3"})]})}window.wbProxiesPanel={load:async()=>{await cp(),await Ml()},visibleColumns:()=>sD().map(e=>({key:e.key}))};const oD='.page[data-page="proxies"]';function iD(){const e=document.querySelector(oD);!e||e.dataset.mounted==="1"||(e.dataset.mounted="1",e.replaceChildren(),vn.createRoot(e).render(s.jsx(aX,{})),tr().wbApp?.currentPage==="proxies"&&(cp(),Ml()))}document.querySelector(oD)?iD():document.addEventListener("DOMContentLoaded",iD,{once:!0});const Wg=["today","7","30","month","all","custom"],d0="7",f0="custom",cD="workbuddy-desktop-report-range",uD="workbuddy-desktop-report-custom-range",dD={today:r("今天"),7:r("近 7 天"),30:r("近 30 天"),month:r("本月"),all:r("全部"),custom:r("自定义区间")},uX={today:r("今天"),7:r("7 天"),30:r("30 天"),month:r("本月"),all:r("全部"),custom:r("自定义")};function dX(){try{const e=localStorage.getItem(cD);return e!==null&&Wg.includes(e)?e:d0}catch{return d0}}function p0(e){const t=a=>String(a).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function fX(){const e=new Date;return{start:p0(new Date(e.getFullYear(),e.getMonth(),e.getDate()-6)),end:p0(e)}}const Jg=/^\d{4}-\d{2}-\d{2}$/;function pX(){try{const e=localStorage.getItem(uD);if(e){const t=JSON.parse(e),a=typeof t?.start=="string"?t.start:"",o=typeof t?.end=="string"?t.end:"";if(Jg.test(a)&&Jg.test(o)&&a<=o)return{start:a,end:o}}}catch{}return fX()}function mX(e){try{localStorage.setItem(uD,JSON.stringify(e))}catch{}}const hX=[[0,r("一")],[2,r("三")],[4,r("五")]],fD=400;function Zi(e){const t=m0();return t.formatInt?t.formatInt(e):(Number(e)||0).toLocaleString("zh-CN")}function m0(){return window.wbUnits||{}}function ns(e){const t=m0();return t.formatTokens?t.formatTokens(e):String(Number(e)||0)}function pD(e,t){const a=m0();return a.formatAxis?a.formatAxis(e,t):String(e)}function Wi(e){return`${((Number(e)||0)*100).toFixed(1)}%`}function Pt(e){return Math.round(e*10)/10}function ex(e){return[...e].reduce((t,a)=>t+(/[\u2e80-\u9fff]/.test(a)?9.7:5.4),0)}function tx(e){const[t,a,o]=String(e||"").split("-").map(Number);return new Date(t||1970,(a||1)-1,o||1)}const gX=[r("日"),r("一"),r("二"),r("三"),r("四"),r("五"),r("六")];function nx(e){const t=tx(e);return r("{m}月{d}日 周{wd}",{m:t.getMonth()+1,d:t.getDate(),wd:gX[t.getDay()]})}function mD(e){const t=String(e||"").slice(11,13);return t?`${t}:00`:"—"}const xX=8;function hD(e,t){const a=(Array.isArray(e)?e:[]).map(d=>({name:String(d?.label??d?.model??"").trim()||r("未知模型"),tokens:Number(d?.tokens)||0})).filter(d=>d.tokens>0);if(!a.length)return[];const o=a.slice(0,xX),c=o.map(d=>`${t?`[${t(d.name)}]`:""}${r("{model}:{tokens} tokens",{model:d.name,tokens:ns(d.tokens)})}`);return a.length>o.length&&c.push(r("…还有 {n} 个模型",{n:a.length-o.length})),c}function gD(e,t){return[nx(e.date),r("总 Token:{tokens}({n} 次请求)",{tokens:ns(e.tokens),n:Zi(e.requests)}),...hD(e.models,t)].join(` +`)}function bX(e,t){return[`${nx(String(e.hour).slice(0,10))} ${mD(e.hour)}`,r("命中率 {rate}(命中 {hit} / 输入 {input})",{rate:Wi(e.rate),hit:ns(e.hitTokens),input:ns(e.inputTokens)}),r("总 Token:{tokens}",{tokens:ns(e.totalTokens)}),...hD(e.models,t)].join(` +`)}const vX=[1,1.5,2,2.5,3,4,5,6,8,10];function yX(e){if(!(e>0))return 1;const t=10**Math.floor(Math.log10(e)),a=e/t;return(vX.find(c=>c>=a-1e-9)??10)*t}function h0(e){return yX(e/4)*4}function jX(e,t,a){const o=e||{},c=o.topModel,d=Number(o.requests)||0,f=Number(o.successful)||0,p=d?`${(f/d*100).toFixed(1)}%`:"—",g=[{key:"requests",label:r("总请求数"),value:Zi(d),sub:dD[t]||"",mono:!1},{key:"successful",label:r("成功请求数"),value:Zi(f),sub:r("成功率 {rate}",{rate:p}),mono:!1},{key:"tokens",label:r("总 Token"),value:ns(o.tokens),sub:r("输入 + 输出"),mono:!1},{key:"activeDays",label:r("活跃天数"),value:Zi(o.activeDays),sub:r("区间共 {n} 天",{n:a}),mono:!1},{key:"streak",label:r("当前连续天数"),value:Zi(o.streak),sub:r("含今天在内往前数"),mono:!1}];return g.push(c?{key:"topModel",label:r("Top 模型"),value:String(c.model??""),sub:r("{tokens} tokens · 占 {pct}",{tokens:ns(c.tokens),pct:Wi(c.percentage)}),mono:!0}:{key:"topModel",label:r("Top 模型"),value:"—",sub:r("所选范围内还没有模型用量"),mono:!1}),g}function xD(e){if(!Array.isArray(e))return null;const t=e.map(c=>({id:String(c?.id??"").trim(),label:String(c?.label??"").trim(),tokens:Number(c?.totalTokens??c?.tokens)||0})).filter(c=>c.tokens>0);if(!t.length)return[];const a=t.reduce((c,d)=>c+d.tokens,0),o=c=>a?c/a*100:0;return[...t].sort((c,d)=>d.tokens-c.tokens).map((c,d)=>{const f=o(c.tokens),p=ns(c.tokens),g=c.label||c.id||r("未知"),v=c.id?r("{name}({id})",{name:g,id:c.id}):g;return{key:`${d}-${c.id||g}`,id:c.id,name:g,full:v,tip:r("{name}:{tokens} tokens · 占 {pct}%",{name:v,tokens:p,pct:f.toFixed(1)}),tokensText:p,percentText:`${f.toFixed(1)}%`,barWidth:`${f.toFixed(1)}%`}})}function bD(e){return`${ns(e.reduce((t,a)=>t+(Number(a?.totalTokens??a?.tokens)||0),0))} tokens`}const sx=["#f73b00","#f7bb07","#4aaa4d","#1872cb","#3444a3","#13c2c2","#722ed1","#eb2f96","#a0d911","#34d399","#d946ef","#ff85c0","#b37feb","#9d174d","#ffa39e","#69b1ff"],wX={size:220,inner:.62,outer:.88,padAngle:2};function SX(e,t,a,o,c,d){const f=D=>(D-90)*Math.PI/180,p=(D,C)=>[Pt(e+D*Math.cos(f(C))),Pt(t+D*Math.sin(f(C)))],g=d-c;if(g>=359.999){const[D,C]=p(a,0),[A,R]=p(a,180),[I,P]=p(o,0),[O,_]=p(o,180);return`M ${D} ${C} A ${a} ${a} 0 1 1 ${A} ${R} A ${a} ${a} 0 1 1 ${D} ${C} Z M ${I} ${P} A ${o} ${o} 0 1 0 ${O} ${_} A ${o} ${o} 0 1 0 ${I} ${P} Z`}const[v,y]=p(a,c),[b,j]=p(a,d),[w,S]=p(o,d),[N,k]=p(o,c),E=g>180?1:0;return`M ${v} ${y} A ${a} ${a} 0 ${E} 1 ${b} ${j} L ${w} ${S} A ${o} ${o} 0 ${E} 0 ${N} ${k} Z`}const NX="#9aa0a6";function vD(e){const t=new Map;for(const a of Array.isArray(e)?e:[]){const o=String(a?.label??a?.model??a?.id??"").trim();!o||t.has(o)||(Number(a?.totalTokens??a?.tokens)||0)>0&&t.set(o,sx[t.size%sx.length])}return t}function yD(e,t){const a=(Array.isArray(e)?e:[]).map(k=>({label:String(k?.label??k?.model??k?.id??"").trim()||t,tokens:Number(k?.totalTokens??k?.tokens)||0,requests:Number(k?.requests)||0})).filter(k=>k.tokens>0);if(!a.length)return null;const o=a.reduce((k,E)=>k+E.tokens,0);if(!o)return null;const c=vD(e),{size:d,inner:f,outer:p,padAngle:g}=wX,v=d/2,y=d/2,b=d/2*p,j=d/2*f;let w=0;const S=[],N=[];return a.forEach((k,E)=>{const D=k.tokens/o,C=D*360,A=a.length>1?Math.min(g/2,C/4):0,R=w+A,I=w+C-A;w+=C;const P=c.get(k.label)??sx[E%sx.length];let O=null;if(D>=.03){const _=(R+I)/2,L=j+(b-j)*.6,H=(_-90)*Math.PI/180;O={x:Pt(v+L*Math.cos(H)),y:Pt(y+L*Math.sin(H)),text:`${Math.round(D*100)}%`}}I>R&&S.push({key:`${E}-${k.label}`,d:SX(v,y,b,j,R,I),fill:P,evenOdd:C>=359.999,label:O,tip:`${k.label} · ${ns(k.tokens)} tokens · ${Wi(D)}`}),N.push({key:`${E}-${k.label}`,fill:P,name:k.label,tokensText:ns(k.tokens),percentText:Wi(D),tip:r("{name} · {tokens} tokens · {n} 次请求 · {pct}",{name:k.label,tokens:ns(k.tokens),n:Zi(k.requests),pct:Wi(D)})})}),{size:d,slices:S,legend:N,totalText:ns(o)}}const kX=[1,1.25,1.5,2,2.5,3,4,5,6,8,10];function CX(e){if(!(e>0))return 1;const t=10**Math.floor(Math.log10(e)),a=e/t;let o=1;for(const c of kX)c<=a+1e-9&&(o=c);return o*t}function TX(e){const t=Number(e)||0;if(t<=0)return[0,1,2,3,1/0];const a=Math.max(1,CX(t/4));return[0,a,a*2,a*3,1/0]}function EX(e,t){if(e===0)return"0";const a=t[e-1],o=t[e];return Number.isFinite(o)?a===0?`≤${ns(o)}`:`${ns(a)}–${ns(o)}`:`>${ns(a)}`}function jD(e){const t=Array.isArray(e)?e:[];return TX(t.reduce((a,o)=>Math.max(a,Number(o?.tokens)||0),0))}function AX(e,t){const a=Array.isArray(e)?e:[];if(!a.length)return null;const o=(tx(a[0].date).getDay()+6)%7,c=new Array(o).fill(null).concat(a),d=Math.ceil(c.length/7),f=3,p=20,g=t-p,v=Math.floor((g-f*(d-1))/d),y=Math.max(7,Math.min(26,v)),b=y+3,j=y+f,w=p+d*j-f,S=Math.max(0,Math.round((t-w)/2)),N=b+7*j-f+2,k=Math.max(w,Math.round(t)),E=jD(a),D=O=>E.findIndex(_=>Number(O)<=_),C=[];for(let O=0;O({key:_,x:S+p-6,y:Pt(b+O*j+y/2),text:_})),R=[];let I=-1,P=-9;for(let O=0;O({level:t,text:EX(t,e)}))}function OX(e){const t=e||{};return[["last10m",r("近 10 分钟")],["last1h",r("近 1 小时")],["last24h",r("近 24 小时")],["last7d",r("近 7 天")]].map(([o,c])=>{const d=t[o]||{},f=Number(d.inputTokens)||0;return{key:o,label:c,value:f?Wi(d.rate):"—",sub:r("命中 {hit} / 输入 {input}",{hit:ns(d.hitTokens),input:ns(f)})}})}function MX(e,t,a){const o=Array.isArray(e)?e:[];if(!o.length)return null;const c=230,d={left:44,right:56,top:26,bottom:24},f=Math.max(40,t-d.left-d.right),p=c-d.top-d.bottom,g=o.map(q=>Number(q.rate)||0),v=o.map(q=>Number(q.totalTokens)||0),y=Math.max(1,h0(Math.max(...g))),b=Math.max(...v),j=h0(b),w=b>0,S=q=>d.left+(o.length>1?f*q/(o.length-1):f/2),N=q=>d.top+p-p*q/y,k=q=>d.top+p-p*q/j,E=[],D=[],C=[];for(let q=0;q<=4;q+=1){const $=y*q/4,Y=Pt(N($)),F=$*100;E.push({key:`g${q}`,y:Y}),D.push({key:`r${q}`,x:d.left-8,y:Y,anchor:"end",text:`${Number.isInteger(F)?F:F.toFixed(1)}%`}),w&&C.push({key:`t${q}`,x:Pt(d.left+f+8),y:Y,anchor:"start",text:pD(j*q/4,j)})}const A=o.length===1?4.5:2.5,R=(q,$)=>({points:q.map((Y,F)=>`${Pt(S(F))},${Pt($(Y))}`).join(" "),dots:q.map((Y,F)=>({key:`d${F}`,cx:Pt(S(F)),cy:Pt($(Y))}))}),I=[],P=(q,$,Y,F)=>{const G=ex(Y),W=F==="middle"?q-G/2:F==="end"?q-G:q,le={left:W,right:W+G,top:$-8.5,bottom:$+2.5};return I.some(M=>le.leftM.left-2&&le.topM.top-1)?null:(I.push(le),{key:`${Y}-${q}-${$}`,x:Pt(q),y:Pt($),text:Y,anchor:F})},O=(q,$)=>{const Y=ex($)/2;return q-Yd.left+f+6?"end":"middle"},_=[];w&&o.forEach((q,$)=>{if(!(Number(q.totalTokens)>0))return;const Y=k(v[$]),F=Y-12>=d.top-10,G=ns(v[$]),W=P(S($),F?Y-12:Y+13,G,O(S($),G));W&&_.push({...W,key:`tl${$}`})});const L=[];o.forEach((q,$)=>{if(!((Number(q.inputTokens)||0)+(Number(q.hitTokens)||0)>0))return;const F=N(g[$]),G=F+15<=d.top+p+8,W=Wi(g[$]),le=P(S($),G?F+13:F-7,W,O(S($),W));le&&L.push({...le,key:`rl${$}`})});const H=o.length>1?f/(o.length-1):f,B=d.left,z=d.left+f,Q=o.length<=fD?o.map((q,$)=>{const Y=Math.max(B,S($)-H/2),F=Math.min(z,S($)+H/2);return{key:`h${$}`,x:Pt(Y),width:Pt(F-Y),tip:bX(q,a)}}):null,K=Math.max(1,Math.ceil(o.length/8)),X=[];for(let q=0;q=o.length;X.push({key:`x${q}`,x:Pt(S(q)),y:c-8,anchor:q===0?"start":$?"end":"middle",text:mD(o[q].hour)})}return{width:t,height:c,plotLeft:B,plotW:f,plotH:p,plotTop:d.top,grid:E,rateTicks:D,tokenTicks:C,rateLine:R(g,N),tokenLine:w?R(v,k):null,dotR:A,rateLabels:L,tokenLabels:_,hourTicks:X,hits:Q}}const DX=13;function IX(e,t,a){const o=Array.isArray(e)?e:[];if(!o.length)return null;const c=240,d={left:50,right:14,top:26,bottom:26},f=Math.max(40,t-d.left-d.right),p=f/o.length,g=o.map(K=>Number(K.tokens)>0?ns(K.tokens):""),v=Math.max(0,...g.map(ex)),y=g.every(K=>!K)||v+4<=p,b=!y&&p>=DX;b&&(d.top=10+Math.ceil(v*1.25));const j=c-d.top-d.bottom,w=o.map(K=>Number(K.tokens)||0),S=Math.max(...w),N=h0(S),k=Math.max(1,Math.min(28,p*.68)),E=d.top+j,D=K=>d.top+j-j*K/N,C=o.length<=fD,A=S<=0,R=[],I=[];if(!A)for(let K=0;K<=4;K+=1){const X=N*K/4,q=Pt(D(X));R.push({key:`g${K}`,x1:d.left,y:q,x2:Pt(d.left+f)}),I.push({key:`v${K}`,x:d.left-8,y:q,anchor:"end",text:pD(X,N)})}const P=[];o.forEach((K,X)=>{const q=Number(K.tokens)||0;if(q<=0)return;const $=D(q);P.push({key:String(K.date??X),x:Pt(d.left+p*X+(p-k)/2),y:Pt($),width:Pt(k),height:Pt(Math.max(1,E-$)),rx:k>4?2:1,tip:gD(K),nativeTip:!C})});const O=[],_=[],L=(K,X)=>{const q=g[K],$=D(Number(o[K].tokens)||0),Y=Pt(d.left+p*K+p/2);if(b)return{key:`b${K}`,x:Y,y:Pt($-6),anchor:"start",text:q,rotate:!0};const F=$-6,G=F-9M.leftU.left-2&&M.topU.top-1))return null;_.push(M)}return{key:`b${K}`,x:Y,y:W,anchor:"middle",text:q}};if(y||b)g.forEach((K,X)=>{if(!K)return;const q=L(X,!1);q&&O.push(q)});else{const K=o.map((X,q)=>({index:q,value:Number(X.tokens)||0})).filter(X=>X.value>0).sort((X,q)=>q.value-X.value);for(const X of K){if(O.length>=8)break;const q=L(X.index,!0);q&&O.push(q)}}const H=C?o.map((K,X)=>({key:`h${X}`,x:Pt(d.left+p*X),width:Pt(p),tip:gD(K,a)})):null,B=Math.max(1,Math.ceil(o.length/6)),z=[];for(let K=0;K{const X=o.length===1,q=!X&&K===o.length-1,$=tx(o[K].date);return{key:`d${K}`,x:X?d.left+f/2:q?d.left+f:Pt(d.left+p*K+p/2),y:c-8,anchor:X?"middle":q?"end":K===0?"start":"middle",text:`${$.getMonth()+1}/${$.getDate()}`}});return{width:t,height:c,plotLeft:d.left,plotW:f,plotH:j,plotTop:d.top,grid:R,valueTicks:I,bars:P,barLabels:O,dateTicks:Q,hits:H,blank:A}}function Ji(){return window}const wD=1e3,PX=Wg.map(e=>({value:e,label:uX[e]})),_X=r("所选范围内每个账号各消耗了多少 Token,按 Token 用量从多到少排。账号是比提供商更细的一维:同一家可以挂多个账号,转发时按优先级在候选链上依次尝试,所以这里反映的是「具体哪个登录态在出力」。百分比按本区间的总 Token 数算(这一块只看用量,请求次数与成功率在概览卡片里)。「未知账号」是指那批请求没有账号身份:走默认登录态转发(未配置账号列表)时会这样;这一维上线前写出的旧聚合行也没有账号明细,但它们会在升级导入旧数据时按明细自动补算回来 —— 只有明细已被手动清理掉的那几天补不回来,仍留在「未知账号」里,那是确实无从恢复的部分。"),LX=r("所选范围内每个提供商各消耗了多少 Token,按 Token 用量从多到少排。同一个模型名可能有多家都能提供,网关按设置页「转发路由」的优先级依次尝试,所以占比也反映了实际落到谁身上。百分比按本区间的总 Token 数算(这一块只看用量,请求次数与成功率在概览卡片里)。「未知」是指那批请求没记下承载它的提供商 —— 主要是记录提供商这个功能上线之前的旧明细,其次是请求在选定上游之前就失败了(请求体非法、模型不存在、没有可用账号)。这一维与账号那一维不同:旧明细里根本没有「哪家承载」的信息(早期版本只有单一上游,但那是配置事实而非逐条记录),所以无法回算,旧数据会一直留在「未知」里;此后新产生的请求都会记上具体的提供商。"),zX=r("所选范围内每个模型各消耗了多少 Token,按用量从多到少排,扇区角度即占比。中心是这一维的合计(等于概览里的总 Token),右侧每行给出该模型的 Token 用量与百分比。扇区内的百分比只在 ≥3% 时标出,更小的会挤成一团 —— 完整读数在右侧列表与悬停气泡里。颜色按用量排名分配:最大的那段是红色,依次往后;同一份报表里换个维度看,配色口径不变。"),BX=r("所选范围内每个提供商各消耗了多少 Token,按用量从多到少排,扇区角度即占比。同一个模型名可能有多家都能提供,网关按设置页「转发路由」的优先级依次尝试,所以占比也反映了实际落到谁身上。中心是这一维的合计(等于概览里的总 Token),右侧每行给出该提供商的 Token 用量与百分比。「未知」是指那批请求没记下承载它的提供商 —— 主要是记录提供商这个功能上线之前的旧明细,其次是请求在选定上游之前就失败了。"),HX=r("命中率 = 缓存读取 Token / 输入 Token(promptTokens)。窗口越短越贴近「此刻」:上游把缓存读取与输入分开上报时,该比值合法地可能超过 100%,此处不夹取值、如实展示。"),UX=r("每天的总 Token 用量(输入 + 输出)。柱顶标出当天的读数;区间很长、柱子挤到放不下时只标最高的那几天,其余悬停柱子即可读到。");let rx=wD,ax=!0,g0=!1,x0=!1,b0=0,Po=null,ec=null,lx=null;function tc(e,t="empty"){return s.jsx("div",{className:t,style:{padding:"14px 0"},children:e})}function ox({text:e}){return s.jsx("span",{className:"tip-q","data-tip":e})}function VX({accountId:e}){const t=(Ji().wbApp?.getState?.()?.accounts?.accounts||[]).find(f=>f?.id===e),a=typeof t?.provider=="string"?t.provider:"";if(!a)return null;const o=Ji().wbProviders?.labelOf?.(a)||a,c=t&&Ji().wbAccountsModel?.editionSuffix?.(t)||"",d=c?`${o} ${c}`:o;return s.jsx("span",{className:`pbadge p-${a}`,title:r("提供商:{text}",{text:d}),children:d})}function FX({summary:e,range:t}){const a=Array.isArray(e.dailyTrend)?e.dailyTrend:[];return s.jsx(s.Fragment,{children:jX(e.overview,t,a.length).map(o=>s.jsxs("div",{className:"field",children:[s.jsx("div",{className:"label",children:o.label}),s.jsxs("div",{className:o.mono?"value mono":"value",children:[o.value,o.sub?s.jsx("div",{className:"sub",children:o.sub}):null]})]},o.key))})}function SD({panelId:e,listId:t,labelId:a,title:o,tip:c,rows:d,totalText:f,withBadge:p,emptyText:g}){return s.jsxs("section",{className:"panel",id:e,children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:o}),s.jsx(ox,{text:c}),s.jsx("span",{className:"panel-sub",id:a,children:f})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"rank-shares",id:t,children:d.length?d.map(v=>s.jsxs("div",{className:"rank-row","data-tip":v.tip,children:[s.jsxs("span",{className:"name",title:v.full,children:[p?s.jsx(VX,{accountId:v.id}):null,v.name]}),s.jsx("span",{className:"track",children:s.jsx("span",{className:"bar",style:{width:v.barWidth}})}),s.jsx("span",{className:"num",title:`${v.tokensText} tokens`,children:v.tokensText}),s.jsx("span",{className:"pct",children:v.percentText})]},v.key)):tc(g)})})]})}function ND({panelId:e,listId:t,title:a,tip:o,ariaLabel:c,view:d,emptyText:f}){return s.jsxs("section",{className:"panel",id:e,children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:a}),s.jsx(ox,{text:o})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{id:t,children:d?s.jsxs("div",{className:"donut-layout",children:[s.jsxs("div",{className:"donut-wrap",children:[s.jsx("svg",{className:"donut-svg",width:d.size,height:d.size,viewBox:`0 0 ${d.size} ${d.size}`,role:"img","aria-label":c,children:d.slices.map(p=>s.jsxs(x.Fragment,{children:[s.jsx("path",{className:"donut-slice",d:p.d,fill:p.fill,fillRule:p.evenOdd?"evenodd":void 0,tabIndex:-1,"data-tip":p.tip}),p.label?s.jsx("text",{className:"donut-label",x:p.label.x,y:p.label.y,textAnchor:"middle",dominantBaseline:"central",children:p.label.text}):null]},p.key))}),s.jsxs("div",{className:"donut-center",children:[s.jsx("div",{className:"donut-center-value",children:d.totalText}),s.jsx("div",{className:"donut-center-label",children:r("总 Token")})]})]}),s.jsx("div",{className:"donut-legend",children:d.legend.map(p=>s.jsxs("div",{className:"donut-legend-row","data-tip":p.tip,children:[s.jsx("span",{className:"donut-dot",style:{background:p.fill}}),s.jsx("span",{className:"donut-legend-name",title:p.name,children:p.name}),s.jsx("span",{className:"donut-legend-tokens",children:p.tokensText}),s.jsx("span",{className:"donut-legend-percent",children:p.percentText})]},p.key))})]}):tc(f)})})]})}function $X({view:e}){return s.jsxs("svg",{className:"report-svg",width:e.width,height:e.height,viewBox:`0 0 ${e.width} ${e.height}`,role:"img","aria-label":r("近 365 天活跃热力图"),children:[e.months.map(t=>s.jsx("text",{className:"hm-axis",x:t.x,y:10,children:t.text},t.key)),e.weekdays.map(t=>s.jsx("text",{className:"hm-axis",x:t.x,y:t.y,textAnchor:"end",dominantBaseline:"middle",children:t.text},t.key)),e.cells.map(t=>s.jsx("rect",{className:`hm-cell l${t.level}`,x:t.x,y:t.y,width:t.size,height:t.size,rx:2,tabIndex:-1,"data-tip":t.tip},t.key))]})}function kD({line:e,cls:t,radius:a}){return s.jsxs(s.Fragment,{children:[s.jsx("polyline",{className:`chart-line ${t}`,points:e.points}),e.dots.map(o=>s.jsx("circle",{className:`chart-dot ${t}`,cx:o.cx,cy:o.cy,r:a},o.key))]})}function v0({items:e,cls:t}){return s.jsx(s.Fragment,{children:e.map(a=>s.jsx("text",{className:`chart-label ${t}`,x:a.x,y:a.y,textAnchor:a.anchor,transform:a.rotate?`rotate(-90 ${a.x} ${a.y})`:void 0,dominantBaseline:a.rotate?"central":void 0,children:a.text},a.key))})}function qX({view:e}){const{width:t,height:a,plotLeft:o,plotW:c,plotTop:d,plotH:f}=e;return s.jsxs(s.Fragment,{children:[s.jsxs("svg",{className:"report-svg",width:t,height:a,viewBox:`0 0 ${t} ${a}`,role:"img","aria-label":r("近 24 小时缓存命中率与总 Token 趋势"),children:[e.grid.map(p=>s.jsx("line",{className:"chart-grid",x1:o,y1:p.y,x2:Pt(o+c),y2:p.y},p.key)),e.rateTicks.map(p=>s.jsx("text",{className:"chart-axis",x:p.x,y:p.y,textAnchor:p.anchor,dominantBaseline:"middle",children:p.text},p.key)),e.tokenTicks.map(p=>s.jsx("text",{className:"chart-axis",x:p.x,y:p.y,textAnchor:p.anchor,dominantBaseline:"middle",children:p.text},p.key)),e.tokenLine?s.jsx(kD,{line:e.tokenLine,cls:"tokens",radius:e.dotR}):null,s.jsx(kD,{line:e.rateLine,cls:"rate",radius:e.dotR}),s.jsx(v0,{items:e.tokenLabels,cls:"tokens"}),s.jsx(v0,{items:e.rateLabels,cls:"rate"}),e.hourTicks.map(p=>s.jsx("text",{className:"chart-axis",x:p.x,y:p.y,textAnchor:p.anchor,children:p.text},p.key))]}),e.hits?s.jsx("svg",{className:"report-svg chart-hit-layer",width:t,height:a,viewBox:`0 0 ${t} ${a}`,"aria-hidden":"true",children:e.hits.map(p=>s.jsx("rect",{className:"chart-hit",x:p.x,y:d,width:p.width,height:Pt(f),tabIndex:-1,"data-tip":p.tip,"data-tip-variant":"plain"},p.key))}):null]})}function GX({view:e}){const{width:t,height:a,plotLeft:o,plotW:c,plotTop:d,plotH:f}=e;return s.jsxs(s.Fragment,{children:[s.jsxs("svg",{className:"report-svg",width:t,height:a,viewBox:`0 0 ${t} ${a}`,role:"img","aria-label":r("按天 Token 趋势"),children:[e.grid.map(p=>s.jsx("line",{className:"chart-grid",x1:p.x1,y1:p.y,x2:p.x2,y2:p.y},p.key)),e.valueTicks.map(p=>s.jsx("text",{className:"chart-axis",x:p.x,y:p.y,textAnchor:p.anchor,dominantBaseline:"middle",children:p.text},p.key)),e.bars.map(p=>p.nativeTip?s.jsx("rect",{className:"bar",x:p.x,y:p.y,width:p.width,height:p.height,rx:p.rx,children:s.jsx("title",{children:p.tip})},p.key):s.jsx("rect",{className:"bar",x:p.x,y:p.y,width:p.width,height:p.height,rx:p.rx},p.key)),s.jsx(v0,{items:e.barLabels,cls:"tokens"}),e.dateTicks.map(p=>s.jsx("text",{className:"chart-axis",x:p.x,y:p.y,textAnchor:p.anchor,children:p.text},p.key)),e.blank?s.jsx("text",{className:"chart-empty",x:Pt(o+c/2),y:Pt(d+f/2),textAnchor:"middle",children:r("所选范围内暂无请求")}):null]}),e.hits?s.jsx("svg",{className:"report-svg chart-hit-layer",width:t,height:a,viewBox:`0 0 ${t} ${a}`,"aria-hidden":"true",children:e.hits.map(p=>s.jsx("rect",{className:"chart-hit",x:p.x,y:d,width:p.width,height:Pt(f),tabIndex:-1,"data-tip":p.tip,"data-tip-variant":"plain"},p.key))}):null]})}const KX=680;function y0(){const e=x.useRef(null),[t,a]=x.useState(0);return x.useLayoutEffect(()=>{const o=e.current;if(!o)return;let c=o.clientWidth;if(c&&a(c),typeof ResizeObserver!="function")return;const d=new ResizeObserver(()=>{const f=o.clientWidth;!f||f===c||(c=f,a(f))});return d.observe(o),()=>d.disconnect()},[]),[e,t||KX]}async function CD(){if(!g0)try{const e=await Ji().workbuddyDesktop?.getScheduledTasks(),t=(e?.tasks||[]).find(a=>a.id==="reportAutoRefresh");j0(t||null),g0=Array.isArray(e?.tasks)}catch(e){console.warn("读取报表自动刷新间隔失败,按默认 1 秒:",e instanceof Error?e.message:e),j0(null)}}function j0(e){g0=!0;const t=Number(e?.interval);!!e&&typeof e=="object"&&Number.isFinite(t)&&t>0&&(e.unit==="seconds"||e.unit==="minutes")?(ax=e.enabled!==!1,rx=e.unit==="minutes"?t*6e4:t*1e3):(ax=!0,rx=wD),ec?.applyAutoConfig(rx,ax)}const YX={summary:null,error:null};function XX(){const[e,t]=x.useState(YX),[a,o]=x.useState(dX),[c,d]=x.useState(pX),[f,p]=x.useState(()=>({ms:rx,enabled:ax})),[,g]=x.useState(0),v=x.useRef(a),y=x.useRef(c),b=x.useCallback(G=>{t(G)},[]),j=x.useCallback(async(G={})=>{CD();const W=++b0,le=v.current,M=le===f0?y.current:void 0;try{const U=Ji().workbuddyDesktop;if(!U)throw new Error("后端桥不可用");const Z=await U.getStatsSummary(le,M);if(W!==b0)return Po;if(!Z||typeof Z!="object")throw new Error("后端未返回报表数据");return Po=Z,b({summary:Z,error:null}),Po}catch(U){if(W!==b0)return Po;const Z=U instanceof Error?U.message:"";return Po=null,G.silent||console.warn("读取报表数据失败:",Z),b({summary:null,error:Z||r("未知错误")}),null}},[b]),w=x.useCallback(G=>{G!==void 0&&(Po=G||null,G&&b({summary:G,error:null}))},[b]),S=x.useCallback(G=>{const W=Wg.includes(G)?G:d0;if(W!==v.current){v.current=W,o(W);try{localStorage.setItem(cD,W)}catch{}j()}},[j]),N=x.useCallback(G=>{const W={...y.current,...G};if(!Jg.test(W.start)||!Jg.test(W.end))return;const le=W.start<=W.end?W:G.start?{start:W.start,end:W.start}:{start:W.end,end:W.end};y.current=le,d(le),mX(le),v.current===f0&&j()},[j]);x.useEffect(()=>{if(ec={load:j,render:w,applyAutoConfig:(G,W)=>p({ms:G,enabled:W})},lx){const G=lx;lx=null,w(G.data)}return Ji().wbApp?.currentPage==="overview"&&j({silent:!0}),()=>{ec=null}},[j,w]),x.useEffect(()=>{if(!f.enabled||f.ms<=0)return;const G=window.setInterval(()=>{document.hidden||Ji().wbApp?.currentPage!=="overview"||x0||(x0=!0,j({silent:!0}).finally(()=>{x0=!1}))},f.ms);return()=>{window.clearInterval(G)}},[f,j]),x.useEffect(()=>{const G=()=>g(W=>W+1);return window.addEventListener("wb-units-changed",G),()=>window.removeEventListener("wb-units-changed",G)},[]);const k=y0(),E=y0(),D=y0(),{summary:C,error:A}=e,R=C&&Wg.includes(C.range??"")?C.range:a,I=C&&Array.isArray(C.heatmap)?C.heatmap:[],P=C&&Array.isArray(C.cacheTrend24h)?C.cacheTrend24h:[],O=C&&Array.isArray(C.dailyTrend)?C.dailyTrend:[],_=C&&Array.isArray(C.providers)?C.providers:null,L=C&&Array.isArray(C.accounts)?C.accounts:null,H=C&&Array.isArray(C.models)?C.models:null,B=A?tc(r("读取报表失败:{error}",{error:A}),"empty report-error"):null,z=tc(r("正在加载…")),Q=B??z,K=x.useMemo(()=>vD(H||[]),[H]),X=x.useCallback(G=>K.get(G)||NX,[K]),q=C?AX(I,k[1]):null,$=C?MX(P,E[1],X):null,Y=C?IX(O,D[1],X):null,F=p0(new Date);return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("统计概览")}),s.jsx("span",{className:"panel-sub",id:"report-range-label",children:dD[R]||""}),s.jsxs("div",{className:"head-actions",children:[s.jsx(In,{options:PX,value:a,onValueChange:S,"aria-label":r("报表时间范围")}),a===f0?s.jsxs("span",{className:"report-date-range",children:[s.jsx($e,{type:"date",className:"report-date-input w-[132px]",value:c.start,max:c.end||F,"aria-label":r("开始日期"),title:r("起始日期(含当天)"),onChange:G=>N({start:G.target.value})}),s.jsx("span",{className:"report-date-sep","aria-hidden":"true",children:"~"}),s.jsx($e,{type:"date",className:"report-date-input w-[132px]",value:c.end,min:c.start||void 0,max:F,"aria-label":r("结束日期"),title:r("结束日期(含当天)"),onChange:G=>N({end:G.target.value})})]}):null]})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"field-grid",id:"report-overview",children:C?s.jsx(FX,{summary:C,range:R}):Q})})]}),s.jsxs("div",{className:"report-rank-grid",children:[L?s.jsx(SD,{panelId:"report-accounts-panel",listId:"report-accounts",labelId:"report-accounts-label",title:r("Top 账号"),tip:_X,rows:xD(L)||[],totalText:bD(L),withBadge:!0,emptyText:r("所选范围内还没有账号用量")}):null,_?s.jsx(SD,{panelId:"report-providers-panel",listId:"report-providers",labelId:"report-providers-label",title:r("Top 提供商"),tip:LX,rows:xD(_)||[],totalText:bD(_),withBadge:!1,emptyText:r("所选范围内还没有请求记录")}):null]}),s.jsxs("div",{className:"report-donut-grid",children:[H?s.jsx(ND,{panelId:"report-models-panel",listId:"report-models-donut",title:r("模型用量"),tip:zX,ariaLabel:r("模型用量占比"),view:yD(H,r("未知模型")),emptyText:r("所选范围内还没有模型用量")}):null,_?s.jsx(ND,{panelId:"report-providers-pie-panel",listId:"report-providers-donut",title:r("提供商用"),tip:BX,ariaLabel:r("提供商用占比"),view:yD(_,r("未知")),emptyText:r("所选范围内还没有提供商用量")}):null]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("活跃热力图")}),s.jsx("span",{className:"panel-sub",children:r("近 365 天,按天 Token 用量着色(档位按本窗口峰值自动定)")})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"heat-wrap",id:"report-heatmap",ref:k[0],children:C?q?s.jsx($X,{view:q}):tc(r("暂无热力图数据")):Q})}),s.jsxs("div",{className:"panel-foot",children:[s.jsx("span",{className:"heat-scale-label",children:r("Token")}),s.jsx("span",{className:"heat-legend",id:"report-heat-legend",children:C?RX(jD(I)).map(G=>s.jsxs("span",{className:"heat-legend-item",children:[s.jsx("span",{className:`l${G.level}`}),G.text]},G.level)):null}),s.jsx("div",{className:"spacer"}),s.jsx("span",{children:r("方格为本地自然日,无请求显示为空槽")})]})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("缓存命中率")}),s.jsx(ox,{text:HX})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"field-grid",id:"report-cache-rates",children:C?OX(C.cacheRates).map(G=>s.jsxs("div",{className:"field rate",children:[s.jsx("div",{className:"label",children:G.label}),s.jsxs("div",{className:"value big",children:[G.value,s.jsx("div",{className:"sub",children:G.sub})]})]},G.key)):Q})})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("近 24 小时缓存命中率趋势")}),s.jsx("span",{className:"panel-sub",children:r("按本地整点,无请求的整点不标注")})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"chart-wrap",id:"report-cache-trend",ref:E[0],children:C?$?s.jsx(qX,{view:$}):tc(r("暂无缓存趋势数据")):Q})}),s.jsxs("div",{className:"panel-foot",children:[s.jsxs("span",{className:"chart-legend",children:[s.jsx("span",{className:"swatch rate"}),r("缓存命中率"),s.jsx("span",{className:"axis-hint",children:r("左轴")})]}),s.jsxs("span",{className:"chart-legend",children:[s.jsx("span",{className:"swatch tokens"}),r("总 Token"),s.jsx("span",{className:"axis-hint",children:r("右轴")})]}),s.jsx("div",{className:"spacer"}),s.jsx("span",{children:r("无请求的整点按 0% 计,但不写读数")})]})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("按天 Token 趋势")}),s.jsx(ox,{text:UX}),s.jsx("span",{className:"panel-sub",id:"report-trend-label",children:C?`${C.startDate||"—"} ~ ${C.endDate||"—"}`:"—"})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"chart-wrap tall",id:"report-daily-trend",ref:D[0],children:C?Y?s.jsx(GX,{view:Y}):tc(r("暂无趋势数据")):Q})})]})]})}async function QX(e={}){return ec?ec.load(e):Po}function ZX(e){if(e!==void 0){if(!ec){lx={data:e??null};return}ec.render(e)}}function WX(){return Po}window.wbReport={load:QX,render:ZX,lastSummary:WX,applyAutoRefresh:j0};const TD='.page[data-page="overview"]';let ED=!1;function AD(){if(ED)return;const e=document.querySelector(TD);e&&(ED=!0,e.replaceChildren(),vn.createRoot(e).render(s.jsx(XX,{})))}document.querySelector(TD)?AD():document.addEventListener("DOMContentLoaded",AD,{once:!0}),CD();const w0={all:{title:r("全部删除"),desc:r("删除日志记录本身。当前有筛选时只删命中的条目,按天聚合报表不受影响;无筛选时清空全部并重置报表。此方式无法恢复。")},raw:{title:r("仅清空报文原文"),desc:r("保留统计行与报表,只抹掉请求 / 响应正文。清理后详情弹窗的「预览对话」将无原文可看,统计数字分毫不动。")}},JX=["all","raw"],eQ=3e3;function Dl(){return window}let dp=!1;function fp(e,t){Dl().wbApp?.toast?.(e,t)}function tQ(e){const t=Math.max(0,Number(e)||0);if(t<1024)return`${Math.round(t)} B`;const a=t/1024;if(a<1024)return`${a.toFixed(1)} KB`;const o=a/1024;return o<1024?`${o.toFixed(1)} MB`:`${(o/1024).toFixed(2)} GB`}function S0(){const e=Dl().wbRequestsPanel?.clearParams?.();return typeof e=="string"?e:""}function RD(e){return{all:Number(e?.all)||0,raw:Number(e?.raw)||0,dbBytes:Number(e?.dbBytes)||0,vacuumRunning:e?.vacuumRunning===!0}}function N0(e){return e instanceof Error?e.message:String(e)}function OD(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}function nQ({onClose:e}){const[t,a]=x.useState("all"),[o,c]=x.useState({status:"loading"}),[d,f]=x.useState(""),[p,g]=x.useState(!1),[v,y]=x.useState(!1),b=x.useRef(!0),j=x.useRef(null),w=x.useCallback(I=>{dp=I,y(I)},[]),S=x.useCallback(()=>{j.current!==null&&(window.clearInterval(j.current),j.current=null)},[]),N=x.useCallback(I=>{c({status:"ready",all:I.all,raw:I.raw,dbBytes:I.dbBytes}),g(I.vacuumRunning)},[]),k=x.useCallback(async()=>{const I=Dl().workbuddyDesktop;if(!I)return;let P;try{P=await I.getStatsClearPreview(S0())}catch{return}if(!b.current)return;const O=RD(P);N(O),!O.vacuumRunning&&(S(),f(""),fp(r("✅ 压缩完成")),Dl().wbRequestsPanel?.load?.({silent:!0}))},[N,S]),E=x.useCallback(()=>{j.current===null&&(g(!0),j.current=window.setInterval(()=>{k()},eQ))},[k]);async function D(){c({status:"loading"});try{const I=Dl().workbuddyDesktop;if(!I)throw new Error(r("后端桥不可用"));const P=await I.getStatsClearPreview(S0());if(!b.current)return;const O=RD(P);N(O),O.vacuumRunning&&E()}catch(I){if(!b.current)return;c({status:"failed"}),f(r("预览读取失败:{error}",{error:N0(I)}))}}x.useEffect(()=>(b.current=!0,D(),()=>{b.current=!1,S(),dp=!1}),[]);async function C(){const I=Dl().workbuddyDesktop;if(I){g(!0);try{await I.compactStatsDb(),f(r("压缩已在后台开始,完成后会自动提示")),E()}catch(P){const O=N0(P);if(/409|正在进行/.test(O)){fp(r("压缩已在进行中")),f(r("压缩已在进行中,接上它的进度等待完成")),E();return}g(!1),f(r("压缩失败:{message}",{message:O})),fp(r("压缩失败:{message}",{message:O}),"err")}}}async function A(){if(dp)return;const I=Dl().workbuddyDesktop,P=Dl().wbConfirm?.ask;if(!I||!P)return;const O=w0[t].title,_=S0(),L=_.length>0,H=o.status==="ready"?t==="raw"?o.raw:o.all:0;if(await P({title:r("清理请求日志"),html:L?r("确定按当前筛选执行「{label}」?将处理 {count} 条,此操作无法恢复。",{label:OD(O),count:H}):r("确定对全部请求日志执行「{label}」?将处理 {count} 条,此操作无法恢复。",{label:OD(O),count:H}),okText:r(t==="raw"?"抹掉原文":"删除"),okClass:"danger"})){w(!0);try{const z=L?`mode=${t}&${_}`:`mode=${t}&all=1`,Q=await I.clearStatsRequests(z),K=Number(Q?.deleted)||0;fp(t==="raw"?r("已抹掉 {count} 条报文原文",{count:K}):r("已删除 {count} 条",{count:K})),w(!1),e(),Dl().wbRequestsPanel?.notifyCleared?.()}catch(z){const Q=N0(z);f(r("清理失败:{message}",{message:Q})),fp(r("清理失败:{message}",{message:Q}),"err"),w(!1)}}}const R=o.status==="ready"?r("将删除 {count} 条日志 · 其中 {raw} 条仍带报文原文 · 数据库占用 {db}",{count:o.all,raw:o.raw,db:tQ(o.dbBytes)}):o.status==="failed"?r("预览读取失败"):r("正在统计…");return s.jsx(Qt,{open:!0,onOpenChange:(I,P)=>{if(!I){if(dp){P.cancel();return}e()}},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("清理请求日志")})}),s.jsxs(Bt,{children:[s.jsx(kh,{"aria-label":r("清理方式"),value:t,onValueChange:I=>a(I==="raw"?"raw":"all"),children:JX.map(I=>{const P=t===I;return s.jsxs("label",{"data-checked":P?"":void 0,className:"group/card grid cursor-pointer grid-cols-[auto_minmax(0,1fr)] items-center gap-x-2.5 gap-y-0.5 rounded-md border border-border px-3 py-2.5 transition-colors duration-150 ease-out hover:border-border-strong data-checked:border-primary data-checked:bg-primary-soft",children:[s.jsx(bo,{value:I,className:"row-span-2 self-center"}),s.jsx("span",{className:"text-[13px] font-semibold text-foreground group-data-checked/card:text-primary-fg",children:w0[I].title}),s.jsx("span",{className:"text-[11.5px] leading-[1.55] text-subtle",children:w0[I].desc})]},I)})}),s.jsx("p",{className:"text-[11.5px] text-muted-foreground",children:R})]}),s.jsxs(nn,{children:[s.jsx("span",{className:"min-w-0 text-[11.5px] text-muted-foreground",children:d}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",size:"sm",onClick:()=>{C()},disabled:p,title:r(p?"压缩正在后台执行,完成后自动恢复":"回收已删除数据占用的磁盘空间(checkpoint + VACUUM,后台执行)"),children:r(p?"压缩中…":"压缩数据库")}),s.jsx(se,{variant:"outline",onClick:e,disabled:v,children:r("取消")}),s.jsx(se,{variant:"destructive",onClick:()=>{A()},disabled:v,children:r(v?"清理中…":"执行清理")})]})]})})}let pp=null,Vu=null;function MD(){pp&&(pp.unmount(),pp=null),Vu&&(Vu.remove(),Vu=null)}function sQ(){dp||MD()}function rQ(){MD(),Vu=document.createElement("div"),document.body.append(Vu),pp=vn.createRoot(Vu),pp.render(s.jsx(nQ,{onClose:sQ}))}window.wbRequestClearModal={open:rQ};const DD=[{value:"detail",label:r("请求详情")},{value:"preview",label:r("预览对话")},{value:"raw",label:r("原始报文")}],aQ="detail",ID="border-b border-hairline px-2.5 py-[7px] align-top",_o="border border-hairline px-2 py-1 align-top",lQ="border border-hairline bg-surface-2 px-2 py-1 text-[11.5px] tracking-normal",ix="hover:[&>td]:bg-transparent";function Fu(){return window}function k0(){const e=Fu().workbuddyDesktop;if(!e)throw new Error(r("后端桥不可用"));return e}let C0=0;function oQ(e){if(!e)return"—";const t=new Date(e),a=o=>String(o).padStart(2,"0");return`${t.getFullYear()}-${a(t.getMonth()+1)}-${a(t.getDate())} ${a(t.getHours())}:${a(t.getMinutes())}:${a(t.getSeconds())}`}function PD(e){const t=Math.round(Number(e)||0);if(t<1e3)return`${t}ms`;const a=Math.floor(t/1e3);if(a>=60)return r("{m}分{s}秒",{m:Math.floor(a/60),s:a%60});const o=t%1e3;return o>0?r("{s}秒{ms}ms",{s:a,ms:o}):r("{n}秒",{n:a})}function iQ(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"-":PD(t)}const cQ=r("生成速度:输出 token ÷ 流式段用时(总用时 − 首响);流式段不足总用时一半时按总用时计");function uQ(e){const t=Number(e.completionTokens)||0,a=Number(e.durationMs)||0;if(t<=0||a<=0)return"";const o=Number(e.firstResponseMs),c=Number.isFinite(o)&&o>0&&o=500&&c*2>=a,f=t/((d?c:a)/1e3);return`${f>=100?Math.round(f):f.toFixed(1)} tok/s`}function cx(e){return Fu().wbUnits?.formatTokens?.(e)??(Number(e)||0).toLocaleString("zh-CN")}function dQ(e){const t=Math.max(0,Date.now()-(Number(e)||0));return r("{n}秒",{n:Math.max(1,Math.floor(t/1e3))})}function fQ(e){const t=Number(e.status)||0;return t>=200&&t<300&&!e.error}function ux(e){return(Number(e?.status)||0)===0&&!e?.error}function _D(e){const t=String(e.provider??"").trim();return String(e.providerLabel??"").trim()||(t?Fu().wbProviders?.labelOf?.(t)||t:"")}function mp(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function T0(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return""}}function E0(e){return e instanceof Error?e.message:String(e)}const LD=[{label:r("请求头"),pick:e=>T0(e.requestHeaders)},{label:r("请求体"),pick:e=>T0(e.requestBody)},{label:r("响应头"),pick:e=>T0(e.responseHeaders)},{label:r("响应体"),pick:e=>e.responseBody?String(e.responseBody):""}];function dx({text:e,loading:t=!1}){return s.jsxs("div",{className:"flex items-center justify-center gap-2 py-6 text-center text-[12.5px] text-muted-foreground",children:[t?s.jsx(Jd,{className:"size-3.5"}):null,e]})}function ua({label:e,children:t}){return s.jsxs(kl,{className:ix,children:[s.jsx("th",{scope:"row",className:`w-[76px] whitespace-nowrap text-left text-[12.5px] font-semibold text-muted-foreground ${ID}`,children:e}),s.jsx(Nn,{className:ID,children:t})]})}function pQ({row:e}){if(ux(e)){const c=Fu().wbRequestPhase;if(!c?.badgeHtml)return s.jsxs(ze,{variant:"info",shape:"tag",title:r("请求正在转发中,用时列显示的是已用时"),children:[s.jsx(ay,{className:"req-live-dot"}),r("进行中")]});const d=c.elapsedLineHtml?.(e)??"";return s.jsxs("span",{className:"inline-flex flex-wrap items-center gap-1.5",children:[s.jsx("span",{dangerouslySetInnerHTML:{__html:c.badgeHtml(e)}}),d?s.jsx("span",{className:"text-[11.5px] text-muted-foreground",dangerouslySetInnerHTML:{__html:d}}):null]})}const t=Number(e.status)||0,a=fQ(e),o=!a&&t>=200&&t<300?r("HTTP {status},但响应体阶段出错",{status:t}):"";return s.jsx(ze,{variant:a?"success":"destructive",shape:"tag",title:o||void 0,children:t||r("失败")})}function mQ({row:e}){const t=String(e.clientModel??"").trim(),a=String(e.upstreamModel??"").trim(),o=String(e.model??"").trim(),c=String(e.clientReasoning??"").trim(),d=String(e.upstreamReasoning??"").trim(),f=(v,y)=>y?`${v}(${y})`:v;if(!t||!a||a.toLowerCase()===t.toLowerCase())return s.jsx(s.Fragment,{children:f(o,d||c)||"—"});const p=f(a,d),g=f(t,c);return s.jsxs("span",{className:"flex flex-col gap-0.5",children:[s.jsxs("span",{title:r("转发到上游的模型:{model}",{model:p}),children:["⬆️ ",p]}),s.jsxs("span",{className:"text-muted-foreground",title:r("下游请求的模型:{model}",{model:g}),children:["⬇️ ",g]})]})}function hQ(e){const t=Number(e?.status),a=e?.status!==null&&e?.status!==void 0&&Number.isFinite(t),o=e?.error?String(e.error):"";if(o){const c=a?r("失败({status}):{error}",{status:String(t),error:o}):r("失败:{error}",{error:o});return s.jsx("span",{className:"break-words text-destructive",children:c})}return a?s.jsx("span",{className:"text-success",children:r("成功({status})",{status:String(t)})}):s.jsx("span",{className:"text-muted-foreground",children:r("无结果记录")})}function gQ({row:e}){const t=Array.isArray(e.attemptDetails)?e.attemptDetails:[];if(!t.length)return s.jsx(s.Fragment,{children:"-"});const a=Number(e.attempts)||1;return s.jsxs(Vy,{className:"text-[11.5px]",children:[s.jsx(pE,{children:s.jsx(kl,{className:ix,children:[r("轮次"),r("提供商"),r("账号"),r("结果"),r("体积"),r("内部重试"),r("提示")].map(o=>s.jsx(mE,{className:lQ,children:o},o))})}),s.jsxs(Fy,{children:[t.map((o,c)=>{const d=Array.isArray(o?.retries)?o.retries:[],f=d.map(b=>{const j=Number(b?.delayMs),w=Number.isFinite(j)&&j>0?j>=1e3?r(",{n}秒后重试",{n:Math.round(j/1e3)}):r(",{n}毫秒后重试",{n:Math.round(j)}):"";return`${String(b?.reason||r("未知原因"))}${w}`}).join(` +`),p=String(o?.notice??"").trim(),g=Number(o?.bodyBytes),v=Number.isFinite(g)&&g>0?g>=1024*1024?`${(g/1024/1024).toFixed(1)} MB`:g>=1024?`${Math.round(g/1024)} KB`:`${g} B`:"—",y=Number.isFinite(g)&&g>0?r("实际发给上游 {bytes} 字节",{bytes:g.toLocaleString()}):void 0;return s.jsxs(kl,{className:ix,children:[s.jsx(Nn,{className:_o,children:c+1}),s.jsx(Nn,{className:_o,children:_D(o)||(o?.provider?String(o.provider):r("未知"))}),s.jsx(Nn,{className:_o,children:o?.account?String(o.account):"—"}),s.jsx(Nn,{className:_o,children:hQ(o)}),s.jsx(Nn,{className:`${_o} whitespace-nowrap`,title:y,children:v}),s.jsx(Nn,{className:`${_o} whitespace-nowrap`,title:f||void 0,children:d.length?r("↻ {n} 次",{n:d.length}):"-"}),s.jsx(Nn,{className:_o,children:p||"—"})]},c)}),t.lengths.jsxs("li",{className:"py-0.5",children:[s.jsxs("b",{children:[y+1,". ",String(v.name||v.id||"—")]}),s.jsxs("span",{className:"text-muted-foreground",children:[" ",String(v.reason||"")]})]},String(v.id??y)))}):null,p.length?s.jsxs("div",{className:"mt-1 text-muted-foreground",children:[r("被跳过:"),p.map(v=>String(v.name||v.id||"")).join("、")]}):null,g?s.jsx("div",{className:"mt-1",children:r("最终承载:{picked}",{picked:g})}):null]})}function bQ({row:e}){if(!e)return s.jsx(dx,{text:r("列表数据已刷新,请重试(关闭后重新打开这条详情)")});const t=String(e.accountName??"").trim(),a=uQ(e);return s.jsx(Vy,{className:"text-[12.5px] text-subtle [&_tr:last-child>td]:border-b-0 [&_tr:last-child>th]:border-b-0",children:s.jsxs(Fy,{children:[s.jsx(ua,{label:r("时间"),children:oQ(e.ts)}),s.jsx(ua,{label:r("状态"),children:s.jsx(pQ,{row:e})}),s.jsx(ua,{label:r("耗时"),children:ux(e)?s.jsxs(s.Fragment,{children:[dQ(e.ts),s.jsx("span",{className:"text-[11.5px] text-muted-foreground",children:r("(请求仍在转发中)")})]}):r("{duration} / 首帧 {first}",{duration:PD(e.durationMs),first:iQ(e.firstResponseMs)})}),s.jsx(ua,{label:r("重试次数"),children:String(Number(e.attempts)||1)}),s.jsx(ua,{label:r("模型"),children:s.jsx(mQ,{row:e})}),s.jsxs(ua,{label:r("提供商"),children:[_D(e)||"—",t?s.jsx("span",{className:"text-[11.5px] text-muted-foreground",children:r("(账号:{account})",{account:t})}):null]}),s.jsxs(ua,{label:r("令牌"),children:[r("输入 {input} · 输出 {output} · 总计 {total} · 缓存读 {cache}",{input:cx(e.promptTokens),output:cx(e.completionTokens),total:cx(e.totalTokens),cache:cx(e.cacheReadTokens)}),a?s.jsxs("span",{title:cQ,children:[" · ",a]}):null]}),e.isTest?s.jsx(ua,{label:r("来源"),children:s.jsx(ze,{variant:"brand",shape:"tag",title:r("模型管理页操作列那颗「测试」发起的请求:与真实请求同一条转发链路,但不计入报表统计"),children:r("模型测试")})}):null,s.jsx(ua,{label:r("错误"),children:e.error?s.jsx("span",{className:"text-destructive",children:String(e.error)}):"—"}),s.jsx(ua,{label:r("尝试明细"),children:s.jsx(gQ,{row:e})}),e.route?s.jsx(ua,{label:r("路由回放"),children:s.jsx(xQ,{row:e})}):null,s.jsx(ua,{label:r("敏感词"),children:Array.isArray(e.sensitiveHits)&&e.sensitiveHits.length?s.jsx("span",{className:"inline-flex flex-wrap gap-1.5",children:e.sensitiveHits.map((o,c)=>s.jsxs(ze,{variant:"sensitive",shape:"tag",children:[String(o?.word??"")," × ",String(Number(o?.count)||0)]},c))}):"—"})]})})}function vQ({state:e}){if(!e)return s.jsx(dx,{text:r("正在读取…"),loading:!0});const t=e==="gone"?null:e.body,a=t&&Fu().wbConversationPreview?.render?.(t.requestBody,t.responseBody)||"";return a?s.jsxs("div",{children:[e!=="gone"&&e.truncated?s.jsx("div",{className:"mb-2 text-[11.5px] text-warning",children:r("正文超过单条上限,可能已被截断")}):null,s.jsx("div",{dangerouslySetInnerHTML:{__html:a}})]}):s.jsx(dx,{text:r("无报文原文(未开启「调试模式」,或已被清理)")})}function yQ({data:e}){const t=e.status===null||e.status===void 0?"-":String(e.status),a=[e.url?`URL: ${e.url}`:"",e.provider?r("提供商: {provider}",{provider:String(e.provider)}):"",r("上游状态码: {status}",{status:t})].filter(Boolean);return s.jsxs("div",{className:"flex flex-col gap-4",children:[a.length?s.jsx("div",{className:"border-b border-hairline pb-2.5 text-xs leading-[1.7] break-all text-subtle",children:a.map((o,c)=>s.jsx("div",{children:o},c))}):null,LD.map(o=>{const c=o.pick(e)||"";return s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx("h3",{className:"text-[11.5px] font-semibold tracking-[.02em] text-muted-foreground",children:o.label}),c?s.jsx("pre",{className:"max-h-80 overflow-auto rounded-md border border-border bg-surface-2 p-[10px_12px] font-mono text-[11.5px] leading-[1.6] break-words whitespace-pre-wrap text-subtle",children:c}):s.jsx(dx,{text:r("这条请求没有保存这一段报文")})]},o.label)})]})}function jQ({id:e,row:t,token:a,onClose:o}){const[c,d]=x.useState(aQ),[f,p]=x.useState(null),[g,v]=x.useState(null),[y,b]=x.useState("—"),[j,w]=x.useState("idle"),S=x.useRef(!0),N=x.useRef(null),k=x.useRef({detail:0,preview:0,raw:0}),E=x.useCallback(()=>!S.current||a!==C0,[a]);async function D(){try{const O=await k0().getStatsRequestRaw(e);if(E())return;const _=mp(O)?O:null,L=String(_?.requestBody??"").trim()!==""||String(_?.responseBody??"").trim()!=="";p(_&&L?{body:_,truncated:!!_.truncated}:"gone")}catch(O){if(E())return;p("gone"),console.warn("读取原始正文失败(预览对话显示空态):",E0(O))}}async function C(){try{const O=await k0().getDebugTraffic(e);if(E())return;const _=mp(O)?O:{};if(!LD.some(L=>(L.pick(_)||"").trim())){v("gone");return}v({data:_}),b(_.truncated?r("报文超过单条上限,请求体 / 响应体已按上限截断"):r("内容按原样保存,请求头中的凭据字段已替换为 [redacted]"))}catch(O){if(E())return;v("gone"),b(r("在设置 → 通用里开启「调试模式」后,新发生的请求才会保存报文")),console.warn("读取调试报文失败(原始报文标签隐藏):",E0(O))}}x.useEffect(()=>(S.current=!0,D(),C(),()=>{S.current=!1}),[]),x.useLayoutEffect(()=>{const O=N.current;O&&(O.scrollTop=k.current[c])},[c]);function A(O){if(O==="raw"&&!mp(g)||O===c)return;const _=N.current;_&&(k.current[c]=_.scrollTop),d(O)}async function R(){if(!e||!ux(t))return;const O=Fu().wbConfirm?.ask;if(!(!O||!await O({title:r("终止请求"),html:r("确定终止这条正在转发的请求?
上游连接会立即断开,明细将记为「请求已被手动终止」。"),okText:r("终止"),okClass:"danger"}))){w("pending");try{if(await k0().terminateStatsRequest(e),!S.current)return;w("accepted"),b(r("已受理终止:上游连接已断开,列表稍后刷新为「请求已被手动终止」"))}catch(L){if(!S.current)return;w("idle"),b(r("终止失败:{error}",{error:E0(L)}))}}}const I=mp(g),P=x.useMemo(()=>I?DD:DD.filter(O=>O.value!=="raw"),[I]);return s.jsx(Qt,{open:!0,onOpenChange:O=>{O||o()},children:s.jsxs(Zt,{className:"w-[min(920px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("请求详情")})}),s.jsxs(Bt,{ref:N,className:"gap-3",children:[s.jsx(In,{options:P,value:c,onValueChange:A,"aria-label":r("详情内容"),className:"self-start"}),s.jsx("section",{hidden:c!=="detail",children:s.jsx(bQ,{row:t})}),s.jsx("section",{hidden:c!=="preview",children:s.jsx(vQ,{state:f})}),I?s.jsx("section",{hidden:c!=="raw",children:s.jsx(yQ,{data:g.data})}):null]}),s.jsxs(nn,{children:[s.jsx("span",{className:"min-w-0 text-[11.5px] text-muted-foreground",children:y}),s.jsx("div",{className:"mr-auto"}),ux(t)?s.jsx(se,{variant:"destructive",disabled:j!=="idle",onClick:()=>{R()},title:r("断开上游连接,明细记为「请求已被手动终止」"),children:r("终止请求")}):null,s.jsx(se,{variant:"outline",onClick:o,children:r("关闭")})]})]})})}let hp=null,$u=null;function zD(){hp&&(hp.unmount(),hp=null),$u&&($u.remove(),$u=null)}function BD(){C0+=1,zD()}function wQ(e,t){const a=String(e??"").trim();if(!a)return;zD();const o=++C0;$u=document.createElement("div"),document.body.append($u),hp=vn.createRoot($u),hp.render(s.jsx(jQ,{id:a,row:mp(t)?t:null,token:o,onClose:BD}))}window.wbRequestDetail={open:wQ,close:BD};const SQ=150,NQ=80,nc=8,fx=8,kQ=520,CQ=220,TQ=1.1,EQ=900,A0=12,R0="req-hover-panel",AQ=["fixed z-[35] pointer-events-none","max-h-[min(360px,60vh)] overflow-x-hidden overflow-y-auto","rounded-md p-[10px_12px] text-[12px] leading-[1.6] break-normal","bg-surface-2 text-foreground shadow-3","border-0 dark:border dark:border-border-strong dark:bg-surface-3"].join(" "),gp="rh-row rh-dim min-w-0 break-words text-muted-foreground",RQ="rh-row min-w-0 break-words";function OQ(){return window}function O0(e){return typeof e=="object"&&e!==null?e:null}const HD=e=>Array.isArray(e?.attemptDetails)?e.attemptDetails:[],UD=e=>Array.isArray(e?.retries)?e.retries:[],MQ=e=>Array.isArray(e?.sensitiveHits)?e.sensitiveHits:[];function M0(e){const t=String(e??"").trim();return t?OQ().wbProviders?.labelOf?.(t)||t:""}function DQ(e){const t=O0(e);return(Number(t?.attempts)||1)>1?!0:HD(t).some(a=>UD(a).length>0||!!a?.notice)}function VD(e){return e.dataset.reqHover==="sensitive"?"sensitive":"chain"}function IQ({details:e}){if(e.length<2)return null;const t=e.map(a=>M0(a.provider)||r("未知"));return s.jsxs("div",{className:"rh-chain mb-1.5 border-b border-border pb-1.5 break-words",children:[s.jsx("span",{className:"rh-chain-k font-semibold text-muted-foreground",children:r("切换路径:")}),s.jsx("span",{className:"rh-chain-v font-semibold text-foreground",children:t.join(" → ")})]})}function PQ({item:e}){const t=UD(e);return t.length?s.jsxs("div",{className:"rh-retry mt-0.5 mb-1 ml-2.5 border-l-2 border-border-strong pl-2",children:[s.jsx("div",{className:"rh-retry-head text-[11.5px] font-semibold text-warning",children:r("↻ 重试 {n} 次",{n:t.length})}),t.map((a,o)=>{const c=String(a?.reason??"").trim(),d=Number(a?.status),f=a?.status!==null&&a?.status!==void 0&&Number.isFinite(d),p=Number(a?.delayMs),g=Number.isFinite(p)&&p>0?p>=1e3?r(",{n}秒后重试",{n:Math.round(p/1e3)}):r(",{n}毫秒后重试",{n:Math.round(p)}):"";return s.jsxs("div",{className:"rh-retry-row min-w-0 break-words",children:[s.jsx("span",{className:"rh-retry-why mr-1 text-subtle [overflow-wrap:anywhere]",children:c||r("未知原因")}),f?s.jsx("span",{className:"rh-retry-status mr-1 text-muted-foreground tabular-nums whitespace-nowrap",children:`HTTP ${String(d)}`}):null,g?s.jsx("span",{className:"rh-dim text-muted-foreground",children:g}):null]},o)})]}):null}function _Q({item:e,index:t,inFlight:a}){const o=M0(e.provider),c=String(e.account??"").trim(),d=Number(e.status),f=e.status!==null&&e.status!==void 0&&Number.isFinite(d),p=e.error?String(e.error):"",g=String(e.notice??"").trim();return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:RQ,children:[s.jsx("span",{className:"rh-no mr-1 text-muted-foreground",children:r("尝试 {n} ·",{n:t+1})}),s.jsx("span",{className:"rh-who mr-1 font-semibold text-foreground",children:o||r("未知")}),c?s.jsx("span",{className:"rh-account mr-1 text-muted-foreground [overflow-wrap:anywhere]",children:c}):null,s.jsx("span",{className:"rh-arrow mr-1 text-muted-foreground",children:"→"}),p?s.jsx("span",{className:"rh-bad font-medium text-destructive [overflow-wrap:anywhere]",children:f?r("失败({status}):{error}",{status:String(d),error:p}):r("失败:{error}",{error:p})}):f?s.jsx("span",{className:"rh-ok font-medium text-success",children:r("成功({status})",{status:String(d)})}):a?s.jsx("span",{className:"rh-dim text-muted-foreground",children:r("进行中…")}):s.jsx("span",{className:"rh-dim text-muted-foreground",children:r("无结果记录")})]}),g?s.jsx("div",{className:"rh-notice mt-0.5 mb-1 ml-2.5 border-l-2 border-border-strong pl-2 text-warning [overflow-wrap:anywhere]",children:`⚠️ ${g}`}):null,s.jsx(PQ,{item:e})]})}function LQ({entry:e}){const t=Number(e.attempts)||1,a=HD(e);if(!a.length){const c=M0(e.provider),d=c?r("共 {n} 次尝试,最终由 {provider} 承载",{n:t,provider:c}):r("共 {n} 次尝试",{n:t});return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:gp,children:d}),s.jsx("div",{className:gp,children:r("这条记录的尝试明细未采集(该字段上线前的旧数据,或请求在转发前就失败)")})]})}const o=(Number(e.status)||0)===0&&!e.error;return s.jsxs(s.Fragment,{children:[s.jsx(IQ,{details:a}),a.map((c,d)=>s.jsx(_Q,{item:c,index:d,inFlight:o&&d===a.length-1},d)),a.lengths.jsxs("div",{className:"rh-row rh-hit flex items-baseline justify-between gap-2.5",children:[s.jsx("span",{className:"rh-hit-w break-words text-foreground",children:String(a?.word??"")}),s.jsx("span",{className:"rh-hit-c text-muted-foreground tabular-nums whitespace-nowrap",children:`× ${String(Number(a?.count)||0)}`})]},o)),t.length>A0?s.jsx("div",{className:gp,children:r("另有 {n} 个词命中",{n:t.length-A0})}):null]}):s.jsx("div",{className:gp,children:r("这条记录命中了敏感词,但没有留下命中明细")})}function BQ({kind:e,entry:t,panelRef:a}){return s.jsx("div",{ref:a,id:R0,role:"tooltip","data-kind":e,className:AQ,children:e==="sensitive"?s.jsx(zQ,{entry:t}):s.jsx(LQ,{entry:t})})}let Tn=null,Lo=0,xp=0,bp=null,px=null,D0=null,I0=null,sc=null,rc=null,vp=null,FD="chain";function P0(){window.clearTimeout(Lo),window.clearTimeout(xp),Lo=0,xp=0,bp=null}function HQ(){const e=vp?.current,t=Tn;if(!e||!t)return;const a=t.getBoundingClientRect(),o=window.innerWidth-nc*2;e.style.maxWidth="none",e.style.width="max-content";const c=e.offsetWidth,d=FD==="sensitive",p=Math.max(d?CQ:kQ,c)*(d?TQ:1),g=Math.min(p,o,EQ);e.style.maxWidth=`${g}px`,e.style.width=d?`${g}px`:"auto";const v=e.offsetWidth,y=e.offsetHeight,b=window.innerHeight-a.bottom-fx-nc,j=a.top-fx-nc,w=bb,S=a.left+a.width/2,N=Math.max(nc,Math.min(S-v/2,window.innerWidth-nc-v)),k=w?a.top-fx-y:a.bottom+fx;e.style.left=`${Math.round(N)}px`,e.style.top=`${Math.round(Math.max(nc,Math.min(k,window.innerHeight-nc-y)))}px`}function $D(e){if(!Tn)return;const t=e.target;t instanceof Node&&(t===Tn||Tn.contains(t)||Ra())}function qD(){Ra()}function GD(){Ra()}let mx=!1;function UQ(){mx||(mx=!0,document.addEventListener("click",$D,!0),window.addEventListener("scroll",qD,!0),window.addEventListener("resize",GD))}function VQ(){mx&&(mx=!1,document.removeEventListener("click",$D,!0),window.removeEventListener("scroll",qD,!0),window.removeEventListener("resize",GD))}function FQ(){VQ(),rc&&(rc.unmount(),rc=null),sc&&(sc.remove(),sc=null),vp=null}function KD(e,t){FD=e,(!sc||!rc||!vp)&&(sc=document.createElement("div"),document.body.append(sc),vp=x.createRef(),rc=vn.createRoot(sc));const a=rc,o=vp;ks.flushSync(()=>{a.render(s.jsx(BQ,{kind:e,entry:t,panelRef:o}))}),UQ(),HQ()}function YD(e){if(!e.isConnected)return;const t=O0(D0?.(e));t&&(P0(),Tn&&Tn!==e&&Ra(),Tn=e,KD(VD(e),t),e.classList.add("active"),e.setAttribute("aria-describedby",R0))}function Ra(){P0(),Tn&&(Tn.classList.remove("active"),Tn.removeAttribute("aria-describedby"),Tn=null),FQ()}function $Q(){if(!Tn)return;const e=String(Tn.dataset.reqHover||""),t=String(Tn.dataset.reqId||"");I0=!!(e&&t)&&Tn.matches(":hover")&&!xp?{action:"move",kind:e,key:t}:{action:"close"}}function qQ(){const e=I0;if(I0=null,!e||!Tn)return;if(e.action==="close"){Ra();return}const t=px?GQ(px,e.kind,e.key):null,a=t?O0(D0?.(t)):null;if(!t||!a){Ra();return}t!==Tn&&(Tn.classList.remove("active"),Tn.removeAttribute("aria-describedby"),Tn=t,KD(VD(t),a),t.classList.add("active"),t.setAttribute("aria-describedby",R0))}function GQ(e,t,a){for(const o of e.querySelectorAll("[data-req-hover]"))if(String(o.dataset.reqHover||"")===t&&String(o.dataset.reqId||"")===a)return o;return null}function hx(e){const t=e.target;return t instanceof Element?t.closest("[data-req-hover]"):null}function KQ(e){const t=hx(e);if(!t||!px?.contains(t)||(P0(),Tn===t&&rc))return;const a=Tn?0:SQ;Tn&&Ra(),bp=t,Lo=window.setTimeout(()=>{Lo=0,bp=null,YD(t)},a)}function YQ(e){const t=hx(e);if(t){if(bp===t){window.clearTimeout(Lo),Lo=0,bp=null;return}Tn===t&&(window.clearTimeout(Lo),Lo=0,xp=window.setTimeout(()=>{xp=0,Tn===t&&Ra()},NQ))}}function XQ(e){const t=hx(e);t&&YD(t)}function QQ(e){const t=hx(e);t&&Tn===t&&Ra()}function ZQ(e){e.key!=="Escape"||!Tn||Ra()}function WQ(e){const t=e?.host;t&&(px=t,D0=e?.entryOf??null,t.addEventListener("pointerover",KQ),t.addEventListener("pointerout",YQ),t.addEventListener("focusin",XQ),t.addEventListener("focusout",QQ),t.addEventListener("keydown",ZQ))}window.wbRequestHover={bind:WQ,close:Ra,hasProcessFacts:DQ,beforeListRedraw:$Q,afterListRedraw:qQ};function Cs(){return window}function _0(e){return e instanceof Error?e.message:String(e)}function gx(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}const xx={connecting:{label:r("连接中"),cls:"phase-connecting"},waiting:{label:r("等待响应"),cls:"phase-waiting"},streaming:{label:r("响应中"),cls:"phase-streaming"},retrying:{label:r("重试中"),cls:"phase-retrying"},queued:{label:r("排队中"),cls:"phase-queued"}},XD=r("进行中"),JQ="running",QD={connecting:r("请求已受理,正在选路、取凭证、建立上游连接"),waiting:r("上游请求已发出,正在等第一个字节到达(模型的思考时间也在这段)"),streaming:r("首帧已到,上游内容正在下发"),retrying:r("本轮尝试失败,正在退避等待或切换到下一个账号"),queued:r("上游模型繁忙,请求已排进上游队列;网关正按上游建议的时长等待后重发(不是登录态或额度问题)"),"":r("请求正在转发中,用时列显示的是已用时")};function L0(e){const t=String(e?.phase??"").trim().toLowerCase();return Object.prototype.hasOwnProperty.call(xx,t)?t:""}function ZD(e){const t=L0(e);return t?xx[t].label:XD}function WD(e){if(e==null||e==="")return"";const t=Number(e);if(!Number.isFinite(t)||t<0)return"";const a=Math.max(1,Math.floor(t/1e3));return a<60?r("{n}秒",{n:a}):r("{m}分{s}秒",{m:Math.floor(a/60),s:a%60})}function eZ(e){const t=e?.phaseElapsedMs;if(t!=null&&t!==""){const c=Number(t);if(Number.isFinite(c)&&c>=0)return c}const a=Number(e?.phaseStartedAt);if(!Number.isFinite(a)||a<=0)return null;const o=Date.now()-a;return Number.isFinite(o)?Math.max(0,o):null}function tZ(e){const t=L0(e),a=t?xx[t].label:XD,o=t?xx[t].cls:JQ,c=QD[t]||QD[""];return`${gx(a)}`}function nZ(e){const t=WD(eZ(e));if(!t)return"";const a=ZD(e),o=r("进入「{phase}」阶段已持续 {time}",{phase:a,time:t});return`${gx(t)}`}const z0=[{key:"time",label:r("时间"),sel:".req-time",track:"92px"},{key:"target",label:r("提供商 / 账号"),sel:".req-target",track:"minmax(0, 1.1fr)"},{key:"retry",label:r("重试"),sel:".req-retry",track:"52px"},{key:"status",label:r("状态"),sel:".req-status",track:"96px"},{key:"model",label:r("模型"),sel:".req-model",track:"minmax(0, 1.3fr)"},{key:"client",label:r("客户端"),sel:".req-client",track:"110px"},{key:"dur",label:r("用时"),sel:".req-dur",track:"96px",align:"right"},{key:"usage",label:r("用量"),sel:".req-usage",track:"minmax(0, 1.6fr)"},{key:"error",label:r("错误"),sel:".req-error-cell",track:"minmax(0, 1.2fr)"},{key:"detail",label:r("详情"),sel:".req-detail",track:"60px",align:"right"}],JD=1e3,sZ=tg;function eI(e){return typeof e=="number"&&e>0?e:fu}const tI="workbuddy-desktop-logs-requests-range",nI="workbuddy-desktop-requests-filters",rZ=3e4,B0=["today","7","30","month","all"],H0="all",aZ={today:r("今天"),7:r("近 7 天"),30:r("近 30 天"),month:r("本月"),all:r("全部")},lZ={today:r("今天"),7:r("7 天"),30:r("30 天"),month:r("本月"),all:r("全部")},oZ=B0.map(e=>({value:e,label:lZ[e]})),sI=[{value:"",label:r("全部状态")},{value:"ok",label:r("成功")},{value:"error",label:r("失败")}],iZ=r("全部状态"),rI=r("全部提供商"),aI=r("全部模型"),bx={status:"",provider:"",model:""};function vx(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function cZ(e){const t=new Date;switch(e){case"today":return vx(t);case"7":return vx(new Date(t.getFullYear(),t.getMonth(),t.getDate()-6));case"30":return vx(new Date(t.getFullYear(),t.getMonth(),t.getDate()-29));case"month":return vx(new Date(t.getFullYear(),t.getMonth(),1));default:return null}}const en={filters:{...bx},range:uZ(),runningOnly:!1,offset:0,size:eI(sg("requests",tg))};let yx={...bx},U0=!1,lI=!1,V0=[],jx=JD,wx=!0,F0=!1,$0=!1,oI=0,q0=0,G0=null,iI=!1,qu=null;function uZ(){try{const e=localStorage.getItem(tI);return e!==null&&B0.includes(e)?e:H0}catch{return H0}}function dZ(e){try{localStorage.setItem(tI,e)}catch{}}function cI(){const e=Cs().wbFilterMemory;return e?(U0=!0,yx=e.load(nI,{...bx}),en.filters={...yx},{...yx}):{...bx}}function fZ(e){yx={...e},Cs().wbFilterMemory?.save(nI,{status:e.status||"",provider:e.provider||"",model:e.model||""})}function uI(){const e=new URLSearchParams,t=cZ(en.range);t!==null&&e.set("start",String(t));const a=en.runningOnly?"running":en.filters.status;return a&&e.set("status",a),en.filters.provider&&e.set("provider",en.filters.provider),en.filters.model&&e.set("model",en.filters.model),e}function pZ(){const e=uI();return e.set("offset",String(en.offset)),e.set("limit",String(en.size)),e.toString()}function K0(e){const t=Math.round(Number(e)||0);if(t<1e3)return`${t}ms`;const a=Math.floor(t/1e3);if(a>=60)return r("{m}分{s}秒",{m:Math.floor(a/60),s:a%60});const o=t%1e3;return o>0?r("{s}秒{ms}ms",{s:a,ms:o}):r("{n}秒",{n:a})}const mZ=r("生成速度:输出 token ÷ 流式段用时(总用时 − 首响);流式段不足总用时一半时按总用时计"),hZ=500;function gZ(e){const t=Number(e.completionTokens)||0,a=Number(e.durationMs)||0;if(t<=0||a<=0)return"";const o=Number(e.firstResponseMs),c=Number.isFinite(o)&&o>0&&o=hZ&&c*2>=a,f=t/((d?c:a)/1e3);return`${f>=100?Math.round(f):f.toFixed(1)} tok/s`}function xZ(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"-":K0(t)}function Sx(e){return Cs().wbUnits?.formatTokens?.(e)??(Number(e)||0).toLocaleString("zh-CN")}function bZ(e){const t=Math.max(0,Date.now()-(Number(e)||0));return r("{n}秒",{n:Math.max(1,Math.floor(t/1e3))})}function vZ(e){const t=Number(e.promptTokens)||0;return t<=0?"-":`${((Number(e.cacheReadTokens)||0)/t*100).toFixed(2)}%`}function Y0(e){const t=Number(e.status)||0;return t>=200&&t<300&&!e.error}function yp(e){return(Number(e?.status)||0)===0&&!e?.error}const dI=e=>String(e?.id||e?.ts||"");function yZ(e){return(Array.isArray(e?.attemptDetails)?e.attemptDetails:[]).reduce((a,o)=>{const c=o?.retries;return a+(Array.isArray(c)?c.length:0)},0)}function fI(e){return Cs().wbProviders?.labelOf?.(e)||e}function jZ(e){const t=new Set;return e.map((a,o)=>{const c=dI(a)||`i${o}`;let d=c,f=1;for(;t.has(d);)d=`${c}#${f++}`;return t.add(d),d})}async function pI(){if(!(Date.now()-q0({value:String(o?.id||""),label:String(o?.label||o?.id||"")})).filter(o=>o.value),a=(Array.isArray(e?.models)?e.models:[]).map(o=>String(o||"")).filter(Boolean);qu?.setFilterOptions(t,a)}catch(e){console.warn("读取请求日志筛选清单失败,筛选项退化为「全部」:",_0(e))}}}async function wZ(){if(!F0)try{const e=await Cs().workbuddyDesktop?.getScheduledTasks(),t=(e?.tasks||[]).find(a=>a.id==="requestsAutoRefresh");X0(t||null),F0=Array.isArray(e?.tasks)}catch(e){console.warn("读取请求日志自动刷新间隔失败,按默认 1 秒:",_0(e)),X0(null)}}function X0(e){F0=!0;const t=Number(e?.interval),a=e?.unit;!!e&&typeof e=="object"&&Number.isFinite(t)&&t>0&&(a==="seconds"||a==="minutes")?(wx=e.enabled!==!1,jx=a==="minutes"?t*6e4:t*1e3):(wx=!0,jx=JD),qu?.setAuto({ms:jx,enabled:wx})}function SZ(){if(iI)return;const e=Cs().wbColSettings;e&&(iI=!0,G0=e.register({id:"requests",label:r("请求日志表"),columns:z0.map(({key:t,label:a,align:o})=>({key:t,label:a,align:o})),mount:()=>document.querySelector('.page[data-page="requests"] .panel-head .head-actions'),onChange:()=>{ks.flushSync(()=>qu?.repaint()),Cs().wbTableColumns?.repaint?.("requests")}}))}function Q0(){return(G0?G0.apply(z0):z0).map(t=>({...t,align:t.align||"left"}))}const NZ={entries:[],total:0,matched:0,running:0,loaded:!1,error:""};function kZ(e){return e.loaded?e.total?r("没有符合筛选条件的请求"):r("暂无请求日志,网关还没有转发过请求"):r("正在加载请求日志…")}function CZ(e){const t=Number(e.firstResponseMs);return!Number.isFinite(t)||t<=0?null:s.jsx("span",{className:"req-dur-line sub",title:r("首响:上游首帧到达的耗时(请求仍在转发中)"),children:r("首响 {time}",{time:K0(t)})})}function TZ(e,t){const{align:a,key:o}=t,c=t.sel.slice(1)+(o==="dur"?" req-num":""),d=`${c} ta-${a}`;switch(o){case"time":{if(!e.ts)return s.jsx("span",{className:d,children:"—"},o);const f=new Date(e.ts),p=g=>String(g).padStart(2,"0");return s.jsxs("span",{className:d,children:[s.jsx("span",{children:`${f.getFullYear()}-${p(f.getMonth()+1)}-${p(f.getDate())}`}),s.jsx("span",{children:`${p(f.getHours())}:${p(f.getMinutes())}:${p(f.getSeconds())}`})]},o)}case"target":{const f=String(e.provider??"").trim(),g=String(e.providerLabel??"").trim()||(f?fI(f):"");return s.jsxs("span",{className:d,children:[g?s.jsx("span",{className:"req-provider",title:f&&f!==g?r("{name}({id})",{name:g,id:f}):g,children:g}):s.jsx("span",{className:"req-provider is-empty",title:r("这条明细没有记录提供商(旧数据或请求未走到转发)"),children:"—"}),e.accountName?s.jsx("span",{className:"req-acct",title:e.accountId||e.accountName,children:e.accountName}):s.jsx("span",{className:"req-acct is-empty",title:r("请求在任何账号接手之前就失败了"),children:"—"})]},o)}case"retry":{const f=Number(e.attempts)||1,p=dI(e),g=[];if(e.isTest&&g.push(s.jsx(ze,{variant:"brand",shape:"tag",title:r("这条明细是一次模型测试(人工发起):走的是真实转发链路,但不计入报表统计"),children:r("测试")},"test")),Cs().wbRequestHover?.hasProcessFacts?.(e)??f>1){const y=f>1?f:yZ(e);g.push(s.jsx(ze,{variant:"warning",shape:"tag",render:s.jsx("button",{type:"button"}),className:"req-hover-tag","data-req-hover":"chain","data-req-id":p,children:y>1?r("重试 {n}",{n:y}):r("重试")},"chain"))}return Array.isArray(e.sensitiveHits)&&e.sensitiveHits.length&&g.push(s.jsx(ze,{variant:"sensitive",shape:"tag",render:s.jsx("button",{type:"button"}),className:"req-hover-tag","data-req-hover":"sensitive","data-req-id":p,"aria-label":r("命中了敏感词"),children:r("敏")},"sensitive")),g.length?s.jsx("span",{className:d,children:g},o):s.jsx("span",{className:`req-none ta-${a}`,children:"-"},o)}case"status":{if(yp(e)){const v=window.wbRequestPhase;if(!v?.badgeHtml)return s.jsx("span",{className:d,children:s.jsx("span",{className:"req-status-badge",children:s.jsxs(ze,{shape:"tag",variant:"info",title:r("请求正在转发中,用时列显示的是已用时"),children:[s.jsx(ay,{className:"req-live-dot","aria-hidden":"true"}),r("进行中")]})})},o);const y=v.elapsedLineHtml?.(e)??"";return s.jsxs("span",{className:d,children:[s.jsx("span",{className:"req-status-badge",dangerouslySetInnerHTML:{__html:v.badgeHtml(e)}}),y?s.jsx("span",{className:"req-status-line",dangerouslySetInnerHTML:{__html:y}}):null]},o)}const f=Number(e.status)||0,p=Y0(e),g=!p&&f>=200&&f<300?r("HTTP {status},但响应体阶段出错:见错误列",{status:f}):void 0;return s.jsx("span",{className:d,children:s.jsx(ze,{shape:"tag",variant:p?"success":"destructive",title:g,children:f||r("失败")})},o)}case"model":{const f=String(e.clientModel??"").trim(),p=String(e.upstreamModel??"").trim(),g=String(e.model??"").trim(),v=String(e.clientReasoning??"").trim(),y=String(e.upstreamReasoning??"").trim(),b=(S,N)=>N?`${S}(${N})`:S;if(!f||!p||p.toLowerCase()===f.toLowerCase()){const S=b(g,y||v);return s.jsx("span",{className:d,title:S,children:S||"—"},o)}const j=b(p,y),w=b(f,v);return s.jsxs("span",{className:`${d} req-model-split`,children:[s.jsxs("span",{className:"req-model-line",title:r("转发到上游的模型:{model}",{model:j}),children:["⬆️ ",j]}),s.jsxs("span",{className:"req-model-line sub",title:r("下游请求的模型:{model}",{model:w}),children:["⬇️ ",w]})]},o)}case"client":{const f=String(e.client??"").trim();if(!f)return s.jsx("span",{className:`${d} is-empty`,title:r("这条明细没有记录来源客户端(旧数据、模型测试,或请求未带 User-Agent)"),children:"—"},o);const p=f==="other"?r("其它"):f;return s.jsx("span",{className:d,title:f==="other"?r("识别到 User-Agent,但不属于已知的客户端类型:{ua}",{ua:f}):r("来源客户端:{client}",{client:p}),children:p},o)}case"dur":return yp(e)?s.jsxs("span",{className:d,children:[s.jsx("span",{className:"req-dur-line",title:r("已用时(请求仍在转发中)"),children:bZ(e.ts)}),CZ(e)]},o):s.jsxs("span",{className:d,children:[s.jsx("span",{className:"req-dur-line",children:K0(e.durationMs)}),s.jsx("span",{className:"req-dur-line sub",title:r("首响:上游首帧到达的耗时"),children:r("首响 {time}",{time:xZ(e.firstResponseMs)})})]},o);case"usage":{if(yp(e))return s.jsx("span",{className:d},o);if(!Y0(e))return s.jsxs("span",{className:d,title:r("失败请求不记录用量"),children:[s.jsx("span",{className:"req-usage-line",children:"in: - / out: - / all: -"}),s.jsx("span",{className:"req-usage-line sub",children:r("缓存读取: - / 命中率: -")})]},o);const f=`in: ${Sx(e.promptTokens)} / out: ${Sx(e.completionTokens)} / all: ${Sx(e.totalTokens)}`,p=r("缓存读取: {cache} / 命中率: {rate}",{cache:Sx(e.cacheReadTokens),rate:vZ(e)}),g=gZ(e),v=g?`${p} · ${g}`:p;return s.jsxs("span",{className:d,title:[f,v].filter(Boolean).join(` +`),children:[s.jsx("span",{className:"req-usage-line",children:f}),s.jsxs("span",{className:"req-usage-line sub",children:[p,g?s.jsxs("span",{title:mZ,children:[" · ",g]}):null]})]},o)}case"error":return yp(e)?s.jsx("span",{className:d},o):e.error?s.jsx("span",{className:d,title:String(e.error),children:String(e.error)},o):s.jsx("span",{className:`req-none ${c} ta-${a}`,children:"-"},o);case"detail":{const f=e.id?String(e.id):"";return f?s.jsx("span",{className:d,children:s.jsx(se,{size:"sm",variant:"outline",className:"req-detail-btn",title:r("查看该请求的上游原始报文"),onClick:()=>{Cs().wbRequestDetail?.open?.(f,e)},children:r("详情")})},o):s.jsx("span",{className:`req-none ${c} ta-${a}`,children:"-"},o)}default:return null}}function EZ(e){return s.jsx("div",{className:"req-head",children:e.map(t=>s.jsx("span",{"data-col":t.key,className:`${t.sel.slice(1)}${t.key==="dur"?" req-num":""} ta-${t.align}`,children:t.label},t.key))},"__head")}function AZ(){const[e,t]=x.useState(NZ),[a,o]=x.useState(()=>cI()),[c,d]=x.useState(()=>en.range),[f,p]=x.useState(!1),[g,v]=x.useState(0),[y,b]=x.useState(()=>en.size),[j,w]=x.useState(()=>({ms:jx,enabled:wx})),[S,N]=x.useState([]),[k,E]=x.useState([]),[,D]=x.useState(0),C=x.useRef(null),A=x.useRef(null),R=x.useRef(!1),I=x.useCallback(ee=>(en.filters={...en.filters,...ee},o({...en.filters}),en.filters),[]),P=x.useCallback(ee=>{en.range=ee,d(ee)},[]),O=x.useCallback(ee=>{en.offset=ee,v(ee)},[]),_=x.useCallback(ee=>{en.runningOnly=ee,p(ee)},[]),L=x.useCallback(()=>{U0||!Cs().wbFilterMemory||(U0=!0,!lI&&I(cI()))},[I]),H=x.useCallback((ee,fe)=>{Cs().wbRequestHover?.beforeListRedraw?.(),fe&&(V0=fe),R.current=!0,t(ee)},[]),B=x.useCallback(ee=>{Cs().wbRequestHover?.beforeListRedraw?.(),R.current=!0,t(fe=>({...fe,error:ee}))},[]),z=x.useCallback(async(ee={})=>{const{silent:fe=!1,resetPage:te=!1}=ee;te&&O(0),wZ(),L(),fe||pI();const Ce=++oI;try{const re=Cs().workbuddyDesktop;if(!re)throw new Error(r("后端桥不可用"));const de=await re.getStatsRequests(pZ());if(Ce!==oI)return;const ke={entries:Array.isArray(de?.entries)?de.entries:[],total:Number(de?.total)||0,matched:Number(de?.matched)||0,running:Number(de?.running)||0,loaded:!0,error:""},Ee=Math.max(0,(Math.ceil(ke.matched/en.size)-1)*en.size);if(en.offset>Ee)return O(Ee),z({silent:fe});te&&(A.current=0),H(ke,ke.entries)}catch(re){fe||(console.warn("读取请求日志失败:",_0(re)),B(r("读取请求日志失败,详见控制台")))}},[O,H,B,L]);x.useEffect(()=>(qu={load:z,setAuto:ee=>w(ee),setFilterOptions:(ee,fe)=>{N(ee),E(fe)},repaint:()=>D(ee=>ee+1)},Cs().wbRequestHover?.bind?.({host:C.current,entryOf:ee=>{const fe=ee?.dataset?.reqId||"";return fe&&(V0.find(te=>String(te?.id||"")===fe)||V0.find(te=>String(te?.ts||"")===fe))||null}}),z({silent:!0}),pI(),()=>{qu=null}),[z]),x.useLayoutEffect(()=>{SZ(),D(ee=>ee+1)},[]);const Q=e.error||!e.entries.length?"":Q0().map(ee=>ee.key).join("|");x.useLayoutEffect(()=>{Q&&Cs().wbTableColumns?.repaint?.("requests")},[Q]),x.useEffect(()=>{if(!j.enabled||j.ms<=0)return;const ee=window.setInterval(()=>{document.hidden||Cs().wbApp?.currentPage!=="requests"||$0||($0=!0,z({silent:!0}).finally(()=>{$0=!1}))},j.ms);return()=>{window.clearInterval(ee)}},[j,z]),x.useLayoutEffect(()=>{R.current&&(R.current=!1,Cs().wbRequestHover?.afterListRedraw?.());const ee=A.current;if(ee===null)return;A.current=null;const fe=C.current;fe&&(fe.scrollTop=ee)});function K(ee){const fe=Math.max(1,Math.ceil(e.matched/en.size)),Ce=(Math.min(Math.max(1,ee),fe)-1)*en.size;Ce!==en.offset&&(O(Ce),A.current=0,z())}function X(ee){const fe=eI(ee);if(fe===en.size)return;en.size=fe,b(fe),rg("requests",fe);const te=en.offset+1;O(Math.max(0,Math.floor((te-1)/fe)*fe)),A.current=0,z()}function q(ee){lI=!0,fZ(I(ee)),z({resetPage:!0})}function $(ee){const fe=B0.includes(ee)?ee:H0;fe!==en.range&&(P(fe),dZ(fe),z({resetPage:!0}))}function Y(ee){ee!==en.runningOnly&&(_(ee),z({resetPage:!0}))}const F=Q0(),G=Math.max(1,Math.ceil(e.matched/en.size)),W=Math.min(G,Math.floor(g/en.size)+1),le=e.matched?g+1:0,M=e.matched?g+e.entries.length:0,U=e.error?"—":e.matched===e.total?r("{n} 条",{n:e.total}):r("{matched} / {total} 条",{matched:e.matched,total:e.total}),Z=!f&&e.running>0?r(" · {n} 进行中",{n:e.running}):"",ae=[aZ[c]||r("全部")];f?ae.push(r("只看进行中")):a.status==="ok"?ae.push(r("只看成功")):a.status==="error"&&ae.push(r("只看失败")),a.provider&&ae.push(fI(a.provider)),a.model&&ae.push(a.model);const ce=x.useMemo(()=>!a.provider||S.some(ee=>ee.value===a.provider)?S:[{value:a.provider,label:a.provider},...S],[a.provider,S]),J=x.useMemo(()=>!a.model||k.includes(a.model)?k:[a.model,...k],[a.model,k]),ie=jZ(e.entries),ge=e.entries.map((ee,fe)=>s.jsx("div",{className:`req-row${yp(ee)?" running":Y0(ee)?"":" failed"}`,children:F.map(te=>TZ(ee,te))},ie[fe]));return s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("请求日志列表")}),s.jsx(ze,{id:"req-badge",variant:"outline","data-tone":"",children:U+Z}),s.jsx("span",{className:"panel-sub",children:r("按时间倒序,全量保留")}),s.jsx("div",{className:"head-actions",children:s.jsx(se,{id:"btn-req-clear",variant:"destructive",onClick:()=>{Cs().wbRequestClearModal?.open?.()},children:r("清理")})})]}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"log-filters",children:[s.jsx(In,{options:oZ,value:c,onValueChange:$,"aria-label":r("请求日志时间范围"),className:"shrink-0"}),s.jsxs(ft,{value:a.status,disabled:f,onValueChange:ee=>q({status:String(ee??"")}),children:[s.jsx(mt,{id:"req-status",className:"min-w-[120px]",title:r(f?"「仅看进行中」开启时,状态固定为进行中":"按请求结果筛选"),"aria-label":r("按请求结果筛选"),children:s.jsx(pt,{children:sI.find(ee=>ee.value===a.status)?.label??iZ})}),s.jsx(ht,{children:sI.map(ee=>s.jsx(qe,{value:ee.value,children:ee.label},ee.value))})]}),s.jsxs(ft,{value:a.provider,onValueChange:ee=>q({provider:String(ee??"")}),children:[s.jsx(mt,{id:"req-provider",className:"min-w-[120px]",title:r("按提供商筛选(只列日志里出现过的)"),"aria-label":r("按提供商筛选"),children:s.jsx(pt,{children:a.provider?ce.find(ee=>ee.value===a.provider)?.label||a.provider:rI})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"",children:rI}),ce.map(ee=>s.jsx(qe,{value:ee.value,children:ee.label},ee.value))]})]}),s.jsxs(ft,{value:a.model,onValueChange:ee=>q({model:String(ee??"")}),children:[s.jsx(mt,{id:"req-model",className:"min-w-[120px]",title:r("按模型筛选(只列日志里出现过的;精确匹配模型名)"),"aria-label":r("按模型筛选"),children:s.jsx(pt,{children:a.model||aI})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"",children:aI}),J.map(ee=>s.jsx(qe,{value:ee,children:ee},ee))]})]}),s.jsx(k6,{id:"btn-req-running",variant:"outline",size:"default",pressed:f,onPressedChange:Y,title:r("只显示正在转发中的请求(状态列按阶段显示:连接中 / 等待响应 / 响应中 / 重试中,用时列显示已用时)"),children:r("仅看进行中")}),s.jsx("div",{className:"spacer"}),s.jsx("span",{className:"panel-sub",id:"req-summary",children:ae.join(" · ")})]}),s.jsx("div",{className:"log-list",id:"req-list",ref:C,children:e.error?s.jsx("div",{className:"log-empty",children:e.error}):e.entries.length?[EZ(F),...ge]:s.jsx("div",{className:"log-empty",children:kZ(e)})})]}),s.jsx(Li,{total:e.matched,range:{start:le,end:M},page:W,pageCount:G,size:y,sizes:sZ,onSizeChange:X,onPageChange:K,disabled:!e.loaded&&!e.error})]})}async function mI(e={}){await qu?.load(e)}function RZ(){return uI().toString()}function OZ(){return q0=0,mI({resetPage:!0})}const hI='.page[data-page="requests"]';let gI=!1;function xI(){if(gI)return;const e=document.querySelector(hI);e&&(gI=!0,e.replaceChildren(),vn.createRoot(e).render(s.jsx(AZ,{})))}document.querySelector(hI)?xI():document.addEventListener("DOMContentLoaded",xI,{once:!0}),window.wbRequestsPanel={load:mI,applyAutoRefresh:X0,visibleColumns:Q0,clearParams:RZ,notifyCleared:OZ},window.wbRequestPhase={labelOf:ZD,badgeHtml:tZ,elapsedLineHtml:nZ,elapsedText:WD,phaseOf:L0};function MZ(e){if(e.status==="loading")return Ut.appLoading;if(e.status==="unavailable")return Ut.modelsDevUnavailable;const t=e.source==="builtin"?Ut.modelsDevSourceBuiltin:e.source==="cache"?Ut.modelsDevSourceCache:e.source==="network"?Ut.modelsDevSourceNetwork:e.source,a=e.updatedAt>0?String(tt().wbApp?.formatTime?.(e.updatedAt)??""):"";if(!t&&!a&&!e.count)return Ut.modelsDevEmpty;const o=a?r(",{time}",{time:a}):"",c=e.enabled?r("正在联网更新"):r("仅用现有数据、不联网刷新");return r("{count} 条 · 来自{origin}{at} · {mode}",{count:Number(e.count).toLocaleString("zh-CN"),origin:t||r("未知来源"),at:o,mode:c})}function tt(){return window}function _t(e){return e instanceof Error?e.message:String(e)}function Ve(e,t){tt().wbApp?.toast?.(e,t)}async function DZ(e){try{await tt().workbuddyDesktop?.openReleasePage?.(e)}catch(t){Ve(r("打开链接失败:{error}",{error:_t(t)}),"err")}}const Nx=[{id:"general",label:r("通用"),icon:"sliders"},{id:"display",label:r("显示"),icon:"display"},{id:"gateway",label:r("网关"),icon:"traffic"},{id:"routing",label:r("路由"),icon:"route"},{id:"retry",label:r("重试"),icon:"refresh"},{id:"timeout",label:r("超时"),icon:"timer"},{id:"security",label:r("安全"),icon:"shield"},{id:"data",label:r("数据"),icon:"database"},{id:"feedback",label:r("反馈与需求"),icon:"feedback"},{id:"about",label:r("更新"),icon:"download"}],bI="workbuddy-desktop-settings-cat",IZ="workbuddy-desktop-theme",PZ="workbuddy-desktop-zoom",vI="wb:theme",yI="wb:zoom",Z0=80,jI=130,kx=5,_Z=Array.from({length:(jI-Z0)/kx+1},(e,t)=>Z0+t*kx),LZ=[{value:"system",label:r("跟随系统")},{value:"light",label:r("浅色")},{value:"dark",label:r("深色")}];function zZ(){try{const e=localStorage.getItem(IZ);return e==="light"||e==="dark"?e:"system"}catch{return"system"}}function BZ(){try{const e=localStorage.getItem(PZ);if(e===null||e.trim()==="")return 100;const t=Number(e);if(!Number.isFinite(t))return 100;const a=Math.round(t/kx)*kx;return Math.min(jI,Math.max(Z0,a))}catch{return 100}}const W0=1,J0=99999,eS=[{key:"logRetentionDays",id:"settings-retention-log",label:r("事件日志保留天数"),unit:r("天"),min:W0,max:J0,hint:r("登录 / 账号切换 / 429 切换等系统事件,可填 1–99999 天。")},{key:"requestLogRetentionDays",id:"settings-retention-request",label:r("请求日志保留天数"),unit:r("天"),min:W0,max:J0,hint:r("「请求日志」页的逐条请求记录,默认 99999 天(近似全量保留),可填 1–99999 天。")},{key:"dailyAggregateRetentionDays",id:"settings-retention-daily",label:r("按天聚合保留天数"),unit:r("天"),min:W0,max:J0,hint:r("报表页的热力图与按天趋势,默认 99999 天(近似全量保留),可填 1–99999 天。")}],wI=[{key:"retryCount",id:"settings-retry-count",label:r("同一账号重试次数"),unit:r("次"),min:0,max:10,hint:r("在同一个账号上原地重发几次(不含首发;整条请求共用一份,用完后换来的账号只发一次就继续换)。可填 0–10,0 表示失败立即换号。")},{key:"retryCrossProviderCount",id:"settings-retry-cross-provider-count",label:r("切换账号重试次数"),unit:r("次"),min:0,max:10,hint:r("失败后最多再换几个账号试(填 N = 最多换 N 个,首发那个不算)。换到同一家名下另一个账号、或换到另一家,都各算一次;换满仍失败就返回错误。可填 0–10,0 表示失败立即报错。")},{key:"retryIntervalSeconds",id:"settings-retry-interval",label:r("重试间隔"),unit:r("秒"),min:0,max:300,hint:r("两次重试之间的等待时间,两项共用,可填 0–300 秒。")}],SI=[{key:"connectTimeoutSeconds",id:"settings-timeout-connect",label:r("连接中超时"),unit:r("秒"),min:1,max:3600,hint:r("建立上游 TCP/TLS 连接或代理隧道的最大等待时间(秒),默认 30 秒,范围 1~3600。")},{key:"headersTimeoutSeconds",id:"settings-timeout-headers",label:r("等待响应超时"),unit:r("秒"),min:1,max:3600,hint:r("请求发出后等待上游响应头的最大时间(秒),默认 300 秒,范围 1~3600。")},{key:"streamIdleTimeoutSeconds",id:"settings-timeout-stream-idle",label:r("流式响应空闲超时"),unit:r("秒"),min:1,max:3600,hint:r("流式响应相邻数据之间允许的最大空闲时间(秒),收到新数据后重新计时,默认 300 秒,范围 1~3600。")},{key:"bodyTimeoutSeconds",id:"settings-timeout-body",label:r("非流式响应超时"),unit:r("秒"),min:1,max:3600,hint:r("读取完整非流式响应体允许的最大时间(秒),默认 300 秒,范围 1~3600。")}],NI=[{key:"queueMaxWaits",id:"settings-queue-max-waits",label:r("排队等待次数"),unit:r("次"),min:0,max:10,hint:r("上游模型繁忙时会先排队(回一句「建议 N 秒后再来」,Qoder 免费模型就是这样):网关等一会儿再发同一请求,最多等几次。默认 2 次,可填 0–10;填 0 表示不等待,排队直接返回 503 并说明「不是登录态或额度问题」。")},{key:"queueWaitSeconds",id:"settings-queue-wait-seconds",label:r("排队等待秒数"),unit:r("秒"),min:0,max:120,hint:r("每次等待的时长,默认 0 = 跟随上游建议(实测 9~30 秒,上游没给建议时用 15 秒)。可填 0–120 秒强制一个固定时长。")}],kI="noRetryStatusCodes",tS=100,nS=599,CI=50,zo=[{value:"passthrough",optionLabel:r("透传客户端 system(默认)"),toastLabel:r("透传客户端 system")},{value:"custom",optionLabel:r("替换为网关提示词"),toastLabel:r("替换为网关提示词")},{value:"append",optionLabel:r("追加网关提示词"),toastLabel:r("追加网关提示词")}];function TI(e,t,a,o){const c=String(e??"").trim();if(!c)return{ok:!1,message:r("{noun}不能为空(可填 {min}–{max})",{noun:o,min:t,max:a})};if(!/^\d+$/.test(c))return{ok:!1,message:r("{noun}必须是整数",{noun:o})};const d=Number(c);return da?{ok:!1,message:r("{noun}必须在 {min}–{max} 之间(当前填的是 {text})",{noun:o,min:t,max:a,text:c})}:{ok:!0,value:d}}function HZ(e,t){const a={...t};if(e&&typeof e=="object"){const o=e;typeof o.closeToTray=="boolean"&&(a.closeToTray=o.closeToTray),typeof o.autostart=="boolean"&&(a.autostart=o.autostart),typeof o.lanAccess=="boolean"&&(a.lanAccess=o.lanAccess),typeof o.lanPanel=="boolean"&&(a.lanPanel=o.lanPanel),typeof o.lightweightMode=="boolean"&&(a.lightweightMode=o.lightweightMode)}return a}function EI(e,t,a){if(!t||typeof t!="object")return null;const o=t,c={...a||{}};for(const d of e){const f=Number(o[d.key]);Number.isInteger(f)&&f>=d.min&&f<=d.max&&(c[d.key]=f)}return e.some(d=>Number.isInteger(c[d.key]))?c:null}function AI(e){if(!Number.isFinite(e)||e<=0)return"0 B";if(e<1024)return`${e} B`;const t=e/1024;if(t<1024)return`${t.toFixed(1)} KB`;const a=t/1024;return a<1024?`${a.toFixed(1)} MB`:`${(a/1024).toFixed(2)} GB`}function UZ(e){const t=Number(e);return!Number.isFinite(t)||t<0?"—":t.toLocaleString("zh-CN")}const ss={displayTheme:r("控制界面的深浅色,与左侧边栏底部的三个主题按钮是同一个设置(改哪一处,另一处立刻跟上)。「跟随系统」会随操作系统当前的浅色 / 深色自动切换,并在系统主题变化时即时跟上;选「浅色」或「深色」则把界面固定在该模式,不再随系统变化。窗口标题栏的深浅色会一并同步,不会出现深色界面配一条浅色标题栏的情况。"),displayZoom:r("等比放大或缩小整个界面(文字、控件、间距一起变),效果与浏览器按 Ctrl +/- 相同:80%–130%、5% 一档。窗口本身不缩放,变的是页面内容的显示比例,设置立即生效并记住,下次启动直接按这个比例打开。放得越大可视范围越小,窗口较窄或表格较宽时不建议调得太大。"),displayLanguage:r("界面语言。可选简体中文、繁體中文、English、日本語、한국어、Português (Brasil),或「跟随系统」(按浏览器 / 系统的语言列表自动选)。切换后整页立即刷新;该偏好只存在本机(localStorage),不影响账号、密钥与转发。"),tray:r("默认关闭窗口不会退出程序,而是把窗口缩到系统托盘,转发继续在后台运行(OpenAI 客户端不受影响);要彻底退出程序,请在托盘图标上右键选「退出」。关掉这个开关后,点关闭按钮即退出程序、转发随之中断。「开机自动启动」开启后,登录系统时会自动启动本程序(通常直接驻留托盘),不需要手动打开。"),lightweight:r("开启后,关闭窗口不只是隐藏,而是把界面窗口整个销毁:底层的 WebView2 六个常驻进程(约 200MB 内存)随之退出,网关转发、定时签到、余额查询都在后台进程里继续,不受影响;需要界面时点托盘图标重新打开(WebView 冷启动约 1 秒)。注意:界面销毁期间「ZCode 活动套餐」通道的验证码令牌由界面铸造,无法补充 —— 走该通道的请求会以 503 落进请求日志(写明原因),重新打开界面即自动恢复。此开关只在「关闭窗口时最小化到托盘」开启时有意义,最小化窗口不受影响。"),lan:r("默认网关只监听 127.0.0.1,只有本机能访问。开启后网关改听所有网卡,同一局域网内的设备可以把 API 地址指向本机 IP 一起使用。出于安全考虑,开启前必须先注册一个面板管理员:管理接口从此要求管理员会话或网关 Key,模型额度不会对局域网裸奔;一把启用的网关 Key 都没有时,转发接口也会拒绝服务,直到创建第一把。改动需要重启应用生效。「同时开放网页管理面板」把管理界面也出给局域网(其他设备的浏览器打开本机 IP 即可管理),默认关闭 —— 桌面端的面板仍只由本程序自己出。"),units:r("控制报表与请求日志里 Token 读数的写法:开启后按中文量级显示(1.2亿 / 8400万),关闭则用 k / M 缩写(与上游文档、接口字段的写法一致)。这只影响显示口径,不改变任何统计与存储的数值。"),queue:r("只对「排队制」的上游生效(目前是 Qoder 的免费模型):模型繁忙时上游不报错,只回一句「建议 N 秒后再来」(业务码 10605),网关按建议时长等一会儿再发同一请求,等满次数仍排不上才把「排队中」作为错误返回(HTTP 503,文案会说明这不是登录态或额度问题)。等待发生在首个字节之前,吃的是「等待响应超时」那份预算 —— 两项设置一起决定一次请求最多卡多久;排队不会标记账号限额、也不会换账号(换谁都一样在排队)。保存后对下一个请求立即生效,不用重启。"),captchaPool:r("ZCode「活动套餐」通道的每条推理请求都要附一个当次铸造的阿里云无痕验证令牌(一次性、约 2 分钟过期):令牌由界面里的铸造守卫静默铸好、推给网关入池,转发时逐条取用。这里的三个值管的是补货节奏:①「库存目标」= 库存低于它守卫才补铸、补到它为止,默认 3 个;②「轮询间隔」= 守卫多久看一次库存,默认 2500 毫秒,只影响反应速度(库存够用时不会多铸);③「单轮铸造上限」= 发现缺货时一轮最多铸几个,默认 1 个(连铸之间固定隔 500 毫秒)。请求密集、请求日志里连续出现「需要人机验证令牌」的 503 时,把目标与单轮上限适当调大、轮询调快,能让池子跟得上消耗 —— 代价是上游(阿里云)对铸造频率有风控,铸得越多越快越容易触发限流,且用不掉的令牌 2 分钟即过期作废、等于白烧配额,所以建议小步调。保存后对下一轮补货立即生效,不用重启。"),timeouts:r("上游请求四个阶段各自的等待上限(秒,1~3600):①「连接中超时」= 建立 TCP/TLS 连接或代理隧道的最大等待,默认 30 秒;②「等待响应超时」= 请求发出后等上游响应头的最大时间,默认 300 秒 —— 网关请求上游恒带 stream,响应头在 SSE 建立时就到达,与模型思考多久无关;③「流式响应空闲超时」= 流式响应相邻两块数据之间允许的最大空闲,收到新数据即重新计时,默认 300 秒 —— 上游长时间不吐数据即判定连接僵死并断开;④「非流式响应超时」= 读完整份非流式响应体的总预算(一次性计时、不重置),默认 300 秒。四项都是「等待上限」,只要数据还在来,正常的流式回答就一直往下传。保存后对下一个请求立即生效,不用重启。"),retry:r("请求转发到上游失败时(服务器瞬时错误、连接失败,以及 WorkBuddy 的 11-128 敏感词拦截),网关会等一段间隔后再发一次。次数分两档,管的是两件事:①「同一账号重试次数」在同一账号上原地重发几次 —— 一般是提示词被上游拦截、或链路瞬时抖动,等一会儿重发往往就好了;②「切换账号重试次数」这份请求最多再换几个账号试 —— 首发的那个账号不算,每换一个扣一次,不分是不是同一家(换到同一家的下一个账号也算一次),换满还失败就把错误返回给客户端。两项都设为 0 表示失败不重试、直接报错。注意账号级限额(429)不占这里的换号次数 —— 那类失败走「冷却该账号并换下一个账号」的降级,与这里的重试是两条路。另有「指定错误码直接换号」名单(默认 402):命中名单的上游状态码不在同一账号重发,直接按队列换下一个账号继续试(换号也占「切换账号重试次数」),换满仍失败才把错误返回给客户端。"),routing:r("转发一个请求时按什么顺序挑账号:①「路由策略」决定排队规则 —— 顺序优先是排第 1 的接走所有请求、直到它不能答(限流 / 故障 / 额度尽)才轮到下一位;负载均衡是每条请求换下一位,把负载摊到各个账号上。②「会话粘性」让同一会话(相同的模型 + 相同的开头消息)尽量跟住同一个账号 —— 多轮对话的上下文缓存能复用、少换号少浪费;自动档粘 5 分钟、会话内档粘 6 小时、每轮与关闭都不粘。账号的排队位次(账号表的第一列)在所有策略下都是地基,策略在它之上再排。此外路由还有三层自愈保护:转发失败的账号退避休息一会儿(15 分钟起步翻倍、封顶 1 小时)、被 429 的账号垫底排到队尾 30 分钟、余额不足 / Token 周期用量到顶的账号由限制器拦下 —— 前两层可以在下面按需开关,限制器由账号的「限制器」设置管。"),sanitize:r("上游用「逐字精确匹配」的方式审核请求体(不是语义审核):客户端注入的固定模板句、计费头字段名、以及某些裸错误码出现在报文里就会整单拦截,返回 400。开启本项后,网关在每次转发前改写这些指纹 —— 表头键值整段删除,承载语义的模板句只换一个词(如 official CLI for Claude → official CLI tool for Claude),对话内容与语义都不受影响。规则集是内置的,不需要也无法维护词表。关掉本项后客户端模板会原样发往上游,可能重新出现模板句被误拦的报错。"),clineHeaders:r("Cline 上游按请求头判定「调用方是不是 Cline 自家产品」:X-CLIENT-TYPE: cline-sdk 是硬门槛(缺了它免费池模型一律 403),版本号与平台标识让请求更贴近官方客户端的形态。这里列出的是网关默认会发的头:改某一行的值 = 覆盖默认值(也可以新增默认清单之外的自定义头);把值清空保存 = 这个头不发送;在界面删掉被改过的行 = 回落默认值。改完点「保存」,下一个 Cline 请求立即生效。不懂某一行的含义就不要动它 —— 伪装头的价值在「与官方客户端逐字一致」。"),cors:r("网关面(/v1/*)默认不应答浏览器跨源请求:页面直连会被预检拦下,只报「无法连接 API」。注意来源是 * —— 未配「网关 Key」时任何网页都能借本机网关打上游,故默认关闭;只给自己用的话,让页面与网关同源(本地反代 /v1)更稳妥。面板接口(/api/*)不受影响。"),prompt:r("客户端(Claude Code / Codex 等 CLI)会在 system 提示词里注入几十句固定模板,上游按逐字匹配审核,命中就整单拦截(HTTP 400)。指纹脱敏能改写实测命中过的那几句,但换一个客户端版本就可能冒出新的。这里可以把 system 整段换成网关自己那份:①「透传」= 不动客户端 system(默认,行为与之前完全一致);②「替换」= 删掉客户端所有 system / developer 消息,换成网关的提示词(客户端项目规范随之消失);③「追加」= 在开头连续 system 块之后插入一条网关提示词,既有消息逐字不动(客户端规范与网关提示词并用)。那份提示词有两个来源:提示词文件(留空用内置默认),或直接在界面上编辑正文 —— 编辑过就以那份正文为准(优先于文件),清空则回到文件 / 内置默认。另外,透传 / 追加模式下撞了内容拦截(多半是指纹误报)时,网关会自动换一段最小中性提示词重试一次,并把「降级期」开到次日 00:00 —— 期间所有请求直接带中性提示词出门,不再先撞一次 400;这里能看见并提前解除它。上面几项是**默认值**:想给某个提供商单独配,用下面的「按提供商」加一行(带「网关自带」的家默认就列在那里)—— 不同的上游对这些内容的接受程度不一样。"),debug:r("开启后,网关会把每次转发**发给上游的请求**(请求头 + 请求体)与**上游返回的响应**(状态码 + 响应头 + 响应体)完整保存到本地,供请求日志页的「详情」查看。请求头里的 Authorization、Cookie、API Key 等凭据字段一律替换成 [redacted],不会明文落盘;请求体与响应体按原样保存(可能包含你的对话内容)。报文只保留最近 500 条,超出后丢弃最旧的。这是排障用的临时开关,不需要时建议关闭。"),io:r("导出会把全部账号与自定义提供商定义写入一个 JSON 文件,可以拷到另一台机器上导入后继续使用。导入采用合并策略:同提供商下按业务身份(UID / userId / apiKey 等)去重 —— 已存在的账号只更新凭证,保留本机原有的优先级顺序;新账号追加到转发顺序末尾,不会抢占当前正在使用的账号;自定义提供商定义按 id 合并,本机缺失时自动补建。"),backup:r("把整份数据库(账号、网关配置、事件日志、请求统计、调试报文与桌面设置)导出成一个 SQL 文件,恢复时整体替换本机全部数据 —— 与上面「账号导入 / 导出」的逐条合并是两种语义:恢复会连配置、日志与当前启用状态一起换成备份那台机器的状态。导出默认包含日志与调试报文(文件可能很大),不需要时可以取消勾选只备业务数据。恢复前会自动把当前数据备份到配置目录的 backups/ 下,恢复后需要重新登录管理面板。"),retention:r("三档数据各自独立计时,超出保留天数的部分会被删除:事件日志是登录、账号切换、429 切换这类系统事件;请求日志是网关每次转发到上游的逐条记录;按天聚合供报表页的热力图与按天趋势使用。请求日志与按天聚合默认 99999 天(约 274 年,效果上等于全量保留),事件日志默认 30 天。把某一档改小(例如 30 天改成 7 天)保存后会立即删除超出的历史数据,此操作不可恢复;改大或保持不变不会删除任何数据。三档的可填范围均为 1–99999 天。"),storage:r("全部数据(账号、事件日志、请求记录、调试报文、设置)统一保存在配置目录下的 agent2api.db 这一个 SQLite 数据库里。备份时只需拷贝这个文件;更换保存位置请设置环境变量 AGENT2API_PROXY_HOME 后重启程序。"),modelsDev:r("models.dev 是一个开源的模型资料库(社区维护),这里用它补齐「上游没告诉我们」的模型能力:上下文窗口、最大输出、工具调用、图片、视频、是否支持思考,以及这个模型认识哪些思考档位。优先级是:你在「模型能力」里手工改的值 > 上游清单自己声明的值 > models.dev 的值 —— 它只填上游没声明的空位,从不推翻上游已声明的。网关随包内嵌了一份快照,所以离线、首次启动、访问不通时也有数据;开启时会按「模型目录刷新」任务的间隔联网更新(同一轮里一并刷新,也可在这里立即刷新)。关闭只停联网刷新,已经拿到的数据继续用。")},$n={timeouts:r("保存后立即生效,不用重启;超时按上游失败处理(计入请求日志的「错误」列,并按「请求重试」的设置决定是否重试)。"),queue:r("等待期间请求日志的状态列会显示「排队中」阶段,详情弹窗的「内部重试」里能逐次看到等待时长;等待用尽后返回 HTTP 503(不是 401/429:既不会刷新凭证,也不会把账号标成限额)。"),captchaPool:r("保存后对下一轮补货立即生效,不用重启。守卫跑在应用界面里:轻量模式关窗销毁界面期间无法铸造,走活动套餐通道的请求会以 503 落进请求日志(写明原因),重新打开界面即自动恢复。"),retry:r("保存后立即生效,不用重启;次数用尽仍失败时,错误原样返回给客户端。"),routing:r("保存后立即生效,不用重启:策略与粘性作用于**下一次**转发的选路,进行中的请求不受影响。"),retryCodes:r("命中这些上游状态码的失败不在同一账号重发,直接换下一个账号继续试(换号占用「切换账号重试次数」,换满仍失败才把错误原样返回给客户端)。输入 100–599 的状态码后回车添加,点 × 或退格删除;默认 402(积分不足)。清空全部表示任何错误都照常重试。"),sanitize:r("默认开启。命中明细会记进请求日志的「敏」标签(悬停可看命中了哪几条规则)。本项只改发给上游的副本,客户端看到的响应内容不变。"),clineHeaders:r("值与默认值相同的行不占覆盖(存的是「改过的键」,不是全量配置);值留空保存表示这个头不发送,删除改过的行表示回落默认值。改完立即生效,不用重启。"),cors:r("默认关闭。改动立即生效,不用重启;关闭期间的跨源请求会被预检拦下。"),debug:r("开启后新发生的请求才会被记录(已经过去的请求补不回来)。报文统一存放在本地数据库里,只保留最近 500 条(超出后丢弃最旧的),条数见左侧「数据 → 数据存储」的「调试报文」。"),promptMode:r("替换 = 客户端 system / developer 消息全部删掉,换成网关的提示词;追加 = 保留客户端内容,只在开头 system 块之后多插一条。两者都只改发给上游的副本,客户端看到的响应不变。"),promptFile:r("UTF-8 文本文件路径,留空用内置默认提示词(通用编码助手提示词,不含任何会被上游拦截的模板句)。只在「替换 / 追加」模式下生效,透传模式不读它。"),promptText:r("在这里直接编辑提示词正文:保存后以这份文本为准(优先于上面的提示词文件),清空则回到文件 / 内置默认。改一个字不必再去编辑器里开文件。"),promptGatewayText:r("上游按「结构」校验身份:三段必须各自成块,所以这里分开编辑三段(不能合成一段)。动态段里的运行值写成占位符,发请求时才替换:{cwd} 工作目录、{platform} 平台、{shell} shell、{os_version} 系统版本、{git} 是否 git 仓库、{provider} 提供方标识、{model} 模型名。清空某一段 = 那一段恢复官方原文。第三段发出时前面会自带一个空行(官方形状)。"),prompt:r("改完立即生效,不用重启(下一个请求就用新模式)。降级是自动的临时状态,解除后本模式自己的提示词立刻恢复。"),promptProviders:r("「用哪份提示词」本来是按上游分别决定的事,所以每家可以有自己的模式、提示词文件与正文:不在这里列出的提供商一律沿用上面那份默认设置,「跟随默认」把这一家取消、回到默认。带「网关自带」那一行的家(目前是 ZCode 两家)默认就列在这里 —— 那一段是网关自己装上去的文本,不来自客户端也不来自提示词文件,默认开启、可以关掉,也可以改它的正文(改过的那一段以你的文本为准);关掉后还能不能通过上游校验,取决于上游当下的口径,行内说明了实测依据。「模式 / 提示词文件 / 正文」管的是客户端自己的 system 怎么处理,与那个开关是两件事。"),modelsDev:r("「模型管理」里每个能力的来源标记(上游 / models.dev / 已覆盖)读的就是这份数据;映射弹窗的思考档位下拉也按这里的数据只列该模型真实认识的档位。"),retention:r("保存后立即生效:改小保留天数会立刻删除超出的历史数据,且不可恢复。"),storageFile:r("配置目录下的 agent2api.db(账号、日志、请求记录、调试报文与设置都在里面)。"),storageSize:r("库主文件的大小(不含运行期间的 WAL 临时文件,退出时已自动并回)。"),storage:r("数据统一保存在配置目录下的 agent2api.db;如需更换位置,请设置环境变量 AGENT2API_PROXY_HOME 后重启程序。"),captcha:r("开启后,登录页在浏览器后台自动完成验证(对真人无感),而脚本每次尝试都要先算一道题 —— 暴力破解与抢注的成本显著上升。仅影响面板的登录 / 注册,与 API 客户端的 API Key 无关。"),panelLogin:r("当前浏览器以管理员身份登录着本面板。「退出登录」会撤销这台设备的登录会话(30 天内的自动续期一并失效),需要重新输入账号密码;其他已登录的设备不受影响。"),exportDanger:r("导出文件内含 accessToken / refreshToken / apiKey 等凭证与自定义提供商定义,可直接用于登录。请妥善保管,不要外传或上传到公共位置。"),backupDanger:r("备份文件内含全部账号凭证、网关 API Key 与面板管理员凭据,可直接用于登录。请妥善保管,不要外传或上传到公共位置。")},Ut={appLoading:"—",appUnavailable:r("主进程未返回启动设置,请更新桌面端后重试"),appTrayOn:r("关闭窗口时程序不退出,转发继续在后台运行;退出请用托盘菜单"),appTrayOff:r("关闭窗口即退出程序,后台转发随之中断"),appLightOn:r("轻量模式已开启:关窗即销毁界面进程(释放约 200MB 内存),网关在后台继续;界面销毁期间 ZCode 活动套餐通道不可用,相关请求会在请求日志里注明原因"),appLightOff:r("未开启轻量模式:关窗仅隐藏窗口,界面进程常驻内存,随时打开不等待"),unitsOn:r("当前显示为「1.2亿 / 8400万」这类中文量级。"),unitsOff:r("当前显示为「1.20M / 8.4k」这类英文缩写。"),debugUnavailable:r("未能读取调试模式设置,请稍后重试"),debugOn:r("正在保存上游原始报文:"),debugOff:r("未开启,转发时不保存任何原始报文。"),sanitizeUnavailable:r("未能读取指纹脱敏设置,请稍后重试"),sanitizeOn:r("正在剥离出站请求里的审核指纹:表头键值整段删除,模板句最小改写。"),sanitizeOff:r("未开启,客户端 system 模板会原样发往上游,可能被内容审核误拦(400)。"),corsUnavailable:r("未能读取网关跨域访问设置,请稍后重试"),corsOn:r("正在应答跨源请求:浏览器跨域请求可直连 /v1/*。"),corsOff:r("未开启,浏览器跨域无法直连网关。"),modelsDevUnavailable:r("未能读取 models.dev 元数据状态,请稍后重试"),modelsDevSourceBuiltin:r("随包内嵌的快照(发版时的那份)"),modelsDevSourceCache:r("上次成功刷新的结果(存在本机数据库里)"),modelsDevSourceNetwork:r("刚刚从 models.dev 拉到的最新数据"),modelsDevEmpty:r("还没有装载任何数据。"),promptUnavailable:r("未能读取系统提示词设置,请稍后重试"),degradeUntilFallback:r("次日 00:00"),themeSystem:r("当前跟随操作系统的深浅色设置,系统切换时界面会自动跟上。"),themeLight:r("当前固定为浅色模式,不随系统变化。"),themeDark:r("当前固定为深色模式,不随系统变化。"),zoomWeb:r("网页端的界面缩放由浏览器自己控制(Ctrl + / Ctrl -,或浏览器菜单里的缩放),此项不可调。"),zoomDefault:r("当前按 100% 显示(默认比例)。"),languageHint:r("界面语言只保存在本机(localStorage)。切换后整页立即刷新,不影响账号、密钥与转发。")},Cx=[{value:"order",label:r("顺序优先"),tip:r("排第 1 的接走所有请求,直到它不能答(限流 / 故障 / 额度尽)才轮到下一位 —— 就是「从上往下」的现状行为。")},{value:"rotate",label:r("负载均衡"),tip:r("每条请求轮换到下一个可用账号;新会话交给当前最闲的那位。适合想把手里的号摊开用、不让某一个一直扛。")},{value:"provider",label:r("家内轮询"),tip:r("家之间仍按优先级,只有同一家内部轮流用各账号 —— 想优先用某几家、又不愿把某一家的某个账号焊死时用它。")}],Tx=[{value:"auto",label:r("自动"),tip:r("同一会话在 5 分钟内尽量跟住同一个账号;停了 5 分钟再发就算新会话。多数场景用它 —— 多轮对话少换号,也不至于把账号焊死。")},{value:"session",label:r("会话内"),tip:r("同一会话在 6 小时内跟住同一个账号;适合一坐几个小时的长会话,上游的上下文缓存能吃到更多。")},{value:"turn",label:r("每轮"),tip:r("每条请求都重新按策略选路 —— 行为与「关闭」一致,仅保留会话识别的记录。")},{value:"off",label:r("关闭"),tip:r("不做会话识别,每条请求都重新按策略选路。")}],VZ=[{key:"routingFailoverBackoff",label:r("失败退避"),defaultOn:!0,tip:r("转发失败的账号休息一会儿再回来:15 分钟起步,连续失败翻倍,封顶 1 小时;成功一次立即恢复。目的是「让这次失败先凉一会儿」,免得一条条地反复撞同一个坏账号。")},{key:"routingSink",label:r("限流垫底"),defaultOn:!0,tip:r("还有额度时被 429 的账号排到队尾,30 分钟后自动回到队列(成功转发一次也会立即回来)。它标记的是「疑似共享池被别人抢」,不是「这个账号本身有问题」。⚠️ 注意它与路由策略的配合:在「家内轮询」下,队尾意味着这一家整体被往后排 —— 如果某个提供商的账号被批量限流,它们会集体沉到队尾,那个家可能长时间轮不到。这时可以关掉本项,让 429 过的账号只受冷却约束(冷却到点自动回来)。")},{key:"routingBreakerEnabled",label:r("熔断"),defaultOn:!1,tip:r("连续失败到阈值后把这个账号整个打开(默认关)。与失败退避的分工:退避管「单次失败先凉一会儿」,惩罚轻、自动恢复;熔断管「这个账号现在整体不对劲,别再一条条地试」,要连续成功若干次才关。打开期间该账号被跳过,除非全场只剩它 —— 那时仍放行试一次。")}],RI=[{key:"zcodeCaptchaPoolTarget",id:"settings-captcha-pool-target",label:r("库存目标"),unit:r("个"),min:1,max:10,hint:r("ZCode 活动套餐通道每条请求都要消耗一个当次铸造的人机验证令牌(一次性,2 分钟过期),库存低于该值时界面自动补铸到它。默认 3 个。调大能吸收突发并发,但用不掉的令牌 2 分钟就过期作废,烧的是上游风控配额。可填 1–10。")},{key:"zcodeCaptchaPoolPollMs",id:"settings-captcha-pool-poll-ms",label:r("轮询间隔"),unit:r("毫秒"),min:1e3,max:3e4,hint:r("铸造守卫每隔多久看一次库存(毫秒)。只影响发现缺货的反应速度 —— 库存够用时轮询不会铸造任何令牌。默认 2500 毫秒,可填 1000–30000。")},{key:"zcodeCaptchaPoolMaxPerRound",id:"settings-captcha-pool-max-per-round",label:r("单轮铸造上限"),unit:r("个"),min:1,max:5,hint:r("发现缺货时一轮最多铸几个(连铸之间固定隔 500 毫秒)。默认 1 个:SDK 同一实例连铸容易互相干扰。调大补货更快,但单轮连铸越多越容易触发上游风控。可填 1–5。")}];function OI(){return tt().workbuddyDesktop?.platform==="web"}let dt={...{category:Nx[0].id,scrollReset:0,busy:null,app:{status:"loading",closeToTray:!1,autostart:!1,lanAccess:!1,lanPanel:!1,lightweightMode:!1,lanIp:null,port:0,adminRegistered:null},unitsChinese:!0,retention:{status:"loading",values:null},retry:{status:"loading",values:null},retryCodes:null,timeouts:{status:"loading",values:null},queue:{status:"loading",values:null},captchaPool:{status:"loading",values:null},routing:{status:"loading",strategy:"order",sticky:"auto",failoverBackoff:!0,sink:!0,breakerEnabled:!1},debug:{status:"loading",on:!1,count:null,limit:null},sanitize:{status:"loading",on:!1},clineHeaders:{status:"loading",defaults:{},overrides:{},effective:{}},cors:{status:"loading",on:!1},prompt:{status:"loading",mode:"passthrough",file:"",text:"",source:"",lines:0,fileError:"",degradeActive:!1,degradeUntilText:"",providers:[],gateway:{},gatewayText:{},options:[]},storage:{status:"loading",available:!0,file:"",bytes:0,accounts:null,logs:null,requests:null,dailyDays:null,debug:null},captcha:{available:!0,enabled:!1},modelsDev:{status:"loading",enabled:!0,source:"",updatedAt:0,count:0},ioFailure:null,retentionConfirm:null,dbIncludeLogs:!0,dbBackupConfirm:null,dbWarning:null,lanConfirm:null,lanRegister:null,panelLogin:!1},panelLogin:OI()};const sS=new Set;function FZ(e){return sS.add(e),()=>{sS.delete(e)}}function $Z(){return dt}function qZ(){return x.useSyncExternalStore(FZ,$Z)}function Ze(e){dt={...dt,...e};for(const t of sS)t()}function Oa(e){Ze({app:{...dt.app,...e}})}function nl(){Ze({})}let En=null;function us(e){En=e,Ze({busy:e})}function rs(){En=null,Ze({busy:null})}function rS(e){const t=Nx.some(a=>a.id===e)?String(e):Nx[0].id;Ze({category:t,scrollReset:dt.scrollReset+1})}function GZ(e){rS(e);try{localStorage.setItem(bI,e)}catch{}}function MI(){let e=null;try{e=localStorage.getItem(bI)}catch{e=null}rS(e)}function DI(){Ze({unitsChinese:tt().wbUnits?.isChinese?.()!==!1})}function KZ(e){tt().wbUnits?.setChinese?.(e),DI(),Ve(r(e?"✅ 已改用本地量级词(万 / 亿式)":"✅ 已改用 k / M 缩写"))}function aS(e){if(e===void 0)return;if(!e||typeof e!="object"){Oa({status:"unavailable"});return}const t=e;Oa({status:"ready",closeToTray:t.closeToTray===!0,autostart:t.autostart===!0,lanAccess:t.lanAccess===!0,lanPanel:t.lanPanel===!0,lightweightMode:t.lightweightMode===!0})}async function II(){try{aS(await tt().workbuddyDesktop?.getAppSettings())}catch(e){console.warn("读取应用设置失败:",_t(e)),aS(null)}}async function YZ(){const e=tt().workbuddyDesktop;if(e?.localIp){try{Oa({lanIp:await e.localIp()||null})}catch{}try{const t=Number((await e.getBackendStatus?.())?.port)||0;t&&Oa({port:t})}catch{}try{const t=(await e.panelAdminStatus?.())?.registered===!0;Oa({adminRegistered:t})}catch{}}}async function lS(e,t){if(En){nl();return}const a=dt.app,o={closeToTray:e==="tray"?t:a.closeToTray,autostart:e==="autostart"?t:a.autostart,lanAccess:a.lanAccess,lanPanel:a.lanPanel,lightweightMode:e==="lightweight"?t:a.lightweightMode};us("app"),Oa(o);const c=r(e==="autostart"?"开机自动启动":e==="lightweight"?"轻量模式":"关闭窗口时最小化到托盘");try{const d=tt().workbuddyDesktop;if(!d)throw new Error(r("主进程桥不可用"));const f=await d.saveAppSettings(o);Oa({status:"ready",...HZ(f,o)}),Ve(r("✅ 已更新「{label}」",{label:c}))}catch(d){Oa(a),Ve(r("保存失败:{message}",{message:_t(d)}),"err")}finally{rs()}}function XZ(e){if(En){nl();return}Ze({lanConfirm:{mode:e?"enable":"disable",panel:dt.app.lanPanel}})}function QZ(e){if(En){nl();return}Ze({lanConfirm:{mode:"panel",panel:e}})}function oS(e){const t=dt.lanConfirm;if(Ze({lanConfirm:null}),!(!t||!e)){if(t.mode==="disable"){Ex(!1,!1);return}if(t.mode==="panel"){Ex(!0,t.panel);return}ZZ()}}async function ZZ(){const e=tt().workbuddyDesktop;if(!e?.panelAdminStatus){Ve(r("当前环境不支持局域网访问设置"),"err");return}us("lan");let t;try{t=(await e.panelAdminStatus())?.registered===!0}catch(a){rs(),Ve(r("查询管理员状态失败:{message}",{message:_t(a)}),"err");return}if(rs(),Oa({adminRegistered:t}),t){await Ex(!0,dt.app.lanPanel);return}Ze({lanRegister:{busy:!1,error:""}})}async function WZ(e,t){if(En)return;const a=tt().workbuddyDesktop;if(!a?.panelRegister)return;const o=e.trim();if(!o||o.length>64){Ze({lanRegister:{busy:!1,error:r("请填写管理员账号(64 字符以内)")}});return}if(t.length<8){Ze({lanRegister:{busy:!1,error:r("密码至少 8 位")}});return}Ze({lanRegister:{busy:!0,error:""}});try{if(await a.panelRegister(o,t),dt.lanRegister===null)return;Ze({lanRegister:null}),Oa({adminRegistered:!0}),await Ex(!0,dt.app.lanPanel)}catch(c){Ze({lanRegister:{busy:!1,error:_t(c)}})}}function PI(){Ze({lanRegister:null})}async function Ex(e,t){if(En)return;const a=tt().workbuddyDesktop;if(!a?.changeLanAccess){Ve(r("当前环境不支持局域网访问设置"),"err");return}us("lan"),Oa({lanAccess:e,lanPanel:t});try{(await a.changeLanAccess(e,t))?.createdKey&&Ve(r("✅ 已自动创建网关 Key「默认」(可在「网关 Key」页查看)")),Ve(r("✅ 设置已保存,应用正在重启…"))}catch(o){Ve(r("保存失败:{message}",{message:_t(o)}),"err"),await II()}finally{rs()}}async function JZ(){if(!En){Ze({ioFailure:null}),us("export");try{const e=await tt().workbuddyDesktop?.exportAccounts();if(e?.canceled){Ve(r("已取消导出"));return}const t=Number(e?.count)||0,a=Number(e?.customProviders)||0;if(!t&&!a){Ve(r("没有可导出的账号"),"err");return}const o=a?r("、{n} 个自定义提供商",{n:a}):"",c=e?.file?r(" 到 {file}",{file:e.file}):"";Ve(r("✅ 已导出 {count} 个账号{note}{file}",{count:t,note:o,file:c}))}catch(e){Ve(r("操作失败:{message}",{message:_t(e)}),"err")}finally{rs()}}}async function eW(){if(!En){Ze({ioFailure:null}),us("import");try{const e=await tt().workbuddyDesktop?.importAccounts();if(e?.canceled){Ve(r("已取消导入"));return}const t=Number(e?.added)||0,a=Number(e?.updated)||0,o=Number(e?.skipped)||0,c=Number(e?.failed)||0,d=Array.isArray(e?.errors)?e.errors:[],f=e?.customProviders??{},p=Number(f.added)||0,g=Number(f.updated)||0,v=[];o&&v.push(r("跳过 {n} 个",{n:o})),c&&v.push(r("失败 {n} 个",{n:c}));const y=v.length?r(",{items}",{items:v.join(r("、"))}):"",b=p||g?r(",自定义提供商新增 {added} 个、更新 {updated} 个",{added:p,updated:g}):"",j=r("新增 {added} 个、更新 {updated} 个{suffix}{note}",{added:t,updated:a,suffix:y,note:b});if(c){Ve(r("导入完成:{summary}",{summary:j}),"err");const w=d.slice(0,3).map(S=>{const N=S?.customProvider?r("自定义提供商 {id}",{id:S?.id||r("(无 id)")}):S?.id??r("未知账号"),k=S?.message??r("未知原因");return r("{label}({message})",{label:N,message:k})}).join(r(";"));Ze({ioFailure:{failed:c,detail:w,more:d.length>3}})}else Ve(r("✅ 导入完成:{summary}",{summary:j}));(t||a||p||g)&&await tt().wbApp?.refresh?.()}catch(e){Ve(r("操作失败:{message}",{message:_t(e)}),"err")}finally{rs()}}}function tW(e){Ze({dbIncludeLogs:e})}async function nW(){if(!En){us("dbExport");try{const e=tt().workbuddyDesktop;if(!e?.exportDatabase){Ve(r("当前环境不支持整库备份(仅桌面端可用)"),"err");return}const t=await e.exportDatabase(dt.dbIncludeLogs);if(t?.canceled){Ve(r("已取消导出"));return}const a=Number(t?.bytes)||0,o=Array.isArray(t?.tables)?t.tables.length:0;Ve(r("✅ 已备份 {n} 张表({size})到 {file}",{n:o,size:AI(a),file:t?.file||""}))}catch(e){Ve(r("操作失败:{message}",{message:_t(e)}),"err")}finally{rs()}}}function sW(){En||Ze({dbBackupConfirm:{includeLogs:dt.dbIncludeLogs}})}function iS(e){Ze({dbBackupConfirm:null}),e&&rW()}async function rW(){if(En)return;const e=tt().workbuddyDesktop;if(!e?.importDatabase){Ve(r("当前环境不支持整库恢复(仅桌面端可用)"),"err");return}us("dbImport"),Ze({dbWarning:null});try{const t=await e.importDatabase(),a=Array.isArray(t?.tables)?t.tables.length:0,o=t?.safetyBackup?r(",替换前的数据已备份为 {name}",{name:t.safetyBackup}):"";Ve(r("✅ 已恢复 {n} 张表{note}",{n:a,note:o}));const c=typeof t?.warning=="string"?t.warning.trim():"";c&&Ze({dbWarning:c}),await jS(),await tt().wbApp?.refresh?.()}catch(t){Ve(r("恢复失败:{message}",{message:_t(t)}),"err")}finally{rs()}}function Ax(e){if(e===void 0)return;const t=EI(eS,e,dt.retention.values);Ze({retention:{status:t===null?"unavailable":"ready",values:t}})}async function Rx(){try{Ax(await tt().workbuddyDesktop?.getRetention())}catch(e){console.warn("读取数据保留设置失败:",_t(e)),Ax(null)}}let Ox=null;function Mx(e){const t=Ox;Ox=null,Ze({retentionConfirm:null}),t?.(e)}function aW(e){return new Promise(t=>{Ox&&Mx(!1),Ox=t,Ze({retentionConfirm:{head:e}})})}function lW(e,t,a){return t===null?r("没能读到「{label}」的当前值,改为 {days} 天可能会删除超出的历史数据。",{label:e.label,days:a}):r("「{label}」将从 {previous} 天改为 {days} 天。",{label:e.label,previous:t,days:a})}async function oW(e,t){if(En||dt.retentionConfirm)return;const a=TI(t,e.min,e.max,r("天数"));if(!a.ok){Ve(a.message,"err");return}const o=dt.retention.values?.[e.key],c=typeof o=="number"&&Number.isInteger(o)?o:null;if(c!==null&&a.value===c)return;const d=c===null||a.valueNumber.isInteger(d?.[f.key]))){const f=d?.[e.key]??t;Ve(a?r("✅ 已保留 {days} 天,超出部分已清理",{days:f}):r("✅ 已保留 {days} 天",{days:f}));return}await Rx(),Ve(a?r("✅ 已保留 {days} 天,超出部分已清理",{days:t}):r("✅ 已保留 {days} 天",{days:t}))}catch(c){Ve(r("保存失败:{message}",{message:_t(c)}),"err"),await Rx()}finally{rs()}}function jp(e,t){if(t===void 0)return;const a=EI(e.fields,t,e.read().values);e.write({status:a===null?"unavailable":"ready",values:a}),e.syncExtras?.(a===null?null:t)}async function Gu(e){try{jp(e,await e.get())}catch(t){console.warn(`${e.consoleLabel}失败:`,_t(t)),jp(e,null)}}async function Dx(e,t,a){if(En)return;const o=TI(a,t.min,t.max,t.label);if(!o.ok){Ve(o.message,"err");return}const c=e.read().values?.[t.key];if(Number.isInteger(c)&&o.value===c)return;us(e.scope);const d=e.read().values;d&&e.write({status:"ready",values:{...d,[t.key]:o.value}});try{const f=await e.save({[t.key]:o.value});jp(e,f);const p=e.read().values?.[t.key],g=Number.isInteger(p)?p:o.value;Ve(r("✅ 已保存:{label} {value}",{label:t.label,value:String(g)}))}catch(f){Ve(r("保存失败:{message}",{message:_t(f)}),"err"),await Gu(e)}finally{rs()}}const _I={scope:"queue",fields:NI,consoleLabel:"读取排队等待设置",get:()=>tt().workbuddyDesktop?.getQueue(),save:e=>tt().workbuddyDesktop?.saveQueue(e),read:()=>dt.queue,write:e=>Ze({queue:e})};async function LI(){await Gu(_I)}async function cW(e,t){await Dx(_I,e,t)}const zI={scope:"captchaPool",fields:RI,consoleLabel:"读取验证码令牌池设置",get:()=>tt().workbuddyDesktop?.getCaptchaPool(),save:e=>tt().workbuddyDesktop?.saveCaptchaPool(e),read:()=>dt.captchaPool,write:e=>Ze({captchaPool:e})};async function BI(){await Gu(zI)}async function uW(e,t){await Dx(zI,e,t)}const HI="routingStrategy",UI="routingSticky",dW="routingFailoverBackoff",fW="routingSink",pW="routingBreakerEnabled",mW={[HI]:new Set(Cx.map(e=>e.value)),[UI]:new Set(Tx.map(e=>e.value))};function VI(e){const t=e&&typeof e=="object"?e:{},a=(c,d)=>{const f=t[c];return typeof f=="string"&&mW[c].has(f)?f:d},o=(c,d)=>{const f=t[c];return typeof f=="boolean"?f:d};return{strategy:a(HI,"order"),sticky:a(UI,"auto"),failoverBackoff:o(dW,!0),sink:o(fW,!0),breakerEnabled:o(pW,!1)}}async function Ix(){try{const e=await tt().workbuddyDesktop?.getRoutingConfig();if(e===void 0){Ze({routing:{...dt.routing,status:"unavailable"}});return}Ze({routing:{status:"ready",...VI(e)}})}catch(e){console.warn("读取路由设置失败:",_t(e)),Ze({routing:{...dt.routing,status:"unavailable"}})}}async function cS(e){if(En)return;const t=tt().workbuddyDesktop;if(!t?.setRoutingConfig){Ve(r("桌面运行时不可用,暂时无法保存"),"err");return}us("routing");try{const a=await t.setRoutingConfig(e);a!==void 0?Ze({routing:{status:"ready",...VI(a)}}):await Ix(),Ve(r("✅ 路由设置已保存"))}catch(a){Ve(r("保存失败:{message}",{message:_t(a)}),"err"),await Ix()}finally{rs()}}const wp={scope:"retry",fields:wI,consoleLabel:"读取请求重试设置",get:()=>tt().workbuddyDesktop?.getRetry(),save:e=>tt().workbuddyDesktop?.saveRetry(e),read:()=>dt.retry,write:e=>Ze({retry:e}),syncExtras:e=>{if(e===null){Ze({retryCodes:null});return}const t=e[kI];if(!Array.isArray(t))return;Ze({retryCodes:t.filter(o=>typeof o=="number"&&Number.isInteger(o)&&o>=tS&&o<=nS)})}};function hW(e){jp(wp,e)}async function FI(){await Gu(wp)}async function gW(e,t){await Dx(wp,e,t)}async function uS(e){if(!En){Ze({retryCodes:e}),us("codes");try{const t=await tt().workbuddyDesktop?.saveRetry({[kI]:e});jp(wp,t),Ve(r("✅ 已保存:指定错误码直接换号"))}catch(t){Ve(r("保存失败:{message}",{message:_t(t)}),"err"),await Gu(wp)}finally{rs()}}}async function xW(e){const t=dt.retryCodes;if(t===null)return;const a=String(e??"").trim();if(!a)return;if(!/^\d+$/.test(a)||Number(a)nS){Ve(r("状态码必须是 {min}–{max} 的整数(收到: {text})",{min:tS,max:nS,text:a}),"err");return}const o=Number(a);if(t.includes(o)){Ve(r("状态码 {code} 已在名单里",{code:o}));return}if(t.length>=CI){Ve(r("名单最多 {max} 个状态码",{max:CI}),"err");return}await uS([...t,o])}async function bW(e){const t=dt.retryCodes;!t||!t.includes(e)||await uS(t.filter(a=>a!==e))}async function vW(){const e=dt.retryCodes;e?.length&&await uS(e.slice(0,-1))}const $I={scope:"timeouts",fields:SI,consoleLabel:"读取请求超时设置",get:()=>tt().workbuddyDesktop?.getTimeouts(),save:e=>tt().workbuddyDesktop?.saveTimeouts(e),read:()=>dt.timeouts,write:e=>Ze({timeouts:e})};async function qI(){await Gu($I)}async function yW(e,t){await Dx($I,e,t)}function Px(e){if(e===void 0)return;if(!e||typeof e!="object"){Ze({debug:{status:"unavailable",on:!1,count:null,limit:null}});return}const t=e,a=Number(t.count),o=Number(t.limit);Ze({debug:{status:"ready",on:t.debugMode===!0,count:Number.isInteger(a)?a:null,limit:Number.isInteger(o)?o:null}})}async function dS(){try{Px(await tt().workbuddyDesktop?.getDebug())}catch(e){console.warn("读取调试模式设置失败:",_t(e)),Px(null)}}async function jW(e){if(En){nl();return}us("debug"),Ze({debug:{...dt.debug,on:e}});try{const t=await tt().workbuddyDesktop?.saveDebug(e);Px(t),Ve(r(e?"✅ 调试模式已开启":"✅ 调试模式已关闭"))}catch(t){Ve(r("保存失败:{message}",{message:_t(t)}),"err"),await dS()}finally{rs()}}function _x(e){if(e===void 0)return;if(!e||typeof e!="object"){Ze({sanitize:{status:"unavailable",on:!1}});return}Ze({sanitize:{status:"ready",on:e.sanitizeBlacklistFingerprints===!0}})}async function fS(){try{_x(await tt().workbuddyDesktop?.getSanitize())}catch(e){console.warn("读取出站指纹脱敏设置失败:",_t(e)),_x(null)}}async function wW(e){if(En){nl();return}us("sanitize"),Ze({sanitize:{status:"ready",on:e}});try{const t=await tt().workbuddyDesktop?.saveSanitize(e);_x(t),Ve(r(e?"✅ 出站指纹脱敏已开启":"已关闭出站指纹脱敏"))}catch(t){Ve(r("保存失败:{message}",{message:_t(t)}),"err"),await fS()}finally{rs()}}function pS(e){if(!e||typeof e!="object")return{};const t={};for(const[a,o]of Object.entries(e))typeof o=="string"&&(t[a]=o);return t}function mS(e){if(e===void 0)return;if(!e||typeof e!="object"){Ze({clineHeaders:{status:"unavailable",defaults:{},overrides:{},effective:{}}});return}const t=e;Ze({clineHeaders:{status:"ready",defaults:pS(t.defaults),overrides:pS(t.overrides),effective:pS(t.effective)}})}async function hS(){try{mS(await tt().workbuddyDesktop?.getClineHeaders())}catch(e){console.warn("读取 Cline 伪装头失败:",_t(e)),mS(null)}}async function SW(){await hS(),Ve(r("Cline 伪装头已刷新"))}async function GI(e){if(En){nl();return}us("clineHeaders");try{const t=await tt().workbuddyDesktop?.saveClineHeaders(e);mS(t),Ve(r("✅ Cline 伪装头已保存"))}catch(t){Ve(r("保存失败:{message}",{message:_t(t)}),"err"),await hS()}finally{rs()}}function gS(e){if(e===void 0)return;if(!e||typeof e!="object"){Ze({cors:{status:"unavailable",on:!1}});return}Ze({cors:{status:"ready",on:e.corsEnabled===!0}})}async function xS(){try{gS(await tt().workbuddyDesktop?.getCors())}catch(e){console.warn("读取网关跨域访问设置失败:",_t(e)),gS(null)}}async function NW(e){if(En){nl();return}us("cors"),Ze({cors:{status:"ready",on:e}});try{const t=await tt().workbuddyDesktop?.saveCors(e);gS(t),Ve(r(e?"网关跨域访问已开启":"已关闭网关跨域访问"))}catch(t){Ve(r("保存失败:{message}",{message:_t(t)}),"err"),await xS()}finally{rs()}}async function KI(){try{const e=await tt().workbuddyDesktop?.getCaptchaSetting();Ze({captcha:{available:!0,enabled:e?.captchaEnabled===!0}})}catch(e){Ze({captcha:{available:!1,enabled:!1}}),console.warn("读取机器人校验设置失败:",_t(e))}}async function kW(e){if(En){nl();return}us("captcha"),Ze({captcha:{...dt.captcha,enabled:e}});try{const t=await tt().workbuddyDesktop?.saveCaptchaSetting(e);Ze({captcha:{available:!0,enabled:t?.captchaEnabled===!0}}),Ve(r(e?"✅ 机器人校验已开启":"⚠️ 机器人校验已关闭"))}catch(t){Ve(r("保存失败:{message}",{message:_t(t)}),"err"),await KI()}finally{rs()}}function bS(e){return!e||typeof e!="object"?{status:"unavailable",enabled:!0,source:"",updatedAt:0,count:0}:{status:"ready",enabled:e.modelsDevEnabled!==!1,source:typeof e.source=="string"?e.source:"",updatedAt:Number(e.updatedAt)||0,count:Number(e.count)||0}}async function vS(){try{const e=await tt().workbuddyDesktop?.getModelsDev?.();Ze({modelsDev:bS(e)})}catch(e){Ze({modelsDev:{...dt.modelsDev,status:"unavailable"}}),console.warn("读取 models.dev 元数据设置失败:",_t(e))}}async function CW(e){if(En){nl();return}us("modelsDev"),Ze({modelsDev:{...dt.modelsDev,enabled:e}});try{const t=await tt().workbuddyDesktop?.saveModelsDev?.(e);Ze({modelsDev:bS(t)}),Ve(r(e?"✅ models.dev 模型元数据已开启":"已关闭 models.dev 联网刷新"))}catch(t){Ve(r("保存失败:{message}",{message:_t(t)}),"err"),await vS()}finally{rs()}}async function TW(){if(En){nl();return}us("modelsDevRefresh");try{const e=await tt().workbuddyDesktop?.refreshModelsDev?.();Ze({modelsDev:bS(e?.status)});const t=e?.result,a=String(t?.status||"");a==="refreshed"?Ve(r("models.dev 元数据已更新({count} 条)",{count:Number(t?.count)||0})):a==="failed"?Ve(r("刷新失败:{message}",{message:String(t?.message||"")}),"err"):Ve(String(t?.message||r("本次无需刷新")))}catch(e){Ve(r("刷新失败:{message}",{message:_t(e)}),"err"),await vS()}finally{rs()}}function Ku(e){if(e===void 0)return;if(!e||typeof e!="object"){Ze({prompt:{...dt.prompt,status:"unavailable"}});return}const t=e,a=RW(t.promptGateway);Ze({prompt:{status:"ready",mode:String(t.promptMode||"passthrough"),file:String(t.promptFile||""),text:String(t.promptText||""),source:String(t.promptSource||""),lines:Number(t.promptLines)||0,fileError:String(t.promptFileError||""),degradeActive:t.degradeActive===!0,degradeUntilText:String(t.degradeUntilText||""),providers:EW(t.promptProviders,a),gateway:a,gatewayText:OW(t.promptGatewayText),options:AW(t.promptProviderOptions)}})}function EW(e,t){return!e||typeof e!="object"?[]:Object.entries(e).filter(([a,o])=>!!a&&!!o&&typeof o=="object").map(([a,o])=>{const c=o;return{id:a,mode:String(c.promptMode||"passthrough"),file:String(c.promptFile||""),text:String(c.promptText||""),source:String(c.promptSource||""),lines:Number(c.promptLines)||0,fileError:String(c.promptFileError||""),gateway:t[a]??!0,configured:!0}}).sort((a,o)=>a.id.localeCompare(o.id))}function AW(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&String(t.id||"")).map(t=>{const a=t;return{id:String(a.id),label:String(a.label||a.id),gatewayNote:String(a.gatewayNote||""),gatewayChars:Number(a.gatewayChars)||0,gatewayBlocks:MW(a.gatewayBlocks)}}):[]}function RW(e){if(!e||typeof e!="object")return{};const t={};for(const[a,o]of Object.entries(e)){const c=String(a||"").trim();!c||typeof o!="boolean"||(t[c]=o)}return t}function OW(e){if(!e||typeof e!="object")return{};const t={};for(const[a,o]of Object.entries(e)){const c=String(a||"").trim();if(!c||!o||typeof o!="object")continue;const d=o,f={identity:"",stable:"",dynamic:""};let p=!1;for(const g of["identity","stable","dynamic"]){const v=String(d[g]||"");f[g]=v,v.trim()&&(p=!0)}p&&(t[c]=f)}return t}function MW(e){if(!e||typeof e!="object")return null;const t=e,a={identity:String(t.identity||""),stable:String(t.stable||""),dynamic:String(t.dynamic||"")};return!a.identity.trim()&&!a.stable.trim()&&!a.dynamic.trim()?null:a}async function ac(){try{Ku(await tt().workbuddyDesktop?.getPrompt())}catch(e){console.warn("读取系统提示词设置失败:",_t(e)),Ku(null)}}async function Sp(e,t){if(En)return await ac(),!1;us("prompt");try{const a=await tt().workbuddyDesktop?.savePrompt(t);return Ku(a),Ve(r("✅ 已保存:{label}",{label:e})),!0}catch(a){return Ve(r("保存失败:{message}",{message:_t(a)}),"err"),await ac(),!1}finally{rs()}}async function DW(e){const t=zo.find(a=>a.value===e);await Sp(r("模式改为「{mode}」",{mode:t?.toastLabel??e}),{promptMode:e})}async function IW(e){await Sp(e.trim()?r("提示词文件已更新"):r("已改回内置默认提示词"),{promptFile:e})}async function PW(e){const t=!e.trim();return Sp(r(t?"已清掉界面编辑的提示词(回落文件 / 内置默认)":"提示词正文已更新"),{promptText:t?"":e})}function Bo(e,t){return e.options.find(a=>a.id===t)?.label||t}function lc(e){const t=e==null?"":String(e).trim();return t&&dt.prompt.options.some(a=>a.id===t)?t:""}async function Np(e,t,a){return Sp(e,{promptProviders:{[t]:a}})}function Lx(e,t){const a=!t.configured;return{promptMode:t.mode,promptFile:t.file,promptText:a&&e.source==="inline"?e.text:""}}async function _W(e){const t=lc(e);if(!t)return;const a=dt.prompt;await Np(r("已为「{label}」单独配置提示词",{label:Bo(a,t)}),t,Lx(a,{mode:a.mode,file:a.file,text:a.text,source:a.source,lines:a.lines,fileError:a.fileError,gateway:a.gateway[t]??!0,configured:!1}))}async function LW(e,t){const a=lc(e.id);if(!a||!zo.some(c=>c.value===t))return;const o=zo.find(c=>c.value===t);await Np(r("「{label}」的模式改为「{mode}」",{label:Bo(dt.prompt,a),mode:o?.toastLabel??t}),a,{...Lx(dt.prompt,e),promptMode:t})}async function zW(e,t){const a=lc(e.id);a&&await Np(t.trim()?r("「{label}」的提示词文件已更新",{label:Bo(dt.prompt,a)}):r("「{label}」改用内置默认提示词",{label:Bo(dt.prompt,a)}),a,{...Lx(dt.prompt,e),promptFile:t})}async function BW(e,t){const a=lc(e.id);if(!a)return!1;const o=!t.trim(),c=Bo(dt.prompt,a);return Np(o?r("已清掉「{label}」界面编辑的正文",{label:c}):r("「{label}」的提示词正文已更新",{label:c}),a,{...Lx(dt.prompt,e),promptText:o?"":t})}async function HW(e){const t=lc(e);t&&await Np(r("已取消「{label}」的单独配置",{label:Bo(dt.prompt,t)}),t,null)}async function UW(e,t){const a=lc(e);if(!a)return;const o=Bo(dt.prompt,a);if(En){await ac();return}us("prompt");try{const c=await tt().workbuddyDesktop?.savePrompt({promptGateway:{[a]:t}});Ku(c),Ve(t?r("✅ 已为「{label}」装上网关自带提示词",{label:o}):r("已关闭「{label}」的网关自带提示词:能否通过上游校验取决于上游当前口径",{label:o}),t?"ok":"err")}catch(c){Ve(r("保存失败:{message}",{message:_t(c)}),"err"),await ac()}finally{rs()}}async function VW(e,t){const a=lc(e);if(!a)return!1;const o=Bo(dt.prompt,a),c=!t||!(t.identity.trim()||t.stable.trim()||t.dynamic.trim());return Sp(c?r("「{label}」的网关自带提示词已改回官方原文",{label:o}):r("「{label}」的网关自带提示词正文已更新",{label:o}),{promptGatewayText:{[a]:c?null:t}})}async function FW(){if(!En){us("prompt");try{const e=await tt().workbuddyDesktop?.savePrompt({clearDegrade:!0});Ku(e),Ve(r("✅ 已解除内容拦截降级"))}catch(e){Ve(r("解除失败:{message}",{message:_t(e)}),"err"),await ac()}finally{rs()}}}function kp(e){const t=Number(e);return Number.isFinite(t)?t:null}function yS(e){if(e===void 0)return;const t=e&&typeof e=="object"?e.database:null;if(!t||typeof t!="object"){Ze({storage:{...dt.storage,status:"unavailable"}});return}const a=t;Ze({storage:{status:"ready",available:a.available!==!1,file:String(a.file||""),bytes:Number(a.bytes)||0,accounts:kp(a.accounts),logs:kp(a.logs),requests:kp(a.requests),dailyDays:kp(a.dailyDays),debug:kp(a.debug)}})}async function YI(){try{yS(await tt().workbuddyDesktop?.getStorage())}catch(e){console.warn("读取数据存储概况失败:",_t(e)),yS(null)}}async function $W(){try{return await tt().workbuddyDesktop?.panelLogout(),window.location.href="/login",!0}catch(e){return Ve(r("退出失败:{message}",{message:_t(e)}),"err"),!1}}async function jS(){MI(),DI(),Ze({panelLogin:OI()}),await Promise.all([II(),YZ(),Rx(),FI(),qI(),LI(),BI(),Ix(),dS(),fS(),hS(),xS(),ac(),YI(),KI(),vS(),tt().wbUpdatePanel?.load?.()])}async function qW(){await Rx(),Ve(r("保留天数已刷新"))}async function GW(){await FI(),Ve(r("重试设置已刷新"))}async function KW(){await qI(),Ve(r("超时设置已刷新"))}async function YW(){await LI(),Ve(r("排队等待设置已刷新"))}async function XW(){await BI(),Ve(r("验证码令牌池设置已刷新"))}async function QW(){await Ix(),Ve(r("路由设置已刷新"))}async function ZW(){await dS(),Ve(r("调试模式设置已刷新"))}async function WW(){await fS(),Ve(r("指纹脱敏设置已刷新"))}async function JW(){await xS(),Ve(r("网关跨域访问设置已刷新"))}async function eJ(){await ac(),Ve(r("系统提示词设置已刷新"))}async function tJ(){await YI(),Ve(r("存储概况已刷新"))}const zx=[{key:"identity",label:r("第一段(身份句)"),short:r("第一段"),hint:r("官方原文只有一句:声明自己是 ZCode。")},{key:"stable",label:r("第二段(稳定段)"),short:r("第二段"),hint:r("工具用法与环境说明那一大段。")},{key:"dynamic",label:r("第三段(动态段)"),short:r("第三段"),hint:r("沟通方式 / 上下文管理 + Environment 段。")}];function nJ(e){return r(e==="inline"?"界面里编辑的正文":e==="file"?"提示词文件":e==="builtin"?"内置默认提示词":"(未生效)")}function XI({title:e,text:t,source:a,file:o,disabled:c,save:d,onClose:f}){const[p,g]=x.useState(t),[v,y]=x.useState(!1),b=v||c,j=p!==t;async function w(S){y(!0);try{await d(S)&&f()}finally{y(!1)}}return s.jsx(Qt,{open:!0,onOpenChange:S=>{S||b||f()},children:s.jsxs(Zt,{className:"w-[min(880px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:e})}),s.jsxs(Bt,{children:[s.jsxs(Vn,{children:[s.jsx("h3",{children:r("保存后以这里的文本为准")}),s.jsxs("p",{children:[r("这一份就是「替换 / 追加」模式下网关要发的 system 正文。"),a==="none"?r("当前是透传模式:存下来也不会发出,切成「替换 / 追加」之后才生效。"):r("当前生效的正文来自{source}{file}。保存后这一份会盖过提示词文件与内置默认{note}。",{source:nJ(a),file:o.trim()&&a!=="inline"?r("(文件:{path})",{path:o.trim()}):"",note:a!=="inline"&&o.trim()?r(",文件里后续的改动在清空这里之前不再生效"):""}),r("想回到原来那份,把这里清空再保存即可(不会删掉你配的文件路径)。")]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(Je,{htmlFor:"settings-prompt-body",children:r("提示词正文")}),s.jsx(Zc,{id:"settings-prompt-body",rows:18,className:"min-h-[320px]",spellCheck:!1,disabled:b,value:p,onChange:S=>g(S.currentTarget.value)}),s.jsx("div",{className:"hint",children:p.trim()?r("{lines} 行、{chars} 字符(按当前草稿计)",{lines:p.split(` +`).length,chars:p.length}):r("空 = 不要这一份,回落提示词文件 / 内置默认提示词。")})]})]}),s.jsxs(nn,{children:[s.jsx(se,{variant:"outline",className:"mr-auto",disabled:b||a!=="inline",onClick:()=>{w("")},children:r("清除这里的正文")}),s.jsx(se,{variant:"outline",disabled:b,onClick:f,children:r("取消")}),s.jsx(se,{variant:"default",disabled:b||!j,onClick:()=>{w(p)},children:r(v?"保存中…":"保存")})]})]})})}function sJ({prompt:e,locked:t,busy:a}){const[o,c]=x.useState(!1);return s.jsxs(s.Fragment,{children:[s.jsx(se,{id:"btn-prompt-edit-body",variant:"outline",disabled:t||a,onClick:()=>c(!0),children:r("编辑正文")}),o?s.jsx(XI,{title:r("编辑提示词正文 · 全局"),text:e.text,source:e.source,file:e.file,disabled:a,save:PW,onClose:()=>c(!1)}):null]})}function rJ({item:e,label:t,locked:a,busy:o}){const[c,d]=x.useState(!1);return s.jsxs(s.Fragment,{children:[s.jsx(se,{id:`btn-prompt-edit-body-${e.id}`,variant:"outline",disabled:a||o,onClick:()=>d(!0),children:r("编辑正文")}),c?s.jsx(XI,{title:r("编辑提示词正文 · {label}",{label:t}),text:e.text,source:e.source,file:e.file,disabled:o,save:f=>BW(e,f),onClose:()=>d(!1)}):null]})}function aJ({id:e,title:t,official:a,over:o,enabled:c,disabled:d,onClose:f}){const[p,g]=x.useState(()=>({identity:o?.identity?.trim()?o.identity:a.identity,stable:o?.stable?.trim()?o.stable:a.stable,dynamic:o?.dynamic?.trim()?o.dynamic:a.dynamic})),[v,y]=x.useState(!1),b=v||d,j=zx.some(N=>p[N.key]!==a[N.key]),w=zx.filter(N=>o?.[N.key]?.trim()).map(N=>N.label);async function S(N){y(!0);try{await VW(e,N)&&f()}finally{y(!1)}}return s.jsx(Qt,{open:!0,onOpenChange:N=>{N||b||f()},children:s.jsxs(Zt,{className:"w-[min(880px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:t})}),s.jsxs(Bt,{children:[s.jsxs(Vn,{children:[s.jsx("h3",{children:r("三段各自成块,所以分开编辑")}),s.jsxs("p",{children:[r("上游按"),s.jsx("strong",{children:r("结构")}),r("校验身份:这三段必须各自成块排在最前(实测:三段并成一段会被回 405 / 3012)。因此这里按段编辑,不能合成一段。改过的段以你的文本为准,没改的段继续用官方原文;清空某一段 = 那一段恢复官方原文。"),w.length?r("当前已改过:{edited}。",{edited:w.join(r("、"))}):r("当前三段都是官方原文。"),c?"":r("注意:这一家的「网关自带」开关现在是关的,改过的正文要等开关打开才生效。")]}),s.jsx("p",{children:$n.promptGatewayText})]}),zx.map(N=>s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs(Je,{htmlFor:`settings-prompt-block-${e}-${N.key}`,children:[N.label,s.jsx("span",{className:"ml-2 font-normal text-subtle",children:p[N.key]===a[N.key]?r("(官方原文)"):r("(已改)")})]}),s.jsx(Zc,{id:`settings-prompt-block-${e}-${N.key}`,rows:N.key==="identity"?2:10,className:N.key==="identity"?"min-h-[64px]":"min-h-[200px]",spellCheck:!1,disabled:b,value:p[N.key],onChange:k=>{const E=k.currentTarget.value;g(D=>({...D,[N.key]:E}))}}),s.jsx("div",{className:"hint",children:N.hint})]},N.key))]}),s.jsxs(nn,{children:[s.jsx(se,{variant:"outline",className:"mr-auto",disabled:b||!w.length,onClick:()=>{S(null)},children:r("恢复官方原文")}),s.jsx(se,{variant:"outline",disabled:b,onClick:f,children:r("取消")}),s.jsx(se,{variant:"default",disabled:b||!j,onClick:()=>{S(p)},children:r(v?"保存中…":"保存")})]})]})})}function lJ({item:e,option:t,over:a,locked:o,busy:c}){const[d,f]=x.useState(!1),p=t.gatewayBlocks;return p?s.jsxs(s.Fragment,{children:[s.jsx(se,{id:`btn-prompt-gateway-text-${e.id}`,variant:"outline",disabled:o||c,onClick:()=>f(!0),children:r("编辑正文")}),d?s.jsx(aJ,{id:e.id,title:r("编辑网关自带提示词 · {label}",{label:t.label}),official:p,over:a,enabled:e.gateway,disabled:c,onClose:()=>f(!1)}):null]}):null}function oJ(e){return e?zx.filter(t=>(e[t.key]||"").trim()).map(t=>t.short).join(r("、")):""}function QI(e,t){return tt().wbIcons?.icon?.(e,t)||""}function cn({tone:e,children:t}){const a=e==="ok"?"success":e==="bad"?"destructive":"outline";return s.jsx(ze,{variant:a,children:t})}function Qn({title:e,tip:t,badge:a,actions:o}){return s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:e}),t?s.jsx("span",{className:"tip-q","data-tip":t}):null,a,o?s.jsx("div",{className:"head-actions",children:o}):null]})}function iJ({title:e,tip:t,badge:a,actions:o,children:c}){function d(f){f.target.closest(".tip-q, .head-actions")&&f.preventDefault()}return s.jsxs("details",{className:"panel panel-fold",children:[s.jsxs("summary",{className:"panel-head",onClick:d,children:[s.jsx("span",{className:"fold-caret","aria-hidden":!0,dangerouslySetInnerHTML:{__html:QI("caretRight",14)}}),s.jsx("h2",{children:e}),t?s.jsx("span",{className:"tip-q","data-tip":t}):null,a,o?s.jsx("div",{className:"head-actions",children:o}):null]}),c]})}function da({id:e,label:t,checked:a,disabled:o,tip:c,onCheckedChange:d}){return s.jsxs("label",{className:"switch",children:[s.jsx(ms,{id:e,checked:a,disabled:o,onCheckedChange:f=>d(f)}),s.jsx("span",{children:t}),c?s.jsx("span",{className:"tip-q","data-tip":c}):null]})}function Cp({field:e,value:t,disabled:a,onCommit:o}){const[c,d]=x.useState(null),f=c!==null?c:t===null?"":String(t);async function p(){const g=c;if(g!==null)try{await o(g)}finally{d(null)}}return s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:e.id,children:e.label}),s.jsxs("span",{className:"retention-input",children:[s.jsx($e,{id:e.id,type:"number",min:e.min,max:e.max,step:1,inputMode:"numeric",className:"w-[92px] max-w-[92px] text-center tabular-nums",value:f,disabled:a||t===null,onChange:g=>d(g.target.value),onFocus:()=>d(String(t??"")),onBlur:()=>{p()},onKeyDown:g=>{g.key==="Enter"&&g.currentTarget.blur()}}),s.jsx("span",{className:"unit",children:e.unit})]}),s.jsx("div",{className:"hint",children:e.hint})]})}function Tp(e){return e.status==="ready"?s.jsx(cn,{tone:"ok",children:r("已生效")}):e.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")})}function Br({id:e,onClick:t}){return s.jsx(se,{id:e,variant:"outline",onClick:t,children:r("刷新")})}function cJ(e){const{lanAccess:t,lanPanel:a,lanIp:o,port:c}=e.app;if(!t)return r("未开启:网关只监听 127.0.0.1,仅本机可以访问。");const d=`http://${o||r("<本机IP>")}${c?`:${c}`:""}`,f=a?r(";网页管理面板已一并开放(浏览器打开同一地址)"):"";return r("已开启:其他设备把 API 地址指向 {url}{panel}。",{url:`${d}/v1`,panel:f})}function uJ({snap:e}){const t=e.app,a=t.status==="unavailable"?Ut.appUnavailable:t.status==="loading"?Ut.appLoading:t.closeToTray?t.lightweightMode?Ut.appLightOn:Ut.appTrayOn:Ut.appTrayOff;return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("启动与托盘"),tip:ss.tray,badge:t.status==="ready"?s.jsx(cn,{tone:"ok",children:r("已应用")}):t.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"settings-switches",children:[s.jsx(da,{id:"settings-close-to-tray",label:r("关闭窗口时最小化到托盘"),checked:t.closeToTray,disabled:e.busy==="app",onCheckedChange:o=>{lS("tray",o)}}),s.jsx(da,{id:"settings-lightweight",label:r("轻量模式(关窗释放界面内存)"),tip:ss.lightweight,checked:t.lightweightMode,disabled:e.busy==="app"||!t.closeToTray,onCheckedChange:o=>{lS("lightweight",o)}}),s.jsx(da,{id:"settings-autostart",label:r("开机自动启动"),checked:t.autostart,disabled:e.busy==="app",onCheckedChange:o=>{lS("autostart",o)}})]}),s.jsx("div",{className:"settings-state",children:a})]})]}),!e.panelLogin&&s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("局域网访问"),tip:ss.lan}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"settings-switches",children:[s.jsx(da,{id:"settings-lan-access",label:r("允许局域网内的设备访问网关"),checked:e.app.lanAccess,disabled:e.busy==="lan",onCheckedChange:XZ}),s.jsx(da,{id:"settings-lan-panel",label:r("同时开放网页管理面板"),checked:e.app.lanPanel,disabled:e.busy==="lan"||!e.app.lanAccess,onCheckedChange:QZ})]}),s.jsx("div",{className:"settings-state",children:cJ(e)})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("计量单位"),tip:ss.units}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"settings-switches",children:s.jsx(da,{id:"settings-chinese-units",label:r("使用中文单位(亿 / 万)"),checked:e.unitsChinese,onCheckedChange:KZ})}),s.jsx("div",{className:"settings-state",children:e.unitsChinese?Ut.unitsOn:Ut.unitsOff})]})]})]})}function dJ(e){return e==="light"?Ut.themeLight:e==="dark"?Ut.themeDark:Ut.themeSystem}function fJ(){const[e,t]=x.useState(zZ),[a,o]=x.useState(BZ),c=tt().workbuddyDesktop?.platform==="web";x.useEffect(()=>{const f=g=>t(String(g.detail||"system")),p=g=>o(Number(g.detail)||100);return window.addEventListener(vI,f),window.addEventListener(yI,p),()=>{window.removeEventListener(vI,f),window.removeEventListener(yI,p)}},[]);const d=a===100?r("100%(默认)"):`${a}%`;return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("显示模式"),tip:ss.displayTheme}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{children:s.jsx(In,{"aria-label":r("显示模式"),options:LZ,value:e,onValueChange:f=>tt().wbApp?.applyTheme?.(f)})}),s.jsx("div",{className:"settings-state",children:dJ(e)})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("界面缩放"),tip:ss.displayZoom}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"retention-list",children:s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"settings-zoom",children:r("缩放比例")}),s.jsx("span",{className:"prompt-input",children:s.jsxs(ft,{value:String(a),onValueChange:f=>tt().wbApp?.applyZoom?.(Number(f)),children:[s.jsx(mt,{id:"settings-zoom",className:"w-[140px]",disabled:c,"aria-label":r("界面缩放比例"),children:s.jsx(pt,{children:d})}),s.jsx(ht,{children:_Z.map(f=>s.jsx(qe,{value:String(f),children:f===100?r("100%(默认)"):`${f}%`},f))})]})}),s.jsx("div",{className:"hint",children:r("放大或缩小整个界面(文字与控件一起变),效果与浏览器 Ctrl +/- 相同:共 11 档,立即生效并记住。")})]})}),s.jsx("div",{className:"settings-state",children:c?Ut.zoomWeb:a===100?Ut.zoomDefault:r("当前按 {n}% 显示。",{n:a})})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("语言设置"),tip:ss.displayLanguage}),s.jsxs("div",{className:"panel-body",children:[s.jsx(pJ,{}),s.jsx("div",{className:"settings-state",children:Ut.languageHint})]})]})]})}function pJ(){const e=window.wbI18n,t=e?.rawLocale?.()??"auto",a=e?.LOCALES??[],o=c=>c==="auto"?r("跟随系统"):a.find(d=>d.code===c)?.label??c;return s.jsx("div",{className:"retention-list",children:s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"settings-language",children:r("界面语言")}),s.jsx("span",{className:"prompt-input",children:s.jsxs(ft,{value:t,onValueChange:c=>{c&&e?.setLocale(c)},children:[s.jsx(mt,{id:"settings-language",className:"w-[200px]","aria-label":r("界面语言"),children:s.jsx(pt,{children:o(t)})}),s.jsxs(ht,{children:[s.jsx(qe,{value:"auto",children:r("跟随系统")}),a.map(c=>s.jsx(qe,{value:c.code,children:c.label},c.code))]})]})})]})})}function mJ({codes:e,status:t,busy:a}){const[o,c]=x.useState(""),d=x.useRef(null),f=t==="unavailable";return s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"settings-retry-no-codes-input",children:r("指定错误码直接换号")}),s.jsx("div",{className:"retention-input",children:s.jsxs("div",{className:f?"tag-input disabled":"tag-input",onClick:()=>d.current?.focus(),children:[(e||[]).map(p=>s.jsxs("span",{className:"tag-chip",children:[s.jsx("span",{className:"v",children:p}),s.jsx(se,{type:"button",variant:"ghost",size:"icon-2xs",className:"tag-x text-muted-foreground hover:bg-destructive-soft hover:text-destructive",title:r("删除 {code}",{code:p}),"aria-label":r("删除状态码 {code}",{code:p}),onClick:g=>{g.stopPropagation(),bW(p)},children:"✕"})]},p)),s.jsx($e,{ref:d,id:"settings-retry-no-codes-input",type:"text",className:"tag-input-field h-auto border-0 bg-transparent px-0 shadow-none focus:shadow-none",placeholder:f?"—":r("输入状态码,回车添加"),inputMode:"numeric",autoComplete:"off",value:o,disabled:f||a,onChange:p=>c(p.target.value),onKeyDown:p=>{if(p.key==="Enter"){p.preventDefault(),xW(o),c("");return}p.key==="Backspace"&&!o&&vW()}})]})}),s.jsx("div",{className:"hint",children:$n.retryCodes})]})}function hJ({prompt:e,locked:t,busy:a}){const[o,c]=x.useState(null);async function d(){const f=o;if(f!==null)try{await IW(f)}finally{c(null)}}return s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"settings-prompt-file",children:r("提示词文件")}),s.jsx("span",{className:"prompt-input",children:s.jsx($e,{id:"settings-prompt-file",type:"text",placeholder:r("留空 = 用内置默认提示词"),value:o!==null?o:e.file,disabled:t||a,onChange:f=>c(f.target.value),onFocus:()=>c(e.file),onBlur:()=>{d()},onKeyDown:f=>{f.key==="Enter"&&f.currentTarget.blur()}})}),s.jsx("div",{className:"hint",children:$n.promptFile})]})}function gJ(e){if(e.status==="loading")return Ut.appLoading;if(e.status==="unavailable")return Ut.promptUnavailable;const t=ZI(e.source),a=[];return e.mode==="passthrough"?a.push(r("客户端 system 原样出站(只靠指纹脱敏改写模板句)。")):a.push(r("{mode}生效:上游收到的 system 来自{source}{lines}。",{mode:e.mode==="custom"?r("替换"):r("追加"),source:t,lines:e.lines?r("({n} 行)",{n:e.lines}):""})),e.fileError&&a.push(`⚠️ ${e.fileError}`),a.join("")}function ZI(e){return e==="inline"?r("界面里编辑的正文"):e==="file"?r("提示词文件"):e==="builtin"?r("内置默认提示词"):""}function xJ(e){return r("已自动切换到最小中性提示词(撞了上游内容拦截,多半是 system 指纹误报),到 {until} 自动解除。",{until:e.degradeUntilText||Ut.degradeUntilFallback})+r("期间本模式自己的提示词不会发出;把提示词改好后可以立即解除。")}function bJ({item:e,label:t,locked:a,busy:o}){const[c,d]=x.useState(null);async function f(){const p=c;if(p!==null)try{p!==e.file&&await zW(e,p)}finally{d(null)}}return s.jsx("span",{className:"prompt-input",children:s.jsx($e,{id:`settings-prompt-file-${e.id}`,type:"text",placeholder:r("留空 = 用内置默认提示词"),"aria-label":r("{label} 提示词文件",{label:t}),value:c!==null?c:e.file,disabled:a||o,onChange:p=>d(p.target.value),onFocus:()=>d(e.file),onBlur:()=>{f()},onKeyDown:p=>{p.key==="Enter"&&p.currentTarget.blur()}})})}function vJ(e,t){if(!t)return r("未单独配置:模式、提示词文件与正文都跟随上面的全局配置(当前「{mode}」)。",{mode:zo.find(o=>o.value===e.mode)?.toastLabel??e.mode});if(e.mode==="passthrough")return r("客户端 system 原样出站。");const a=r("{mode}生效:上游收到的 system 来自{source}{lines}。",{mode:e.mode==="custom"?r("替换"):r("追加"),source:ZI(e.source),lines:e.lines?r("({n} 行)",{n:e.lines}):""});return e.fileError?`${a} ⚠️ ${e.fileError}`:a}function yJ({item:e,option:t,over:a,locked:o,busy:c}){const d=e.gateway,f=t.gatewayChars,p=f?r("约 {n} 字符",{n:f.toLocaleString("zh-CN")}):r("一段内置装配"),g=oJ(a);return s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{className:"prompt-gateway-label",children:r("网关自带")}),s.jsxs("span",{className:"prompt-input",children:[s.jsx(da,{id:`settings-prompt-gateway-${e.id}`,label:r("装上{size}的官方身份提示词",{size:p}),checked:d,disabled:o||c,onCheckedChange:v=>{UW(e.id,v)}}),s.jsx(lJ,{item:e,option:t,over:a,locked:o,busy:c})]}),s.jsxs("div",{className:d?"hint":"hint prompt-gateway-off",children:[d?t.gatewayNote:r("已关闭。{note}",{note:t.gatewayNote}),g?r(" 正文已改:{edited}(其余段用官方原文)。",{edited:g}):""]})]})}function jJ({prompt:e,locked:t,busy:a}){const o=e.options,c=new Map(e.providers.map(w=>[w.id,w])),d=[];for(const w of o)w.gatewayNote&&d.push(c.get(w.id)??{id:w.id,mode:e.mode,file:e.file,text:e.text,source:e.source,lines:e.lines,fileError:e.fileError,gateway:e.gateway[w.id]??!0,configured:!1});for(const w of e.providers)d.some(S=>S.id===w.id)||d.push({...w,gateway:e.gateway[w.id]??!0,configured:!0});const f=new Set(d.map(w=>w.id)),p=o.filter(w=>!w.gatewayNote&&!f.has(w.id)),[g,v]=x.useState(""),y=w=>o.find(S=>S.id===w)?.label||w,b=w=>o.find(S=>S.id===w),j=w=>b(w)?.gatewayNote||"";return s.jsxs(s.Fragment,{children:[d.map(w=>{const S=y(w.id),N=zo.find(D=>D.value===w.mode)?.optionLabel??w.mode,k=j(w.id),E=b(w.id);return s.jsxs(x.Fragment,{children:[s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:`settings-prompt-mode-${w.id}`,children:S}),s.jsxs("span",{className:"prompt-input",children:[s.jsxs(ft,{value:w.mode,onValueChange:D=>{D!=null&&String(D)&&LW(w,String(D))},children:[s.jsx(mt,{id:`settings-prompt-mode-${w.id}`,className:"w-[240px]",disabled:t||a,"aria-label":r("{label} 的提示词模式",{label:S}),children:s.jsx(pt,{children:N})}),s.jsx(ht,{children:zo.map(D=>s.jsx(qe,{value:D.value,children:D.optionLabel},D.value))})]}),s.jsx(bJ,{item:w,label:S,locked:t,busy:a}),s.jsx(rJ,{item:w,label:S,locked:t,busy:a}),w.configured?s.jsx(se,{variant:"outline",disabled:t||a,onClick:()=>{HW(w.id)},children:r("跟随默认")}):null]}),s.jsx("div",{className:"hint",children:vJ(w,w.configured)})]}),E&&k?s.jsx(yJ,{item:w,option:E,over:e.gatewayText[w.id],locked:t,busy:a}):null]},w.id)}),s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"settings-prompt-provider-add",children:r("添加提供商")}),s.jsx("span",{className:"prompt-input",children:s.jsxs(ft,{value:g,onValueChange:w=>{v("");const S=w==null?"":String(w);S&&_W(S)},children:[s.jsx(mt,{id:"settings-prompt-provider-add",className:"w-[240px]",disabled:t||a||p.length===0,"aria-label":r("添加要单独配置的提供商"),children:s.jsx(pt,{children:g?y(g):p.length?r("添加提供商…"):r("全部已配置")})}),s.jsx(ht,{children:p.map(w=>s.jsx(qe,{value:w.id,children:w.label},w.id))})]})}),s.jsx("div",{className:"hint",children:$n.promptProviders})]})]})}function wJ({snap:e}){const t=e.prompt,a=t.status!=="ready",o=e.busy==="prompt",c=zo.find(d=>d.value===t.mode)?.optionLabel??t.mode;return s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("系统提示词"),tip:ss.prompt,badge:t.status==="ready"?s.jsx(cn,{tone:"ok",children:t.mode==="passthrough"?r("透传"):r("已接管")}):t.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Br,{id:"btn-prompt-refresh",onClick:()=>{eJ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"retention-list",children:[s.jsxs("div",{className:"prompt-group",children:[r("全局配置"),s.jsx("span",{className:"note",children:r("所有未单独配置的提供商都用这一份")})]}),s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"settings-prompt-mode",children:r("模式")}),s.jsx("span",{className:"prompt-input",children:s.jsxs(ft,{value:t.mode,onValueChange:d=>{d!=null&&String(d)&&DW(String(d))},children:[s.jsx(mt,{id:"settings-prompt-mode",className:"w-[240px]",disabled:a||o,"aria-label":r("系统提示词模式"),children:s.jsx(pt,{children:c})}),s.jsx(ht,{children:zo.map(d=>s.jsx(qe,{value:d.value,children:d.optionLabel},d.value))})]})}),s.jsx("div",{className:"hint",children:$n.promptMode})]}),s.jsx(hJ,{prompt:t,locked:a,busy:o}),s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"btn-prompt-edit-body",children:r("提示词正文")}),s.jsx("span",{className:"prompt-input",children:s.jsx(sJ,{prompt:t,locked:a,busy:o})}),s.jsxs("div",{className:"hint",children:[$n.promptText,t.source==="inline"?r("(当前生效的就是这一份,{n} 行)",{n:t.lines}):t.text.trim()?r("(已存一份正文,{n} 行;切成「替换 / 追加」后生效)",{n:t.lines}):""]})]}),s.jsxs("div",{className:"prompt-group",children:[r("按提供商配置"),s.jsx("span",{className:"note",children:r("只列单独配置过的家,其余沿用上面的全局配置")})]}),s.jsx(jJ,{prompt:t,locked:a,busy:o}),t.status==="ready"&&t.degradeActive?s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{children:r("内容拦截降级")}),s.jsx("span",{className:"prompt-input",children:s.jsx(se,{id:"btn-prompt-clear-degrade",variant:"outline",disabled:o,onClick:()=>{FW()},children:r("立即解除")})}),s.jsx("div",{className:"hint",children:xJ(t)})]}):null]}),s.jsx("div",{className:"settings-state",children:gJ(t)}),s.jsx("div",{className:"hint retention-note",children:$n.prompt})]})]})}function SJ(e){if(e.status==="loading")return Ut.appLoading;if(e.status==="unavailable")return Ut.debugUnavailable;const t=e.count!==null&&e.limit!==null?r("已保存 {count} / {limit} 条报文(超出后丢弃最旧的)。",{count:e.count,limit:e.limit}):"";return e.on?`${Ut.debugOn}${t}${r("凭据类请求头已脱敏。")}`:Ut.debugOff}function NJ({snap:e}){return s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("请求超时"),tip:ss.timeouts,badge:Tp(e.timeouts),actions:s.jsx(Br,{id:"btn-timeouts-refresh",onClick:()=>{KW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"retention-list",children:SI.map(t=>s.jsx(Cp,{field:t,value:e.timeouts.values?.[t.key]??null,disabled:e.busy==="timeouts",onCommit:a=>yW(t,a)},t.key))}),s.jsx("div",{className:"hint retention-note",children:$n.timeouts})]})]})}function kJ({snap:e}){return s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("请求重试"),tip:ss.retry,badge:Tp(e.retry),actions:s.jsx(Br,{id:"btn-retry-refresh",onClick:()=>{GW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"retention-list",children:[wI.map(t=>s.jsx(Cp,{field:t,value:e.retry.values?.[t.key]??null,disabled:e.busy==="retry",onCommit:a=>gW(t,a)},t.key)),s.jsx(mJ,{codes:e.retryCodes,status:e.retry.status,busy:e.busy==="codes"||e.busy==="retry"})]}),s.jsx("div",{className:"hint retention-note",children:$n.retry})]})]})}const CJ={routingFailoverBackoff:"failoverBackoff",routingSink:"sink",routingBreakerEnabled:"breakerEnabled"};function TJ({snap:e}){const t=e.routing,a=e.busy==="routing"||t.status!=="ready",o=Cx.find(d=>d.value===t.strategy)?.value??"order",c=Tx.find(d=>d.value===t.sticky)?.value??"auto";return s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("账号路由"),tip:ss.routing,badge:t.status==="ready"?void 0:t.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Br,{id:"btn-routing-refresh",onClick:()=>{QW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"retention-list",children:[s.jsx("div",{className:"prompt-group",children:r("选路规则")}),s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{children:r("路由策略")}),s.jsxs("div",{className:"routing-row",children:[s.jsx("span",{className:"tip-q","data-tip":Cx.find(d=>d.value===o)?.tip}),s.jsx(In,{options:Cx.map(d=>({value:d.value,label:d.label})),value:o,disabled:a,"aria-label":r("路由策略"),onValueChange:d=>{cS({routingStrategy:String(d)})}})]})]}),s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{children:r("会话粘性")}),s.jsxs("div",{className:"routing-row",children:[s.jsx("span",{className:"tip-q","data-tip":Tx.find(d=>d.value===c)?.tip}),s.jsx(In,{options:Tx.map(d=>({value:d.value,label:d.label})),value:c,disabled:a,"aria-label":r("会话粘性"),onValueChange:d=>{cS({routingSticky:String(d)})}})]})]}),s.jsxs("div",{className:"prompt-group",children:[r("自愈保护"),s.jsx("span",{className:"note",children:r("默认值通常够用,出问题时才需要调")})]}),VZ.map(d=>{const f=`route-protection-${d.key}`;return s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:f,children:d.label}),s.jsxs("div",{className:"routing-row",children:[s.jsx("span",{className:"tip-q","data-tip":d.tip}),s.jsx(ms,{id:f,checked:t[CJ[d.key]],disabled:a,onCheckedChange:p=>{cS({[d.key]:p})}})]})]},d.key)})]}),s.jsx("div",{className:"hint retention-note",children:$n.routing})]})]})}function EJ({snap:e}){return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("排队等待"),tip:ss.queue,badge:Tp(e.queue),actions:s.jsx(Br,{id:"btn-queue-refresh",onClick:()=>{YW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"retention-list",children:NI.map(t=>s.jsx(Cp,{field:t,value:e.queue.values?.[t.key]??null,disabled:e.busy==="queue",onCommit:a=>cW(t,a)},t.key))}),s.jsx("div",{className:"hint retention-note",children:$n.queue})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("验证码令牌池"),tip:ss.captchaPool,badge:Tp(e.captchaPool),actions:s.jsx(Br,{id:"btn-captcha-pool-refresh",onClick:()=>{XW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"retention-list",children:RI.map(t=>s.jsx(Cp,{field:t,value:e.captchaPool.values?.[t.key]??null,disabled:e.busy==="captchaPool",onCommit:a=>uW(t,a)},t.key))}),s.jsx("div",{className:"hint retention-note",children:$n.captchaPool})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("models.dev 模型元数据"),tip:ss.modelsDev,badge:e.modelsDev.status==="ready"?s.jsx(cn,{tone:"ok",children:r("{count} 条",{count:Number(e.modelsDev.count).toLocaleString("zh-CN")})}):e.modelsDev.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Br,{id:"btn-modelsdev-refresh",onClick:()=>{TW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx(da,{id:"settings-modelsdev",label:r("用 models.dev 补齐上游没声明的模型能力与思考档位(联网刷新,内嵌快照始终生效)"),checked:e.modelsDev.enabled,disabled:e.modelsDev.status!=="ready"||e.busy==="modelsDev",onCheckedChange:t=>{CW(t)}}),s.jsx("div",{className:"settings-state",children:MZ(e.modelsDev)}),s.jsx("div",{className:"hint retention-note",children:$n.modelsDev})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("指纹脱敏"),tip:ss.sanitize,badge:e.sanitize.status==="ready"?s.jsx(cn,{tone:"ok",children:r("已生效")}):e.sanitize.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Br,{id:"btn-sanitize-refresh",onClick:()=>{WW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"settings-switches",children:s.jsx(da,{id:"settings-sanitize",label:r("剥离上游审核黑名单指纹(改写请求体里的模板句与表头)"),checked:e.sanitize.on,disabled:e.sanitize.status!=="ready"||e.busy==="sanitize",onCheckedChange:t=>{wW(t)}})}),s.jsx("div",{className:"settings-state",children:e.sanitize.status==="loading"?Ut.appLoading:e.sanitize.status==="unavailable"?Ut.sanitizeUnavailable:e.sanitize.on?Ut.sanitizeOn:Ut.sanitizeOff}),s.jsx("div",{className:"hint retention-note",children:$n.sanitize})]})]}),s.jsx(RJ,{snap:e}),s.jsx(wJ,{snap:e}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("调试模式"),tip:ss.debug,badge:e.debug.status==="ready"?s.jsx(cn,{tone:"ok",children:r("已生效")}):e.debug.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Br,{id:"btn-debug-refresh",onClick:()=>{ZW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"settings-switches",children:s.jsx(da,{id:"settings-debug-mode",label:r("保存上游原始报文(请求头、请求体、响应头、响应体)"),checked:e.debug.on,disabled:e.debug.status!=="ready"||e.busy==="debug",onCheckedChange:t=>{jW(t)}})}),s.jsx("div",{className:"settings-state",children:SJ(e.debug)}),s.jsx("div",{className:"hint retention-note",children:$n.debug})]})]})]})}function WI(e){const t=Object.entries(e.defaults).map(([a,o])=>({key:a,value:a in e.overrides?e.overrides[a]:o,isDefault:!0}));for(const[a,o]of Object.entries(e.overrides))a in e.defaults||t.push({key:a,value:o,isDefault:!1});return t}function AJ(e,t){const a=Object.keys(e);return a.length!==Object.keys(t).length?!1:a.every(o=>e[o]===t[o])}function RJ({snap:e}){const t=e.clineHeaders,[a,o]=x.useState(()=>WI(t));x.useEffect(()=>{o(WI(t))},[t]);const c=e.busy==="clineHeaders",d=t.status==="ready";function f(v,y){o(b=>b.map((j,w)=>w===v?{...j,...y}:j))}function p(){const v={};for(const y of a){const b=y.key.trim();b&&(y.isDefault?y.value!==(t.defaults[b]??"")&&(v[b]=y.value):y.value!==""&&(v[b]=y.value))}return v}const g=d&&!AJ(p(),t.overrides);return s.jsx(iJ,{title:r("Cline 伪装头"),tip:ss.clineHeaders,badge:t.status==="ready"?s.jsx(cn,{tone:"ok",children:r("已生效")}):t.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Br,{id:"btn-cline-headers-refresh",onClick:()=>{SW()}}),children:s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"retention-list",children:[d?a.map((v,y)=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx($e,{className:"w-[190px] shrink-0 font-mono text-[13px]",value:v.key,readOnly:v.isDefault,disabled:c,placeholder:"X-Custom-Header",onChange:b=>f(y,{key:b.target.value})}),s.jsx($e,{className:"flex-1 font-mono text-[13px]",value:v.value,disabled:c,placeholder:v.isDefault?r("值(留空 = 不发送)"):r("值"),onChange:b=>f(y,{value:b.target.value})}),s.jsx(se,{variant:"ghost",disabled:c,onClick:()=>{v.isDefault?f(y,{value:t.defaults[v.key]??""}):o(b=>b.filter((j,w)=>w!==y))},children:v.isDefault?r("还原"):r("删除")})]},String(y))):null,s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(se,{variant:"outline",disabled:c||!d,onClick:()=>o(v=>[...v,{key:"",value:"",isDefault:!1}]),children:r("添加自定义头")}),s.jsx("div",{className:"flex-1"}),s.jsx(se,{variant:"ghost",disabled:c||!d||Object.keys(t.overrides).length===0,onClick:()=>{GI({})},children:r("恢复默认")}),s.jsx(se,{disabled:c||!d||!g,onClick:()=>{GI(p())},children:r("保存")})]})]}),s.jsx("div",{className:"settings-state",children:t.status==="loading"?Ut.appLoading:t.status==="unavailable"?r("未能读取 Cline 伪装头设置,请稍后重试"):g?r("有未保存的修改"):r("{n} 个头将随每个 Cline 请求发送",{n:Object.keys(t.effective).length})+(Object.keys(t.overrides).length>0?r("({n} 项被覆盖)",{n:Object.keys(t.overrides).length}):r("(全部为默认值)"))}),s.jsx("div",{className:"hint retention-note",children:$n.clineHeaders})]})})}function OJ({snap:e}){const[t,a]=x.useState(!1);async function o(){a(!0),await $W()||a(!1)}return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("网关跨域访问(CORS)"),tip:ss.cors,badge:e.cors.status==="ready"?e.cors.on?s.jsx(cn,{tone:"bad",children:r("已开启")}):s.jsx(cn,{tone:"ok",children:r("已关闭")}):e.cors.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Br,{id:"btn-cors-refresh",onClick:()=>{JW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"settings-switches",children:s.jsx(da,{id:"settings-cors",label:r("允许浏览器里的页面跨来源调用网关(/v1/*)"),checked:e.cors.on,disabled:e.cors.status!=="ready"||e.busy==="cors",onCheckedChange:c=>{NW(c)}})}),s.jsx("div",{className:"settings-state",children:e.cors.status==="loading"?Ut.appLoading:e.cors.status==="unavailable"?Ut.corsUnavailable:e.cors.on?Ut.corsOn:Ut.corsOff}),s.jsx("div",{className:"hint retention-note",children:$n.cors})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("机器人校验")}),s.jsxs("div",{className:"panel-body",children:[s.jsx(da,{id:"settings-captcha",label:r("登录 / 注册需要通过 ALTCHA 人机验证(工作量证明)"),checked:e.captcha.enabled,disabled:!e.captcha.available||e.busy==="captcha",onCheckedChange:c=>{kW(c)}}),s.jsx("div",{className:"hint",children:$n.captcha})]})]}),e.panelLogin?s.jsxs("section",{className:"panel",id:"panel-login-section",children:[s.jsx(Qn,{title:r("面板登录")}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"hint",children:$n.panelLogin}),s.jsx("div",{className:"mt-2.5",children:s.jsx(se,{id:"btn-panel-logout",variant:"outline",disabled:t,onClick:()=>{o()},children:r("退出登录")})})]})]}):null]})}function Ep({label:e,value:t}){return s.jsxs("div",{className:"storage-count",children:[s.jsx("span",{className:"k",children:e}),s.jsx("span",{className:"v",children:t})]})}function MJ(e){return e.status==="loading"?s.jsx(cn,{tone:"idle",children:r("检测中…")}):e.status==="unavailable"?s.jsx(cn,{tone:"bad",children:r("不可用")}):s.jsx(cn,{tone:e.available?"ok":"bad",children:e.available?r("已生效"):r("数据库不可用")})}function DJ({snap:e}){const t=e.busy,a=e.storage,o=tt().workbuddyDesktop?.platform==="web",c=a.status==="ready",d=c&&a.available,f=c&&a.file?a.file:"—",p=g=>d&&g!==null?UZ(g):"—";return s.jsxs(s.Fragment,{children:[!o&&s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("整库备份 / 恢复"),tip:ss.backup,actions:s.jsxs(s.Fragment,{children:[s.jsx(se,{id:"btn-settings-db-export",variant:"outline",disabled:t==="dbExport"||t==="dbImport",onClick:()=>{nW()},children:r(t==="dbExport"?"备份中…":"备份整库")}),s.jsx(se,{id:"btn-settings-db-restore",variant:"destructive",disabled:t==="dbExport"||t==="dbImport",onClick:()=>sW(),children:r(t==="dbImport"?"恢复中…":"恢复整库")})]})}),s.jsxs("div",{className:"panel-body",children:[e.dbWarning?s.jsxs("div",{className:"danger-zone",id:"settings-db-warning",children:[s.jsx("strong",{children:r("⚠️ 密钥警告")}),s.jsx("br",{}),e.dbWarning]}):null,s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"settings-db-include-logs",children:r("包含日志与调试报文")}),s.jsx(ms,{id:"settings-db-include-logs",checked:e.dbIncludeLogs,disabled:t!==null,onCheckedChange:tW}),s.jsx("div",{className:"hint",children:r("取消勾选后只备份业务数据(账号、配置与余额记录),文件显著变小;事件日志、请求统计与调试报文不会进备份文件。")})]}),s.jsx("div",{className:"danger-zone",children:s.jsx("strong",{children:$n.backupDanger})})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("账号导入 / 导出"),tip:ss.io,actions:s.jsxs(s.Fragment,{children:[s.jsx(se,{id:"btn-settings-export",variant:"outline",disabled:t==="export",onClick:()=>{JZ()},children:r(t==="export"?"导出中…":"导出账号")}),s.jsx(se,{id:"btn-settings-import",variant:"default",disabled:t==="import",onClick:()=>{eW()},children:r(t==="import"?"导入中…":"导入账号")})]})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"danger-zone",children:[s.jsx("strong",{children:r("导出文件内含 accessToken / refreshToken / apiKey 等凭证与自定义提供商定义")}),r(",可直接用于登录。请妥善保管,不要外传或上传到公共位置。")]}),e.ioFailure?s.jsx("div",{className:"io-result",children:s.jsxs("span",{className:"text-destructive",children:[r("失败 {n} 个:{detail}",{n:e.ioFailure.failed,detail:e.ioFailure.detail}),e.ioFailure.more?r(" 等"):""]})}):null]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("数据保留"),tip:ss.retention,badge:Tp(e.retention),actions:s.jsx(Br,{id:"btn-retention-refresh",onClick:()=>{qW()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"retention-list",children:eS.map(g=>s.jsx(Cp,{field:g,value:e.retention.values?.[g.key]??null,disabled:e.busy==="retention",onCommit:v=>oW(g,v)},g.key))}),s.jsx("div",{className:"hint retention-note",children:$n.retention})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("数据存储"),tip:ss.storage,badge:MJ(a),actions:s.jsx(Br,{id:"btn-storage-refresh",onClick:()=>{tJ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"retention-list",children:[s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"storage-db-path",children:r("数据库文件")}),s.jsx("span",{className:"storage-line",children:s.jsx("span",{className:"storage-path",id:"storage-db-path",title:f,children:f})}),s.jsx("div",{className:"hint",children:$n.storageFile})]}),s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"storage-db-size",children:r("占用大小")}),s.jsx("span",{className:"storage-line",children:s.jsx("span",{className:"storage-path",id:"storage-db-size",children:d?AI(a.bytes):"—"})}),s.jsx("div",{className:"hint",children:$n.storageSize})]})]}),s.jsxs("div",{className:"retention-list storage-counts",children:[s.jsx(Ep,{label:r("账号"),value:p(a.accounts)}),s.jsx(Ep,{label:r("事件日志"),value:p(a.logs)}),s.jsx(Ep,{label:r("请求记录"),value:p(a.requests)}),s.jsx(Ep,{label:r("报表天数"),value:p(a.dailyDays)}),s.jsx(Ep,{label:r("调试报文"),value:p(a.debug)})]}),s.jsx("div",{className:"hint retention-note",children:$n.storage})]})]})]})}const IJ=[{title:r("问题反馈"),desc:r("遇到 Bug、报错或异常行为"),cta:r("去反馈"),url:"https://github.com/aimod-cc/agent2api/issues/new?template=bug_report.yml"},{title:r("功能建议"),desc:r("想要的新功能或改进想法"),cta:r("提建议"),url:"https://github.com/aimod-cc/agent2api/issues/new?template=feature_request.yml"},{title:r("请求提供商 / 模型支持"),desc:r("希望接入新的提供商或模型"),cta:r("去申请"),url:"https://github.com/aimod-cc/agent2api/issues/new?template=provider_request.yml"}];function PJ(){return s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("反馈与需求")}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"hint",children:r("点下面的入口会用系统默认浏览器打开 GitHub 的对应表单(需要 GitHub 账号,模板已预设好,填完直接提交即可)。")}),s.jsx("div",{className:"mt-3 flex flex-col gap-2",children:IJ.map(e=>s.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-md border border-hairline bg-surface-2 px-3 py-2.5",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12.5px] text-foreground",children:e.title}),s.jsx("div",{className:"mt-0.5 text-[12px] text-subtle",children:e.desc})]}),s.jsx(se,{variant:"outline",size:"sm",onClick:()=>{DZ(e.url)},children:e.cta})]},e.url))})]})]})}function _J({confirm:e}){const t=x.useRef(null);return s.jsx(Qt,{open:e!==null,onOpenChange:a=>{a||Mx(!1)},children:s.jsxs(Zt,{className:"w-[min(440px,calc(100vw-48px))]",initialFocus:t,children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("确认缩短保留天数")})}),s.jsx(Bt,{children:s.jsxs("div",{className:"danger-zone",children:[e?.head,s.jsx("br",{}),s.jsx("strong",{children:r("超出的历史数据会被立即删除,且不可恢复。")}),r("确定继续?")]})}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{ref:t,variant:"outline",onClick:()=>Mx(!1),children:r("取消")}),s.jsx(se,{variant:"destructive",onClick:()=>Mx(!0),children:r("继续并清理")})]})]})})}const wS={enable:{title:r("开启局域网访问"),body:()=>s.jsxs(s.Fragment,{children:[r("为了安全,开启前需要先注册一个"),s.jsx("b",{children:r("面板管理员账号")}),r("(已注册过会跳过这一步,直接生效)。"),s.jsx("br",{}),r("开启后网关将监听所有网卡,同一局域网内的设备即可把 API 地址指向本机 IP 一起使用;管理接口从此要求管理员会话或网关 Key,转发接口在没有一把启用的 Key 时也会拒绝服务(届时会自动创建一把名为「默认」的 Key)。"),s.jsx("br",{}),s.jsx("strong",{children:r("保存后应用将重启以生效。")}),r("确定继续?")]}),label:r("继续")},disable:{title:r("关闭局域网访问"),body:()=>s.jsxs(s.Fragment,{children:[r("关闭后网关回到只监听 127.0.0.1,局域网内的设备将无法继续访问;已配置的网关 Key 与账号都不受影响。"),s.jsx("br",{}),s.jsx("strong",{children:r("保存后应用将重启以生效。")}),r("确定继续?")]}),label:r("关闭并重启")},panel:{title:r("变更网页管理面板"),body:e=>e?s.jsxs(s.Fragment,{children:[r("开放后,局域网内其他设备的浏览器打开本机 IP 即可进入管理面板(需管理员账号登录)。"),s.jsx("br",{}),s.jsx("strong",{children:r("保存后应用将重启以生效。")}),r("确定继续?")]}):s.jsxs(s.Fragment,{children:[r("关闭后,管理界面不再从局域网提供,只有本机的桌面程序可以管理;已开启的 API 转发不受影响。"),s.jsx("br",{}),s.jsx("strong",{children:r("保存后应用将重启以生效。")}),r("确定继续?")]}),label:r("保存并重启")}};function LJ({confirm:e}){const t=x.useRef(null);return s.jsx(Qt,{open:e!==null,onOpenChange:a=>{a||iS(!1)},children:s.jsxs(Zt,{className:"w-[min(440px,calc(100vw-48px))]",initialFocus:t,children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("恢复整库备份")})}),s.jsx(Bt,{children:s.jsxs("div",{className:"danger-zone",children:[r("本机的全部数据(账号、网关配置、日志统计与桌面设置)将被所选备份文件"),s.jsx("strong",{children:r("整体替换")}),r(",包括恢复后需要重新登录管理面板。"),s.jsx("br",{}),s.jsx("strong",{children:r("替换前会自动把当前数据备份到配置目录的 backups/ 文件夹。")}),r("确定继续?")]})}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{ref:t,variant:"outline",onClick:()=>iS(!1),children:r("取消")}),s.jsx(se,{variant:"destructive",onClick:()=>iS(!0),children:r("选择备份文件并恢复")})]})]})})}function zJ({confirm:e,register:t}){const a=x.useRef(null),o=x.useRef(null),c=x.useRef(null),d=e!==null||t!==null,f=()=>{t!==null?PI():oS(!1)},p=()=>{WZ(o.current?.value??"",c.current?.value??"")};return s.jsx(Qt,{open:d,onOpenChange:g=>{g||f()},children:s.jsx(Zt,{className:"w-[min(480px,calc(100vw-48px))]",initialFocus:a,children:t!==null?s.jsxs(s.Fragment,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("注册管理员账号")})}),s.jsxs(Bt,{children:[s.jsx("div",{children:r("局域网开放后,管理接口要求登录。请设置管理员账号与密码,注册完成会直接继续开启流程。")}),s.jsxs("form",{onSubmit:g=>{g.preventDefault(),t.busy||p()},children:[s.jsx(Je,{htmlFor:"lan-admin-name",className:"mt-3.5 mb-[5px] block text-[12.5px]",children:r("账号")}),s.jsx($e,{ref:o,id:"lan-admin-name",autoComplete:"username",placeholder:r("管理员账号"),disabled:t.busy}),s.jsx(Je,{htmlFor:"lan-admin-password",className:"mt-3.5 mb-[5px] block text-[12.5px]",children:r("密码")}),s.jsx($e,{ref:c,id:"lan-admin-password",type:"password",autoComplete:"new-password",placeholder:r("至少 8 位"),disabled:t.busy})]}),s.jsx("div",{className:"mt-3 min-h-5 text-[13px] whitespace-pre-wrap text-destructive",children:t.error})]}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{ref:a,variant:"outline",onClick:PI,disabled:t.busy,children:r("取消")}),s.jsx(se,{onClick:p,disabled:t.busy,children:t.busy?r("正在注册…"):r("注册并开启")})]})]}):s.jsxs(s.Fragment,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:e?wS[e.mode].title:""})}),s.jsx(Bt,{children:s.jsx("div",{children:e?wS[e.mode].body(e.panel):null})}),s.jsxs(nn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{ref:a,variant:"outline",onClick:()=>oS(!1),children:r("取消")}),s.jsx(se,{onClick:()=>oS(!0),children:e?wS[e.mode].label:r("继续")})]})]})})})}function BJ(){const e=qZ(),t=x.useRef(null);x.useEffect(()=>{const o=t.current;o&&(o.scrollTop=0)},[e.scrollReset]);const a=o=>e.category===o?"settings-pane active":"settings-pane";return s.jsxs("div",{className:"settings-layout",children:[s.jsx("nav",{className:"settings-nav",id:"settings-nav",children:Nx.map(o=>s.jsxs("button",{type:"button",className:e.category===o.id?"settings-nav-item active":"settings-nav-item","data-cat":o.id,onClick:()=>GZ(o.id),children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:QI(o.icon,17)}}),o.label]},o.id))}),s.jsxs("div",{className:"settings-panes",ref:t,children:[s.jsx("div",{className:a("general"),"data-cat":"general",children:s.jsx(uJ,{snap:e})}),s.jsx("div",{className:a("display"),"data-cat":"display",children:s.jsx(fJ,{})}),s.jsx("div",{className:a("gateway"),"data-cat":"gateway",children:s.jsx(EJ,{snap:e})}),s.jsx("div",{className:a("routing"),"data-cat":"routing",children:s.jsx(TJ,{snap:e})}),s.jsx("div",{className:a("retry"),"data-cat":"retry",children:s.jsx(kJ,{snap:e})}),s.jsx("div",{className:a("timeout"),"data-cat":"timeout",children:s.jsx(NJ,{snap:e})}),s.jsx("div",{className:a("security"),"data-cat":"security",children:s.jsx(OJ,{snap:e})}),s.jsx("div",{className:a("data"),"data-cat":"data",children:s.jsx(DJ,{snap:e})}),s.jsx("div",{className:a("feedback"),"data-cat":"feedback",children:s.jsx(PJ,{})}),s.jsx("div",{className:a("about"),"data-cat":"about"})]}),s.jsx(_J,{confirm:e.retentionConfirm}),s.jsx(LJ,{confirm:e.dbBackupConfirm}),s.jsx(zJ,{confirm:e.lanConfirm,register:e.lanRegister})]})}const JI='.page[data-page="settings"]';let SS=null;function eP(){if(SS)return;const e=document.querySelector(JI);e&&(e.replaceChildren(),SS=vn.createRoot(e),ks.flushSync(()=>{SS?.render(s.jsx(BJ,{}))}))}MI(),document.querySelector(JI)?eP():document.addEventListener("DOMContentLoaded",eP,{once:!0}),window.wbSettingsPanel={load:jS,render:aS,renderRetention:Ax,renderRetry:hW,renderDebug:Px,renderSanitize:_x,renderPrompt:Ku,renderStorage:yS,showCategory:rS},tt().wbApp?.currentPage==="settings"&&jS();const tP="agent2api-col-config:",NS=[{value:"left",label:r("左")},{value:"center",label:r("中")},{value:"right",label:r("右")}],HJ=e=>NS.some(t=>t.value===e),UJ=NS.map(e=>`ta-${e.value}`),nP="colset-dragging",sP="open";let kS=null;const rP="grid grid-cols-[18px_minmax(78px,1fr)_44px_minmax(106px,auto)] items-center gap-2";function aP(){return window}const Bx=new Map;function CS(e){return e.columns.map(t=>({key:t.key,visible:t.visible!==!1,align:t.align||"left"}))}function VJ(e,t){const a=Array.isArray(t),o=!a&&t&&typeof t=="object"?t:null,c=a?t:Array.isArray(o?.items)?o.items:[],d=o?.defaults&&typeof o.defaults=="object"?o.defaults:null,f=new Map(e.columns.map(y=>[y.key,y])),p=new Map(CS(e).map(y=>[y.key,y])),g=[],v=new Set;for(const y of c){const b=y&&typeof y=="object"?y:{},j=String(b.key||"");if(!f.has(j)||v.has(j))continue;v.add(j);const w=f.get(j),S=w.align||"left",N=d?d[j]??S:w.legacyAlign??S,k=HJ(b.align)?b.align:null;g.push({key:j,visible:b.visible!==!1,align:k&&k!==N?k:S})}for(const y of e.columns)v.has(y.key)||FJ(g,e,{...p.get(y.key)});return g}function FJ(e,t,a){const o=t.columns.findIndex(c=>c.key===a.key);for(let c=o-1;c>=0;c-=1){const d=e.findIndex(f=>f.key===t.columns[c].key);if(d>=0){e.splice(d+1,0,a);return}}e.unshift(a)}function $J(e){try{const t=localStorage.getItem(tP+e.id);return VJ(e,t?JSON.parse(t):[])}catch{return CS(e)}}function qJ(e){try{const t={};for(const a of e.columns)t[a.key]=a.align||"left";localStorage.setItem(tP+e.id,JSON.stringify({v:2,defaults:t,items:e.config}))}catch{}}const GJ=e=>Bx.get(e)?.config||null,KJ=(e,t)=>e.columns.find(a=>a.key===t)?.label||t;function lP(e,t){const a=Bx.get(e);if(!a)return t;const o=new Map(t.map(c=>[c.key,c]));return a.config.filter(c=>c.visible&&o.has(c.key)).map(c=>({...o.get(c.key),align:c.align}))}function Ap(e,{silent:t=!1}={}){qJ(e),t||e.onChange?.(e.config),Il&&Il.id===e.id&&Il.repaint()}let Il=null;function Hx(){if(!Il)return;const e=Il;Il=null,e.destroy()}function YJ(e,t){Hx();const a=document.createElement("div");document.body.append(a);const o=vn.createRoot(a),c={current:null};Il={id:e.id,spec:e,repaint:()=>c.current?.(),destroy:()=>{o.unmount(),a.remove()}},o.render(s.jsx(JJ,{spec:e,anchor:t,repaintRef:c,onClose:Hx}))}function XJ(e,t){Il&&Il.id===e.id?Hx():YJ(e,t)}function QJ(e,t,a){const o=[...e],[c]=o.splice(t,1);return o.splice(a,0,c),o}function ZJ(e,t,a,o){const c=document.elementFromPoint(e,t)?.closest?.("[data-col-key]");if(!c||!a||!a.contains(c))return"";const d=c.getAttribute("data-col-key")||"";return o.some(f=>f.key===d)?d:""}const WJ=s.jsxs("svg",{viewBox:"0 0 24 24",width:13,height:13,fill:"currentColor","aria-hidden":"true",className:"block",children:[s.jsx("circle",{cx:"9",cy:"6",r:"1.6"}),s.jsx("circle",{cx:"15",cy:"6",r:"1.6"}),s.jsx("circle",{cx:"9",cy:"12",r:"1.6"}),s.jsx("circle",{cx:"15",cy:"12",r:"1.6"}),s.jsx("circle",{cx:"9",cy:"18",r:"1.6"}),s.jsx("circle",{cx:"15",cy:"18",r:"1.6"})]});function JJ({spec:e,anchor:t,repaintRef:a,onClose:o}){const c=t,d=x.useRef(null),[f,p]=x.useState(null),g=x.useRef(null),[,v]=x.useState(0),y=x.useCallback(()=>v(N=>N+1),[]);x.useLayoutEffect(()=>(a.current=y,()=>{a.current=null}),[y,a]),x.useEffect(()=>(c.classList.add(sP),c.setAttribute("aria-expanded","true"),()=>{c.classList.remove(sP),c.setAttribute("aria-expanded","false")}),[c]),x.useEffect(()=>{const N=()=>{const k=c.getBoundingClientRect();(!c.isConnected||!k.width||k.bottom<=0||k.top>=window.innerHeight)&&o()};return window.addEventListener("scroll",N,!0),window.addEventListener("resize",N),()=>{window.removeEventListener("scroll",N,!0),window.removeEventListener("resize",N)}},[c,o]),x.useEffect(()=>()=>{const N=g.current;N&&(N.teardown(),Ap(e))},[e]);function b(N,k){const E=e.config.find(D=>D.key===N);E&&(!k&&e.config.filter(D=>D.visible).length<=1||(E.visible=k,Ap(e)))}function j(N,k){const E=e.config.find(D=>D.key===N);!E||E.align===k||(E.align=k,Ap(e))}function w(){e.config=CS(e),Ap(e)}function S(N,k){k.preventDefault(),g.current?.teardown(),p(N),document.body.classList.add(nP);const E=d.current;function D(){window.removeEventListener("pointermove",C),window.removeEventListener("pointerup",A),document.body.classList.remove(nP),g.current=null,p(null)}function C(R){const I=ZJ(R.clientX,R.clientY,E,e.config);if(!I||I===N)return;const P=e.config.findIndex(_=>_.key===N),O=e.config.findIndex(_=>_.key===I);P<0||O<0||(e.config=QJ(e.config,P,O),y())}function A(){D(),Ap(e)}g.current={teardown:D},window.addEventListener("pointermove",C),window.addEventListener("pointerup",A)}return s.jsx(mf,{open:!0,modal:!1,onOpenChange:(N,k)=>{N||(k?.reason==="outside-press"&&(kS=k.event??null),o())},children:s.jsxs(hf,{anchor:c,side:"bottom",align:"end",sideOffset:6,collisionPadding:8,className:"w-[336px]","aria-label":r("{name}的列设置",{name:e.label||e.id}),children:[s.jsxs("div",{className:Ue(rP,"border-b border-hairline px-3 pt-[9px] pb-[7px]","text-[10.5px] font-semibold tracking-[.05em] text-muted-foreground"),children:[s.jsx("span",{}),s.jsx("span",{className:"text-center",children:r("列")}),s.jsx("span",{className:"text-center",children:r("显示")}),s.jsx("span",{className:"text-center",children:r("对齐")})]}),s.jsx("div",{ref:d,className:"min-h-0 flex-1 overflow-y-auto px-3 py-1",children:e.config.map(N=>{const k=KJ(e,N.key),E=f===N.key;return s.jsxs("div",{"data-col-key":N.key,className:Ue(rP,"rounded-sm py-[5px] hover:bg-nav-hover",E&&"opacity-50"),children:[s.jsx("span",{className:"flex cursor-grab items-center justify-center text-muted-foreground opacity-50 hover:opacity-100",title:r("按住拖动调整列顺序"),onPointerDown:D=>S(N.key,D),children:WJ}),s.jsx("span",{className:"min-w-0 truncate text-xs text-foreground",title:k,children:k}),s.jsx(ms,{className:"justify-self-center",checked:N.visible,onCheckedChange:D=>b(N.key,D),"aria-label":r("显示「{label}」列",{label:k}),title:N.visible?r("这一列正在显示"):r("这一列已隐藏")}),s.jsx(In,{className:"w-full justify-center",options:NS,value:N.align,onValueChange:D=>j(N.key,D),"aria-label":r("「{label}」列的对齐",{label:k})})]},N.key)})}),s.jsxs("div",{className:"flex items-center gap-2 border-t border-hairline px-3 pt-2 pb-[9px]",children:[s.jsx("span",{className:"flex-1 text-[11px] text-muted-foreground",children:r("拖动 ⋮⋮ 调整顺序")}),s.jsx(se,{variant:"outline",size:"sm",onClick:w,children:r("恢复默认")})]})]})})}function eee(e,t){e&&(e.classList.remove(...UJ),e.classList.add(`ta-${t}`))}const oP=new Map;function tee(e,t){const a=oP.get(e);if(a&&a.table===t&&a.row.isConnected)return a;const o=t?.querySelector("thead tr");if(!o)return null;const c=t?.querySelector("colgroup")??null,d={table:t,row:o,group:c,ths:new Map([...o.querySelectorAll("th[data-col]")].map(f=>[f.getAttribute("data-col")||"",f])),cols:new Map([...c?.querySelectorAll("col[data-col]")||[]].map(f=>[f.getAttribute("data-col")||"",f]))};return oP.set(e,d),d}function nee(e,t,a){const o=Bx.get(e);if(!o||!t)return;const c=tee(e,t);if(!c)return;const{row:d,group:f,ths:p,cols:g}=c;for(const v of o.config){const y=p.get(v.key);if(!y)continue;const b=g.get(v.key);if(!v.visible||a?.has(v.key)){y.remove(),b?.remove();continue}eee(y,v.align),d.appendChild(y),b&&f&&f.appendChild(b)}aP().wbTableColumns?.repaint?.(e)}function see(e){const t=document.createElement("button");return t.type="button",t.className=`sm colset-btn${e.buttonClass?` ${e.buttonClass}`:""}`,t.id=`btn-colset-${e.id}`,t.title=r("调整「{name}」的列:显示 / 隐藏、顺序、对齐",{name:e.label||e.id}),t.innerHTML=`${aP().wbIcons?.icon?.("settings",14)||""}${r("列设置")}`,t.setAttribute("aria-haspopup","dialog"),t.setAttribute("aria-expanded","false"),t.addEventListener("click",a=>{if(kS===a){kS=null;return}XJ(e,t)}),t}function ree(e){return(typeof e.mount=="function"?e.mount():e.mount?document.querySelector(e.mount):null)||null}function aee(e){const t={...e,config:$J(e)};Bx.set(e.id,t);const a=ree(e),o=see(t);return a&&(e.buttonPlacement==="last"?a.appendChild(o):a.insertBefore(o,a.firstChild)),{apply:c=>lP(e.id,c),config:()=>t.config}}window.wbColSettings={register:aee,apply:lP,configOf:GJ,syncStaticHead:nee,close:Hx};function sl(){return window}const lee=new Set(["updateCheck"]);function iP(e){return(Array.isArray(e?.tasks)?e.tasks:[]).filter(a=>!lee.has(a.id))}const oee=2e4,cP=1,iee=" · ";function Yu(e,t){sl().wbApp?.toast?.(e,t)}function Ux(e){return e instanceof Error?e.message:String(e)}function uP(e){return r(e==="seconds"?"秒":"分钟")}function dP(e){const t=Number(e)||0;return t?new Date(t).toLocaleTimeString("zh-CN",{hour12:!1}):""}function fP(e){const t=Number(e)||0;if(!t)return"";const a=t-Date.now();if(a<=0)return r("即将执行");const o=Math.round(a/1e3);if(o<60)return r("{n} 秒后",{n:o});const c=Math.round(o/60);if(c<60)return r("{n} 分钟后",{n:c});const d=Math.round(c/60);return d<24?r("{n} 小时后",{n:d}):r("{n} 天后",{n:Math.round(d/24)})}function cee(e){const t=e.runner==="backend",a=[];if(e.lastRunAt){const o=dP(e.lastRunAt);a.push(e.lastResult?r("上次执行 {time}({result})",{time:o,result:e.lastResult}):r("上次执行 {time}",{time:o}))}else a.push(r(t?"还没有执行记录":"由页面按间隔自动刷新"));return t&&e.enabled&&e.nextRunAt&&a.push(r("下次执行 {time}({relative})",{time:dP(e.nextRunAt),relative:fP(e.nextRunAt)})),t&&e.retryAt&&e.retryAt>Date.now()&&a.push(r("冷却中,{relative}重试",{relative:fP(e.retryAt)})),a.join(iee)}function uee(e,t){const a=String(t??"").trim(),o=uP(e.unit);if(!a)return{ok:!1,message:r("间隔不能为空(可填 {min}–{max} {unit})",{min:e.min,max:e.max,unit:o})};if(!/^\d+$/.test(a))return{ok:!1,message:r("间隔必须是整数")};const c=Number(a);return ce.max?{ok:!1,message:r("间隔必须在 {min}–{max} {unit} 之间(当前填的是 {value})",{min:e.min,max:e.max,unit:o,value:a})}:{ok:!0,value:c}}function dee(e){const t=sl();e.id==="logsAutoRefresh"?t.wbLogsPanel?.applyAutoRefresh?.(e):e.id==="requestsAutoRefresh"?t.wbRequestsPanel?.applyAutoRefresh?.(e):e.id==="reportAutoRefresh"&&t.wbReport?.applyAutoRefresh?.(e)}let oc=!1,Vx=null,TS=!1;async function pP(){if(!Vx){TS=!0;return}await Vx()}function fee(){const[e,t]=x.useState([]),[a,o]=x.useState(!1),[c,d]=x.useState(null),[f,p]=x.useState({});function g(I){p(P=>{if(!(I in P))return P;const O={...P};return delete O[I],O})}const v=x.useCallback(async()=>{const I=sl().workbuddyDesktop;try{if(!I)throw new Error(r("后端桥不可用"));const P=await I.getScheduledTasks();t(iP(P)),o(!0)}catch(P){console.warn("读取定时任务失败:",Ux(P)),t([]),o(!0)}},[]),y=x.useCallback(async()=>{if(oc||document.hidden||sl().wbApp?.currentPage!=="tasks")return;const I=sl().workbuddyDesktop;if(I)try{const P=await I.getScheduledTasks();t(iP(P))}catch(P){console.warn("同步定时任务状态失败:",Ux(P))}},[]);x.useEffect(()=>{const I=window.setInterval(()=>{y()},oee);return()=>{window.clearInterval(I)}},[y]),x.useEffect(()=>{sl().wbApp?.renderTopbarStatus?.()},[e,a]),x.useEffect(()=>(Vx=v,TS&&(TS=!1,v()),()=>{Vx=null}),[v]);async function b(I,P,O){if(oc)return;const _=sl().workbuddyDesktop;if(_){oc=!0;try{const L=await _.saveScheduledTask(I,P);t(H=>H.map(B=>B.id===I?L:B)),dee(L),Yu(r("✅ 已更新「{label}」",{label:O}))}catch(L){Yu(r("保存失败:{reason}",{reason:Ux(L)}),"err"),await v()}finally{oc=!1}}}async function j(I,P){const O=uee(I,P);if(!O.ok){Yu(O.message,"err"),g(I.id);return}if(O.value===I.interval){g(I.id);return}await b(I.id,{interval:O.value},r("{name}间隔",{name:r(I.label)})),g(I.id)}async function w(I){if(oc)return;const P=sl().workbuddyDesktop;if(P){oc=!0,d(I.id);try{const O=await P.runScheduledTask(I.id);if(O?.task){const _=O.task;t(L=>L.map(H=>H.id===I.id?_:H))}Yu(r("✅ {task}:{summary}",{task:r(I.label),summary:O?.summary||r("已执行")})),I.id==="credentialMaintenance"&&await sl().wbApp?.refresh?.()}catch(O){Yu(r("执行失败:{reason}",{reason:Ux(O)}),"err"),await v()}finally{oc=!1,d(null)}}}function S(I){const P=uP(I.unit),O=c===I.id;return s.jsxs("div",{className:"task-item","data-task":I.id,children:[s.jsxs("div",{className:"task-main",children:[s.jsxs("div",{className:"task-title",children:[s.jsxs("label",{className:"switch",children:[s.jsx(ms,{checked:I.enabled===!0,onCheckedChange:_=>{b(I.id,{enabled:_},r("{name}开关",{name:r(I.label)}))}}),s.jsx("span",{className:"task-name",children:r(I.label)})]}),s.jsx("span",{className:"tip-q","data-tip":r(I.description)}),s.jsx(ze,{className:"task-badge",variant:I.enabled?"success":"outline",children:I.enabled?r("已开启"):r("已关闭")}),I.running?s.jsx(ze,{className:"task-badge",variant:"warning",children:r("执行中…")}):null]}),s.jsx("div",{className:"task-state",children:cee(I)})]}),s.jsxs("div",{className:"task-actions",children:[s.jsxs("span",{className:"task-interval",children:[s.jsx("span",{className:"task-interval-label",children:r("每")}),s.jsx($e,{type:"number",inputMode:"numeric",min:I.min,max:I.max,step:1,className:"w-[74px] max-w-[74px] text-center tabular-nums",value:f[I.id]??String(I.interval),title:r("可填 {min}–{max} {unit}(默认 {def} {unit})",{min:I.min,max:I.max,unit:P,def:I.defaultInterval}),onChange:_=>{const L=_.currentTarget.value;p(H=>({...H,[I.id]:L}))},onBlur:_=>{j(I,_.currentTarget.value)},onKeyDown:_=>{_.key==="Enter"&&_.currentTarget.blur()}}),s.jsx("span",{className:"task-interval-unit",children:P})]}),I.canRun===!0?s.jsx(se,{size:"sm",variant:"outline",disabled:O||I.running===!0,onClick:()=>{w(I)},children:r(O?"执行中…":"立即执行")}):null]})]},I.id)}const N=e.length===0,k=e.filter(I=>I.enabled).length,E=N?a?r("不可用"):"—":r("{enabled} / {total} 个已开启",{enabled:k,total:e.length}),D=N?a?"destructive":"outline":k?"success":"outline",C=D==="destructive"?"bad":D==="success"?"ok":"",A=e.map(I=>S(I)),R=A.slice(cP);return s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("任务清单")}),s.jsx(ze,{id:"tasks-badge",variant:D,"data-tone":C,children:E}),s.jsx("span",{className:"panel-sub",children:r("状态每 20 秒自动同步")}),s.jsx("div",{className:"head-actions",children:s.jsx(se,{variant:"outline",onClick:()=>{v().then(()=>Yu(r("定时任务已刷新")))},children:r("刷新")})})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"task-list",children:N?s.jsx("div",{className:"log-empty",children:r(a?"没有可显示的定时任务。后端未返回任务清单,请确认网关正在运行。":"正在加载定时任务…")}):s.jsxs(s.Fragment,{children:[A.slice(0,cP),R.length?s.jsx("div",{className:"task-grid",children:R}):null]})})}),s.jsxs("div",{className:"panel-foot",children:[s.jsxs("span",{children:[r("任务配置保存在 "),s.jsx("code",{children:"~/.agent2api/config.json"}),r(" 的 "),s.jsx("code",{children:"scheduledTasks"}),r(" 字段")]}),s.jsx("span",{children:r("改动立即生效,不需要重启程序")})]})]})}const mP='.page[data-page="tasks"]';let hP=!1;function gP(){if(hP)return;const e=document.querySelector(mP);e&&(hP=!0,e.replaceChildren(),vn.createRoot(e).render(s.jsx(fee,{})))}document.querySelector(mP)?gP():document.addEventListener("DOMContentLoaded",gP,{once:!0}),window.wbTasksPanel={load:pP},sl().wbApp?.currentPage==="tasks"&&pP();const xP="workbuddy-desktop-update-skip";function pee(){try{return localStorage.getItem(xP)||""}catch{return""}}function mee(e){try{localStorage.setItem(xP,e)}catch{}}let bP="";function Fx(e,t){if(!e||e.hasUpdate!==!0||e.pendingRestart===!0)return;const a=String(e.latestVersion||"").trim();a&&Pn().wbApp?.currentPage!=="settings"&&(a===pee()||a===bP||(bP=a,vP(),Xu=document.createElement("div"),document.body.append(Xu),Rp=vn.createRoot(Xu),Rp.render(s.jsx(hee,{info:e,onGoUpdate:t,onClose:vP}))))}function hee({info:e,onGoUpdate:t,onClose:a}){const o=String(e.latestVersion||""),c=String(e.notes||"").trim(),d=c?q2(c):"";function f(){mee(o),a()}function p(){a();const g=Pn();g.wbApp?.showPage?.("settings"),g.wbSettingsPanel?.showCategory?.("about"),t(e)}return s.jsx(Qt,{open:!0,onOpenChange:g=>{g||a()},children:s.jsxs(Zt,{children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("检测到更新")})}),s.jsxs(Bt,{children:[s.jsxs("p",{className:"text-[12.5px] leading-[1.6] text-subtle",children:[r("新版本 "),s.jsx("strong",{className:"text-foreground",children:o}),r(" 已发布(当前 {current}),更新日志如下:",{current:e.currentVersion||r("未知")})]}),s.jsx("div",{className:"max-h-[46vh] overflow-y-auto overscroll-contain pr-1.5",onClick:G2,children:d?s.jsx("div",{className:"md-body",dangerouslySetInnerHTML:{__html:d}}):s.jsx("div",{className:"md-body",children:s.jsx("p",{className:"md-body-empty",children:r("这个版本没有填写发布说明。")})})})]}),s.jsxs(nn,{children:[s.jsx(se,{variant:"outline",size:"sm",onClick:f,children:r("跳过此次更新")}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:a,children:r("取消")}),s.jsx(se,{variant:"default",onClick:p,children:r("去更新")})]})]})})}let Rp=null,Xu=null;function vP(){Rp&&(Rp.unmount(),Rp=null),Xu&&(Xu.remove(),Xu=null)}const yP="updateCheck",Qu=1,$x=1440,gee="https://github.com/settings/tokens/new?description="+encodeURIComponent("Agent2API 更新检查");function xee(e){return e?e.error?{badge:s.jsx(ze,{shape:"tag",variant:"destructive",title:e.error,children:r("无法解密")}),hint:r("重新粘贴保存一次即可自愈")}:e.filled&&e.origin==="stored"?{badge:s.jsx(ze,{shape:"tag",variant:"success",children:r("已填写")}),hint:r("已加密存储在本地,不显示具体值;粘贴新令牌可覆盖")}:e.filled?{badge:s.jsx(ze,{shape:"tag",variant:"secondary",children:r("环境变量")}),hint:r("已配置 GITHUB_TOKEN 环境变量,界面保存的令牌优先于它")}:{badge:s.jsx(ze,{shape:"tag",variant:"outline",children:r("未填写")}),hint:r("填写后检查限额 60 → 5000 次/小时(创建令牌无需勾选任何权限)")}:{badge:s.jsx(ze,{shape:"tag",variant:"outline",children:r("读取中")}),hint:""}}function bee({open:e,onClose:t}){const[a,o]=x.useState(K2),[c,d]=x.useState(null),[f,p]=x.useState(""),[g,v]=x.useState(!1),[y,b]=x.useState(null),[j,w]=x.useState(""),[S,N]=x.useState(!1),k=Y2(a);x.useEffect(()=>{e&&(p(""),PY().then(o),(async()=>{try{d(await Pn().workbuddyDesktop?.getUpdateToken()??null)}catch{}})(),(async()=>{try{const L=((await Pn().workbuddyDesktop?.getScheduledTasks?.())?.tasks??[]).find(z=>z.id===yP),H=L?.enabled===!0,B=Math.max(Qu,Math.round(Number(L?.interval)||0));b({enabled:H,interval:B}),w(String(B))}catch{}})())},[e]);async function E(_){if(!S){N(!0);try{const L=await Pn().workbuddyDesktop?.saveScheduledTask?.(yP,_),H=L?.enabled===!0,B=Math.max(Qu,Math.round(Number(L?.interval)||0));b({enabled:H,interval:B}),w(String(B)),nr(r("✅ 自动检查更新已保存"))}catch(L){nr(r("保存失败:{error}",{error:zr(L)}),"err")}finally{N(!1)}}}async function D(){const _=Math.round(Number(j));if(!Number.isFinite(_)||_$x){nr(r("检查间隔必须是 {min} ~ {max} 分钟",{min:Qu,max:$x}),"err");return}y&&_===y.interval||await E({interval:_})}async function C(_){const L=await _Y(_);L&&o(H=>({...H,proxyChoice:L.choice}))}async function A(){const _=f.trim();if(!_){nr(r("请先粘贴 GitHub 令牌"),"err");return}v(!0);try{const L=await Pn().workbuddyDesktop?.setUpdateToken({token:_});d(L??null),p(""),L?.saved===!1?nr(r("令牌已生效,但写入磁盘失败(重启后会丢失)"),"err"):nr(r("✅ GitHub 令牌已保存(加密存储,界面不再显示)"))}catch(L){nr(r("保存失败:{error}",{error:zr(L)}),"err")}finally{v(!1)}}async function R(){v(!0);try{const _=await Pn().workbuddyDesktop?.setUpdateToken({token:null});d(_??null),nr(r("✅ 已清除界面保存的 GitHub 令牌(环境变量若配置过则继续生效)"))}catch(_){nr(r("清除失败:{error}",{error:zr(_)}),"err")}finally{v(!1)}}const I=xee(c),P=!!c?.error||c?.origin==="stored",O=c?.filled&&c?.origin!=="env"?r("已填写(粘贴新令牌可覆盖)"):r("粘贴 GitHub 令牌(ghp_… / github_pat_…)");return s.jsx(Qt,{open:e,onOpenChange:_=>{_||t()},children:s.jsxs(Zt,{className:"w-[min(460px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("更新设置")})}),s.jsxs(Bt,{className:"gap-3.5",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:r("自动检查更新")}),s.jsx(ms,{checked:y?.enabled===!0,disabled:S||!y,onCheckedChange:_=>{E({enabled:_===!0})},"aria-label":r("自动检查更新")})]}),s.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[s.jsx($e,{type:"number",min:Qu,max:$x,step:1,className:"w-[110px]",disabled:S||!y||y.enabled!==!0,value:j,onChange:_=>w(_.currentTarget.value),onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),D())},"aria-label":r("检查间隔(分钟)")}),s.jsx("span",{className:"text-[12px] text-subtle",children:r("分钟({min} ~ {max})",{min:Qu,max:$x})}),s.jsx(se,{variant:"outline",size:"sm",disabled:S||!y||Math.round(Number(j))===y.interval,onClick:()=>{D()},children:r("保存")})]}),s.jsx("div",{className:"mt-1.5 text-[12px] text-subtle",children:r("到点自动向 GitHub 查询新版本,查到就走「检测到更新」弹窗;关闭后「检查更新」按钮仍可手动触发")})]}),s.jsx("div",{className:"h-px bg-hairline"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:r("出网代理")}),s.jsx("div",{className:"mt-1.5",children:s.jsxs(ft,{value:k.current,onValueChange:_=>{C(String(_))},children:[s.jsx(mt,{className:Ue("w-full",k.broken&&"border-destructive-bd"),title:k.title,"aria-label":r("更新出网代理"),children:s.jsx(pt,{className:"min-w-0 truncate",children:k.selected?.label||r("直连")})}),s.jsx(ht,{children:k.items.map(_=>s.jsx(qe,{value:_.value,disabled:_.disabled,children:_.label},_.value))})]})})]}),s.jsx("div",{className:"h-px bg-hairline"}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:r("GitHub 令牌")}),s.jsx(se,{variant:"outline",size:"xs",title:r("在默认浏览器中打开 GitHub 的令牌创建页(备注已预设,无需勾选任何权限,直接点 Generate token)"),onClick:()=>{$2(gee)},children:r("打开 GitHub 令牌页面")})]}),s.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[I.badge,s.jsx("span",{className:"text-[12px] text-subtle",children:I.hint})]}),s.jsxs("div",{className:"mt-2 flex items-center gap-2",children:[s.jsx($e,{type:"password",className:"flex-1",placeholder:O,autoComplete:"new-password",spellCheck:!1,value:f,onChange:_=>p(_.currentTarget.value),onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),A())}}),s.jsx(se,{variant:"default",size:"sm",disabled:g||!f.trim(),onClick:()=>{A()},children:r("保存")}),P?s.jsx(se,{variant:"outline",size:"sm",disabled:g,onClick:()=>{R()},children:r("清除")}):null]})]})]})]})})}function vee({open:e,onClose:t}){return s.jsx(Qt,{open:e,onOpenChange:a=>{a||t()},children:s.jsxs(Zt,{className:"w-[min(320px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("加入 QQ 群")})}),s.jsxs(Bt,{className:"items-center gap-3 text-center",children:[s.jsx("img",{className:"qq-qr",src:IY,alt:r("QQ 群二维码")}),s.jsxs("div",{className:"qq-no",children:[s.jsx("span",{className:"k",children:r("群号")}),s.jsx("code",{children:Yg}),s.jsx(se,{type:"button",size:"sm",variant:"ghost","data-copy":Yg,children:r("复制")})]}),s.jsx("p",{className:"qq-hint",children:r("用手机 QQ 扫上面的二维码,或在 QQ 里搜索群号加入。")})]})]})})}const yee=1e3,jP=8,jee=10,wee=1e3,See={"":"outline",ok:"success",warn:"warning",bad:"destructive"},Nee={info:null,checkedAt:0,repository:"",badgeText:r("未检查"),badgeTone:"",stateText:r("点击「检查更新」查询最新发布版本。"),stateError:!1,percent:0,phase:"idle",readyPath:"",checking:!1,actionBusy:!1,restartSeconds:0};function Pl(e){return String(e).padStart(2,"0")}function kee(e){const t=new Date(String(e??""));return!e||Number.isNaN(t.getTime())?"":`${t.getFullYear()}-${Pl(t.getMonth()+1)}-${Pl(t.getDate())} ${Pl(t.getHours())}:${Pl(t.getMinutes())}`}function wP(e){const t=new Date(e);if(!e||Number.isNaN(t.getTime()))return"";const a=new Date,o=t.getFullYear()===a.getFullYear()&&t.getMonth()===a.getMonth()&&t.getDate()===a.getDate(),c=`${Pl(t.getHours())}:${Pl(t.getMinutes())}:${Pl(t.getSeconds())}`;return o?c:`${Pl(t.getMonth()+1)}-${Pl(t.getDate())} ${c}`}function qx(e){return e?.installerKind?e.installerKind==="dmg":/Mac|iPhone|iPad/.test(navigator.userAgent||"")}function Ma(e){return e?.selfUpdate===!0}function SP(e){return e?Ma(e)?e.serverAsset??null:e.asset??null:null}function Cee(e){return Ma(e)?r("正在下载服务端更新包…(下载完成后由面板完成替换,重启容器内的服务后生效)"):qx(e)?r("正在下载安装包…(下载完成后会挂载磁盘映像,把应用拖进「应用程序」即可完成安装)"):r("正在下载安装包…(下载完成后启动安装程序需要管理员权限,会弹出 UAC 确认框)")}function NP(e,t){return Ma(e)?r("更新包已就绪:{name}。点「安装并重启」后,面板会校验并替换容器内的程序与界面文件,然后重启服务(页面会自动刷新)。",{name:t}):qx(e)?r("安装包已就绪:{name}。点击「打开安装包」后会挂载磁盘映像,把应用拖进「应用程序」即可完成安装。",{name:t}):r("安装包已就绪:{name}。点击「安装并重启」后需要管理员权限,会弹出 UAC 确认框。",{name:t})}function Tee(e){return Ma(e)?r("安装并重启"):qx(e)?r("打开安装包"):r("安装并重启")}let fa=Nee;const ES=new Set;function AS(){return fa}function Eee(e){return ES.add(e),()=>{ES.delete(e)}}function zn(e){fa={...fa,...e};for(const t of ES)t()}let wr=!1,RS=null,Gx=null;function Zu(){Gx!==null&&(window.clearInterval(Gx),Gx=null)}function Ts(e,t=""){zn({badgeText:e,badgeTone:t})}function An(e,t=!1){zn({stateText:e,stateError:t})}function Kx(){const{info:e,checkedAt:t}=fa;if(!e)return;const a=t?r("(检查于 {time})",{time:wP(t)}):"";if(e.pendingRestart===!0){Ts(r("待重启"),"warn"),An(r("更新已应用到容器内,重启服务后生效。{at}",{at:a}));return}if(e.hasUpdate===!0){if(Ts(r("有新版本"),"warn"),Ma(e)&&!e.serverAsset){An(r("发现新版本 {latest}(当前 {current}),但该版本没有提供容器内更新包;请在宿主机执行 docker compose pull && docker compose up -d 升级。{at}",{latest:String(e.latestVersion||""),current:String(e.currentVersion||""),at:a}));return}An(r("发现新版本 {latest}(当前 {current})。{at}",{latest:String(e.latestVersion||""),current:String(e.currentVersion||""),at:a}))}else e.hasUpdate===!1?(Ts(r("已是最新"),"ok"),An(r("当前已是最新版本({current})。{at}",{current:String(e.currentVersion||""),at:a}))):(Ts(r("无法比较"),"warn"),An(e.latestVersion?r("最新发布版本为 {latest},但当前版本号「{current}」无法解析,未做新旧判断。{at}",{latest:e.latestVersion,current:e.currentVersion||r("未知"),at:a}):r("仓库暂无发布版本。{at}",{at:a})))}function kP(e){!e||e.checked===!1||(zn({info:e,checkedAt:Number(e.checkedAt)||0}),e.repository&&OS(e.repository),fa.phase==="idle"&&Kx())}function OS(e){const t=String(e||"").trim();/^[\w.-]+\/[\w.-]+$/.test(t)&&zn({repository:t})}function MS(e){if(!e)return!1;if(e.active){const t=Math.max(0,Math.min(100,Number(e.percent)||0)),a=(Number(e.received)||0)/1024/1024,o=(Number(e.total)||0)/1024/1024;return zn({phase:"downloading",percent:t}),Ts(r("下载中"),"warn"),An(r("正在下载 {name}:{percent}%({received} / {total} MB)",{name:e.filename||r("安装包"),percent:t,received:a.toFixed(1),total:o.toFixed(1)})),!0}if(Zu(),zn({percent:0}),e.error)return Ts(r("下载失败"),"bad"),An(r("下载失败:{error}",{error:e.error}),!0),zn({phase:"failed"}),!0;if(e.canceled)return Ts(r("已取消"),"warn"),An(Ma(fa.info)?r("下载已取消,可重新点击「下载并更新」。"):r("下载已取消,可重新点击「下载并安装」。")),zn({phase:"idle"}),!0;if(e.done&&e.path){const t=e.path,a=e.filename||t;return Ts(r("可安装"),"ok"),zn({phase:"ready",readyPath:t}),Ma(fa.info)?(An(NP(fa.info,a)),!0):(t!==RS?(RS=t,An(qx(fa.info)?r("安装包已下载完成,正在挂载磁盘映像…"):r("安装包已下载完成,正在启动安装程序(需要管理员权限,会弹出 UAC 确认框)…")),TP(t)):An(NP(fa.info,a)),!0)}return!1}async function Aee(){try{const e=await Pn().workbuddyDesktop?.updateProgress();if(!e){Zu();return}MS(e)}catch(e){Zu(),An(r("读取下载进度失败:{error}",{error:zr(e)}),!0)}}function CP(){Zu(),Gx=window.setInterval(()=>{Aee()},yee)}async function TP(e){const t=Pn().workbuddyDesktop;if(t)try{const o=(await t.runInstaller(e,!0))?.restart!==!1;An(r(o?"安装程序已启动,本程序将退出以便完成覆盖安装。安装程序需要管理员权限,会弹出 UAC 确认框,请选择「是」。":"安装包已挂载,请在弹出的窗口里把应用拖进「应用程序」完成安装。安装完成后重新打开本程序即可。"))}catch(a){Ts(r("启动失败"),"bad"),An(r("启动安装程序失败:{error}",{error:zr(a)}),!0)}}async function Ree(){const e=Pn().workbuddyDesktop;if(e?.installUpdate)try{Ts(r("安装中"),"warn"),An(r("正在校验并替换容器内的程序与界面文件…"));const t=await e.installUpdate(),a=String(t?.version||"").trim();An(a?r("已替换为 {version},正在重启服务…",{version:a}):r("替换完成,正在重启服务…")),await e.restartService?.().catch(()=>{}),DS(a)}catch(t){Ts(r("安装失败"),"bad"),An(r("安装失败:{error}",{error:zr(t)}),!0)}}async function Oee(){const e=Pn().workbuddyDesktop;if(!(!e?.rollbackUpdate||wr)){wr=!0,zn({actionBusy:!0});try{Ts(r("回滚中"),"warn"),An(r("正在回滚到上一版本…")),await e.rollbackUpdate(),An(r("已还原上一版本,正在重启服务…")),await e.restartService?.().catch(()=>{}),DS("")}catch(t){Ts(r("回滚失败"),"bad"),An(r("回滚失败:{error}",{error:zr(t)}),!0)}finally{wr=!1,zn({actionBusy:!1})}}}function DS(e){Zu(),zn({phase:"restarting",restartSeconds:jP,readyPath:""}),Ts(r("重启中"),"warn");let t=jP;const a=()=>{if(An(e?r("{version} 已就位,服务正在重启,页面会在恢复后自动刷新…({seconds}s)",{version:e,seconds:Math.max(0,t)}):r("服务正在重启,页面会在恢复后自动刷新…({seconds}s)",{seconds:Math.max(0,t)})),t<=0){window.clearInterval(o),Mee();return}t-=1,zn({restartSeconds:t})},o=window.setInterval(a,1e3);a()}async function Mee(){for(let e=0;e{window.setTimeout(t,wee)})}window.location.reload()}async function EP(){if(wr)return null;wr=!0,zn({checking:!0}),Ts(r("检查中"),"warn"),An(r("正在查询 GitHub 上的最新发布版本…"));let e=null;try{const t=Pn().workbuddyDesktop;if(!t)throw new Error(r("后端桥不可用"));e=await t.checkUpdate()??null,zn({info:e,checkedAt:Number(e?.checkedAt)||Date.now()}),e?.repository&&OS(e.repository),Kx()}catch(t){e=null,zn({info:null,checkedAt:0}),Ts(r("检查失败"),"bad"),An(r("检查更新失败:{error}",{error:zr(t)}),!0)}finally{wr=!1,zn({checking:!1})}return Pn().wbApp?.updateUpdateBadge?.(e),Fx(e,Op),e}async function AP(){let e=null;try{e=await Pn().workbuddyDesktop?.getUpdateStatus()??null}catch{}if(e&&e.checked!==!1){kP(e),Pn().wbApp?.updateUpdateBadge?.(e),Fx(e,Op);return}fa.info||(Ts(r("未检查")),An(r("点击「检查更新」查询 GitHub 上的最新发布版本。")))}async function IS(){if(wr)return;const e=AS();if(e.info?.pendingRestart===!0&&e.phase!=="downloading"){wr=!0,zn({actionBusy:!0});try{await Pn().workbuddyDesktop?.restartService?.().catch(()=>{}),DS("")}finally{wr=!1,zn({actionBusy:!1})}return}if(e.phase!=="downloading"&&e.readyPath){wr=!0,zn({actionBusy:!0});try{Ma(e.info)?await Ree():await TP(e.readyPath)}finally{wr=!1,zn({actionBusy:!1})}return}if(e.phase==="downloading"){try{await Pn().workbuddyDesktop?.cancelUpdate(),An(r("正在取消下载…"))}catch(a){nr(r("取消失败:{error}",{error:zr(a)}),"err")}return}const t=SP(e.info);if(!t?.url){nr(Ma(e.info)?r("这一版没有提供容器内更新包"):r("没有可下载的安装包"),"err");return}if(OP(e)){wr=!0,zn({actionBusy:!0});try{await Pn().workbuddyDesktop?.downloadUpdate({url:t.url,name:t.name}),RS=null,zn({phase:"downloading",readyPath:"",percent:0}),Ts(r("下载中"),"warn"),An(Cee(e.info)),CP()}catch(a){Ts(r("下载失败"),"bad"),An(r("下载失败:{error}",{error:zr(a)}),!0)}finally{wr=!1,zn({actionBusy:!1})}}}async function RP(){Kx(),await AP();try{const e=await Pn().workbuddyDesktop?.updateProgress();if(e?.active){MS(e),CP();return}if(e?.done&&e.path){MS(e);return}}catch{}}async function Op(e){if(e?.pendingRestart===!0){await IS();return}e?.hasUpdate===!0&&(zn({info:e,checkedAt:Number(e.checkedAt)||fa.checkedAt}),e.repository&&OS(e.repository),Kx(),Pn().wbApp?.updateUpdateBadge?.(e),Fx(e,Op)),await RP();const t=AS();if(!(t.phase==="downloading"||t.readyPath)&&t.info?.hasUpdate)for(let a=0;a<3;a+=1){if(wr){await new Promise(o=>{window.setTimeout(o,400)});continue}await IS();return}}function OP(e){return e.phase==="restarting"?null:e.info?.pendingRestart===!0&&e.phase==="idle"?{label:r("立即重启"),disabled:e.actionBusy}:!(e.info?.hasUpdate===!0&&!!SP(e.info)?.url)&&e.phase!=="downloading"&&e.phase!=="ready"?null:{label:e.phase==="downloading"?r("取消下载"):e.phase==="failed"?r("重试下载"):e.phase==="ready"?Tee(e.info):Ma(e.info)?r("下载并更新"):r("下载并安装"),disabled:e.actionBusy}}function Dee(e,t){const a=e.info,o=String(a?.notes||"").trim();if(!o)return s.jsx("div",{className:"update-log-hint",children:r(a?"这个版本没有填写发布说明。":"点击「检查更新」后,这里会显示最新版本的更新说明。")});const c=q2(o),d=F2(a?.pageUrl),f=kee(a?.publishedAt);return s.jsxs("div",{className:"rel-note",children:[s.jsxs("div",{className:"rel-note-head",children:[s.jsx("span",{className:"rel-tag",children:String(a?.latestVersion||r("最新版本"))}),a?.prerelease===!0?s.jsx(ze,{shape:"tag",variant:"warning",children:r("预发布")}):null,f?s.jsx("span",{className:"rel-date",children:f}):null]}),s.jsxs("div",{className:"rel-note-body",children:[c?s.jsx("div",{className:"md-body",dangerouslySetInnerHTML:{__html:c}}):s.jsx("div",{className:"md-body",children:s.jsx("p",{className:"md-body-empty",children:r("这个版本没有填写发布说明。")})}),s.jsxs("div",{className:"rel-foot",children:[d?s.jsx("a",{href:d,"data-external":d,target:"_blank",rel:"noopener",children:r("在 GitHub 查看完整说明")}):null,s.jsx(se,{type:"button",variant:"link",size:"sm",className:"h-auto border-0 px-0 text-[11.5px] font-semibold text-primary-fg underline-offset-auto",title:r("群号:{group}",{group:Yg}),onClick:t,children:r("加入 QQ 群")})]})]})]})}function Iee(){const e=x.useSyncExternalStore(Eee,AS),t=OP(e),[a,o]=x.useState(!1),[c,d]=x.useState(!1);x.useEffect(()=>()=>{Zu()},[]);const f=e.repository?`https://github.com/${e.repository}`:"",p=e.repository?`https://github.com/${e.repository.split("/")[0]}`:"",g=Ma(e.info),v=g&&e.info?.backupAvailable===!0&&e.phase!=="downloading"&&e.phase!=="ready"&&e.phase!=="restarting",y=e.info?.latestVersion?e.info.prerelease?r("{version}(预发布)",{version:e.info.latestVersion}):e.info.latestVersion:"—",b=String(e.info?.latestVersion||"").trim(),j=b?`${b}${e.checkedAt?r(" · 检查于 {time}",{time:wP(e.checkedAt)}):""}`:"";return s.jsxs("section",{className:"panel",onClick:G2,children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:r("软件更新")}),s.jsx("span",{className:"tip-q","data-tip":r(g?"容器内更新:更新包从 GitHub 发布页下载,校验 sha256 后由面板替换容器内的程序与界面文件,再重启服务(容器由 restart 策略拉起,页面会自动刷新)。更新的是容器里的文件,compose 里的镜像标签不变 —— 之后执行 docker compose pull && up -d 会回到镜像里的版本;更新失败可一键回滚到上一版本。检查更新与下载的出网线路、GitHub 令牌都在「更新设置」里。":"更新包从 GitHub 发布页下载,下载完成后可直接启动安装程序并自动重启本程序。安装包会先校验来源域名与文件完整性。检查更新与下载安装包的出网线路、GitHub 令牌都在「更新设置」里:线路默认直连(直连失败时自动借 Clash Verge 的混合端口重试一次),选定指定出口后只走该出口;填写 GitHub 令牌可把检查限额从 60 次/小时提高到 5000 次/小时。")}),s.jsx(ze,{id:"update-badge",variant:See[e.badgeTone],"data-tone":e.badgeTone,children:e.badgeText}),s.jsxs("div",{className:"head-actions",children:[s.jsx(se,{id:"btn-update-settings",variant:"outline",title:r("出网线路与 GitHub 令牌设置"),onClick:()=>o(!0),children:r("更新设置")}),s.jsx(se,{id:"btn-update-check",variant:"outline",disabled:e.checking||e.phase==="restarting",onClick:()=>{EP()},children:e.checking?r("检查中…"):r("检查更新")}),v?s.jsx(se,{id:"btn-update-rollback",variant:"outline",disabled:e.actionBusy,title:r("把容器内的程序与界面文件还原到更新前的版本,并重启服务"),onClick:()=>{Oee()},children:r("回滚到上一版本")}):null,t?s.jsx(se,{id:"btn-update-download",variant:"default",disabled:t.disabled,onClick:()=>{IS()},children:t.label}):null]})]}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"update-version",children:[s.jsxs("span",{className:"version-pill",children:[s.jsx("span",{className:"k",children:r("当前版本")}),s.jsx("span",{className:"v",id:"update-current",children:e.info?.currentVersion||"—"})]}),s.jsx("span",{className:"version-arrow",children:"→"}),s.jsxs("span",{className:"version-pill new",children:[s.jsx("span",{className:"k",children:r("最新版本")}),s.jsx("span",{className:"v",id:"update-latest",children:y})]})]}),s.jsx("div",{className:"detail",id:"update-state",style:e.stateError?{color:"var(--danger)"}:void 0,children:e.stateText}),e.phase==="downloading"&&e.percent>0&&e.percent<100?s.jsx(ef,{value:e.percent}):null,p&&f?s.jsxs("div",{className:"update-author",id:"update-author",children:[s.jsxs("div",{className:"update-author-text",children:[s.jsx("strong",{children:r("关于作者")}),s.jsxs("span",{children:[r("本工具由")," ",s.jsx("a",{id:"update-author-link",href:p,"data-external":p,target:"_blank",rel:"noopener",children:e.repository.split("/")[0]})," ",r("个人开发并开源维护,免费使用、不带广告,也不会收集你的账号数据。如果它帮到了你,欢迎到项目仓库点个 Star 支持一下。")]})]}),s.jsx("div",{className:"update-author-actions",children:s.jsx(se,{id:"btn-update-favorite",type:"button",size:"sm",variant:"outline","data-external":f,title:r("在浏览器中打开项目仓库,点 Star 支持作者"),children:r("收藏项目")})})]}):null,s.jsxs("div",{className:"update-log",id:"update-notes",children:[s.jsxs("div",{className:"update-log-head",children:[s.jsx("span",{className:"update-log-title",children:r("更新日志")}),s.jsx("span",{className:"update-log-meta",id:"update-log-meta",children:j})]}),s.jsx("div",{className:"update-log-body",id:"update-log-body",children:Dee(e,()=>d(!0))})]})]}),a?s.jsx(bee,{open:!0,onClose:()=>o(!1)}):null,c?s.jsx(vee,{open:!0,onClose:()=>d(!1)}):null]})}const MP='.settings-pane[data-cat="about"]';let PS=null;function DP(){if(PS)return;const e=document.querySelector(MP);e&&(e.replaceChildren(),PS=vn.createRoot(e),PS.render(s.jsx(Iee,{})))}document.querySelector(MP)?DP():document.addEventListener("DOMContentLoaded",DP,{once:!0}),window.wbUpdatePanel={load:RP,check:EP,syncFromCache:AP,openAndDownload:Op,applyStatus:kP,showUpdateModal:e=>Fx(e,Op)};const Pee="zcode.z.ai/billing",_ee={active:"success",pending:"warning",expired:"ghost",unknown:"outline"};function Lee(e){const t=String(e||"").trim().toLowerCase();return t==="daily"?r("每日"):t==="weekly"?r("每周"):t==="monthly"?r("每月"):""}function zee(e){const t=Number(e);if(!Number.isFinite(t)||t<=0)return"";const a=window.wbUnits;return a?.formatTokens?a.formatTokens(t):String(t)}function ic(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"":Pe().wbApp?.formatTime?.(t*1e3)||new Date(t*1e3).toLocaleString()}function Bee(e){const t=zee(e.grantUnits),a=String(e.unitType||"").trim(),o=t?[t,a].filter(Boolean).join(" "):"",c=Lee(e.period),d=[String(e.showName||"").trim(),o].filter(Boolean).join(" ");return d?c?r("{body}({period})",{body:d,period:c}):d:""}function IP(e){return(e.entitlements||[]).map(Bee).filter(Boolean).join(r("、"))}function Hee(e){const t=ic(e.startsAt),a=ic(e.endsAt);return t&&a?`${t} → ${a}`:a?r("到期 {time}",{time:a}):t?r("开始 {time}",{time:t}):""}function Uee(e){const t=new Date(e*1e3);if(Number.isNaN(t.getTime()))return"";const a=`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}`,o=d=>Math.floor(Date.UTC(d.getFullYear(),d.getMonth(),d.getDate())/864e5),c=o(t)-o(new Date);return c===0?r("今天 {time}",{time:a}):c===1?r("明天 {time}",{time:a}):ic(e)}function Vee(e){const t=[],a=Number(e.pendingUntil);if(Number.isFinite(a)&&a>0){const c=Uee(a);c&&t.push(r("待生效 {time}",{time:c}))}const o=ic(e.endsAt);if(o&&t.push(r("到期 {time}",{time:o})),t.length===0){const c=ic(e.startsAt);c&&t.push(r("开始 {time}",{time:c}))}return t.join(" · ")}function Fee({options:e,onClose:t}){const a=e.id,[,o]=x.useState(0);x.useEffect(()=>UA(()=>o(P=>P+1)),[]);const[c,d]=x.useState([]),[f,p]=x.useState({status:"loading"}),[g,v]=x.useState(""),y=Ea(a),b=String(y?.name||e.name||a),j=$h(y),w=[...new Set([...j,...c])],S=y?.claimPlans&&typeof y.claimPlans=="object"&&!Array.isArray(y.claimPlans)?y.claimPlans:{},N=y?Qa(y):void 0,k=N&&typeof N=="object"&&!Array.isArray(N)?N:null,E=k&&Array.isArray(k.plans)?k.plans:[],D=w.filter(P=>P&&!E.some(O=>String(O.planId||"")===P)),C=Zs().usageInflight.has(a),A=Pe().wbZcodeClaim,R=x.useCallback(async()=>{if(!A?.preview){p({status:"error",message:r("当前环境不支持领取(桥接方法缺失)")});return}p({status:"loading"});try{const P=await A.preview(a);p({status:"ready",result:P||{}})}catch(P){p({status:"error",message:ut(P)})}},[A,a]);x.useEffect(()=>{R();const P=Ea(a);P&&Qa(P)===void 0&&Wh(a)},[a,R]);async function I(P){if(!(!A?.claim||g)){v(P);try{const O=await A.claim(a,P);if(O?.ok||O?.failure==="already_claimed"){const _=O.planId||P;_&&d(L=>L.includes(_)?L:[...L,_]),Wh(a),Pe().wbApp?.refresh?.(),R()}}finally{v("")}}}return s.jsx(Qt,{open:!0,onOpenChange:(P,O)=>{if(!P){if(g){O.cancel();return}t()}},children:s.jsxs(Zt,{className:"w-[min(560px,calc(100vw-48px))]",children:[s.jsx(Kt,{children:s.jsx(Gt,{children:r("ZCode 套餐明细 — {name}",{name:b})})}),s.jsxs(Bt,{className:"space-y-4",children:[s.jsxs("section",{children:[s.jsxs("div",{className:"mb-1.5 flex items-center gap-2 text-[12px] font-semibold text-muted-foreground",children:[r("可领取的套餐"),s.jsx(ze,{variant:"outline",shape:"tag",children:r("官方限时活动")})]}),f.status==="loading"?s.jsxs("div",{className:"flex items-center gap-2 py-2 text-[12.5px] text-muted-foreground",children:[s.jsx(Jd,{className:"size-3"}),r("正在探测可领取的套餐…")]}):f.status==="error"?s.jsxs("div",{className:"py-1 text-[12.5px] text-destructive",children:[r("探测失败:{message}",{message:f.message}),s.jsx(se,{variant:"outline",size:"xs",className:"ml-2",onClick:()=>{R()},children:r("重试")})]}):f.result.deployed?(f.result.plans||[]).length===0?s.jsx("p",{className:"py-1 text-[12.5px] text-muted-foreground",children:r("当前没有可领取的套餐(活动期内每天发一份,明天可再领)")}):s.jsx("ul",{className:"m-0 list-none p-0",children:(f.result.plans||[]).map(P=>{const O=String(P.planId||""),_=w.includes(O),L=IP(P),H=Hee(P);return s.jsxs("li",{className:"flex items-start justify-between gap-3 border-b border-hairline py-2 last:border-b-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[13px] font-medium",children:[s.jsx("span",{className:"truncate",children:P.name||O||r("套餐")}),_?s.jsx(ze,{variant:"success",shape:"tag",children:r("今日已领")}):null]}),H?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:H}):null,L?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:L}):null,P.description?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:P.description}):null]}),s.jsx(se,{variant:"outline",size:"xs",className:"flex-none",title:_?r("这一份今天已经领过了(重复领取上游会回「已领取过」)"):void 0,disabled:g!=="",onClick:()=>{I(O)},children:r(g===O?"领取中…":_?"再领一次":"领取")})]},O||P.name)})}):s.jsx("p",{className:"py-1 text-[12.5px] text-muted-foreground",children:r("当前没有可领取的套餐(活动尚未开始)")}),s.jsx("p",{className:"mt-1.5 text-[11.5px] text-muted-foreground",children:r("活动期内每天发一份新套餐;同一份当天重复领取会提示「已领取过」,次日可再领。领取要走一次人机验证(滑块)。")}),f.status==="ready"&&f.result.activationError?s.jsx("p",{className:"text-[11.5px] text-muted-foreground",children:r("(激活事件补报失败,可能影响领取资格:{message})",{message:f.result.activationError})}):null]}),s.jsxs("section",{children:[s.jsxs("div",{className:"mb-1.5 flex items-center gap-2 text-[12px] font-semibold text-muted-foreground",children:[r("我的套餐"),Array.isArray(k?.wallets)&&k.wallets.length>0&&k.availableView?s.jsx(ze,{variant:"outline",shape:"tag",children:String(k.walletsFrom||"")==="monitor"?String(k.availableView):r("可用 {value}",{value:String(k.availableView)})}):null,s.jsx("div",{className:"ml-auto",children:s.jsx(se,{variant:"outline",size:"xs",disabled:C,title:r("重新读取该账号的余额与套餐(走余额查询那条链)"),onClick:()=>{Wh(a)},children:r(C?"查询中…":"查询余额")})})]}),E.length>0?s.jsx("ul",{className:"m-0 list-none p-0",children:E.map(P=>{const O=String(P.planId||""),_=String(P.state||"unknown"),L=IP(P),H=Vee(P),B=O&&y?.claimPlans&&Number(y.claimPlans[O])||0;return s.jsxs("li",{className:"flex items-start justify-between gap-3 border-b border-hairline py-2 last:border-b-0",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 text-[13px] font-medium",children:[s.jsx("span",{className:"truncate",children:P.name||O||r("套餐")}),s.jsx(ze,{variant:_ee[_]||"outline",shape:"tag",children:AA(_)})]}),H?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:H}):null,L?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:L}):null]}),B>0?s.jsx("span",{className:"flex-none text-[11.5px] text-muted-foreground",children:r("本地领取于 {time}",{time:ic(B/1e3)})}):null]},O||P.name)})}):s.jsx("p",{className:"py-1 text-[12.5px] text-muted-foreground",children:N===void 0?r("还没有余额读数(已自动查询一次,稍候;也可以点右上角「查询余额」重读)"):k&&k.source&&k.source!==Pee?r("这个账号的余额走窗口限额通道(只配了编码套餐 API Key):只有每 N 小时的剩余比例,读不到套餐清单"):r("读数里没有套餐清单(免费账号、或套餐的上游状态还没刷新;可点右上角「查询余额」重读)")}),D.length>0?s.jsx("p",{className:"mt-1.5 text-[11.5px] text-muted-foreground",children:r("本地台账里今天还领过这些,但上面的读数里还没有:{plans}(读数刷新可能有延迟)",{plans:D.map(P=>{const O=Number(S[P])||0,_=O>0?ic(O/1e3):"";return _?r("{plan}({time} 领取)",{plan:P,time:_}):P}).join(r("、"))})}):null]})]}),s.jsxs(nn,{children:[s.jsx("span",{className:"min-w-0 text-[11.5px] text-muted-foreground",children:w.length>0?r("今天(北京时间)已领取 {n} 份:{plans}",{n:w.length,plans:w.join(r("、"))}):r("今天还没有领过:上面「可领取的套餐」里逐份点「领取」即可")}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("关闭")})]})]})})}let Mp=null,Wu=null;function PP(){Mp&&(Mp.unmount(),Mp=null),Wu&&(Wu.remove(),Wu=null)}function $ee(e){e?.id&&(PP(),Wu=document.createElement("div"),document.body.append(Wu),Mp=vn.createRoot(Wu),Mp.render(s.jsx(Fee,{options:e,onClose:PP})))}window.wbZcodePlans={open:$ee};const _P="w-auto flex-auto";function LP({onInput:e,domRef:t,icon:a,className:o,inputClassName:c,...d}){const f=g=>{t.current=g},p=g=>{e?.(g.currentTarget.value)};return a?s.jsxs(Ci,{className:Ue(_P,o),children:[s.jsx(Ei,{ref:f,className:c,onInput:p,...d}),s.jsx(Ti,{"aria-hidden":"true",children:a})]}):s.jsx($e,{ref:f,className:Ue(_P,c),onInput:p,...d})}function qee(e,t){const a=vn.createRoot(e),o={current:null};return a.render(s.jsx(LP,{domRef:o,defaultValue:t.value,placeholder:t.placeholder,type:t.type??"search",icon:t.icon,"aria-label":t.ariaLabel,onInput:t.onInput})),{setValue(c){const d=o.current;d&&d.value!==c&&(d.value=c)},getValue(){return o.current?.value??""},focus(){o.current?.focus()},unmount(){a.unmount()}}}const Gee=[["id","id"],["type","type"],["name","name"],["title","title"],["placeholder","placeholder"],["min","min"],["max","max"],["step","step"],["autocomplete","autoComplete"]];function Kee(e){const t={defaultValue:e.value||void 0,inputClassName:e.className||void 0};for(const[f,p]of Gee){const g=e.getAttribute(f);g!=null&&(t[p]=g)}const a=e.getAttribute("maxlength");a!=null&&(t.maxLength=Number(a));const o=e.getAttribute("inputmode");o!=null&&(t.inputMode=o),e.hasAttribute("spellcheck")&&(t.spellCheck=e.spellcheck),e.disabled&&(t.disabled=!0),e.readOnly&&(t.readOnly=!0),e.hidden&&(t.hidden=!0);const c=e.getAttribute("aria-label");c!=null&&(t["aria-label"]=c);for(const f of e.getAttributeNames())!f.startsWith("data-")||f.startsWith("data-island-")||(t[f]=e.getAttribute(f)??"");const d=e.getAttribute("data-island-icon");return d!=null&&(t.icon=d),t}function zP(e){if(e.dataset.islandUpgraded)return;e.dataset.islandUpgraded="1";const t=Kee(e),a=e.parentElement?.classList.contains("input-affix")?e.parentElement:null;let o;a?(a.className=a.className.replace(/\binput-affix\b/,"").trim(),a.style.display="flex",a.style.alignItems="center",o=a):(o=document.createElement("span"),o.style.display="contents",e.replaceWith(o));const c={current:null},d=vn.createRoot(o);ks.flushSync(()=>{d.render(s.jsx(LP,{...t,domRef:c}))})}function BP(e=document){if(e instanceof HTMLInputElement&&e.matches("[data-island-input]")){zP(e);return}e.querySelectorAll("input[data-island-input]").forEach(zP)}function Yee(){BP();const e=new MutationObserver(t=>{for(const a of t)for(const o of a.addedNodes)o instanceof Element&&BP(o)});return e.observe(document.body,{childList:!0,subtree:!0}),e}function Xee(e,t){const a=vn.createRoot(e);let o={options:t.options,value:t.value,ariaLabel:t.ariaLabel,className:t.className};const c=()=>{a.render(s.jsx(In,{options:o.options,value:o.value,onValueChange:t.onChange,"aria-label":o.ariaLabel,className:o.className}))};return c(),{setValue(d){d!==o.value&&(o={...o,value:d},c())},setOptions(d){o={...o,options:d},c()},unmount(){a.unmount()}}}window.wbSegmented={mount:Xee},window.wbInput={mount:qee},Yee()})();