From 779523b06d9d2286930c91af2e1140772c50f668 Mon Sep 17 00:00:00 2001 From: coulsontl <149155411+coulsontl@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:34:39 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=EF=BC=9A=E8=AE=BE=E7=BD=AE?= =?UTF-8?q?=E9=A1=B5=E3=80=8C=E8=B7=AF=E7=94=B1=E3=80=8D=E5=88=86=E7=B1=BB?= =?UTF-8?q?=E8=A2=AB=E6=97=A7=E7=89=88=E8=A6=86=E7=9B=96=E6=95=B4=E5=9D=97?= =?UTF-8?q?=E5=88=A0=E6=8E=89=20=E2=80=94=E2=80=94=20=E8=B7=AF=E7=94=B1?= =?UTF-8?q?=E7=AD=96=E7=95=A5=E3=80=81=E4=BC=9A=E8=AF=9D=E7=B2=98=E6=80=A7?= =?UTF-8?q?=E3=80=81=E4=B8=89=E4=B8=AA=E8=87=AA=E6=84=88=E5=BC=80=E5=85=B3?= =?UTF-8?q?=E4=B8=80=E5=B9=B6=E6=81=A2=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 上游 bc8e843(2026-10-15)在开发「网络代理页 · 代理设置弹窗」时,夹带提交了一份 本地的旧版 `settings-page.tsx`,把整个设置页覆盖成了**硬编码中文、且不含路由分类** 的版本;同一提交对 `settings-model.ts` 的改动是「把桥类型搬到文件顶部」,搬迁时漏掉了 `modelsDevStateText` 函数、`ROUTE_PROTECTION_SWITCHES` 表,以及 `STATES` 里的一组 `modelsDev*` 文案 —— 于是恢复 `settings-page.tsx` 所需的 import 有两处悬空。 症状(官方镜像 v3.0.4 / v3.0.5):设置页里**既没有「路由策略」,也没有「会话粘性」**, 三个自愈开关更无从谈起 —— 整个「路由」分类消失。 判据:上游**所有** `.tsx` 里都没有路由设置的渲染代码,而 `settings-model.ts` 里的 `ROUTE_STRATEGIES` / `ROUTE_STICKY_OPTIONS` / `ROUTE_PROTECTION_SWITCHES` 三张表还在 (官方 `ui.js` 里 grep 得到「家内轮询」,界面上却什么都看不到)—— 典型的「删了消费方、 没删数据源」。 修复:把 `settings-page.tsx` 与 `settings-model.ts` 恢复成 bc8e843 **之前**(`8bae439`) 的版本。两者在 bc8e843 之后都没有再被改动过,且 bc8e843 对它们的改动分别是「整份旧版 覆盖」与「等价搬迁(同名类型换位置)」,所以整份恢复不会丢掉任何有意为之的改动。 前端产物已重建。 `t('` 使用量(i18n 被抹的直接指标): | 文件 | 覆盖前 | 被覆盖后 | 恢复后 | |---|---|---|---| | `settings-page.tsx` | 230 | **5** | 230 | | `settings-model.ts` | 168 | **23** | 168 | ⚠️ **顺带提醒(本 PR 未改,请自行判断是否有意为之)**:bc8e843 还回退了 - `ui/index.html` —— PWA 声明(`apple-mobile-web-app-capable` 等,PR #228 的移动端适配) - `ui/login.html` —— i18n 语言引导的「只写域清单 manifest」新版 - `ui/units.js` —— 多语言量级词(萬 / 億 / 만 / 억)退回中文版 这三处无法从提交信息判断是否有意,所以本 PR 不动它们,留给维护者定夺。 --- .../ui-islands/src/islands/settings-model.ts | 654 ++++++++------ .../ui-islands/src/islands/settings-page.tsx | 804 ++++++++++++------ desktop-tauri/ui/islands/ui.js | 26 +- 3 files changed, 956 insertions(+), 528 deletions(-) diff --git a/desktop-tauri/ui-islands/src/islands/settings-model.ts b/desktop-tauri/ui-islands/src/islands/settings-model.ts index 6d8c6f82..20c404ab 100644 --- a/desktop-tauri/ui-islands/src/islands/settings-model.ts +++ b/desktop-tauri/ui-islands/src/islands/settings-model.ts @@ -18,43 +18,6 @@ import { t } from '../i18n' - -// ── 从 HEAD 恢复的类型(桥成员的返回形状)────────────── - -export type DatabaseTableStat = { table?: string; rows?: number } - -/** 整库导出结果(壳命令 export_database) */ -export type DatabaseExportResult = { - canceled?: boolean - bytes?: number - file?: string - tables?: DatabaseTableStat[] -} - -export type DatabaseImportResult = { - /** 恢复后的各表行数 */ - tables?: DatabaseTableStat[] - /** 替换前自动建的安全备份文件名({config_dir}/backups/ 下) */ - safetyBackup?: string - /** - * 密钥指纹不匹配的警告(**只在有问题的恢复里出现**,文案由后端 `db::backup` 的 - * `account_key_warning` 生成并给全)。 - * - * 它**不是失败**:导入照常完成,但这份备份是用另一把加密密钥做的(或备份时本机 - * 还没生成过密钥),导入后的账号数据解不开、账号列表会是空的。所以界面**必须** - * 把它常驻显示出来(面板内的警告框)—— 只塞进几秒即逝的 toast 等于没提示, - * 用户错过后只会对着空账号列表发懵。 - */ - warning?: string -} - -export type ModelsDevRefreshResult = { - status?: string - message?: string - count?: number - refreshedAt?: number -} - /* ─── 桥与共享全局 ─────────────────────────── */ /** 启动与托盘设置(壳命令 get_app_settings / save_app_settings) */ @@ -94,6 +57,35 @@ export type ExportResult = { file?: string } +/** 整库导出里每张表的行数统计(导出与恢复的响应同形) */ +export type DatabaseTableStat = { table?: string; rows?: number } + +/** 整库导出结果(壳命令 export_database) */ +export type DatabaseExportResult = { + canceled?: boolean + bytes?: number + file?: string + tables?: DatabaseTableStat[] +} + +/** 整库恢复结果(壳命令 import_database) */ +export type DatabaseImportResult = { + /** 恢复后的各表行数 */ + tables?: DatabaseTableStat[] + /** 替换前自动建的安全备份文件名({config_dir}/backups/ 下) */ + safetyBackup?: string + /** + * 密钥指纹不匹配的警告(**只在有问题的恢复里出现**,文案由后端 `db::backup` 的 + * `account_key_warning` 生成并给全)。 + * + * 它**不是失败**:导入照常完成,但这份备份是用另一把加密密钥做的(或备份时本机 + * 还没生成过密钥),导入后的账号数据解不开、账号列表会是空的。所以界面**必须** + * 把它常驻显示出来(面板内的警告框)—— 只塞进几秒即逝的 toast 等于没提示, + * 用户错过后只会对着空账号列表发懵。 + */ + warning?: string +} + /** * 网关自带提示词的**三段正文**(身份句 / 稳定段 / 动态段)。 * @@ -146,6 +138,68 @@ export type ClineHeadersData = { effective: Record } +/** models.dev 模型元数据的当前状态(GET / PUT `/api/models/metadata` 同形)。 */ +export type ModelsDevState = { + /** 联网刷新开关(关闭后已装载的数据继续用,见后端 `KEY_MODELS_DEV_ENABLED`) */ + modelsDevEnabled?: boolean + /** 这份索引的来历:`builtin`(内嵌快照)/ `cache`(上次刷新结果)/ `network`(刚拉的) */ + source?: string + /** 这份数据的生成时刻(毫秒;0 = 未知) */ + updatedAt?: number + /** 收录的模型条数 */ + count?: number +} + +/** 立即刷新的一行结果(字段与各家目录刷新的结果行同形,见后端 `api::model_meta`)。 */ +export type ModelsDevRefreshResult = { + status?: string + message?: string + count?: number + refreshedAt?: number +} + +/** 面板状态行要的那几个字段(避免这里 import 状态层的类型造成循环依赖) */ +type ModelsDevView = { + status: 'loading' | 'ready' | 'unavailable' + enabled: boolean + source: string + updatedAt: number + count: number +} + +/** + * models.dev 面板的状态行:把「开关 + 数据来历 + 生成时刻 + 条数」写成一句话。 + * + * 为什么不只写「已开启」:这个开关的价值全在**那份元数据是什么时候的、有多少 + * 条** —— 只报开关状态,用户没法判断「我的档位为什么还是老样子」是没开、 + * 是没拉到、还是这份快照本来就旧。 + */ +export function modelsDevStateText(state: ModelsDevView): string { + if (state.status === 'loading') return STATES.appLoading + if (state.status === 'unavailable') return STATES.modelsDevUnavailable + const origin = state.source === 'builtin' + ? STATES.modelsDevSourceBuiltin + : state.source === 'cache' + ? STATES.modelsDevSourceCache + : state.source === 'network' + ? STATES.modelsDevSourceNetwork + // 后端将来加了档位时原样回显,不显示成空白 + : state.source + const stamp = state.updatedAt > 0 + // 与别处的时间展示同源(app.js 提供的 `formatTime`;岛里从共享桥取) + ? String(shared().wbApp?.formatTime?.(state.updatedAt) ?? '') + : '' + if (!origin && !stamp && !state.count) return STATES.modelsDevEmpty + const at = stamp ? t(',{time}', { time: stamp }) : '' + const mode = state.enabled ? t('正在联网更新') : t('仅用现有数据、不联网刷新') + return t('{count} 条 · 来自{origin}{at} · {mode}', { + count: Number(state.count).toLocaleString('zh-CN'), + origin: origin || t('未知来源'), + at, + mode, + }) +} + /** 本页用到的壳 / HTTP 桥(方法名与 bridge.rs 一一对应,一个都不能改) */ export type SettingsBridge = { /** 'desktop' | 'web':面板登录那一块只在网页端有意义 */ @@ -154,6 +208,11 @@ export type SettingsBridge = { saveAppSettings(patch: AppSettings): Promise exportAccounts(): Promise importAccounts(): Promise + // ── 整库备份 / 恢复(仅桌面端;web 端 shim 不提供,按钮也只在桌面端渲染)── + /** 整库备份:弹保存框,后端把整库导出为 SQL 文件直写到该路径 */ + exportDatabase?(includeLogs: boolean): Promise + /** 整库恢复:弹打开框,后端校验后整体替换数据库(替换前自动安全备份) */ + importDatabase?(): Promise getRetention(): Promise saveRetention(patch: Record): Promise getRetry(): Promise @@ -162,6 +221,11 @@ export type SettingsBridge = { saveTimeouts(patch: Record): Promise getQueue(): Promise saveQueue(patch: Record): Promise + getCaptchaPool(): Promise + saveCaptchaPool(patch: Record): Promise + // ── 账号路由(「路由」分类):GET/PUT /api/routing,PUT 返回生效后的全量值 ── + getRoutingConfig(): Promise + setRoutingConfig(patch: Record): Promise getDebug(): Promise saveDebug(enabled: boolean): Promise getSanitize(): Promise @@ -175,6 +239,11 @@ export type SettingsBridge = { getStorage(): Promise getCaptchaSetting(): Promise<{ captchaEnabled?: boolean } | null | undefined> saveCaptchaSetting(on: boolean): Promise<{ captchaEnabled?: boolean } | null | undefined> + /** models.dev 模型元数据:开关 + 当前索引状态(见后端 `api::model_meta`) */ + getModelsDev(): Promise + saveModelsDev(on: boolean): Promise + /** 立即刷新:真打公网;返回一行结果(与各家目录刷新同形)+ 刷新后的状态 */ + refreshModelsDev(): Promise<{ result?: ModelsDevRefreshResult; status?: ModelsDevState } | null | undefined> panelLogout(): Promise /** 后端就绪状态(局域网地址展示要拼网关端口;其余字段本页不消费) */ getBackendStatus?(): Promise<{ port?: number } | null | undefined> @@ -189,16 +258,6 @@ export type SettingsBridge = { localIp?(): Promise /** 打开外链的唯一出口(只放行 http(s)):桌面走系统浏览器,网页端 shim 是 window.open */ openReleasePage?(url: string): Promise - // ── 以下成员从 HEAD 恢复(并行改动移走了定义但 settings-state.ts 仍引用)── - exportDatabase?(includeLogs: boolean): Promise - importDatabase?(): Promise - getCaptchaPool(): Promise - saveCaptchaPool(patch: Record): Promise - getRoutingConfig(): Promise - setRoutingConfig(patch: Record): Promise - getModelsDev(): Promise - saveModelsDev(on: boolean): Promise - refreshModelsDev(): Promise<{ result?: ModelsDevRefreshResult; status?: ModelsDevState } | null | undefined> } /** @@ -221,6 +280,8 @@ export type SharedWindow = { applyTheme?: (mode: string) => void /** 应用界面缩放(传百分数,如 105):由 app.js 落到 WebView 层并记档 */ applyZoom?: (percent: number) => void + /** 时间戳 → 本地时间串(app.js 的全局实现;models.dev 面板的「数据是什么时候的」用它) */ + formatTime?: (value: unknown) => string } /** Token 计量单位的展示口径(units.js):本页只负责拨开关,格式化在那边 */ wbUnits?: { isChinese?: () => boolean; setChinese?: (on: boolean) => void } @@ -253,7 +314,7 @@ export async function openExternal(url: string): Promise { try { await shared().workbuddyDesktop?.openReleasePage?.(url) } catch (error) { - toast(`打开链接失败:${errorMessage(error)}`, 'err') + toast(t('打开链接失败:{error}', { error: errorMessage(error) }), 'err') } } @@ -282,17 +343,117 @@ export async function openExternal(url: string): Promise { * 改名会让两者当场失配 —— 用户看到的只是标签,id 是内部契约。 */ export const CATEGORIES = [ - { id: 'general', label: '通用', icon: 'sliders' }, - { id: 'display', label: '显示', icon: 'display' }, - { id: 'gateway', label: '网关', icon: 'traffic' }, - { id: 'retry', label: '重试', icon: 'refresh' }, - { id: 'timeout', label: '超时', icon: 'timer' }, - { id: 'security', label: '安全', icon: 'shield' }, - { id: 'data', label: '数据', icon: 'database' }, - { id: 'feedback', label: '反馈与需求', icon: 'feedback' }, - { id: 'about', label: '更新', icon: 'download' }, + { id: 'general', label: t('通用'), icon: 'sliders' }, + { id: 'display', label: t('显示'), icon: 'display' }, + { id: 'gateway', label: t('网关'), icon: 'traffic' }, + { id: 'routing', label: t('路由'), icon: 'route' }, + { id: 'retry', label: t('重试'), icon: 'refresh' }, + { id: 'timeout', label: t('超时'), icon: 'timer' }, + { id: 'security', label: t('安全'), icon: 'shield' }, + { id: 'data', label: t('数据'), icon: 'database' }, + { id: 'feedback', label: t('反馈与需求'), icon: 'feedback' }, + { id: 'about', label: t('更新'), icon: 'download' }, ] as const +/** + * 「路由」分类的档位表:转发选路的策略与会话粘性(取值与后端 /api/routing 逐字对应)。 + * + * `tip` 是行内问号([data-tip])的说明全文 —— 这组设置原来在账号页的路由抽屉里 + * (说明平铺成段),抽屉撤除后搬到设置页,说明收进问号气泡,档位值不变。 + * + * ── 余额优先为什么没了(2026-10)───────────────────────────── + * 曾经有「余额优先」:它的 `value` 写的是 `balance`,而后端只认 `order` / + * `rotate` / `usage` —— 选中它保存必然报「未知的路由策略「balance」」,等于一直 + * 是坏的。这次连同后端的 `usage` 策略一起移除(按用户要求)。 + * 后端 `RouteStrategy::from_id` 把历史配置里的 `usage` 归到负载均衡。 + * + * ── 家内轮询是本仓自己加的(上游没有)─────────────────────── + * 上游 `RouteStrategy` 只有 `order` / `rotate` 两档,`rotate` 是**全局一条环** + * (轮一转会跨家)。想在「家之间保持优先级」的前提下把同一家的账号摊开用, + * 只能自己加一档 —— 后端的 `RouteStrategy::Provider` 与 + * `routing::provider_order` 是同一条线的两端,改档位值必须两边一起改。 + */ +export const ROUTE_STRATEGIES = [ + { + value: 'order', + label: t('顺序优先'), + tip: t('排第 1 的接走所有请求,直到它不能答(限流 / 故障 / 额度尽)才轮到下一位 —— 就是「从上往下」的现状行为。'), + }, + { + value: 'rotate', + label: t('负载均衡'), + tip: t('每条请求轮换到下一个可用账号;新会话交给当前最闲的那位。适合想把手里的号摊开用、不让某一个一直扛。'), + }, + { + value: 'provider', + label: t('家内轮询'), + tip: t('家之间仍按优先级,只有同一家内部轮流用各账号 —— 想优先用某几家、又不愿把某一家的某个账号焊死时用它。'), + }, +] as const + +/** 会话粘性档位:同一会话的后续请求是否尽量跟住同一个账号(会话 = 模型 + 首条用户消息) */ +export const ROUTE_STICKY_OPTIONS = [ + { + value: 'auto', + label: t('自动'), + tip: t('同一会话在 5 分钟内尽量跟住同一个账号;停了 5 分钟再发就算新会话。多数场景用它 —— 多轮对话少换号,也不至于把账号焊死。'), + }, + { + value: 'session', + label: t('会话内'), + tip: t('同一会话在 6 小时内跟住同一个账号;适合一坐几个小时的长会话,上游的上下文缓存能吃到更多。'), + }, + { + value: 'turn', + label: t('每轮'), + tip: t('每条请求都重新按策略选路 —— 行为与「关闭」一致,仅保留会话识别的记录。'), + }, + { + value: 'off', + label: t('关闭'), + tip: t('不做会话识别,每条请求都重新按策略选路。'), + }, +] as const + +/** 路由档位的取值(SegmentedControl 的泛型参数用它,视图里不必再写字面量联合) */ +export type RouteStrategyValue = (typeof ROUTE_STRATEGIES)[number]['value'] +export type RouteStickyValue = (typeof ROUTE_STICKY_OPTIONS)[number]['value'] + +/** + * 「路由」分类的三个自愈开关(后端 `/api/routing` 的布尔字段)。 + * + * ── 为什么要有这一组(本仓新增,2026-10-13)─────────────────── + * 后端 v3.0.2 起就有这三个开关(默认值见每项的 `defaultOn`),但前端一直 + * 没有入口 —— 说明文案还写着「三层自愈保护默认生效,不需要配置」。默认值 + * 下这句话成立,可一旦某个开关的实际行为不合预期(实测:垫底会把一整个 + * 提供商永久压在队尾,见 `routingSink` 的 tip),用户就无从下手了。 + * + * `key` 是后端字段名(PUT 的键),`defaultOn` 只用于界面提示「当前是默认值 + * 吗」,真正的兜底在后端。 + */ +export const ROUTE_PROTECTION_SWITCHES = [ + { + key: 'routingFailoverBackoff', + label: t('失败退避'), + defaultOn: true, + tip: t('转发失败的账号休息一会儿再回来:15 分钟起步,连续失败翻倍,封顶 1 小时;成功一次立即恢复。目的是「让这次失败先凉一会儿」,免得一条条地反复撞同一个坏账号。'), + }, + { + key: 'routingSink', + label: t('限流垫底'), + defaultOn: true, + tip: t('还有额度时被 429 的账号排到队尾,30 分钟后自动回到队列(成功转发一次也会立即回来)。它标记的是「疑似共享池被别人抢」,不是「这个账号本身有问题」。⚠️ 注意它与路由策略的配合:在「家内轮询」下,队尾意味着这一家整体被往后排 —— 如果某个提供商的账号被批量限流,它们会集体沉到队尾,那个家可能长时间轮不到。这时可以关掉本项,让 429 过的账号只受冷却约束(冷却到点自动回来)。'), + }, + { + key: 'routingBreakerEnabled', + label: t('熔断'), + defaultOn: false, + tip: t('连续失败到阈值后把这个账号整个打开(默认关)。与失败退避的分工:退避管「单次失败先凉一会儿」,惩罚轻、自动恢复;熔断管「这个账号现在整体不对劲,别再一条条地试」,要连续成功若干次才关。打开期间该账号被跳过,除非全场只剩它 —— 那时仍放行试一次。'), + }, +] as const + +export type RouteProtectionKey = (typeof ROUTE_PROTECTION_SWITCHES)[number]['key'] + /** * 「设置页当前分类」的 localStorage 键:纯前端偏好(与主题、计量单位同类), * 主进程不参与。键名沿用旧实现的取值,别改 —— 否则用户上次停留的分类会丢。 @@ -337,9 +498,9 @@ export const ZOOM_PERCENTS: number[] = Array.from( * 这里用了更书面的一种)。 */ export const THEME_MODES = [ - { value: 'system', label: '跟随系统' }, - { value: 'light', label: '浅色' }, - { value: 'dark', label: '深色' }, + { value: 'system', label: t('跟随系统') }, + { value: 'light', label: t('浅色') }, + { value: 'dark', label: t('深色') }, ] as const /** 显示模式取值(SegmentedControl 的泛型参数要用它,免得在视图里转字面量联合) */ @@ -397,33 +558,22 @@ export type NumberField = { export const RETENTION_MIN = 1 export const RETENTION_MAX = 3650 +/** + * 保留期字段(「数据保留」面板)。 + * + * 只剩事件日志一项:请求日志 / 按天聚合 / 签到记录已全量保留,没有保留天数 + * 可设 —— 对应的两个后端配置键(`requestRetentionDays` / `dailyRetentionDays`) + * 与 `/api/retention` 响应字段一并退役。 + */ export const RETENTION_FIELDS: NumberField[] = [ { key: 'logRetentionDays', id: 'settings-retention-log', - label: '事件日志保留天数', - unit: '天', - min: RETENTION_MIN, - max: RETENTION_MAX, - hint: '登录 / 账号切换 / 429 切换等系统事件,可填 1–3650 天。', - }, - { - key: 'requestRetentionDays', - id: 'settings-retention-request', - label: '请求日志保留天数', - unit: '天', - min: RETENTION_MIN, - max: RETENTION_MAX, - hint: '「请求日志」页的逐条请求记录,可填 1–3650 天。', - }, - { - key: 'dailyRetentionDays', - id: 'settings-retention-daily', - label: '按天聚合保留天数', - unit: '天', + label: t('事件日志保留天数'), + unit: t('天'), min: RETENTION_MIN, max: RETENTION_MAX, - hint: '报表页的热力图与按天趋势,可填 1–3650 天。', + hint: t('登录 / 账号切换 / 429 切换等系统事件,可填 1–3650 天。'), }, ] @@ -436,29 +586,29 @@ export const RETRY_FIELDS: NumberField[] = [ { key: 'retryCount', id: 'settings-retry-count', - label: '同一账号重试次数', - unit: '次', + label: t('同一账号重试次数'), + unit: t('次'), min: 0, max: 10, - hint: '在同一个账号上原地重发几次(不含首发;整条请求共用一份,用完后换来的账号只发一次就继续换)。可填 0–10,0 表示失败立即换号。', + hint: t('在同一个账号上原地重发几次(不含首发;整条请求共用一份,用完后换来的账号只发一次就继续换)。可填 0–10,0 表示失败立即换号。'), }, { key: 'retryCrossProviderCount', id: 'settings-retry-cross-provider-count', - label: '切换账号重试次数', - unit: '次', + label: t('切换账号重试次数'), + unit: t('次'), min: 0, max: 10, - hint: '失败后最多再换几个账号试(填 N = 最多换 N 个,首发那个不算)。换到同一家名下另一个账号、或换到另一家,都各算一次;换满仍失败就返回错误。可填 0–10,0 表示失败立即报错。', + hint: t('失败后最多再换几个账号试(填 N = 最多换 N 个,首发那个不算)。换到同一家名下另一个账号、或换到另一家,都各算一次;换满仍失败就返回错误。可填 0–10,0 表示失败立即报错。'), }, { key: 'retryIntervalSeconds', id: 'settings-retry-interval', - label: '重试间隔', - unit: '秒', + label: t('重试间隔'), + unit: t('秒'), min: 0, max: 300, - hint: '两次重试之间的等待时间,两项共用,可填 0–300 秒。', + hint: t('两次重试之间的等待时间,两项共用,可填 0–300 秒。'), }, ] @@ -467,38 +617,38 @@ export const TIMEOUT_FIELDS: NumberField[] = [ { key: 'connectTimeoutSeconds', id: 'settings-timeout-connect', - label: '连接中超时', - unit: '秒', + label: t('连接中超时'), + unit: t('秒'), min: 1, max: 3600, - hint: '建立上游 TCP/TLS 连接或代理隧道的最大等待时间(秒),默认 30 秒,范围 1~3600。', + hint: t('建立上游 TCP/TLS 连接或代理隧道的最大等待时间(秒),默认 30 秒,范围 1~3600。'), }, { key: 'headersTimeoutSeconds', id: 'settings-timeout-headers', - label: '等待响应超时', - unit: '秒', + label: t('等待响应超时'), + unit: t('秒'), min: 1, max: 3600, - hint: '请求发出后等待上游响应头的最大时间(秒),默认 300 秒,范围 1~3600。', + hint: t('请求发出后等待上游响应头的最大时间(秒),默认 300 秒,范围 1~3600。'), }, { key: 'streamIdleTimeoutSeconds', id: 'settings-timeout-stream-idle', - label: '流式响应空闲超时', - unit: '秒', + label: t('流式响应空闲超时'), + unit: t('秒'), min: 1, max: 3600, - hint: '流式响应相邻数据之间允许的最大空闲时间(秒),收到新数据后重新计时,默认 300 秒,范围 1~3600。', + hint: t('流式响应相邻数据之间允许的最大空闲时间(秒),收到新数据后重新计时,默认 300 秒,范围 1~3600。'), }, { key: 'bodyTimeoutSeconds', id: 'settings-timeout-body', - label: '非流式响应超时', - unit: '秒', + label: t('非流式响应超时'), + unit: t('秒'), min: 1, max: 3600, - hint: '读取完整非流式响应体允许的最大时间(秒),默认 300 秒,范围 1~3600。', + hint: t('读取完整非流式响应体允许的最大时间(秒),默认 300 秒,范围 1~3600。'), }, ] @@ -507,20 +657,51 @@ export const QUEUE_FIELDS: NumberField[] = [ { key: 'queueMaxWaits', id: 'settings-queue-max-waits', - label: '排队等待次数', - unit: '次', + label: t('排队等待次数'), + unit: t('次'), min: 0, max: 10, - hint: '上游模型繁忙时会先排队(回一句「建议 N 秒后再来」,Qoder 免费模型就是这样):网关等一会儿再发同一请求,最多等几次。默认 2 次,可填 0–10;填 0 表示不等待,排队直接返回 503 并说明「不是登录态或额度问题」。', + hint: t('上游模型繁忙时会先排队(回一句「建议 N 秒后再来」,Qoder 免费模型就是这样):网关等一会儿再发同一请求,最多等几次。默认 2 次,可填 0–10;填 0 表示不等待,排队直接返回 503 并说明「不是登录态或额度问题」。'), }, { key: 'queueWaitSeconds', id: 'settings-queue-wait-seconds', - label: '排队等待秒数', - unit: '秒', + label: t('排队等待秒数'), + unit: t('秒'), min: 0, max: 120, - hint: '每次等待的时长,默认 0 = 跟随上游建议(实测 9~30 秒,上游没给建议时用 15 秒)。可填 0–120 秒强制一个固定时长。', + hint: t('每次等待的时长,默认 0 = 跟随上游建议(实测 9~30 秒,上游没给建议时用 15 秒)。可填 0–120 秒强制一个固定时长。'), + }, +] + +/** 验证码令牌池字段:键名与 config.rs 的 KEY_CAPTCHA_POOL_* 指向的 JSON 键逐字一致 */ +export const CAPTCHA_POOL_FIELDS: NumberField[] = [ + { + key: 'zcodeCaptchaPoolTarget', + id: 'settings-captcha-pool-target', + label: t('库存目标'), + unit: t('个'), + min: 1, + max: 10, + hint: t('ZCode 活动套餐通道每条请求都要消耗一个当次铸造的人机验证令牌(一次性,2 分钟过期),库存低于该值时界面自动补铸到它。默认 3 个。调大能吸收突发并发,但用不掉的令牌 2 分钟就过期作废,烧的是上游风控配额。可填 1–10。'), + }, + { + key: 'zcodeCaptchaPoolPollMs', + id: 'settings-captcha-pool-poll-ms', + label: t('轮询间隔'), + unit: t('毫秒'), + min: 1000, + max: 30000, + hint: t('铸造守卫每隔多久看一次库存(毫秒)。只影响发现缺货的反应速度 —— 库存够用时轮询不会铸造任何令牌。默认 2500 毫秒,可填 1000–30000。'), + }, + { + key: 'zcodeCaptchaPoolMaxPerRound', + id: 'settings-captcha-pool-max-per-round', + label: t('单轮铸造上限'), + unit: t('个'), + min: 1, + max: 5, + hint: t('发现缺货时一轮最多铸几个(连铸之间固定隔 500 毫秒)。默认 1 个:SDK 同一实例连铸容易互相干扰。调大补货更快,但单轮连铸越多越容易触发上游风控。可填 1–5。'), }, ] @@ -534,9 +715,9 @@ export const RETRY_MAX_CODES = 50 export type PromptModeOption = { value: string; optionLabel: string; toastLabel: string } export const PROMPT_MODES: PromptModeOption[] = [ - { value: 'passthrough', optionLabel: '透传客户端 system(默认)', toastLabel: '透传客户端 system' }, - { value: 'custom', optionLabel: '替换为网关提示词', toastLabel: '替换为网关提示词' }, - { value: 'append', optionLabel: '追加网关提示词', toastLabel: '追加网关提示词' }, + { value: 'passthrough', optionLabel: t('透传客户端 system(默认)'), toastLabel: t('透传客户端 system') }, + { value: 'custom', optionLabel: t('替换为网关提示词'), toastLabel: t('替换为网关提示词') }, + { value: 'append', optionLabel: t('追加网关提示词'), toastLabel: t('追加网关提示词') }, ] /* ─── 校验与归一化 ─────────────────────────── */ @@ -552,11 +733,11 @@ export type ParseResult = { ok: true; value: number } | { ok: false; message: st export function parseInteger(raw: unknown, min: number, max: number, noun: string): ParseResult { const text = String(raw ?? '').trim() // 空串要单独挡:空值过不了下面的正则,但提示语不同(「不能为空」比「必须是整数」更准) - if (!text) return { ok: false, message: `${noun}不能为空(可填 ${min}–${max})` } - if (!/^\d+$/.test(text)) return { ok: false, message: `${noun}必须是整数` } + if (!text) return { ok: false, message: t('{noun}不能为空(可填 {min}–{max})', { noun, min, max }) } + if (!/^\d+$/.test(text)) return { ok: false, message: t('{noun}必须是整数', { noun }) } const value = Number(text) if (value < min || value > max) { - return { ok: false, message: `${noun}必须在 ${min}–${max} 之间(当前填的是 ${text})` } + return { ok: false, message: t('{noun}必须在 {min}–{max} 之间(当前填的是 {text})', { noun, min, max, text }) } } return { ok: true, value } } @@ -608,13 +789,13 @@ export function normalizeNumbers( /** 字节数 → 可读大小(库主文件通常几百 KB 到几十 MB,四档够用) */ export function formatBytes(bytes: number): string { - if (!Number.isFinite(bytes) || bytes <= 0) return '0 B' - if (bytes < 1024) return `${bytes} B` + if (!Number.isFinite(bytes) || bytes <= 0) return t('0 B') + if (bytes < 1024) return t('{n} B', { n: bytes }) const kb = bytes / 1024 - if (kb < 1024) return `${kb.toFixed(1)} KB` + if (kb < 1024) return t('{n} KB', { n: kb.toFixed(1) }) const mb = kb / 1024 - if (mb < 1024) return `${mb.toFixed(1)} MB` - return `${(mb / 1024).toFixed(2)} GB` + if (mb < 1024) return t('{n} MB', { n: mb.toFixed(1) }) + return t('{n} GB', { n: (mb / 1024).toFixed(2) }) } /** 条数 → 带千分位的文本(用户对着看更省事);非法值给「—」 */ @@ -628,172 +809,91 @@ export function formatCount(value: unknown): string { /** 标题右侧问号(`[data-tip]`)的说明全文:tooltip.js 仍在页面上跑,照旧服务这些元素 */ export const TIPS = { - displayTheme: '控制界面的深浅色,与左侧边栏底部的三个主题按钮是同一个设置(改哪一处,另一处立刻跟上)。「跟随系统」会随操作系统当前的浅色 / 深色自动切换,并在系统主题变化时即时跟上;选「浅色」或「深色」则把界面固定在该模式,不再随系统变化。窗口标题栏的深浅色会一并同步,不会出现深色界面配一条浅色标题栏的情况。', - displayZoom: '等比放大或缩小整个界面(文字、控件、间距一起变),效果与浏览器按 Ctrl +/- 相同:80%–130%、5% 一档。窗口本身不缩放,变的是页面内容的显示比例,设置立即生效并记住,下次启动直接按这个比例打开。放得越大可视范围越小,窗口较窄或表格较宽时不建议调得太大。', - displayLanguage: '界面语言。可选简体中文、繁體中文、English、日本語、한국어、Português (Brasil),或「跟随系统」(按浏览器 / 系统的语言列表自动选)。切换后整页立即刷新;该偏好只存在本机(localStorage),不影响账号、密钥与转发。', - tray: '默认关闭窗口不会退出程序,而是把窗口缩到系统托盘,转发继续在后台运行(OpenAI 客户端不受影响);要彻底退出程序,请在托盘图标上右键选「退出」。关掉这个开关后,点关闭按钮即退出程序、转发随之中断。「开机自动启动」开启后,登录系统时会自动启动本程序(通常直接驻留托盘),不需要手动打开。', - lightweight: '开启后,关闭窗口不只是隐藏,而是把界面窗口整个销毁:底层的 WebView2 六个常驻进程(约 200MB 内存)随之退出,网关转发、定时签到、余额查询都在后台进程里继续,不受影响;需要界面时点托盘图标重新打开(WebView 冷启动约 1 秒)。注意:界面销毁期间「ZCode 活动套餐」通道的验证码令牌由界面铸造,无法补充 —— 走该通道的请求会以 503 落进请求日志(写明原因),重新打开界面即自动恢复。此开关只在「关闭窗口时最小化到托盘」开启时有意义,最小化窗口不受影响。', - lan: '默认网关只监听 127.0.0.1,只有本机能访问。开启后网关改听所有网卡,同一局域网内的设备可以把 API 地址指向本机 IP 一起使用。出于安全考虑,开启前必须先注册一个面板管理员:管理接口从此要求管理员会话或网关 Key,模型额度不会对局域网裸奔;一把启用的网关 Key 都没有时,转发接口也会拒绝服务,直到创建第一把。改动需要重启应用生效。「同时开放网页管理面板」把管理界面也出给局域网(其他设备的浏览器打开本机 IP 即可管理),默认关闭 —— 桌面端的面板仍只由本程序自己出。', - units: '控制报表与请求日志里 Token 读数的写法:开启后按中文量级显示(1.2亿 / 8400万),关闭则用 k / M 缩写(与上游文档、接口字段的写法一致)。这只影响显示口径,不改变任何统计与存储的数值。', - queue: '只对「排队制」的上游生效(目前是 Qoder 的免费模型):模型繁忙时上游不报错,只回一句「建议 N 秒后再来」(业务码 10605),网关按建议时长等一会儿再发同一请求,等满次数仍排不上才把「排队中」作为错误返回(HTTP 503,文案会说明这不是登录态或额度问题)。等待发生在首个字节之前,吃的是「等待响应超时」那份预算 —— 两项设置一起决定一次请求最多卡多久;排队不会标记账号限额、也不会换账号(换谁都一样在排队)。保存后对下一个请求立即生效,不用重启。', - timeouts: '上游请求四个阶段各自的等待上限(秒,1~3600):①「连接中超时」= 建立 TCP/TLS 连接或代理隧道的最大等待,默认 30 秒;②「等待响应超时」= 请求发出后等上游响应头的最大时间,默认 300 秒 —— 网关请求上游恒带 stream,响应头在 SSE 建立时就到达,与模型思考多久无关;③「流式响应空闲超时」= 流式响应相邻两块数据之间允许的最大空闲,收到新数据即重新计时,默认 300 秒 —— 上游长时间不吐数据即判定连接僵死并断开;④「非流式响应超时」= 读完整份非流式响应体的总预算(一次性计时、不重置),默认 300 秒。四项都是「等待上限」,只要数据还在来,正常的流式回答就一直往下传。保存后对下一个请求立即生效,不用重启。', - retry: '请求转发到上游失败时(服务器瞬时错误、连接失败,以及 WorkBuddy 的 11-128 敏感词拦截),网关会等一段间隔后再发一次。次数分两档,管的是两件事:①「同一账号重试次数」在同一账号上原地重发几次 —— 一般是提示词被上游拦截、或链路瞬时抖动,等一会儿重发往往就好了;②「切换账号重试次数」这份请求最多再换几个账号试 —— 首发的那个账号不算,每换一个扣一次,不分是不是同一家(换到同一家的下一个账号也算一次),换满还失败就把错误返回给客户端。两项都设为 0 表示失败不重试、直接报错。注意账号级限额(429)不占这里的换号次数 —— 那类失败走「冷却该账号并换下一个账号」的降级,与这里的重试是两条路。另有「指定错误码直接换号」名单(默认 402):命中名单的上游状态码不在同一账号重发,直接按队列换下一个账号继续试(换号也占「切换账号重试次数」),换满仍失败才把错误返回给客户端。', - sanitize: '上游用「逐字精确匹配」的方式审核请求体(不是语义审核):客户端注入的固定模板句、计费头字段名、以及某些裸错误码出现在报文里就会整单拦截,返回 400。开启本项后,网关在每次转发前改写这些指纹 —— 表头键值整段删除,承载语义的模板句只换一个词(如 official CLI for Claude → official CLI tool for Claude),对话内容与语义都不受影响。规则集是内置的,不需要也无法维护词表。关掉本项后客户端模板会原样发往上游,可能重新出现模板句被误拦的报错。', - clineHeaders: 'Cline 上游按请求头判定「调用方是不是 Cline 自家产品」:X-CLIENT-TYPE: cline-sdk 是硬门槛(缺了它免费池模型一律 403),版本号与平台标识让请求更贴近官方客户端的形态。这里列出的是网关默认会发的头:改某一行的值 = 覆盖默认值(也可以新增默认清单之外的自定义头);把值清空保存 = 这个头不发送;在界面删掉被改过的行 = 回落默认值。改完点「保存」,下一个 Cline 请求立即生效。不懂某一行的含义就不要动它 —— 伪装头的价值在「与官方客户端逐字一致」。', - cors: '网关面(/v1/*)默认不应答浏览器跨源请求:页面直连会被预检拦下,只报「无法连接 API」。注意来源是 * —— 未配「网关 Key」时任何网页都能借本机网关打上游,故默认关闭;只给自己用的话,让页面与网关同源(本地反代 /v1)更稳妥。面板接口(/api/*)不受影响。', - prompt: '客户端(Claude Code / Codex 等 CLI)会在 system 提示词里注入几十句固定模板,上游按逐字匹配审核,命中就整单拦截(HTTP 400)。指纹脱敏能改写实测命中过的那几句,但换一个客户端版本就可能冒出新的。这里可以把 system 整段换成网关自己那份:①「透传」= 不动客户端 system(默认,行为与之前完全一致);②「替换」= 删掉客户端所有 system / developer 消息,换成网关的提示词(客户端项目规范随之消失);③「追加」= 在开头连续 system 块之后插入一条网关提示词,既有消息逐字不动(客户端规范与网关提示词并用)。那份提示词有两个来源:提示词文件(留空用内置默认),或直接在界面上编辑正文 —— 编辑过就以那份正文为准(优先于文件),清空则回到文件 / 内置默认。另外,透传 / 追加模式下撞了内容拦截(多半是指纹误报)时,网关会自动换一段最小中性提示词重试一次,并把「降级期」开到次日 00:00 —— 期间所有请求直接带中性提示词出门,不再先撞一次 400;这里能看见并提前解除它。上面几项是**默认值**:想给某个提供商单独配,用下面的「按提供商」加一行(带「网关自带」的家默认就列在那里)—— 不同的上游对这些内容的接受程度不一样。', - debug: '开启后,网关会把每次转发**发给上游的请求**(请求头 + 请求体)与**上游返回的响应**(状态码 + 响应头 + 响应体)完整保存到本地,供请求日志页的「详情」查看。请求头里的 Authorization、Cookie、API Key 等凭据字段一律替换成 [redacted],不会明文落盘;请求体与响应体按原样保存(可能包含你的对话内容)。报文只保留最近 500 条,超出后丢弃最旧的。这是排障用的临时开关,不需要时建议关闭。', - io: '导出会把全部账号与自定义提供商定义写入一个 JSON 文件,可以拷到另一台机器上导入后继续使用。导入采用合并策略:同提供商下按业务身份(UID / userId / apiKey 等)去重 —— 已存在的账号只更新凭证,保留本机原有的优先级顺序;新账号追加到转发顺序末尾,不会抢占当前正在使用的账号;自定义提供商定义按 id 合并,本机缺失时自动补建。', - retention: '三类数据各自独立计时,超出保留天数的部分会被删除:事件日志是登录、账号切换、429 切换这类系统事件;请求日志是网关每次转发到上游的逐条记录;按天聚合供报表页的热力图与按天趋势使用。把某一档改小(例如 30 天改成 7 天)保存后会立即删除超出的历史数据,此操作不可恢复;改大或保持不变不会删除任何数据。三项的可填范围均为 1–3650 天。', - storage: '全部数据(账号、事件日志、请求记录、调试报文、设置)统一保存在配置目录下的 agent2api.db 这一个 SQLite 数据库里。备份时只需拷贝这个文件;更换保存位置请设置环境变量 AGENT2API_PROXY_HOME 后重启程序。', + displayTheme: t('控制界面的深浅色,与左侧边栏底部的三个主题按钮是同一个设置(改哪一处,另一处立刻跟上)。「跟随系统」会随操作系统当前的浅色 / 深色自动切换,并在系统主题变化时即时跟上;选「浅色」或「深色」则把界面固定在该模式,不再随系统变化。窗口标题栏的深浅色会一并同步,不会出现深色界面配一条浅色标题栏的情况。'), + displayZoom: t('等比放大或缩小整个界面(文字、控件、间距一起变),效果与浏览器按 Ctrl +/- 相同:80%–130%、5% 一档。窗口本身不缩放,变的是页面内容的显示比例,设置立即生效并记住,下次启动直接按这个比例打开。放得越大可视范围越小,窗口较窄或表格较宽时不建议调得太大。'), + displayLanguage: t('界面语言。可选简体中文、繁體中文、English、日本語、한국어、Português (Brasil),或「跟随系统」(按浏览器 / 系统的语言列表自动选)。切换后整页立即刷新;该偏好只存在本机(localStorage),不影响账号、密钥与转发。'), + tray: t('默认关闭窗口不会退出程序,而是把窗口缩到系统托盘,转发继续在后台运行(OpenAI 客户端不受影响);要彻底退出程序,请在托盘图标上右键选「退出」。关掉这个开关后,点关闭按钮即退出程序、转发随之中断。「开机自动启动」开启后,登录系统时会自动启动本程序(通常直接驻留托盘),不需要手动打开。'), + lightweight: t('开启后,关闭窗口不只是隐藏,而是把界面窗口整个销毁:底层的 WebView2 六个常驻进程(约 200MB 内存)随之退出,网关转发、定时签到、余额查询都在后台进程里继续,不受影响;需要界面时点托盘图标重新打开(WebView 冷启动约 1 秒)。注意:界面销毁期间「ZCode 活动套餐」通道的验证码令牌由界面铸造,无法补充 —— 走该通道的请求会以 503 落进请求日志(写明原因),重新打开界面即自动恢复。与「开机自动启动」同时开启时,开机后也不建界面(只留托盘与后台进程),点托盘才打开 —— 效果与关窗后一致。此开关只在「关闭窗口时最小化到托盘」开启时有意义,最小化窗口不受影响。'), + lan: t('默认网关只监听 127.0.0.1,只有本机能访问。开启后网关改听所有网卡,同一局域网内的设备可以把 API 地址指向本机 IP 一起使用。出于安全考虑,开启前必须先注册一个面板管理员:管理接口从此要求管理员会话或网关 Key,模型额度不会对局域网裸奔;一把启用的网关 Key 都没有时,转发接口也会拒绝服务,直到创建第一把。改动需要重启应用生效。「同时开放网页管理面板」把管理界面也出给局域网(其他设备的浏览器打开本机 IP 即可管理),默认关闭 —— 桌面端的面板仍只由本程序自己出。'), + units: t('控制报表与请求日志里 Token 读数的写法:开启后按「万 / 亿」式的本地量级词显示(简体为万 / 亿,繁体为萬 / 億,日文为万 / 億,韩文为만 / 억),关闭则用 k / M 缩写(与上游文档、接口字段的写法一致)。英文 / 葡语的本地量级词就是 k / M,这项对它们没有区别。只影响显示口径,不改变任何统计与存储的数值。'), + queue: t('只对「排队制」的上游生效(目前是 Qoder 的免费模型):模型繁忙时上游不报错,只回一句「建议 N 秒后再来」(业务码 10605),网关按建议时长等一会儿再发同一请求,等满次数仍排不上才把「排队中」作为错误返回(HTTP 503,文案会说明这不是登录态或额度问题)。等待发生在首个字节之前,吃的是「等待响应超时」那份预算 —— 两项设置一起决定一次请求最多卡多久;排队不会标记账号限额、也不会换账号(换谁都一样在排队)。保存后对下一个请求立即生效,不用重启。'), + captchaPool: t('ZCode「活动套餐」通道的每条推理请求都要附一个当次铸造的阿里云无痕验证令牌(一次性、约 2 分钟过期):令牌由界面里的铸造守卫静默铸好、推给网关入池,转发时逐条取用。这里的三个值管的是补货节奏:①「库存目标」= 库存低于它守卫才补铸、补到它为止,默认 3 个;②「轮询间隔」= 守卫多久看一次库存,默认 2500 毫秒,只影响反应速度(库存够用时不会多铸);③「单轮铸造上限」= 发现缺货时一轮最多铸几个,默认 1 个(连铸之间固定隔 500 毫秒)。请求密集、请求日志里连续出现「需要人机验证令牌」的 503 时,把目标与单轮上限适当调大、轮询调快,能让池子跟得上消耗 —— 代价是上游(阿里云)对铸造频率有风控,铸得越多越快越容易触发限流,且用不掉的令牌 2 分钟即过期作废、等于白烧配额,所以建议小步调。保存后对下一轮补货立即生效,不用重启。'), + timeouts: t('上游请求四个阶段各自的等待上限(秒,1~3600):①「连接中超时」= 建立 TCP/TLS 连接或代理隧道的最大等待,默认 30 秒;②「等待响应超时」= 请求发出后等上游响应头的最大时间,默认 300 秒 —— 网关请求上游恒带 stream,响应头在 SSE 建立时就到达,与模型思考多久无关;③「流式响应空闲超时」= 流式响应相邻两块数据之间允许的最大空闲,收到新数据即重新计时,默认 300 秒 —— 上游长时间不吐数据即判定连接僵死并断开;④「非流式响应超时」= 读完整份非流式响应体的总预算(一次性计时、不重置),默认 300 秒。四项都是「等待上限」,只要数据还在来,正常的流式回答就一直往下传。保存后对下一个请求立即生效,不用重启。'), + retry: t('请求转发到上游失败时(服务器瞬时错误、连接失败,以及 WorkBuddy 的 11-128 敏感词拦截),网关会等一段间隔后再发一次。次数分两档,管的是两件事:①「同一账号重试次数」在同一账号上原地重发几次 —— 一般是提示词被上游拦截、或链路瞬时抖动,等一会儿重发往往就好了;②「切换账号重试次数」这份请求最多再换几个账号试 —— 首发的那个账号不算,每换一个扣一次,不分是不是同一家(换到同一家的下一个账号也算一次),换满还失败就把错误返回给客户端。两项都设为 0 表示失败不重试、直接报错。注意账号级限额(429)不占这里的换号次数 —— 那类失败走「冷却该账号并换下一个账号」的降级,与这里的重试是两条路。另有「指定错误码直接换号」名单(默认 402):命中名单的上游状态码不在同一账号重发,直接按队列换下一个账号继续试(换号也占「切换账号重试次数」),换满仍失败才把错误返回给客户端。'), + routing: t('转发一个请求时按什么顺序挑账号:①「路由策略」决定排队规则 —— 顺序优先是排第 1 的接走所有请求、直到它不能答(限流 / 故障 / 额度尽)才轮到下一位;负载均衡是每条请求换下一位,把负载摊到各个账号上。②「会话粘性」让同一会话(相同的模型 + 相同的开头消息)尽量跟住同一个账号 —— 多轮对话的上下文缓存能复用、少换号少浪费;自动档粘 5 分钟、会话内档粘 6 小时、每轮与关闭都不粘。账号的排队位次(账号表的第一列)在所有策略下都是地基,策略在它之上再排。此外路由还有三层自愈保护:转发失败的账号退避休息一会儿(15 分钟起步翻倍、封顶 1 小时)、被 429 的账号垫底排到队尾 30 分钟、余额不足 / Token 周期用量到顶的账号由限制器拦下 —— 前两层可以在下面按需开关,限制器由账号的「限制器」设置管。'), + sanitize: t('上游用「逐字精确匹配」的方式审核请求体(不是语义审核):客户端注入的固定模板句、计费头字段名、以及某些裸错误码出现在报文里就会整单拦截,返回 400。开启本项后,网关在每次转发前改写这些指纹 —— 表头键值整段删除,承载语义的模板句只换一个词(如 official CLI for Claude → official CLI tool for Claude),对话内容与语义都不受影响。规则集是内置的,不需要也无法维护词表。关掉本项后客户端模板会原样发往上游,可能重新出现模板句被误拦的报错。'), + clineHeaders: t('Cline 上游按请求头判定「调用方是不是 Cline 自家产品」:X-CLIENT-TYPE: cline-sdk 是硬门槛(缺了它免费池模型一律 403),版本号与平台标识让请求更贴近官方客户端的形态。这里列出的是网关默认会发的头:改某一行的值 = 覆盖默认值(也可以新增默认清单之外的自定义头);把值清空保存 = 这个头不发送;在界面删掉被改过的行 = 回落默认值。改完点「保存」,下一个 Cline 请求立即生效。不懂某一行的含义就不要动它 —— 伪装头的价值在「与官方客户端逐字一致」。'), + cors: t('网关面(/v1/*)默认不应答浏览器跨源请求:页面直连会被预检拦下,只报「无法连接 API」。注意来源是 * —— 未配「网关 Key」时任何网页都能借本机网关打上游,故默认关闭;只给自己用的话,让页面与网关同源(本地反代 /v1)更稳妥。面板接口(/api/*)不受影响。'), + prompt: t('客户端(Claude Code / Codex 等 CLI)会往 system 里塞几十句固定模板,上游逐字审核,命中就整单拦截(HTTP 400)。「模式」决定网关怎么处理这份 system:透传 = 原样不动(默认);替换 = 删掉客户端的 system / developer,换成网关提示词;追加 = 保留客户端内容,只在最前面插一条网关提示词。网关提示词来自「提示词文件」或界面里编辑的正文(正文优先,清空回到文件 / 内置默认)。撞上拦截时会自动改用一段最小中性提示词,次日 00:00 自动恢复,也可以随时解除。'), + debug: t('开启后,网关会把每次转发**发给上游的请求**(请求头 + 请求体)与**上游返回的响应**(状态码 + 响应头 + 响应体)完整保存到本地,供请求日志页的「详情」查看;请求日志详情的「预览对话」也依赖本开关 —— 它保存的是客户端发来的请求体与网关下发的响应体(两侧各截断到 128 KiB),不开这个开关时预览对话没有数据可看。请求头里的 Authorization、Cookie、API Key 等凭据字段一律替换成 [redacted],不会明文落盘;请求体与响应体按原样保存(可能包含你的对话内容)。上游报文只保留最近 500 条,超出后丢弃最旧的。这是排障用的临时开关,不需要时建议关闭。'), + io: t('导出会把全部账号与自定义提供商定义写入一个 JSON 文件,可以拷到另一台机器上导入后继续使用。导入采用合并策略:同提供商下按业务身份(UID / userId / apiKey 等)去重 —— 已存在的账号只更新凭证,保留本机原有的优先级顺序;新账号追加到转发顺序末尾,不会抢占当前正在使用的账号;自定义提供商定义按 id 合并,本机缺失时自动补建。'), + backup: t('把整份数据库(账号、网关配置、事件日志、请求统计、调试报文与桌面设置)导出成一个 SQL 文件,恢复时整体替换本机全部数据 —— 与上面「账号导入 / 导出」的逐条合并是两种语义:恢复会连配置、日志与当前启用状态一起换成备份那台机器的状态。导出默认包含日志与调试报文(文件可能很大),不需要时可以取消勾选只备业务数据。恢复前会自动把当前数据备份到配置目录的 backups/ 下,恢复后需要重新登录管理面板。'), + retention: t('超出保留天数的部分会被删除:事件日志是登录、账号切换、429 切换这类系统事件。把天数改小(例如 30 天改成 7 天)保存后会立即删除超出的历史数据,此操作不可恢复;改大或保持不变不会删除任何数据。可填范围为 1–3650 天。请求日志 / 按天聚合 / 签到记录已全量保留、不再自动删除,要清历史请到对应页面手动清空。'), + storage: t('全部数据(账号、事件日志、请求记录、调试报文、设置)统一保存在配置目录下的 agent2api.db 这一个 SQLite 数据库里。备份时只需拷贝这个文件;更换保存位置请设置环境变量 AGENT2API_PROXY_HOME 后重启程序。'), + modelsDev: t('models.dev 是一个开源的模型资料库(社区维护),这里用它补齐「上游没告诉我们」的模型能力:上下文窗口、最大输出、工具调用、图片、视频、是否支持思考,以及这个模型认识哪些思考档位。优先级是:你在「模型能力」里手工改的值 > 上游清单自己声明的值 > models.dev 的值 —— 它只填上游没声明的空位,从不推翻上游已声明的。网关随包内嵌了一份快照,所以离线、首次启动、访问不通时也有数据;开启时会按「模型目录刷新」任务的间隔联网更新(同一轮里一并刷新,也可在这里立即刷新)。关闭只停联网刷新,已经拿到的数据继续用。'), } as const /** 面板底注(`.hint.retention-note`)与各面板内的说明行 */ export const NOTES = { - timeouts: '保存后立即生效,不用重启;超时按上游失败处理(计入请求日志的「错误」列,并按「请求重试」的设置决定是否重试)。', - queue: '等待期间请求日志的状态列会显示「排队中」阶段,详情弹窗的「内部重试」里能逐次看到等待时长;等待用尽后返回 HTTP 503(不是 401/429:既不会刷新凭证,也不会把账号标成限额)。', - retry: '保存后立即生效,不用重启;次数用尽仍失败时,错误原样返回给客户端。', - retryCodes: '命中这些上游状态码的失败不在同一账号重发,直接换下一个账号继续试(换号占用「切换账号重试次数」,换满仍失败才把错误原样返回给客户端)。输入 100–599 的状态码后回车添加,点 × 或退格删除;默认 402(积分不足)。清空全部表示任何错误都照常重试。', - sanitize: '默认开启。命中明细会记进请求日志的「敏」标签(悬停可看命中了哪几条规则)。本项只改发给上游的副本,客户端看到的响应内容不变。', - clineHeaders: '值与默认值相同的行不占覆盖(存的是「改过的键」,不是全量配置);值留空保存表示这个头不发送,删除改过的行表示回落默认值。改完立即生效,不用重启。', - cors: '默认关闭。改动立即生效,不用重启;关闭期间的跨源请求会被预检拦下。', - debug: '开启后新发生的请求才会被记录(已经过去的请求补不回来)。报文统一存放在本地数据库里,只保留最近 500 条(超出后丢弃最旧的),条数见左侧「数据 → 数据存储」的「调试报文」。', - promptMode: '替换 = 客户端 system / developer 消息全部删掉,换成网关的提示词;追加 = 保留客户端内容,只在开头 system 块之后多插一条。两者都只改发给上游的副本,客户端看到的响应不变。', - promptFile: 'UTF-8 文本文件路径,留空用内置默认提示词(通用编码助手提示词,不含任何会被上游拦截的模板句)。只在「替换 / 追加」模式下生效,透传模式不读它。', - promptText: '在这里直接编辑提示词正文:保存后以这份文本为准(优先于上面的提示词文件),清空则回到文件 / 内置默认。改一个字不必再去编辑器里开文件。', - promptGatewayText: '上游按「结构」校验身份:三段必须各自成块,所以这里分开编辑三段(不能合成一段)。动态段里的运行值写成占位符,发请求时才替换:{cwd} 工作目录、{platform} 平台、{shell} shell、{os_version} 系统版本、{git} 是否 git 仓库、{provider} 提供方标识、{model} 模型名。清空某一段 = 那一段恢复官方原文。第三段发出时前面会自带一个空行(官方形状)。', - prompt: '改完立即生效,不用重启(下一个请求就用新模式)。降级是自动的临时状态,解除后本模式自己的提示词立刻恢复。', - promptProviders: '「用哪份提示词」本来是按上游分别决定的事,所以每家可以有自己的模式、提示词文件与正文:不在这里列出的提供商一律沿用上面那份默认设置,「跟随默认」把这一家取消、回到默认。带「网关自带」那一行的家(目前是 ZCode 两家)默认就列在这里 —— 那一段是网关自己装上去的文本,不来自客户端也不来自提示词文件,默认开启、可以关掉,也可以改它的正文(改过的那一段以你的文本为准);关掉后还能不能通过上游校验,取决于上游当下的口径,行内说明了实测依据。「模式 / 提示词文件 / 正文」管的是客户端自己的 system 怎么处理,与那个开关是两件事。', - retention: '保存后立即生效:改小保留天数会立刻删除超出的历史数据,且不可恢复。', - storageFile: '配置目录下的 agent2api.db(账号、日志、请求记录、调试报文与设置都在里面)。', - storageSize: '库主文件的大小(不含运行期间的 WAL 临时文件,退出时已自动并回)。', - storage: '数据统一保存在配置目录下的 agent2api.db;如需更换位置,请设置环境变量 AGENT2API_PROXY_HOME 后重启程序。', - captcha: '开启后,登录页在浏览器后台自动完成验证(对真人无感),而脚本每次尝试都要先算一道题 —— 暴力破解与抢注的成本显著上升。仅影响面板的登录 / 注册,与 API 客户端的 API Key 无关。', - panelLogin: '当前浏览器以管理员身份登录着本面板。「退出登录」会撤销这台设备的登录会话(30 天内的自动续期一并失效),需要重新输入账号密码;其他已登录的设备不受影响。', - exportDanger: '导出文件内含 accessToken / refreshToken / apiKey 等凭证与自定义提供商定义,可直接用于登录。请妥善保管,不要外传或上传到公共位置。', + timeouts: t('保存后立即生效,不用重启;超时按上游失败处理(计入请求日志的「错误」列,并按「请求重试」的设置决定是否重试)。'), + queue: t('等待期间请求日志的状态列会显示「排队中」阶段,详情弹窗的「内部重试」里能逐次看到等待时长;等待用尽后返回 HTTP 503(不是 401/429:既不会刷新凭证,也不会把账号标成限额)。'), + captchaPool: t('保存后对下一轮补货立即生效,不用重启。守卫跑在应用界面里:轻量模式关窗销毁界面期间无法铸造,走活动套餐通道的请求会以 503 落进请求日志(写明原因),重新打开界面即自动恢复。'), + retry: t('保存后立即生效,不用重启;次数用尽仍失败时,错误原样返回给客户端。'), + routing: t('保存后立即生效,不用重启:策略与粘性作用于**下一次**转发的选路,进行中的请求不受影响。'), + retryCodes: t('命中这些上游状态码的失败不在同一账号重发,直接换下一个账号继续试(换号占用「切换账号重试次数」,换满仍失败才把错误原样返回给客户端)。输入 100–599 的状态码后回车添加,点 × 或退格删除;默认 402(积分不足)。清空全部表示任何错误都照常重试。'), + sanitize: t('默认开启。命中明细会记进请求日志的「敏」标签(悬停可看命中了哪几条规则)。本项只改发给上游的副本,客户端看到的响应内容不变。'), + clineHeaders: t('值与默认值相同的行不占覆盖(存的是「改过的键」,不是全量配置);值留空保存表示这个头不发送,删除改过的行表示回落默认值。改完立即生效,不用重启。'), + cors: t('默认关闭。改动立即生效,不用重启;关闭期间的跨源请求会被预检拦下。'), + debug: t('开启后新发生的请求才会被记录(已经过去的请求补不回来),请求日志的「预览对话」也随之开始保存原始正文。上游报文统一存放在本地数据库里,只保留最近 500 条(超出后丢弃最旧的),条数见左侧「数据 → 数据存储」的「调试报文」。'), + promptMode: t('透传 = 不动客户端 system;替换 = 删掉客户端的 system / developer,换成网关提示词;追加 = 保留客户端内容,在最前面多插一条。'), + promptFile: t('UTF-8 文本文件路径。留空用内置默认;只在「替换 / 追加」下读取。'), + promptText: t('保存后以这份为准(优先于上面的文件);清空回到文件 / 内置默认。'), + promptGatewayText: t('三段必须各自成块(上游按结构校验,并成一段会被回 405),所以这里分开编辑。动态段里的运行值写成占位符,发请求时才替换:{cwd} 工作目录、{platform} 平台、{shell} shell、{os_version} 系统版本、{git} 是否 git 仓库、{provider} 提供方标识、{model} 模型名。清空某一段 = 那一段恢复官方原文。'), + prompt: t('保存后立即生效,不用重启(下一个请求就用新模式)。'), + promptProviders: t('不在这里列出的提供商都用上面的全局配置;「跟随默认」取消这一家的单独配置。带「网关自带」的家列在这里:那段文本是网关自己装上去的(可关、可改正文),与「模式」是两件事。'), + retention: t('保存后立即生效:改小保留天数会立刻删除超出的历史数据,且不可恢复。'), + storageFile: t('配置目录下的 agent2api.db(账号、日志、请求记录、调试报文与设置都在里面)。'), + storageSize: t('库主文件的大小(不含运行期间的 WAL 临时文件,退出时已自动并回)。'), + storage: t('数据统一保存在配置目录下的 agent2api.db;如需更换位置,请设置环境变量 AGENT2API_PROXY_HOME 后重启程序。'), + captcha: t('开启后,登录页在浏览器后台自动完成验证(对真人无感),而脚本每次尝试都要先算一道题 —— 暴力破解与抢注的成本显著上升。仅影响面板的登录 / 注册,与 API 客户端的 API Key 无关。'), + panelLogin: t('当前浏览器以管理员身份登录着本面板。「退出登录」会撤销这台设备的登录会话(30 天内的自动续期一并失效),需要重新输入账号密码;其他已登录的设备不受影响。'), + exportDanger: t('导出文件内含 accessToken / refreshToken / apiKey 等凭证与自定义提供商定义,可直接用于登录。请妥善保管,不要外传或上传到公共位置。'), + backupDanger: t('备份文件内含全部账号凭证、网关 API Key 与面板管理员凭据,可直接用于登录。请妥善保管,不要外传或上传到公共位置。'), + modelsDev: t('「模型管理」里每个能力的来源标记(上游 / models.dev / 已覆盖)读的就是这份数据;映射弹窗的思考档位下拉也按这里的数据只列该模型真实认识的档位。'), } as const /** 状态行(`.settings-state`)的派生文案:与旧实现的赋值逐字一致 */ export const STATES = { appLoading: '—', - appUnavailable: '主进程未返回启动设置,请更新桌面端后重试', - appTrayOn: '关闭窗口时程序不退出,转发继续在后台运行;退出请用托盘菜单', - appTrayOff: '关闭窗口即退出程序,后台转发随之中断', - appLightOn: '轻量模式已开启:关窗即销毁界面进程(释放约 200MB 内存),网关在后台继续;界面销毁期间 ZCode 活动套餐通道不可用,相关请求会在请求日志里注明原因', - appLightOff: '未开启轻量模式:关窗仅隐藏窗口,界面进程常驻内存,随时打开不等待', - unitsOn: '当前显示为「1.2亿 / 8400万」这类中文量级。', - unitsOff: '当前显示为「1.20M / 8.4k」这类英文缩写。', - debugUnavailable: '未能读取调试模式设置,请稍后重试', - debugOn: '正在保存上游原始报文:', - debugOff: '未开启,转发时不保存任何原始报文。', - sanitizeUnavailable: '未能读取指纹脱敏设置,请稍后重试', - sanitizeOn: '正在剥离出站请求里的审核指纹:表头键值整段删除,模板句最小改写。', - sanitizeOff: '未开启,客户端 system 模板会原样发往上游,可能被内容审核误拦(400)。', - corsUnavailable: '未能读取网关跨域访问设置,请稍后重试', - corsOn: '正在应答跨源请求:浏览器跨域请求可直连 /v1/*。', - corsOff: '未开启,浏览器跨域无法直连网关。', - promptUnavailable: '未能读取系统提示词设置,请稍后重试', - degradeUntilFallback: '次日 00:00', + appUnavailable: t('主进程未返回启动设置,请更新桌面端后重试'), + appTrayOn: t('关闭窗口时程序不退出,转发继续在后台运行;退出请用托盘菜单'), + appTrayOff: t('关闭窗口即退出程序,后台转发随之中断'), + appLightOn: t('轻量模式已开启:关窗即销毁界面进程(释放约 200MB 内存),网关在后台继续;界面销毁期间 ZCode 活动套餐通道不可用,相关请求会在请求日志里注明原因'), + appLightOff: t('未开启轻量模式:关窗仅隐藏窗口,界面进程常驻内存,随时打开不等待'), + unitsOn: t('当前按「万 / 亿」式本地量级词显示(如 1.2亿 / 8400万)。'), + unitsOff: t('当前按 k / M 缩写显示(如 1.20M / 8.4k)。'), + debugUnavailable: t('未能读取调试模式设置,请稍后重试'), + debugOn: t('正在保存上游原始报文:'), + debugOff: t('未开启,转发时不保存任何原始报文。'), + sanitizeUnavailable: t('未能读取指纹脱敏设置,请稍后重试'), + sanitizeOn: t('正在剥离出站请求里的审核指纹:表头键值整段删除,模板句最小改写。'), + sanitizeOff: t('未开启,客户端 system 模板会原样发往上游,可能被内容审核误拦(400)。'), + corsUnavailable: t('未能读取网关跨域访问设置,请稍后重试'), + corsOn: t('正在应答跨源请求:浏览器跨域请求可直连 /v1/*。'), + corsOff: t('未开启,浏览器跨域无法直连网关。'), + modelsDevUnavailable: t('未能读取 models.dev 元数据状态,请稍后重试'), + /** 数据来历:内嵌快照(发版时那份)/ 上次刷新结果 / 刚拉的 */ + modelsDevSourceBuiltin: t('随包内嵌的快照(发版时的那份)'), + modelsDevSourceCache: t('上次成功刷新的结果(存在本机数据库里)'), + modelsDevSourceNetwork: t('刚刚从 models.dev 拉到的最新数据'), + modelsDevEmpty: t('还没有装载任何数据。'), + promptUnavailable: t('未能读取系统提示词设置,请稍后重试'), + degradeUntilFallback: t('次日 00:00'), // ── 显示分类(本次新增:不来自静态骨架,是新写的文案)── - themeSystem: '当前跟随操作系统的深浅色设置,系统切换时界面会自动跟上。', - themeLight: '当前固定为浅色模式,不随系统变化。', - themeDark: '当前固定为深色模式,不随系统变化。', - zoomWeb: '网页端的界面缩放由浏览器自己控制(Ctrl + / Ctrl -,或浏览器菜单里的缩放),此项不可调。', - zoomDefault: '当前按 100% 显示(默认比例)。', - languageHint: '界面语言只保存在本机(localStorage)。切换后整页立即刷新,不影响账号、密钥与转发。', + themeSystem: t('当前跟随操作系统的深浅色设置,系统切换时界面会自动跟上。'), + themeLight: t('当前固定为浅色模式,不随系统变化。'), + themeDark: t('当前固定为深色模式,不随系统变化。'), + zoomWeb: t('网页端的界面缩放由浏览器自己控制(Ctrl + / Ctrl -,或浏览器菜单里的缩放),此项不可调。'), + zoomDefault: t('当前按 100% 显示(默认比例)。'), + languageHint: t('界面语言只保存在本机(localStorage)。切换后整页立即刷新,不影响账号、密钥与转发。'), } as const - -// ── 以下成员从 HEAD 恢复 ────────────────────────────── -// settings-state.ts(上一版拆分前的整体状态层)仍 import 它们;并行改动 -// 移走了定义但没改 import,构建因此断在这里。恢复定义而不是动那份 import, -// 等那边的迁移完成后可整体搬走。 - -export const ROUTE_STRATEGIES = [ - { - value: 'order', - label: t('顺序优先'), - tip: t('排第 1 的接走所有请求,直到它不能答(限流 / 故障 / 额度尽)才轮到下一位 —— 就是「从上往下」的现状行为。'), - }, - { - value: 'rotate', - label: t('负载均衡'), - tip: t('每条请求轮换到下一个可用账号;新会话交给当前最闲的那位。适合想把手里的号摊开用、不让某一个一直扛。'), - }, - { - value: 'provider', - label: t('家内轮询'), - tip: t('家之间仍按优先级,只有同一家内部轮流用各账号 —— 想优先用某几家、又不愿把某一家的某个账号焊死时用它。'), - }, -] as const - -/** 会话粘性档位:同一会话的后续请求是否尽量跟住同一个账号(会话 = 模型 + 首条用户消息) */ - -export const ROUTE_STICKY_OPTIONS = [ - { - value: 'auto', - label: t('自动'), - tip: t('同一会话在 5 分钟内尽量跟住同一个账号;停了 5 分钟再发就算新会话。多数场景用它 —— 多轮对话少换号,也不至于把账号焊死。'), - }, - { - value: 'session', - label: t('会话内'), - tip: t('同一会话在 6 小时内跟住同一个账号;适合一坐几个小时的长会话,上游的上下文缓存能吃到更多。'), - }, - { - value: 'turn', - label: t('每轮'), - tip: t('每条请求都重新按策略选路 —— 行为与「关闭」一致,仅保留会话识别的记录。'), - }, - { - value: 'off', - label: t('关闭'), - tip: t('不做会话识别,每条请求都重新按策略选路。'), - }, -] as const - -/** 路由档位的取值(SegmentedControl 的泛型参数用它,视图里不必再写字面量联合) */ - -export const CAPTCHA_POOL_FIELDS: NumberField[] = [ - { - key: 'zcodeCaptchaPoolTarget', - id: 'settings-captcha-pool-target', - label: t('库存目标'), - unit: t('个'), - min: 1, - max: 10, - hint: t('ZCode 活动套餐通道每条请求都要消耗一个当次铸造的人机验证令牌(一次性,2 分钟过期),库存低于该值时界面自动补铸到它。默认 3 个。调大能吸收突发并发,但用不掉的令牌 2 分钟就过期作废,烧的是上游风控配额。可填 1–10。'), - }, - { - key: 'zcodeCaptchaPoolPollMs', - id: 'settings-captcha-pool-poll-ms', - label: t('轮询间隔'), - unit: t('毫秒'), - min: 1000, - max: 30000, - hint: t('铸造守卫每隔多久看一次库存(毫秒)。只影响发现缺货的反应速度 —— 库存够用时轮询不会铸造任何令牌。默认 2500 毫秒,可填 1000–30000。'), - }, - { - key: 'zcodeCaptchaPoolMaxPerRound', - id: 'settings-captcha-pool-max-per-round', - label: t('单轮铸造上限'), - unit: t('个'), - min: 1, - max: 5, - hint: t('发现缺货时一轮最多铸几个(连铸之间固定隔 500 毫秒)。默认 1 个:SDK 同一实例连铸容易互相干扰。调大补货更快,但单轮连铸越多越容易触发上游风控。可填 1–5。'), - }, -] - -/** 「指定错误码直接换号」:键名、状态码范围与名单上限与后端 retry_api.rs 逐字同源 */ - -export type ModelsDevState = { - /** 联网刷新开关(关闭后已装载的数据继续用,见后端 `KEY_MODELS_DEV_ENABLED`) */ - modelsDevEnabled?: boolean - /** 这份索引的来历:`builtin`(内嵌快照)/ `cache`(上次刷新结果)/ `network`(刚拉的) */ - source?: string - /** 这份数据的生成时刻(毫秒;0 = 未知) */ - updatedAt?: number - /** 收录的模型条数 */ - count?: number -} - -/** 立即刷新的一行结果(字段与各家目录刷新的结果行同形,见后端 `api::model_meta`)。 */ diff --git a/desktop-tauri/ui-islands/src/islands/settings-page.tsx b/desktop-tauri/ui-islands/src/islands/settings-page.tsx index 62184e1a..5fcdab09 100644 --- a/desktop-tauri/ui-islands/src/islands/settings-page.tsx +++ b/desktop-tauri/ui-islands/src/islands/settings-page.tsx @@ -22,11 +22,15 @@ import { } from '@ui' import { CATEGORIES, + CAPTCHA_POOL_FIELDS, NOTES, PROMPT_MODES, QUEUE_FIELDS, RETENTION_FIELDS, RETRY_FIELDS, + ROUTE_PROTECTION_SWITCHES, + ROUTE_STICKY_OPTIONS, + ROUTE_STRATEGIES, STATES, THEME_EVENT, THEME_MODES, @@ -36,12 +40,15 @@ import { ZOOM_PERCENTS, formatBytes, formatCount, + modelsDevStateText, openExternal, readThemeMode, readZoomPercent, shared, type GatewayBlocks, type NumberField, + type RouteStickyValue, + type RouteStrategyValue, type ThemeMode, } from './settings-model' import { @@ -50,18 +57,23 @@ import { applyUnits, cancelLanRegister, clearDegrade, + confirmDbRestore, dropLastRetryCode, exportAccounts, + exportDatabase, importAccounts, load, panelLogout, refreshDebug, + refreshCaptchaPool, refreshClineHeaders, refreshCors, + refreshModelsDev, refreshPrompt, refreshQueue, refreshRetention, refreshRetry, + refreshRouting, refreshSanitize, refreshStorage, refreshTimeouts, @@ -75,13 +87,16 @@ import { renderSanitize, renderSettings, renderStorage, + resolveDbBackupConfirm, resolveLanConfirm, resolveRetentionConfirm, restoreCategory, saveCaptcha, + saveCaptchaPoolField, saveClineHeaders, saveCors, saveDebug, + saveModelsDev, savePromptFile, savePromptMode, saveProviderGatewayPrompt, @@ -90,12 +105,14 @@ import { saveQueueField, saveRetentionField, saveRetryField, + saveRoutingField, saveSanitize, saveTimeoutField, saveToggle, selectCategory, showCategory, submitLanRegister, + toggleDbIncludeLogs, toggleLan, toggleLanPanel, useSettings, @@ -108,6 +125,7 @@ import { type PromptState, type ProviderPromptOption, type ProviderPromptState, + type RoutingState, type SettingsSnapshot, type StorageState, } from './settings-state' @@ -204,6 +222,45 @@ function PanelHead({ title, tip, badge, actions }: PanelHeadProps) { ) } +/** + * 可折叠面板:整块(标题栏 + 正文)收进 `
`,默认折叠。 + * + * ── 为什么用原生 details/summary ───────────────────────────── + * 折叠是纯展示行为,原生元素自带键盘可达性(Enter/Space 切换)、 + * 无脚本时也能用,且与请求日志页既有的 `.cv-details` 同一手法。 + * 不引状态:`
` 自己记开合,React 只负责画一次。 + * + * ── 折叠状态跨分类切换会保留 ───────────────────────────────── + * 各分类的 pane 是常驻挂载、靠 CSS 显隐(见 `paneClass`), + * 所以 `
` 的开合态天然跟着组件存活 —— 切走再切回来还是 + * 用户上次的选择,不需要额外持久化。 + */ +function CollapsiblePanel({ title, tip, badge, actions, children }: PanelHeadProps & { children: React.ReactNode }) { + // `summary` 里的一切点击都会切换开合(原生行为),而标题栏里有两类**独立 + // 动作**的控件:问号提示(点开 tooltip)与右侧操作按钮(如「刷新」)。 + // 点它们不该顺手把面板折起来 —— 尤其是「展开 → 点问号看说明」这个动作, + // 正文会在眼前消失。 + // + // 用 `preventDefault` 而不是 `stopPropagation`:开合是 click 的**默认动作** + // (由 `
` 在事件传播结束后执行),`stopPropagation` 拦不住它。 + function keepOpen(event: React.MouseEvent): void { + const target = event.target as HTMLElement + if (target.closest('.tip-q, .head-actions')) event.preventDefault() + } + return ( +
+ + +

{title}

+ {tip ? : null} + {badge} + {actions ?
{actions}
: null} +
+ {children} +
+ ) +} + type SwitchRowProps = { id: string label: string @@ -284,14 +341,14 @@ function NumberRow({ field, value, disabled, onCommit }: NumberRowProps) { /** 数字面板的徽章:首屏「检测中…」、读到「已生效」、读不到「不可用」 */ function numericBadge(state: NumericState): React.ReactNode { - if (state.status === 'ready') return 已生效 - if (state.status === 'unavailable') return 不可用 - return 检测中… + if (state.status === 'ready') return {t('已生效')} + if (state.status === 'unavailable') return {t('不可用')} + return {t('检测中…')} } /** 刷新按钮(无修饰的 button → Button 的 outline 档,与静态骨架的观感一致) */ function RefreshButton({ id, onClick }: { id: string; onClick: () => void }) { - return + return } /* ─── 通用分类 ─────────────────────────────── */ @@ -299,10 +356,62 @@ function RefreshButton({ id, onClick }: { id: string; onClick: () => void }) { /** 「局域网访问」面板的状态行:开着时给出局域网设备该填的 API 地址 */ function lanStateText(snap: SettingsSnapshot): string { const { lanAccess, lanPanel, lanIp, port } = snap.app - if (!lanAccess) return '未开启:网关只监听 127.0.0.1,仅本机可以访问。' - const base = `http://${lanIp || '<本机IP>'}${port ? `:${port}` : ''}` - const panel = lanPanel ? ';网页管理面板已一并开放(浏览器打开同一地址)' : '' - return `已开启:其他设备把 API 地址指向 ${base}/v1${panel}。` + if (!lanAccess) return t('未开启:网关只监听 127.0.0.1,仅本机可以访问。') + const base = `http://${lanIp || t('<本机IP>')}${port ? `:${port}` : ''}` + const panel = lanPanel ? t(';网页管理面板已一并开放(浏览器打开同一地址)') : '' + return t('已开启:其他设备把 API 地址指向 {url}{panel}。', { url: `${base}/v1`, panel }) +} + +/** + * 「界面语言」一行:下拉选 auto 或某个具体语言,选中即整页刷新。 + * + * ── 为什么不进 settings-state 的后端模型 ────────────────────── + * 语言只改本机界面文案:不碰转发、不碰账号,跟「主题 / 缩放 / 计量单位」同属纯前端 + * 偏好。所以它只读写 localStorage(键 workbuddy-desktop-locale,见 ui/i18n.js), + * 与后端 desktop-settings.json 无关,也正因如此这里不需要受控 state —— 切换会 + * location.reload(),重载后本行自然按新值重新渲染。 + * + * ── 选项为什么是双语的 ────────────────────────────────────── + * 'auto' 的标签是中文键(跟随系统),走 t();其余语言名称分两半:label 是**各语言 + * 自己的写法**(English / 日本語 / 한국어 …)—— 选之前就该看得懂,不翻译;nameKey + * 是这门外语的中文名,用 t() 译成当前界面语言,拼成「English(英语)」式双语选项 + * (两者相同则只给一次)。触发器(收起态)只显示 label,避免长名字在窄控件里截断。 + */ +function LanguageRow() { + const api = window.wbI18n + const value = api?.rawLocale?.() ?? 'auto' + const locales = api?.LOCALES ?? [] + /** 选项的双语名:本地写法 + 当前界面语言的写法(相同时只给一次) */ + const nameOf = (item: { label: string; nameKey: string }): string => { + const translated = t(item.nameKey) + return translated && translated !== item.label ? `${item.label}(${translated})` : item.label + } + const labelOf = (code: string): string => ( + code === 'auto' ? t('跟随系统') : (locales.find(item => item.code === code)?.label ?? code) + ) + + return ( +
+
+ + + {/* 与「界面缩放」同一个 Select 形态:展示文案显式给 SelectValue,不依赖 value 自动显示。 + 组件的 onValueChange 可能给 null(被清空),这里只在拿到非空值时切换 */} + + +
+
+ ) } function GeneralPane({ snap }: { snap: SettingsSnapshot }) { @@ -319,15 +428,23 @@ function GeneralPane({ snap }: { snap: SettingsSnapshot }) { return ( <> +
+ +
+ +
{STATES.languageHint}
+
+
+
已应用 + ? {t('已应用')} : app.status === 'unavailable' - ? 不可用 - : 检测中…} + ? {t('不可用')} + : {t('检测中…')}} />
@@ -335,7 +452,7 @@ function GeneralPane({ snap }: { snap: SettingsSnapshot }) { 保存成功即回到「已应用」,不必让用户重开程序 */} void saveToggle('tray', next)} @@ -343,7 +460,7 @@ function GeneralPane({ snap }: { snap: SettingsSnapshot }) { {/* 轻量模式依赖「关闭到托盘」:关掉托盘时该开关无意义,置灰并提示 */} void saveToggle('autostart', next)} @@ -363,21 +480,21 @@ function GeneralPane({ snap }: { snap: SettingsSnapshot }) { {!snap.panelLogin && (
- +
{/* 开 / 关都不直接落盘:走确认框(→ 需要时注册管理员 → 写设置并重启), 流程与文案在 settings-state 的 toggleLan / resolveLanConfirm */} - +
+ {/* 标签不再写死「中文」:开启是「万 / 亿」式本地量级词,繁体 / 日文 / 韩文各自 + 有对应的量级词(萬 / 億、만 / 억),译文里这句话描述的正是那些语言用户看到的东西 */} @@ -418,9 +537,9 @@ function themeStateText(mode: ThemeMode): string { } /** - * 显示分类:显示模式 / 界面缩放 / 语言。 + * 显示分类:显示模式 / 界面缩放。 * - * 三项都是**纯前端偏好** —— 与后端配置无关,所以不参与 settings-state 的 load + * 两项都是**纯前端偏好** —— 与后端配置无关,所以不参与 settings-state 的 load * (那边一次并行取全部后端设置),这里自己持两个受控值就够了。 * * 主题与缩放的**唯一应用入口都在 app.js**(见 settings-model 的显示偏好一节): @@ -450,16 +569,16 @@ function DisplayPane() { } }, []) - const zoomLabel = zoom === 100 ? '100%(默认)' : `${zoom}%` + const zoomLabel = zoom === 100 ? t('100%(默认)') : `${zoom}%` return ( <>
- +
- aria-label='显示模式' + aria-label={t('显示模式')} options={THEME_MODES} value={theme} onValueChange={next => shared().wbApp?.applyTheme?.(next)} @@ -470,11 +589,11 @@ function DisplayPane() {
- +
- + {/* 档位是 80%–130% 的 11 个定值,用下拉而不是滑块:每一档都要能精确 复述(用户问「我现在多少」时答案是个整数),且组件库目前没有 Slider。 @@ -487,87 +606,33 @@ function DisplayPane() { id='settings-zoom' className='w-[140px]' disabled={isWeb} - aria-label='界面缩放比例' + aria-label={t('界面缩放比例')} > {zoomLabel} {ZOOM_PERCENTS.map(percent => ( - {percent === 100 ? '100%(默认)' : `${percent}%`} + {percent === 100 ? t('100%(默认)') : `${percent}%`} ))}
- 放大或缩小整个界面(文字与控件一起变),效果与浏览器 Ctrl +/- 相同: - 共 11 档,立即生效并记住。 + {t('放大或缩小整个界面(文字与控件一起变),效果与浏览器 Ctrl +/- 相同:共 11 档,立即生效并记住。')}
- {isWeb ? STATES.zoomWeb : zoom === 100 ? STATES.zoomDefault : `当前按 ${zoom}% 显示。`} + {isWeb ? STATES.zoomWeb : zoom === 100 ? STATES.zoomDefault : t('当前按 {n}% 显示。', { n: zoom })}
- -
- -
- -
{STATES.languageHint}
-
-
) } -/** - * 「界面语言」一行:下拉选 auto 或某个具体语言,选中即整页刷新。 - * - * ── 为什么不进 settings-state 的后端模型 ────────────────────── - * 语言只改本机界面文案:不碰转发、不碰账号,跟「主题 / 缩放 / 计量单位」同属纯前端 - * 偏好。所以它只读写 localStorage(键 workbuddy-desktop-locale,见 ui/i18n.js), - * 与后端 desktop-settings.json 无关,也正因如此这里不需要受控 state —— 切换会 - * location.reload(),重载后本行自然按新值重新渲染。 - * - * ── 选项文案为什么不都走 t() ───────────────────────────────── - * 'auto' 的标签是中文键(跟随系统),要翻译;其余语言的 label 是**各语言自己的写法** - * (English / 日本語 / 한국어 …),选之前就该看得懂,所以照搬 wbI18n.LOCALES,不翻译。 - */ -function LanguageRow() { - const api = window.wbI18n - const value = api?.rawLocale?.() ?? 'auto' - const locales = api?.LOCALES ?? [] - const labelOf = (code: string): string => ( - code === 'auto' ? t('跟随系统') : (locales.find(item => item.code === code)?.label ?? code) - ) - - return ( -
-
- - - {/* 与「界面缩放」同一个 Select 形态:展示文案显式给 SelectValue,不依赖 value 自动显示。 - 组件的 onValueChange 可能给 null(被清空),这里只在拿到非空值时切换 */} - - -
-
- ) -} - /* ─── 网关分类 ─────────────────────────────── */ /** 「指定错误码直接换号」的标签输入(GitHub Topics 同款:徽章 + 行内输入框) */ @@ -583,7 +648,7 @@ function RetryCodesField({ codes, status, busy }: { return (
- +
{/* 点框体空白处 = 聚焦输入框(整框是一个输入控件的观感,旧实现同) */}
{ event.stopPropagation(); void removeRetryCode(code) }} > ✕ @@ -615,7 +680,7 @@ function RetryCodesField({ codes, status, busy }: { // 框的描边由外层 .tag-input 出,这里把组件库 Input 的边框 / 底色 / 内边距 // 用工具类压平(.tag-input-field 的老规则是非分层的,压不过工具类) className='tag-input-field h-auto border-0 bg-transparent px-0 shadow-none focus:shadow-none' - placeholder={locked ? '—' : '输入状态码,回车添加'} + placeholder={locked ? '—' : t('输入状态码,回车添加')} inputMode='numeric' autoComplete='off' value={text} @@ -655,12 +720,12 @@ function PromptFileRow({ prompt, locked, busy }: { return (
- + setDraft(event.target.value)} @@ -681,11 +746,14 @@ function promptStateText(prompt: PromptState): string { const source = promptSourceText(prompt.source) const parts: string[] = [] if (prompt.mode === 'passthrough') { - parts.push('客户端 system 原样出站(只靠指纹脱敏改写模板句)。') + parts.push(t('客户端 system 原样出站(只靠指纹脱敏改写模板句)。')) } else { parts.push( - `${prompt.mode === 'custom' ? '替换' : '追加'}生效:上游收到的 system 来自${source}` - + `${prompt.lines ? `(${prompt.lines} 行)` : ''}。`, + t('{mode}生效:上游收到的 system 来自{source}{lines}。', { + mode: prompt.mode === 'custom' ? t('替换') : t('追加'), + source, + lines: prompt.lines ? t('({n} 行)', { n: prompt.lines }) : '', + }), ) } if (prompt.fileError) parts.push(`⚠️ ${prompt.fileError}`) @@ -694,17 +762,17 @@ function promptStateText(prompt: PromptState): string { /** 正文来源的中文说法(三处状态行共用;'' = 没有正文可讲) */ function promptSourceText(source: string): string { - if (source === 'inline') return '界面里编辑的正文' - if (source === 'file') return '提示词文件' - if (source === 'builtin') return '内置默认提示词' + if (source === 'inline') return t('界面里编辑的正文') + if (source === 'file') return t('提示词文件') + if (source === 'builtin') return t('内置默认提示词') return '' } /** 降级行的说明:只在真的处于降级期时出现(平时它是一行与用户无关的状态噪音) */ function degradeHint(prompt: PromptState): string { - return '已自动切换到最小中性提示词(撞了上游内容拦截,多半是 system 指纹误报),' - + `到 ${prompt.degradeUntilText || STATES.degradeUntilFallback} 自动解除。` - + '期间本模式自己的提示词不会发出;把提示词改好后可以立即解除。' + return t('已自动改用最小中性提示词(撞了上游内容拦截,多半是 system 指纹误报),到 {until} 自动解除。', { + until: prompt.degradeUntilText || STATES.degradeUntilFallback, + }) } /** @@ -733,8 +801,8 @@ function ProviderFileRow({ item, label, locked, busy }: { setDraft(event.target.value)} @@ -750,10 +818,16 @@ function ProviderFileRow({ item, label, locked, busy }: { function providerStateText(item: ProviderPromptState, configured: boolean): string { // 没单独配过的家(只在「有网关自带提示词」时才会被列出来)走全局那份 —— // 不说这一句的话,用户会以为这一行显示的就是「这家的设置」 - if (!configured) return `未单独配置:模式、提示词文件与正文都跟随上面的全局配置(当前「${PROMPT_MODES.find(option => option.value === item.mode)?.toastLabel ?? item.mode}」)。` - if (item.mode === 'passthrough') return '客户端 system 原样出站。' - const head = `${item.mode === 'custom' ? '替换' : '追加'}生效:上游收到的 system 来自${promptSourceText(item.source)}` - + `${item.lines ? `(${item.lines} 行)` : ''}。` + if (!configured) { + const mode = PROMPT_MODES.find(option => option.value === item.mode)?.toastLabel ?? item.mode + return t('未单独配置:模式、提示词文件与正文都跟随上面的全局配置(当前「{mode}」)。', { mode }) + } + if (item.mode === 'passthrough') return t('客户端 system 原样出站。') + const head = t('{mode}生效:上游收到的 system 来自{source}{lines}。', { + mode: item.mode === 'custom' ? t('替换') : t('追加'), + source: promptSourceText(item.source), + lines: item.lines ? t('({n} 行)', { n: item.lines }) : '', + }) return item.fileError ? `${head} ⚠️ ${item.fileError}` : head } @@ -775,15 +849,15 @@ function ProviderGatewayRow({ item, option, over, locked, busy }: { }) { const on = item.gateway const chars = option.gatewayChars - const size = chars ? `约 ${chars.toLocaleString('zh-CN')} 字符` : '一段内置装配' + const size = chars ? t('约 {n} 字符', { n: chars.toLocaleString('zh-CN') }) : t('一段内置装配') const edited = gatewayEditedText(over) return (
- + void saveProviderGatewayPrompt(item.id, next)} @@ -793,8 +867,8 @@ function ProviderGatewayRow({ item, option, over, locked, busy }: {
- {on ? option.gatewayNote : `已关闭。${option.gatewayNote}`} - {edited ? ` 正文已改:${edited}(其余段用官方原文)。` : ''} + {on ? option.gatewayNote : t('已关闭。{note}', { note: option.gatewayNote })} + {edited ? t(' 正文已改:{edited}(其余段用官方原文)。', { edited }) : ''}
) @@ -879,7 +953,7 @@ function ProviderPromptRows({ prompt, locked, busy }: { id={`settings-prompt-mode-${item.id}`} className='w-[240px]' disabled={locked || busy} - aria-label={`${label} 的提示词模式`} + aria-label={t('{label} 的提示词模式', { label })} > {modeLabel} @@ -899,7 +973,7 @@ function ProviderPromptRows({ prompt, locked, busy }: { disabled={locked || busy} onClick={() => void removeProviderPrompt(item.id)} > - 跟随默认 + {t('跟随默认')} ) : null}
@@ -921,7 +995,7 @@ function ProviderPromptRows({ prompt, locked, busy }: { })}
- + {/* 组件的 Select 不支持占位(必须有一个 value),所以第一个选项就是 「选择要配置的提供商」这个动作本身;选完立刻重置回它。 @@ -941,10 +1015,10 @@ function ProviderPromptRows({ prompt, locked, busy }: { id='settings-prompt-provider-add' className='w-[240px]' disabled={locked || busy || candidates.length === 0} - aria-label='添加要单独配置的提供商' + aria-label={t('添加要单独配置的提供商')} > - {pending ? labelOf(pending) : (candidates.length ? '添加提供商…' : '全部已配置')} + {pending ? labelOf(pending) : (candidates.length ? t('添加提供商…') : t('全部已配置'))} @@ -969,26 +1043,29 @@ function PromptPanel({ snap }: { snap: SettingsSnapshot }) { return (
{prompt.mode === 'passthrough' ? '透传' : '已接管'} + ? {prompt.mode === 'passthrough' ? t('透传') : t('已接管')} : prompt.status === 'unavailable' - ? 不可用 - : 检测中…} + ? {t('不可用')} + : {t('检测中…')}} actions={ void refreshPrompt()} />} />
+ {/* 状态行放在最前面:这一节要回答的第一个问题是「现在到底走哪条路」, + 放在末尾时用户得先读完所有配置项才看得到它(旧实现如此)。 */} +
{promptStateText(prompt)}
{/* 两个分组条把「默认」与「某家的例外」分开:上面那几行是所有未单独配置的 家共用的默认值,下面那张表是逐家的例外 —— 不分开时它们是一串同构的行, 用户读不出哪几行管全部、哪几行只管一家(见 page-settings.css 的 .prompt-group)。 */}
- 全局配置所有未单独配置的提供商都用这一份 + {t('全局配置')}{t('所有未单独配置的提供商都用这一份')}
- + {/* 旧实现是原生 - + + @@ -1826,10 +2150,10 @@ function LanDialog({ confirm, register }: { confirm: LanConfirm; register: LanRe
@@ -1844,10 +2168,10 @@ function LanDialog({ confirm, register }: { confirm: LanConfirm; register: LanRe
@@ -1902,6 +2226,9 @@ function SettingsPage() {
+
+ +
@@ -1928,6 +2255,7 @@ function SettingsPage() {
+
) diff --git a/desktop-tauri/ui/islands/ui.js b/desktop-tauri/ui/islands/ui.js index d62d31ea..8e9d866e 100644 --- a/desktop-tauri/ui/islands/ui.js +++ b/desktop-tauri/ui/islands/ui.js @@ -1,18 +1,18 @@ -var Ite=Object.defineProperty;var Pte=(fi,dl,Zl)=>dl in fi?Ite(fi,dl,{enumerable:!0,configurable:!0,writable:!0,value:Zl}):fi[dl]=Zl;var tn=(fi,dl,Zl)=>Pte(fi,typeof dl!="symbol"?dl+"":dl,Zl);(function(){"use strict";function fi(e,t){for(var r=0;ro[c]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}function dl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Zl={exports:{}},Ad={};var NC;function O3(){if(NC)return Ad;NC=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function r(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 Ad.Fragment=t,Ad.jsx=r,Ad.jsxs=r,Ad}var CC;function M3(){return CC||(CC=1,Zl.exports=O3()),Zl.exports}var s=M3(),Xb={exports:{}},ot={};var kC;function D3(){if(kC)return ot;kC=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),r=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(P){return P===null||typeof P!="object"?null:(P=w&&P[w]||P["@@iterator"],typeof P=="function"?P:null)}var N={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,E={};function R(P,V,J){this.props=P,this.context=V,this.refs=E,this.updater=J||N}R.prototype.isReactComponent={},R.prototype.setState=function(P,V){if(typeof P!="object"&&typeof P!="function"&&P!=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,P,V,"setState")},R.prototype.forceUpdate=function(P){this.updater.enqueueForceUpdate(this,P,"forceUpdate")};function k(){}k.prototype=R.prototype;function A(P,V,J){this.props=P,this.context=V,this.refs=E,this.updater=J||N}var D=A.prototype=new k;D.constructor=A,C(D,R.prototype),D.isPureReactComponent=!0;var I=Array.isArray;function M(){}var O={H:null,A:null,T:null,S:null},_=Object.prototype.hasOwnProperty;function L(P,V,J){var ie=J.ref;return{$$typeof:e,type:P,key:V,ref:ie!==void 0?ie:null,props:J}}function z(P,V){return L(P.type,V,P.props)}function U(P){return typeof P=="object"&&P!==null&&P.$$typeof===e}function B(P){var V={"=":"=0",":":"=2"};return"$"+P.replace(/[=:]/g,function(J){return V[J]})}var Q=/\/+/g;function W(P,V){return typeof P=="object"&&P!==null&&P.key!=null?B(""+P.key):V.toString(36)}function Z(P){switch(P.status){case"fulfilled":return P.value;case"rejected":throw P.reason;default:switch(typeof P.status=="string"?P.then(M,M):(P.status="pending",P.then(function(V){P.status==="pending"&&(P.status="fulfilled",P.value=V)},function(V){P.status==="pending"&&(P.status="rejected",P.reason=V)})),P.status){case"fulfilled":return P.value;case"rejected":throw P.reason}}throw P}function Y(P,V,J,ie,me){var he=typeof P;(he==="undefined"||he==="boolean")&&(P=null);var ae=!1;if(P===null)ae=!0;else switch(he){case"bigint":case"string":case"number":ae=!0;break;case"object":switch(P.$$typeof){case e:case t:ae=!0;break;case y:return ae=P._init,Y(ae(P._payload),V,J,ie,me)}}if(ae)return me=me(P),ae=ie===""?"."+W(P,0):ie,I(me)?(J="",ae!=null&&(J=ae.replace(Q,"$&/")+"/"),Y(me,V,J,"",function(de){return de})):me!=null&&(U(me)&&(me=z(me,J+(me.key==null||P&&P.key===me.key?"":(""+me.key).replace(Q,"$&/")+"/")+ae)),V.push(me)),1;ae=0;var oe=ie===""?".":ie+":";if(I(P))for(var ee=0;ee"u"?!1:e instanceof ShadowRoot||e instanceof bn(e).ShadowRoot}function Md(e){const{overflow:t,overflowX:r,overflowY:o,display:c}=gr(e);return/auto|scroll|overlay|hidden|clip/.test(t+o+r)&&c!=="inline"&&c!=="contents"}function P3(e){return/^(table|td|th)$/.test(_s(e))}function mm(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const _3=/transform|translate|scale|rotate|perspective|filter/,L3=/paint|layout|strict|content/,pi=e=>!!e&&e!=="none";let Zb;function Wb(e){const t=Ct(e)?gr(e):e;return pi(t.transform)||pi(t.translate)||pi(t.scale)||pi(t.rotate)||pi(t.perspective)||!Jb()&&(pi(t.backdropFilter)||pi(t.filter))||_3.test(t.willChange||"")||L3.test(t.contain||"")}function z3(e){let t=Jl(e);for(;an(t)&&!Wl(t);){if(Wb(t))return t;if(mm(t))return null;t=Jl(t)}return null}function Jb(){return Zb==null&&(Zb=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),Zb}function Wl(e){return/^(html|body|#document)$/.test(_s(e))}function gr(e){return bn(e).getComputedStyle(e)}function hm(e){return Ct(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function Jl(e){if(_s(e)==="html")return e;const t=e.assignedSlot||e.parentNode||_c(e)&&e.host||fl(e);return _c(t)?t.host:t}function EC(e){const t=Jl(e);return Wl(t)?(e.ownerDocument||e).body:an(t)&&Md(t)?t:EC(t)}function Lc(e,t,r){var o;t===void 0&&(t=[]),r===void 0&&(r=!0);const c=EC(e),d=c===((o=e.ownerDocument)==null?void 0:o.body),f=bn(c);if(d){const p=ev(f);return t.concat(f,f.visualViewport||[],Md(c)?c:[],p&&r?Lc(p):[])}else return t.concat(c,Lc(c,[],r))}function ev(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}const tv={...I3},RC={};function Ts(e,t){const r=x.useRef(RC);return r.current===RC&&(r.current=e(t)),r}const nv=tv.useInsertionEffect,B3=nv&&nv!==tv.useLayoutEffect?nv:e=>e();function Ie(e){const t=Ts(H3).current;return t.next=e,B3(t.effect),t.trampoline}function H3(){const e={next:void 0,callback:U3,trampoline:(...t)=>e.callback?.(...t),effect:()=>{e.callback=e.next}};return e}function U3(){}const De=typeof document<"u"?x.useLayoutEffect:()=>{};function sv(e,t){if(e&&!t)return e;if(!e&&t)return t;if(e||t)return{...e,...t}}const rv={};function Gr(e,t,r,o,c){if(!r&&!o&&!c&&!e)return gm(t);let d=gm(e);return t&&(d=Dd(d,t)),r&&(d=Dd(d,r)),o&&(d=Dd(d,o)),c&&(d=Dd(d,c)),d}function V3(e){if(e.length===0)return rv;if(e.length===1)return gm(e[0]);let t=gm(e[0]);for(let r=1;r=65&&c<=90&&(typeof t=="function"||typeof t>"u")}function av(e){return typeof e=="function"}function OC(e,t){return av(e)?e(t):e??rv}function q3(e,t){return t?e?(...r)=>{const o=r[0];if(IC(o)){const d=o;xm(d);const f=t(...r);return d.baseUIHandlerPrevented||e?.(...r),f}const c=t(...r);return e?.(...r),c}:MC(t):e}function MC(e){return e&&((...t)=>{const r=t[0];return IC(r)&&xm(r),e(...t)})}function xm(e){return e.preventBaseUIHandler=()=>{e.baseUIHandlerPrevented=!0},e}function DC(e,t){return t?e?t+" "+e:t:e}function IC(e){return e!=null&&typeof e=="object"&&"nativeEvent"in e}function G3(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 nn=G3("https://base-ui.com/production-error","Base UI"),PC=x.createContext(void 0);function _C(e=!1){const t=x.useContext(PC);if(t===void 0&&!e)throw new Error(nn(16));return t}function K3(e){const{focusableWhenDisabled:t,disabled:r,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){r&&t&&y.key!=="Tab"&&y.preventDefault()}};return o||(v.tabIndex=c,!d&&r&&(v.tabIndex=t?c:-1)),(d&&(t||f)||!d&&r)&&(v["aria-disabled"]=r),d&&(!t||p)&&(v.disabled=r),v},[o,r,t,f,p,d,c])}}function zt(e){return e?.ownerDocument||document}function zc(e,t,{detail:r=0}={}){e.dispatchEvent(new(bn(e)).PointerEvent("click",{bubbles:!0,cancelable:!0,composed:!0,detail:r,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey,metaKey:t.metaKey}))}function Kr(e={}){const{disabled:t=!1,focusableWhenDisabled:r,tabIndex:o=0,native:c=!0,composite:d}=e,f=x.useRef(null),p=_C(!0),g=d??p!==void 0,{props:v}=K3({focusableWhenDisabled:r,disabled:t,composite:g,tabIndex:o,isNativeButton:c}),y=x.useCallback(()=>{const w=f.current;lv(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:C,onKeyDown:E,onPointerDown:R,...k}=w;return Gr({onClick(A){if(t){A.preventDefault();return}S?.(A)},onMouseDown(A){t||N?.(A)},onKeyDown(A){if(t||(xm(A),E?.(A),A.baseUIHandlerPrevented))return;const D=A.target===A.currentTarget,I=A.currentTarget,M=lv(I),O=!c&&Y3(I),_=D&&(c?M:!O),L=A.key==="Enter",z=A.key===" ",U=I.getAttribute("role"),B=U?.startsWith("menuitem")||U==="option"||U==="gridcell";if(D&&g&&z){if(A.defaultPrevented&&B)return;A.preventDefault(),(!c||M)&&(A.preventBaseUIHandler(),zc(I,A));return}if(!_||c||!z&&!L){D&&O&&z&&A.preventDefault();return}A.defaultPrevented||(A.preventDefault(),L&&(A.preventBaseUIHandler(),zc(I,A)))},onKeyUp(A){if(!t){if(xm(A),C?.(A),A.target===A.currentTarget&&c&&g&&lv(A.currentTarget)&&A.key===" "){A.preventDefault();return}A.baseUIHandlerPrevented||A.target===A.currentTarget&&!c&&!g&&!A.defaultPrevented&&A.key===" "&&(A.preventBaseUIHandler(),zc(A.currentTarget,A))}},onPointerDown(A){if(t){A.preventDefault();return}R?.(A)}},c?{type:"button"}:{role:"button"},v,k)},[t,v,g,c]),j=Ie(w=>{f.current=w,y()});return{getButtonProps:b,buttonRef:j}}function lv(e){return an(e)&&e.tagName==="BUTTON"}function Y3(e){return an(e)&&e.tagName==="A"&&!!e.href}function Yr(e,t,r,o){const c=Ts(LC).current;return Q3(c,e,t,r,o)&&zC(c,[e,t,r,o]),c.callback}function X3(e){const t=Ts(LC).current;return Z3(t,e)&&zC(t,e),t.callback}function LC(){return{callback:null,cleanup:null,refs:[]}}function Q3(e,t,r,o,c){return e.refs[0]!==t||e.refs[1]!==r||e.refs[2]!==o||e.refs[3]!==c}function Z3(e,t){return e.refs.length!==t.length||e.refs.some((r,o)=>r!==t[o])}function zC(e,t){if(e.refs=t,t.every(r=>r==null)){e.callback=null;return}e.callback=r=>{if(e.cleanup&&(e.cleanup(),e.cleanup=null),r!=null){const o=Array(t.length).fill(null);for(let c=0;c{for(let c=0;c=e}function BC(e){if(!x.isValidElement(e))return null;const t=e,r=t.props;return(ov(19)?r?.ref:t.ref)??null}function Bt(){}const Er=Object.freeze([]),ln=Object.freeze({});function J3(e,t){const r={};for(const o in e){const c=e[o];if(t?.hasOwnProperty(o)){const d=t[o](c);d!=null&&Object.assign(r,d);continue}c===!0?r[`data-${o.toLowerCase()}`]="":c&&(r[`data-${o.toLowerCase()}`]=c.toString())}return r}function e5(e,t){return typeof e=="function"?e(t):e}function t5(e,t){return typeof e=="function"?e(t):e}function bt(e,t,r={}){let o=t.render;r.enabled!==!1&&(o=a5(o));const c=n5(t,r,o);if(r.enabled===!1)return null;const d=r.state??ln;return l5(e,o,c,d)}function n5(e,t,r){const{className:o,style:c}=e,{state:d=ln,ref:f,props:p,stateAttributesMapping:g,enabled:v=!0}=t,y=v?e5(o,d):void 0,b=v?t5(c,d):void 0,j=v?J3(d,g):ln,w=v&&p?s5(p):void 0,S=v?sv(j,w)??{}:ln;return typeof document<"u"&&(v?Array.isArray(f)?S.ref=X3([S.ref,BC(r),...f]):S.ref=Yr(S.ref,BC(r),f):Yr(null,null)),v?(y!==void 0&&(S.className=DC(S.className,y)),b!==void 0&&(S.style=sv(S.style,b)),S):ln}function s5(e){return Array.isArray(e)?V3(e):Gr(void 0,e)}const r5=Symbol.for("react.lazy");function a5(e){if(e?.$$typeof!==r5)return e;const t=x.Children.toArray(e)[0];return x.isValidElement(t)?t:e}function l5(e,t,r,o){if(t){if(typeof t=="function")return t(r,o);const c=Gr(r,t.props);return c.ref=r.ref,x.cloneElement(t,c)}if(e&&typeof e=="string")return o5(e,r);throw new Error(nn(8))}function o5(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 i5=x.forwardRef(function(t,r){const{render:o,className:c,disabled:d=!1,focusableWhenDisabled:f=!1,nativeButton:p=!0,style:g,...v}=t,{getButtonProps:y,buttonRef:b}=Kr({disabled:d,focusableWhenDisabled:f,native:p});return bt("button",t,{state:{disabled:d},ref:[r,b],props:[v,y]})});function HC(e){var t,r,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,$C=UC,Bc=(e,t)=>r=>{var o;if(t?.variants==null)return $C(e,r?.class,r?.className);const{variants:c,defaultVariants:d}=t,f=Object.keys(c).map(v=>{const y=r?.[v],b=d?.[v];if(y===null)return null;const j=VC(y)||VC(b);return c[v][j]}),p=r&&Object.entries(r).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,C]=S;return Array.isArray(C)?C.includes({...d,...p}[N]):{...d,...p}[N]===C})?[...v,b,j]:v},[]);return $C(e,f,g,r?.class,r?.className)},c5=(e,t)=>{const r=new Array(e.length+t.length);for(let o=0;o({classGroupId:e,validator:t}),FC=(e=new Map,t=null,r)=>({nextPart:e,validators:t,classGroupId:r}),bm="-",qC=[],d5="arbitrary..",f5=e=>{const t=m5(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:o}=e;return{getClassGroupId:f=>{if(f.startsWith("[")&&f.endsWith("]"))return p5(f);const p=f.split(bm),g=p[0]===""&&p.length>1?1:0;return GC(p,g,t)},getConflictingClassGroupIds:(f,p)=>{if(p){const g=o[f],v=r[f];return g?v?c5(v,g):g:v||qC}return r[f]||qC}}},GC=(e,t,r)=>{if(e.length-t===0)return r.classGroupId;const c=e[t],d=r.nextPart.get(c);if(d){const v=GC(e,t+1,d);if(v)return v}const f=r.validators;if(f===null)return;const p=t===0?e.join(bm):e.slice(t).join(bm),g=f.length;for(let v=0;ve.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),r=t.indexOf(":"),o=t.slice(0,r);return o?d5+o:void 0})(),m5=e=>{const{theme:t,classGroups:r}=e;return h5(r,t)},h5=(e,t)=>{const r=FC();for(const o in e){const c=e[o];iv(c,r,o,t)}return r},iv=(e,t,r,o)=>{const c=e.length;for(let d=0;d{if(typeof e=="string"){x5(e,t,r);return}if(typeof e=="function"){b5(e,t,r,o);return}v5(e,t,r,o)},x5=(e,t,r)=>{const o=e===""?t:KC(t,e);o.classGroupId=r},b5=(e,t,r,o)=>{if(y5(e)){iv(e(o),t,r,o);return}t.validators===null&&(t.validators=[]),t.validators.push(u5(r,e))},v5=(e,t,r,o)=>{const c=Object.entries(e),d=c.length;for(let f=0;f{let r=e;const o=t.split(bm),c=o.length;for(let d=0;d"isThemeGetter"in e&&e.isThemeGetter===!0,j5=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,r=Object.create(null),o=Object.create(null);const c=(d,f)=>{r[d]=f,t++,t>e&&(t=0,o=r,r=Object.create(null))};return{get(d){let f=r[d];if(f!==void 0)return f;if((f=o[d])!==void 0)return c(d,f),f},set(d,f){d in r?r[d]=f:c(d,f)}}},cv="!",YC=":",w5=[],XC=(e,t,r,o,c)=>({modifiers:e,hasImportantModifier:t,baseClassName:r,maybePostfixModifierPosition:o,isExternal:c}),S5=e=>{const{prefix:t,experimentalParseClassName:r}=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 XC(d,w,j,S)};if(t){const c=t+YC,d=o;o=f=>f.startsWith(c)?d(f.slice(c.length)):XC(w5,!1,f,void 0,!0)}if(r){const c=o;o=d=>r({className:d,parseClassName:c})}return o},N5=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((r,o)=>{t.set(r,1e6+o)}),r=>{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}},C5=e=>({cache:j5(e.cacheSize),parseClassName:S5(e),sortModifiers:N5(e),postfixLookupClassGroupIds:k5(e),...f5(e)}),k5=e=>{const t=Object.create(null),r=e.postfixLookupClassGroups;if(r)for(let o=0;o{const{parseClassName:r,getClassGroupId:o,getConflictingClassGroupIds:c,sortModifiers:d,postfixLookupClassGroupIds:f}=t,p=[],g=e.trim().split(T5);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:C}=r(b);if(j){v=b+(v.length>0?" "+v:v);continue}let E=!!C,R;if(E){const M=N.substring(0,C);R=o(M);const O=R&&f[R]?o(N):void 0;O&&O!==R&&(R=O,E=!1)}else R=o(N);if(!R){if(!E){v=b+(v.length>0?" "+v:v);continue}if(R=o(N),!R){v=b+(v.length>0?" "+v:v);continue}E=!1}const k=w.length===0?"":w.length===1?w[0]:d(w).join(":"),A=S?k+cv:k,D=A+R;if(p.indexOf(D)>-1)continue;p.push(D);const I=c(R,E);for(let M=0;M0?" "+v:v)}return v},R5=(...e)=>{let t=0,r,o,c="";for(;t{if(typeof e=="string")return e;let t,r="";for(let o=0;o{let r,o,c,d;const f=g=>{const v=t.reduce((y,b)=>b(y),e());return r=C5(v),o=r.cache.get,c=r.cache.set,d=p,p(g)},p=g=>{const v=o(g);if(v)return v;const y=E5(g,r);return c(g,y),y};return d=f,(...g)=>d(R5(...g))},O5=[],bs=e=>{const t=r=>r[e]||O5;return t.isThemeGetter=!0,t.themeKey=e,t},ZC=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,WC=/^\((?:(\w[\w-]*):)?(.+)\)$/i,M5=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,D5=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,I5=/\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$/,P5=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix|color|light-dark)\(.+\)$/,_5=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,L5=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,eo=e=>M5.test(e),wt=e=>!!e&&!Number.isNaN(Number(e)),Ua=e=>!!e&&Number.isInteger(Number(e)),uv=e=>e.endsWith("%")&&wt(e.slice(0,-1)),pl=e=>D5.test(e),JC=()=>!0,z5=e=>I5.test(e)&&!P5.test(e),dv=()=>!1,B5=e=>_5.test(e),H5=e=>L5.test(e),U5=e=>!Fe(e)&&!qe(e),V5=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)),$5=e=>to(e,ak,dv),Fe=e=>ZC.test(e),mi=e=>to(e,lk,z5),ek=e=>to(e,Z5,wt),F5=e=>to(e,ik,JC),q5=e=>to(e,ok,dv),tk=e=>to(e,sk,dv),G5=e=>to(e,rk,H5),vm=e=>to(e,ck,B5),qe=e=>WC.test(e),Id=e=>hi(e,lk),K5=e=>hi(e,ok),nk=e=>hi(e,sk),Y5=e=>hi(e,ak),X5=e=>hi(e,rk),ym=e=>hi(e,ck,!0),Q5=e=>hi(e,ik,!0),to=(e,t,r)=>{const o=ZC.exec(e);return o?o[1]?t(o[1]):r(o[2]):!1},hi=(e,t,r=!1)=>{const o=WC.exec(e);return o?o[1]?t(o[1]):r:!1},sk=e=>e==="position"||e==="percentage",rk=e=>e==="image"||e==="url",ak=e=>e==="length"||e==="size"||e==="bg-size",lk=e=>e==="length",Z5=e=>e==="number",ok=e=>e==="family-name",ik=e=>e==="number"||e==="weight",ck=e=>e==="shadow",W5=A5(()=>{const e=bs("color"),t=bs("font"),r=bs("text"),o=bs("font-weight"),c=bs("tracking"),d=bs("leading"),f=bs("breakpoint"),p=bs("container"),g=bs("spacing"),v=bs("radius"),y=bs("shadow"),b=bs("inset-shadow"),j=bs("text-shadow"),w=bs("drop-shadow"),S=bs("blur"),N=bs("perspective"),C=bs("aspect"),E=bs("ease"),R=bs("animate"),k=()=>["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"],D=()=>[...A(),qe,Fe],I=()=>["auto","hidden","clip","visible","scroll"],M=()=>["auto","contain","none"],O=()=>[qe,Fe,g],_=()=>[eo,"full","auto",...O()],L=()=>[Ua,"none","subgrid",qe,Fe],z=()=>["auto",{span:["full",Ua,qe,Fe]},Ua,qe,Fe],U=()=>[Ua,"auto",qe,Fe],B=()=>["auto","min","max","fr",qe,Fe],Q=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],W=()=>["start","end","center","stretch","center-safe","end-safe"],Z=()=>["auto",...O()],Y=()=>[eo,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...O()],q=()=>[p,eo,"screen","full","dvw","lvw","svw","min","max","fit",...O()],G=()=>[eo,"screen","full","lh","dvh","lvh","svh","min","max","fit",...O()],$=()=>[e,qe,Fe],F=()=>[...A(),nk,tk,{position:[qe,Fe]}],X=()=>["no-repeat",{repeat:["","x","y","space","round"]}],re=()=>["auto","cover","contain",Y5,$5,{size:[qe,Fe]}],P=()=>[uv,Id,mi],V=()=>["","none","full",v,qe,Fe],J=()=>["",wt,Id,mi],ie=()=>["solid","dashed","dotted","double"],me=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],he=()=>[wt,uv,nk,tk],ae=()=>["","none",S,qe,Fe],oe=()=>["none",wt,qe,Fe],ee=()=>["none",wt,qe,Fe],de=()=>[wt,qe,Fe],K=()=>[eo,"full",...O()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[pl],breakpoint:[pl],color:[JC],container:[pl],"drop-shadow":[pl],ease:["in","out","in-out"],font:[U5],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[pl],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[pl],shadow:[pl],spacing:["px",wt],text:[pl],"text-shadow":[pl],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",eo,Fe,qe,C]}],container:["container"],"container-type":[{"@container":["","normal","size",qe,Fe]}],"container-named":[V5],columns:[{columns:[wt,"auto",Fe,qe,p]}],"break-after":[{"break-after":k()}],"break-before":[{"break-before":k()}],"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:D()}],overflow:[{overflow:I()}],"overflow-x":[{"overflow-x":I()}],"overflow-y":[{"overflow-y":I()}],overscroll:[{overscroll:M()}],"overscroll-x":[{"overscroll-x":M()}],"overscroll-y":[{"overscroll-y":M()}],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:[Ua,"auto",qe,Fe]}],basis:[{basis:[eo,"full","auto",p,...O()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[wt,eo,"auto","initial","none",Fe]}],grow:[{grow:["",wt,qe,Fe]}],shrink:[{shrink:["",wt,qe,Fe]}],order:[{order:[Ua,"first","last","none",qe,Fe]}],"grid-cols":[{"grid-cols":L()}],"col-start-end":[{col:z()}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":L()}],"row-start-end":[{row:z()}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":B()}],"auto-rows":[{"auto-rows":B()}],gap:[{gap:O()}],"gap-x":[{"gap-x":O()}],"gap-y":[{"gap-y":O()}],"justify-content":[{justify:[...Q(),"normal"]}],"justify-items":[{"justify-items":[...W(),"normal"]}],"justify-self":[{"justify-self":["auto",...W()]}],"align-content":[{content:["normal",...Q()]}],"align-items":[{items:[...W(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...W(),{baseline:["","last"]}]}],"place-content":[{"place-content":Q()}],"place-items":[{"place-items":[...W(),"baseline"]}],"place-self":[{"place-self":["auto",...W()]}],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:Z()}],mx:[{mx:Z()}],my:[{my:Z()}],ms:[{ms:Z()}],me:[{me:Z()}],mbs:[{mbs:Z()}],mbe:[{mbe:Z()}],mt:[{mt:Z()}],mr:[{mr:Z()}],mb:[{mb:Z()}],ml:[{ml:Z()}],"space-x":[{"space-x":O()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":O()}],"space-y-reverse":["space-y-reverse"],size:[{size:Y()}],"inline-size":[{inline:["auto",...q()]}],"min-inline-size":[{"min-inline":["auto",...q()]}],"max-inline-size":[{"max-inline":["none",...q()]}],"block-size":[{block:["auto",...G()]}],"min-block-size":[{"min-block":["auto",...G()]}],"max-block-size":[{"max-block":["none",...G()]}],w:[{w:[p,"screen",...Y()]}],"min-w":[{"min-w":[p,"screen","none",...Y()]}],"max-w":[{"max-w":[p,"screen","none","prose",{screen:[f]},...Y()]}],h:[{h:["screen","lh",...Y()]}],"min-h":[{"min-h":["screen","lh","none",...Y()]}],"max-h":[{"max-h":["screen","lh","none",...Y()]}],"font-size":[{text:["base",r,Id,mi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[o,Q5,F5]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",uv,Fe]}],"font-family":[{font:[K5,q5,t]}],"font-features":[{"font-features":[Fe]}],"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,qe,Fe]}],"line-clamp":[{"line-clamp":[wt,"none",qe,ek]}],leading:[{leading:["none",d,...O()]}],"list-image":[{"list-image":["none",qe,Fe]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",qe,Fe]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:$()}],"text-color":[{text:$()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...ie(),"wavy"]}],"text-decoration-thickness":[{decoration:[wt,"from-font","auto",qe,mi]}],"text-decoration-color":[{decoration:$()}],"underline-offset":[{"underline-offset":[wt,"auto",qe,Fe]}],"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:[Ua,qe,Fe]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",qe,Fe]}],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",qe,Fe]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:F()}],"bg-repeat":[{bg:X()}],"bg-size":[{bg:re()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Ua,qe,Fe],radial:["",qe,Fe],conic:["",Ua,qe,Fe]},X5,G5]}],"bg-color":[{bg:$()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:$()}],"gradient-via":[{via:$()}],"gradient-to":[{to:$()}],rounded:[{rounded:V()}],"rounded-s":[{"rounded-s":V()}],"rounded-e":[{"rounded-e":V()}],"rounded-t":[{"rounded-t":V()}],"rounded-r":[{"rounded-r":V()}],"rounded-b":[{"rounded-b":V()}],"rounded-l":[{"rounded-l":V()}],"rounded-ss":[{"rounded-ss":V()}],"rounded-se":[{"rounded-se":V()}],"rounded-ee":[{"rounded-ee":V()}],"rounded-es":[{"rounded-es":V()}],"rounded-tl":[{"rounded-tl":V()}],"rounded-tr":[{"rounded-tr":V()}],"rounded-br":[{"rounded-br":V()}],"rounded-bl":[{"rounded-bl":V()}],"border-w":[{border:J()}],"border-w-x":[{"border-x":J()}],"border-w-y":[{"border-y":J()}],"border-w-s":[{"border-s":J()}],"border-w-e":[{"border-e":J()}],"border-w-bs":[{"border-bs":J()}],"border-w-be":[{"border-be":J()}],"border-w-t":[{"border-t":J()}],"border-w-r":[{"border-r":J()}],"border-w-b":[{"border-b":J()}],"border-w-l":[{"border-l":J()}],"divide-x":[{"divide-x":J()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":J()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...ie(),"hidden","none"]}],"divide-style":[{divide:[...ie(),"hidden","none"]}],"border-color":[{border:$()}],"border-color-x":[{"border-x":$()}],"border-color-y":[{"border-y":$()}],"border-color-s":[{"border-s":$()}],"border-color-e":[{"border-e":$()}],"border-color-bs":[{"border-bs":$()}],"border-color-be":[{"border-be":$()}],"border-color-t":[{"border-t":$()}],"border-color-r":[{"border-r":$()}],"border-color-b":[{"border-b":$()}],"border-color-l":[{"border-l":$()}],"divide-color":[{divide:$()}],"outline-style":[{outline:[...ie(),"none","hidden"]}],"outline-offset":[{"outline-offset":[wt,qe,Fe]}],"outline-w":[{outline:["",wt,Id,mi]}],"outline-color":[{outline:$()}],shadow:[{shadow:["","inner","none",y,ym,vm]}],"shadow-color":[{shadow:$()}],"inset-shadow":[{"inset-shadow":["none",b,ym,vm]}],"inset-shadow-color":[{"inset-shadow":$()}],"ring-w":[{ring:J()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:$()}],"ring-offset-w":[{"ring-offset":[wt,mi]}],"ring-offset-color":[{"ring-offset":$()}],"inset-ring-w":[{"inset-ring":J()}],"inset-ring-color":[{"inset-ring":$()}],"text-shadow":[{"text-shadow":["none",j,ym,vm]}],"text-shadow-color":[{"text-shadow":$()}],opacity:[{opacity:[wt,qe,Fe]}],"mix-blend":[{"mix-blend":[...me(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":me()}],"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":[wt]}],"mask-image-linear-from-pos":[{"mask-linear-from":he()}],"mask-image-linear-to-pos":[{"mask-linear-to":he()}],"mask-image-linear-from-color":[{"mask-linear-from":$()}],"mask-image-linear-to-color":[{"mask-linear-to":$()}],"mask-image-t-from-pos":[{"mask-t-from":he()}],"mask-image-t-to-pos":[{"mask-t-to":he()}],"mask-image-t-from-color":[{"mask-t-from":$()}],"mask-image-t-to-color":[{"mask-t-to":$()}],"mask-image-r-from-pos":[{"mask-r-from":he()}],"mask-image-r-to-pos":[{"mask-r-to":he()}],"mask-image-r-from-color":[{"mask-r-from":$()}],"mask-image-r-to-color":[{"mask-r-to":$()}],"mask-image-b-from-pos":[{"mask-b-from":he()}],"mask-image-b-to-pos":[{"mask-b-to":he()}],"mask-image-b-from-color":[{"mask-b-from":$()}],"mask-image-b-to-color":[{"mask-b-to":$()}],"mask-image-l-from-pos":[{"mask-l-from":he()}],"mask-image-l-to-pos":[{"mask-l-to":he()}],"mask-image-l-from-color":[{"mask-l-from":$()}],"mask-image-l-to-color":[{"mask-l-to":$()}],"mask-image-x-from-pos":[{"mask-x-from":he()}],"mask-image-x-to-pos":[{"mask-x-to":he()}],"mask-image-x-from-color":[{"mask-x-from":$()}],"mask-image-x-to-color":[{"mask-x-to":$()}],"mask-image-y-from-pos":[{"mask-y-from":he()}],"mask-image-y-to-pos":[{"mask-y-to":he()}],"mask-image-y-from-color":[{"mask-y-from":$()}],"mask-image-y-to-color":[{"mask-y-to":$()}],"mask-image-radial":[{"mask-radial":[qe,Fe]}],"mask-image-radial-from-pos":[{"mask-radial-from":he()}],"mask-image-radial-to-pos":[{"mask-radial-to":he()}],"mask-image-radial-from-color":[{"mask-radial-from":$()}],"mask-image-radial-to-color":[{"mask-radial-to":$()}],"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":[wt]}],"mask-image-conic-from-pos":[{"mask-conic-from":he()}],"mask-image-conic-to-pos":[{"mask-conic-to":he()}],"mask-image-conic-from-color":[{"mask-conic-from":$()}],"mask-image-conic-to-color":[{"mask-conic-to":$()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:F()}],"mask-repeat":[{mask:X()}],"mask-size":[{mask:re()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",qe,Fe]}],filter:[{filter:["","none",qe,Fe]}],blur:[{blur:ae()}],brightness:[{brightness:[wt,qe,Fe]}],contrast:[{contrast:[wt,qe,Fe]}],"drop-shadow":[{"drop-shadow":["","none",w,ym,vm]}],"drop-shadow-color":[{"drop-shadow":$()}],grayscale:[{grayscale:["",wt,qe,Fe]}],"hue-rotate":[{"hue-rotate":[wt,qe,Fe]}],invert:[{invert:["",wt,qe,Fe]}],saturate:[{saturate:[wt,qe,Fe]}],sepia:[{sepia:["",wt,qe,Fe]}],"backdrop-filter":[{"backdrop-filter":["","none",qe,Fe]}],"backdrop-blur":[{"backdrop-blur":ae()}],"backdrop-brightness":[{"backdrop-brightness":[wt,qe,Fe]}],"backdrop-contrast":[{"backdrop-contrast":[wt,qe,Fe]}],"backdrop-grayscale":[{"backdrop-grayscale":["",wt,qe,Fe]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[wt,qe,Fe]}],"backdrop-invert":[{"backdrop-invert":["",wt,qe,Fe]}],"backdrop-opacity":[{"backdrop-opacity":[wt,qe,Fe]}],"backdrop-saturate":[{"backdrop-saturate":[wt,qe,Fe]}],"backdrop-sepia":[{"backdrop-sepia":["",wt,qe,Fe]}],"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",qe,Fe]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[wt,"initial",qe,Fe]}],ease:[{ease:["linear","initial",E,qe,Fe]}],delay:[{delay:[wt,qe,Fe]}],animate:[{animate:["none",R,qe,Fe]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[N,qe,Fe]}],"perspective-origin":[{"perspective-origin":D()}],rotate:[{rotate:oe()}],"rotate-x":[{"rotate-x":oe()}],"rotate-y":[{"rotate-y":oe()}],"rotate-z":[{"rotate-z":oe()}],scale:[{scale:ee()}],"scale-x":[{"scale-x":ee()}],"scale-y":[{"scale-y":ee()}],"scale-z":[{"scale-z":ee()}],"scale-3d":["scale-3d"],skew:[{skew:de()}],"skew-x":[{"skew-x":de()}],"skew-y":[{"skew-y":de()}],transform:[{transform:[qe,Fe,"","none","gpu","cpu"]}],"transform-origin":[{origin:D()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:K()}],"translate-x":[{"translate-x":K()}],"translate-y":[{"translate-y":K()}],"translate-z":[{"translate-z":K()}],"translate-none":["translate-none"],zoom:[{zoom:[Ua,qe,Fe]}],accent:[{accent:$()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:$()}],"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",qe,Fe]}],"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":$()}],"scrollbar-track-color":[{"scrollbar-track":$()}],"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",qe,Fe]}],fill:[{fill:["none",...$()]}],"stroke-w":[{stroke:[wt,Id,mi,ek]}],stroke:[{stroke:["none",...$()]}],"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 W5(UC(e))}const J5=Bc(["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:r,...o}){return s.jsx(i5,{className:Ue(J5({variant:t,size:r}),e),...o})}const ez="data-valid",tz="data-invalid",nz={badInput:!1,customError:!1,patternMismatch:!1,rangeOverflow:!1,rangeUnderflow:!1,stepMismatch:!1,tooLong:!1,tooShort:!1,typeMismatch:!1,valid:null,valueMissing:!1},uk={valid:null,touched:!1,dirty:!1,filled:!1,focused:!1},sz={disabled:!1,...uk},gi={valid(e){return e===null?null:e?{[ez]:""}:{[tz]:""}}},dk={invalid:void 0,name:void 0,validityData:{state:nz,errors:[],error:"",value:"",initialValue:null},setValidityData:Bt,disabled:void 0,setTouched:Bt,setDirty:Bt,setFilled:Bt,setFocused:Bt,validationMode:"onSubmit",shouldValidateOnChange:()=>!1,state:sz,registerFieldControl:Bt,validation:{getValidationProps:(e,t=ln)=>t,inputRef:{current:null},registeredInputs:new Map,registerInput:Bt,getInputControl:()=>null,commit:async()=>{},change:Bt}},fk=x.createContext(dk);function ya(e=!0){const t=x.useContext(fk);if(t.setValidityData===Bt&&!e)throw new Error(nn(28));return t}const rz=x.createContext(void 0);function az(e=!1){const t=x.useContext(rz);if(!t&&!e)throw new Error(nn(86));return t}const lz=x.createContext({elementRef:{current:null},formRef:{current:{fields:new Map}},errors:{},clearErrors:Bt,validationMode:"onSubmit",submitCountRef:{current:0}});function Hc(){return x.useContext(lz)}let pk=0;function oz(e,t="mui"){const[r,o]=x.useState(e),c=e||r;return x.useEffect(()=>{r==null&&(pk+=1,o(`${t}-${pk}`))},[r,t]),c}const mk=tv.useId;function Pd(e,t){if(mk!==void 0){const r=mk();return e??(t?`${t}-${r}`:r)}return oz(e,t)}function ja(e){return Pd(e,"base-ui")}const iz=x.createContext({controlId:void 0,registerControlId:Bt,resetControlId:Bt,labelId:void 0,setLabelId:Bt,messageIds:[],setMessageIds:Bt,getDescriptionProps:e=>e});function ml(){return x.useContext(iz)}function fv(e,t,r,o=!0,c){const[d,f]=x.useState(),p=ja(c?`${c}-label`:void 0),g=e??t??d;return De(()=>{const v=e||t||!o?void 0:cz(r.current,p);d!==v&&f(v)}),g}function cz(e,t){const r=uz(e);if(r)return!r.id&&t&&(r.id=t),r.id||void 0}function uz(e){if(!e)return;const t=e.parentElement;if(t&&t.tagName==="LABEL")return t;const r=e.id;if(r){const c=e.nextElementSibling;if(c&&c.htmlFor===r)return c}const o=e.labels;return o&&o[0]}function no(e={}){const{id:t,enabled:r=!0}=e,{controlId:o,registerControlId:c,resetControlId:d}=ml(),f=ja(),p=Ts(()=>Symbol()),g=x.useRef(!1),v=x.useRef(!1),y=Ie(()=>{!g.current||c===Bt||(g.current=!1,c(p.current,void 0))});return De(()=>{if(!r||c===Bt){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,r,c,d,f,p,y]),De(()=>y,[y]),(r?o:void 0)??t??f}function dz(){return typeof navigator>"u"?{userAgent:"",platform:"",maxTouchPoints:0}:{userAgent:navigator.userAgent,platform:navigator.platform??"",maxTouchPoints:navigator.maxTouchPoints??0}}const{userAgent:fz,platform:pz,maxTouchPoints:mz}=dz(),jm=fz.toLowerCase(),_d=pz.toLowerCase(),Ld=/^i(os$|p)/.test(_d)||_d==="macintel"&&mz>1,hk="android",wm=_d===hk||jm.includes(hk),gk=!Ld&&_d.startsWith("mac");_d.startsWith("win");const hz=gk||Ld,hl=typeof CSS<"u"&&!!CSS.supports?.("-webkit-backdrop-filter:none"),xk=!hl&&jm.includes("firefox");!hl&&jm.includes("chrom");const gz=hz,pv=/jsdom|happydom/.test(jm);function ar(e){let t=e.activeElement;for(;t?.shadowRoot?.activeElement!=null;)t=t.shadowRoot.activeElement;return t}function Ge(e,t){if(!e||!t)return!1;const r=t.getRootNode?.();if(e.contains(t))return!0;if(r&&_c(r)){let o=t;for(;o;){if(e===o)return!0;o=o.parentNode||o.host}}return!1}function ns(e){return"composedPath"in e?e.composedPath()[0]??e.target:e.target}const mv="data-base-ui-focusable",bk="input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])",xi="ArrowLeft",bi="ArrowRight",hv="ArrowUp",Sm="ArrowDown",vk="data-starting-style",xz="data-ending-style",bz={[vk]:""},vz={[xz]:""},so={transitionStatus(e){return e==="starting"?bz:e==="ending"?vz:null}},yz="data-open",jz="data-closed",wz="data-anchor-hidden",yk="data-popup-open",Sz="data-pressed",Nz={[yk]:""},Cz={[yk]:"",[Sz]:""},kz={[yz]:""},Tz={[jz]:""},Ez={[wz]:""},gv={open(e){return e?Nz:null}},xv={open(e){return e?Cz:null}},Uc={open(e){return e?kz:Tz},anchorHidden(e){return e?Ez:null}},bv={...Uc,...so},vv="data-trigger-disabled";function Nm(e,t){if(!Ct(e))return!1;const r=e;if(t.hasElement(r))return!r.hasAttribute(vv);for(const[,o]of t.entries())if(Ge(o,r))return!o.hasAttribute(vv);return!1}function yv(e,t){if(t==null)return!1;if("composedPath"in e)return e.composedPath().includes(t);const r=e;return r.target!=null&&t.contains(r.target)}function Rz(e){return e.matches("html,body")}function Cm(e){return an(e)&&e.matches(bk)}function Az(e){return e?.closest(`button,a[href],[role="button"],select,[tabindex]:not([tabindex="-1"]),${bk}`)!=null}function jv(e){return e?e.getAttribute("role")==="combobox"&&Cm(e):!1}function Oz(e){if(!e||pv)return!0;try{return e.matches(":focus-visible")}catch{return!0}}function km(e){return e?e.hasAttribute(mv)?e:e.querySelector(`[${mv}]`)||e:null}function ro(e,t,r=!0){return e.filter(c=>c.parentId===t).flatMap(c=>[...!r||c.context?.open?[c]:[],...ro(e,c.id,r)])}function jk(e,t){let r=[],o=e.find(c=>c.id===t)?.parentId;for(;o;){const c=e.find(d=>d.id===o);o=c?.parentId,c&&(r=r.concat(c))}return r}function vs(e){e.preventDefault(),e.stopPropagation()}function Mz(e){return"nativeEvent"in e}function Tm(e){return e.pointerType===""&&e.isTrusted?!0:wm&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function wv(e){return pv?!1:!wm&&e.width===0&&e.height===0||wm&&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 ao(e,t){const r=["mouse","pen"];return t||r.push("",void 0),r.includes(e)}function Dz(e){const t=e.type;return t==="click"||t==="mousedown"||t==="keydown"||t==="keyup"}const Vc=Math.min,gl=Math.max,Em=Math.round,vi=Math.floor,xl=e=>({x:e,y:e}),Iz={left:"right",right:"left",bottom:"top",top:"bottom"};function wk(e,t,r){return gl(e,Vc(t,r))}function lo(e,t){return typeof e=="function"?e(t):e}function Xr(e){return e.split("-")[0]}function bl(e){return e.split("-")[1]}function Sv(e){return e==="x"?"y":"x"}function Nv(e){return e==="y"?"height":"width"}function Qr(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function Cv(e){return Sv(Qr(e))}function Pz(e,t,r){r===void 0&&(r=!1);const o=bl(e),c=Cv(e),d=Nv(c);let f=c==="x"?o===(r?"end":"start")?"right":"left":o==="start"?"bottom":"top";return t.reference[d]>t.floating[d]&&(f=Rm(f)),[f,Rm(f)]}function _z(e){const t=Rm(e);return[kv(e),t,kv(t)]}function kv(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const Sk=["left","right"],Nk=["right","left"],Lz=["top","bottom"],zz=["bottom","top"];function Bz(e,t,r){switch(e){case"top":case"bottom":return r?t?Nk:Sk:t?Sk:Nk;case"left":case"right":return t?Lz:zz;default:return[]}}function Hz(e,t,r,o){const c=bl(e);let d=Bz(Xr(e),r==="start",o);return c&&(d=d.map(f=>f+"-"+c),t&&(d=d.concat(d.map(kv)))),d}function Rm(e){const t=Xr(e);return Iz[t]+e.slice(t.length)}function Uz(e){var t,r,o,c;return{top:(t=e.top)!=null?t:0,right:(r=e.right)!=null?r:0,bottom:(o=e.bottom)!=null?o:0,left:(c=e.left)!=null?c:0}}function Ck(e){return typeof e!="number"?Uz(e):{top:e,right:e,bottom:e,left:e}}function zd(e){const{x:t,y:r,width:o,height:c}=e;return{width:o,height:c,top:r,left:t,right:t+o,bottom:r+c,x:t,y:r}}function Am(e,t,r){return Math.floor(e/t)!==r}function oo(e,t){return t<0||t>=e.length}function Om(e,t){return Es(e.current,{disabledIndices:t})}function Tv(e,t){return Es(e.current,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}function Es(e,{startingIndex:t=-1,decrement:r=!1,disabledIndices:o,amount:c=1}={}){let d=t;do d+=r?-c:c;while(d>=0&&d<=e.length-1&&io(e,d,o));return d}function Vz(e,{event:t,orientation:r,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===hv?w="up":t.key===Sm&&(w="down"),w){const S=[],N=[];let C=!1,E=0;{let _=null,L=-1;e.forEach((z,U)=>{if(z==null)return;E+=1;const B=z.closest('[role="row"]');B&&(C=!0),(B!==_||L===-1)&&(_=B,L+=1,S[L]=[]),S[L].push(U),N[U]=L})}let R=!1,k=0;if(C)for(const _ of S){const L=_.length;L>k&&(k=L),L!==f&&(R=!0)}const A=R&&E{if(!R||y===-1)return;const L=N[y];if(L==null)return;const z=S[L].indexOf(y),U=_==="up"?-1:1;for(let B=L+U,Q=0;Q=S.length){if(!o||A)return;if(B=B<0?S.length-1:0,c){const Z=Math.min(z,S[B].length-1),Y=S[B][Z]??S[B][0],q=c(t,y,Y);B=N[q]??B}}const W=S[B];for(let Z=Math.min(z,W.length-1);Z>=0;Z-=1){const Y=W[Z];if(!io(e,Y,p))return Y}}},M=_=>{if(!A||y===-1)return;const L=y%D,z=_==="up"?-D:D,U=v-v%D,B=vi(v/D)+1;for(let Q=y-L+z,W=0;Wv){if(!o)return;Q=Q<0?U:0}const Z=Math.min(Q+D-1,v);for(let Y=Math.min(Q+L,Z);Y>=Q;Y-=1)if(!io(e,Y,p))return Y}};b&&vs(t);const O=I(w)??M(w);if(O!==void 0)j=O;else if(y===-1)j=w==="up"?v:g;else if(j=Es(e,{startingIndex:y,amount:D,decrement:w==="up",disabledIndices:p}),o){if(w==="up"&&(y-D_?z:z-D,c&&(j=c(t,y,j))}w==="down"&&y+D>v&&(j=Es(e,{startingIndex:y%D-D,amount:D,disabledIndices:p}),c&&(j=c(t,y,j)))}oo(e,j)&&(j=y)}if(r==="both"){const S=vi(y/f);t.key===(d?xi:bi)&&(b&&vs(t),y%f!==f-1?(j=Es(e,{startingIndex:y,disabledIndices:p}),o&&Am(j,f,S)&&(j=Es(e,{startingIndex:y-y%f-1,disabledIndices:p}),c&&(j=c(t,y,j)))):o&&(j=Es(e,{startingIndex:y-y%f-1,disabledIndices:p}),c&&(j=c(t,y,j))),Am(j,f,S)&&(j=y)),t.key===(d?bi:xi)&&(b&&vs(t),y%f!==0?(j=Es(e,{startingIndex:y,decrement:!0,disabledIndices:p}),o&&Am(j,f,S)&&(j=Es(e,{startingIndex:y+(f-y%f),decrement:!0,disabledIndices:p}),c&&(j=c(t,y,j)))):o&&(j=Es(e,{startingIndex:y+(f-y%f),decrement:!0,disabledIndices:p}),c&&(j=c(t,y,j))),Am(j,f,S)&&(j=y));const N=vi(v/f)===S;oo(e,j)&&(o&&N?(j=t.key===(d?bi:xi)?v:Es(e,{startingIndex:y-y%f-1,disabledIndices:p}),c&&(j=c(t,y,j))):j=y)}return j}function io(e,t,r){if(typeof r=="function"?r(t):r?.includes(t)??!1)return!0;const c=e[t];return c?!Mm(c)||c.matches(":disabled")?!0:!r&&(c.hasAttribute("disabled")||c.getAttribute("aria-disabled")==="true"):!1}function $z(e){return e.visibility==="hidden"||e.visibility==="collapse"}function Mm(e,t=e?gr(e):null){return!e||!e.isConnected||!t||$z(t)?!1:typeof e.checkVisibility=="function"?e.checkVisibility():t.display!=="none"&&t.display!=="contents"}const Fz='a[href],button,input,select,textarea,summary,details,iframe,object,embed,[tabindex],[contenteditable]:not([contenteditable="false"]),audio[controls],video[controls]';function qz(e){const t=e.assignedSlot;if(t)return t;if(e.parentElement)return e.parentElement;const r=e.getRootNode();return _c(r)?r.host:null}function Ev(e){for(const t of Array.from(e.children))if(_s(t)==="summary")return t;return null}function Gz(e,t){const r=Ev(t);return!!r&&(e===r||Ge(r,e))}function kk(e){const t=e?_s(e):"";return e!=null&&e.matches(Fz)&&(t!=="summary"||e.parentElement!=null&&_s(e.parentElement)==="details"&&Ev(e.parentElement)===e)&&(t!=="details"||Ev(e)==null)&&(t!=="input"||e.type!=="hidden")}function Tk(e){if(!kk(e)||!e.isConnected||e.matches(":disabled"))return!1;for(let t=e;t;t=qz(t)){const r=t!==e,o=_s(t)==="slot";if(t.hasAttribute("inert")||r&&_s(t)==="details"&&!t.open&&!Gz(e,t)||t.hasAttribute("hidden")||!o&&!Kz(t,r))return!1}return!0}function Kz(e,t){const r=gr(e);return t?r.display!=="none":Mm(e,r)}function Ek(e){const t=e.tabIndex;if(t<0){const r=_s(e);if(r==="details"||r==="audio"||r==="video"||an(e)&&e.isContentEditable)return 0}return t}function Rv(e){if(_s(e)!=="input")return null;const t=e;return t.type==="radio"&&t.name!==""?t:null}function Yz(e,t){const r=Rv(e);if(!r)return!0;const o=t.find(c=>{const d=Rv(c);return d?.name===r.name&&d.form===r.form&&d.checked});return o?o===r:t.find(c=>{const d=Rv(c);return d?.name===r.name&&d.form===r.form})===r}function Rk(e){if(an(e)&&_s(e)==="slot"){const t=e.assignedElements({flatten:!0});if(t.length>0)return t}return an(e)&&e.shadowRoot?Array.from(e.shadowRoot.children):Array.from(e.children)}function Ak(e,t){Rk(e).forEach(r=>{kk(r)&&t.push(r),Ak(r,t)})}function Ok(e,t,r){Rk(e).forEach(o=>{an(o)&&o.matches(t)&&r.push(o),Ok(o,t,r)})}function Av(e){return Tk(e)&&Ek(e)>=0}function Mk(e){const t=[];return Ak(e,t),t.filter(Tk)}function Bd(e){const t=Mk(e);return t.filter(r=>Ek(r)>=0&&Yz(r,t))}function Dk(e,t){const r=Bd(e),o=r.length;if(o===0)return;const c=ar(zt(e)),d=r.indexOf(c),f=d===-1?t===1?0:o-1:d+t;return r[f]}function Ov(e){return Dk(zt(e).body,1)||e}function Ik(e){return Dk(zt(e).body,-1)||e}function Pk(e,t){if(!e)return null;const r=Bd(zt(e).body),o=r.length;if(o===0)return null;const c=r.indexOf(e);if(c===-1)return null;const d=(c+t+o)%o;return r[d]}function Xz(e){return Pk(e,1)}function Qz(e){return Pk(e,-1)}function $c(e,t){const r=t||e.currentTarget,o=e.relatedTarget;return!o||!Ge(r,o)}function Zz(e){Bd(e).forEach(r=>{r.dataset.tabindex=r.getAttribute("tabindex")||"",r.setAttribute("tabindex","-1")})}function _k(e){const t=[];Ok(e,"[data-tabindex]",t),t.forEach(r=>{const o=r.dataset.tabindex;delete r.dataset.tabindex,o?r.setAttribute("tabindex",o):r.removeAttribute("tabindex")})}function Mv(e){x.useEffect(e,Er)}const Hd=0;class Zr{constructor(){tn(this,"currentId",Hd);tn(this,"clear",()=>{this.currentId!==Hd&&(clearTimeout(this.currentId),this.currentId=Hd)});tn(this,"disposeEffect",()=>this.clear)}static create(){return new Zr}start(t,r){this.clear(),this.currentId=setTimeout(()=>{this.currentId=Hd,r()},t)}isStarted(){return this.currentId!==Hd}}function Xs(){const e=Ts(Zr.create).current;return Mv(e.disposeEffect),e}function Wz(e,t){return e.matches(":disabled")?!1:!t||e.form===t?!0:e.form===null&&!e.hasAttribute("form")}const Jz=x.createContext({disabled:!1});function Lk(){return x.useContext(Jz)}var Dv={exports:{}},Ls={};var zk;function e4(){if(zk)return Ls;zk=1;var e=Od();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(),Dv.exports=e4(),Dv.exports}var ys=Hk();const Dm=null;class t4{constructor(){tn(this,"callbacks",[]);tn(this,"callbacksCount",0);tn(this,"nextId",1);tn(this,"startId",1);tn(this,"isScheduled",!1);tn(this,"tick",t=>{this.isScheduled=!1;const r=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[r]!==null&&(this.callbacks[r]=null,this.callbacksCount-=1)}}let Im=new t4;class Va{constructor(){tn(this,"currentId",Dm);tn(this,"cancel",()=>{this.currentId!==Dm&&(Im.cancel(this.currentId),this.currentId=Dm)});tn(this,"disposeEffect",()=>this.cancel)}static create(){return new Va}static request(t){return Im.request(t)}static cancel(t){return Im.cancel(t)}request(t){this.cancel(),this.currentId=Im.request(()=>{this.currentId=Dm,t()})}}function Fc(){const e=Ts(Va.create).current;return Mv(e.disposeEffect),e}function vl(e){return e==null?e:"current"in e?e.current:e}let Pm=null;function n4(e){if(!Pm){const t=[];Pm=t,queueMicrotask(()=>{Pm=null,ys.flushSync(()=>{for(const r of t)r()})})}Pm.push(e)}function Uk(e,t=!1,r=!1){const o=Fc();return Ie((c,d=null)=>{o.cancel();const f=vl(e);if(f==null)return;const p=f,g=()=>{if(!r){ys.flushSync(c);return}n4(()=>{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=vk;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 Wr(e){const{enabled:t=!0,open:r,ref:o,batch:c=!1,onComplete:d}=e,f=Ie(d),p=Uk(o,r,c);x.useEffect(()=>{if(!t)return;const g=new AbortController;return p(f,g.signal),()=>{g.abort()}},[t,r,f,p])}function yi(e,t=!1,r=!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"&&!r&&d("ending"),!e&&!f&&c==="ending"&&d(void 0),De(()=>{if(!e&&f&&c!=="ending"&&r){const g=Va.request(()=>{d("ending")});return()=>{Va.cancel(g)}}},[e,f,c,r]),De(()=>{if(!e||t)return;const g=Va.request(()=>{d(void 0)});return()=>{Va.cancel(g)}},[t,e]),De(()=>{if(!e||!t)return;e&&f&&c!=="idle"&&d("starting");const g=Va.request(()=>{d("idle")});return()=>{Va.cancel(g)}},[t,e,f,c]),{mounted:f,setMounted:p,transitionStatus:c}}function $a({controlled:e,default:t,name:r,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 qc(e,t,r,o,c=!0,d){const{registerFieldControl:f}=ya(),p=Ts(()=>Symbol());De(()=>{const g=p.current;if(!c){f(g,void 0);return}f(g,{controlRef:e,getValue:o,id:t,name:d,value:r})},[e,c,o,t,d,f,p,r]),De(()=>{const g=p.current;return()=>{f(g,void 0)}},[f,p])}function Jr(e,t){const r=x.useRef(e),o=Ie(t);De(()=>{r.current!==e&&o(r.current),r.current=e},[e,o])}const Fn="none",co="trigger-press",zs="trigger-hover",_m="trigger-focus",Lm="outside-press",Ud="item-press",Iv="close-press",Vd="input-change",Fa="input-clear",s4="input-press",uo="focus-out",Gc="escape-key",Pv="list-navigation",Vk="keyboard",$k="pointer",Fk="cancel-open",r4="disabled",_v="imperative-action",a4="window-resize";function Ve(e,t,r,o){let c=!1,d=!1;const f=o??ln;return{reason:e,event:t??new Event("base-ui"),cancel(){c=!0},allowPropagation(){d=!0},get isCanceled(){return c},get isPropagationAllowed(){return d},trigger:r,...f}}function l4(e,t,r){const o=r??ln;return{reason:e,event:t??new Event("base-ui"),...o}}const o4=x.forwardRef(function(t,r){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:C,setTouched:E,setDirty:R,validityData:k,setFocused:A,setFilled:D,validationMode:I,validation:M}=ya(),{clearErrors:O,elementRef:_,submitCountRef:L}=Hc(),z=C||g,U=N??f,B={...S,disabled:z},{labelId:Q}=ml(),W=no({id:d}),[Z]=$a({controlled:p,default:y,name:"FieldControl",state:"value"}),Y=p!==void 0,q=Y?Z:void 0,G=q==null?void 0:String(q),$=Ie(()=>M.inputRef.current?.value);qc(M.inputRef,W,G,$,!z,f),De(()=>{const P=G??M.inputRef.current?.value;P!==void 0&&D(P!=="")},[G,M.inputRef,D]),Jr(G,()=>{G!==void 0&&(O(U),R(G!==(k.initialValue??"")),M.change(G))});const F=x.useRef(null),X=Xs();return De(()=>{b&&F.current===ar(zt(F.current))&&A(!0)},[b,A]),bt("input",t,{ref:[r,F],state:B,props:[{id:W,disabled:z,name:U,ref:M.inputRef,"aria-labelledby":Q,autoFocus:b,...Y?{value:q}:{defaultValue:y},onChange(P){const V=P.currentTarget.value,J=Ve(Fn,P.nativeEvent);v?.(V,J),!Y&&(R(V!==(k.initialValue??"")),D(V!==""),!P.nativeEvent.defaultPrevented&&!J.isCanceled&&(O(U),M.change(V)))},onFocus(){A(!0)},onBlur(P){if(E(!0),A(!1),I==="onBlur"){const V=P.currentTarget.value;M.commit(V),Y&&queueMicrotask(()=>{const J=M.inputRef.current?.value;J!==void 0&&J!==V&&J!==(k.initialValue??"")&&M.commit(J)})}},onKeyDown(P){if(P.currentTarget.tagName==="INPUT"&&P.key==="Enter"){E(!0);const V=P.currentTarget.value,J=P.currentTarget.form;if(J&&J===_.current&&!P.defaultPrevented){const ie=P.currentTarget,me=L.current;X.start(0,()=>{L.current===me&&M.commit(ie.value)})}else M.commit(V)}}},w,P=>M.getValidationProps(z,P)],stateAttributesMapping:gi})}),i4=x.forwardRef(function(t,r){return s.jsx(o4,{ref:r,...t})});function Ke({className:e,type:t,ref:r,...o}){return s.jsx(i4,{ref:r,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 $d({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 ji({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 c4=Bc(["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 wi({className:e,align:t="inline-start",...r}){return s.jsx("div",{role:"group","data-slot":"input-group-addon","data-align":t,className:Ue(c4({align:t}),e),onClick:o=>{o.target.closest("button")||o.currentTarget.parentElement?.querySelector("input")?.focus()},...r})}const u4=Bc("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 d4({className:e,type:t="button",variant:r="ghost",size:o="xs",...c}){return s.jsx(se,{type:t,"data-size":o,variant:r,className:Ue(u4({size:o}),e),...c})}function Si({className:e,...t}){return s.jsx(Ke,{"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 f4(e){return bt(e.defaultTagName??"div",e,e)}const p4=Bc("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:r,render:o,...c}){return f4({render:o,defaultTagName:"span",props:Gr({"data-slot":"badge"},c,{className:Ue(p4({variant:t,shape:r}),e)})})}function Lv({className:e,...t}){return s.jsx("span",{className:Ue("size-1.5 flex-none rounded-full bg-current",e),...t})}function fo(e,t){if(typeof window>"u")return e;const r=window.wbI18n;return r?r.t(e,t)??e:e}function Fd({className:e,...t}){return s.jsx("svg",{"data-slot":"spinner",role:"status","aria-label":fo("加载中"),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 tt({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 qk={clipPath:"inset(50%)",overflow:"hidden",whiteSpace:"nowrap",border:0,padding:0,width:1,height:1,margin:-1},Ni={...qk,position:"fixed",top:0,left:0},Kc={...qk,position:"absolute"},Gk=x.createContext(void 0);function m4(){const e=x.useContext(Gk);if(e===void 0)throw new Error(nn(63));return e}const h4="data-checked",g4="data-unchecked",Kk={...gi,checked(e){return e?{[h4]:""}:{[g4]:""}}},x4=x.forwardRef(function(t,r){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:C,uncheckedValue:E,value:R,style:k,...A}=t,{clearErrors:D}=Hc(),{state:I,setTouched:M,setDirty:O,validityData:_,setFilled:L,setFocused:z,validationMode:U,disabled:B,name:Q,validation:W}=ya(),{labelId:Z}=ml(),Y=B||N,q=Q??y,G=x.useRef(null),$=Yr(G,v,W.inputRef),F=x.useRef(null),X=ja(),re=no({id:g}),P=b?void 0:re,[V,J]=$a({controlled:o,default:!!d,name:"Switch",state:"checked"});qc(F,X,V,void 0,!Y,y),De(()=>{L(V)},[V,L]),Jr(V,()=>{D(q),O(V!==_.initialValue),W.change(V)});const{getButtonProps:ie,buttonRef:me}=Kr({disabled:Y,native:b}),he=fv(f,Z,G,!b,P),ae={id:b?re:X,role:"switch","aria-checked":V,"aria-readonly":w||void 0,"aria-required":S||void 0,"aria-labelledby":he,onFocus(){Y||z(!0)},onBlur(){const K=G.current;!K||Y||(M(!0),z(!1),U==="onBlur"&&W.commit(K.checked))},onClick(K){if(w||Y)return;K.preventDefault();const be=G.current;be&&zc(be,K)}},oe={...W.getValidationProps(Y),checked:V,disabled:Y,form:p,id:P,name:q,required:S,style:q?Kc:Ni,tabIndex:-1,type:"checkbox","aria-hidden":!0,ref:$,onChange(K){if(K.nativeEvent.defaultPrevented)return;if(w){K.preventDefault();return}const be=K.currentTarget.checked,ne=Ve(Fn,K.nativeEvent);j?.(be,ne),!ne.isCanceled&&J(be)},onClick(K){K.stopPropagation()},onFocus(){F.current?.focus()},...R!==void 0?{value:R}:ln},ee=x.useMemo(()=>({...I,checked:V,disabled:Y,readOnly:w,required:S}),[I,V,Y,w,S]),de=bt("span",t,{state:ee,ref:[r,F,me],props:[ae,A,ie,K=>W.getValidationProps(Y,K)],stateAttributesMapping:Kk});return s.jsxs(Gk.Provider,{value:ee,children:[de,!V&&q&&E!==void 0&&s.jsx("input",{type:"hidden",form:p,name:q,value:E,disabled:Y}),s.jsx("input",{...oe,suppressHydrationWarning:!0})]})}),b4=x.forwardRef(function(t,r){const{render:o,className:c,style:d,...f}=t,p=m4();return bt("span",t,{state:p,ref:r,stateAttributesMapping:Kk,props:f})});function Rs({className:e,size:t="default",...r}){const o=t==="sm";return s.jsx(x4,{"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),...r,children:s.jsx(b4,{"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 v4(e){if(!e)return null;for(const t of e.elements){const r=t.tagName;if(r==="BUTTON"||r==="INPUT"){const o=t;if(o.type==="submit")return o}}return null}const y4="data-checked",j4="data-unchecked";function Yk(e){return{checked(t){return e.indeterminate?{}:t?{[y4]:""}:{[j4]:""}},...gi}}const w4=x.createContext(void 0);function S4(){return x.useContext(w4)}const Xk=x.createContext(void 0);function N4(){const e=x.useContext(Xk);if(e===void 0)throw new Error(nn(14));return e}const C4="data-parent",k4=x.forwardRef(function(t,r){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:C,required:E=!1,uncheckedValue:R,value:k,nativeButton:A=!1,style:D,...I}=t,{clearErrors:M}=Hc(),{disabled:O,name:_,setDirty:L,setFilled:z,setFocused:U,setTouched:B,state:Q,validationMode:W,validityData:Z,validation:Y}=ya(),q=Lk(),{labelId:G,registerControlId:$,getDescriptionProps:F}=ml(),X=S4(),re=X?.allValues===void 0?void 0:X.parent,P=re!==void 0,V=O||q.disabled||X?.disabled||p,J=_??j,ie=k??J,me=ja(),he=X?.registerControlId!==$,ae=no({id:v||void 0,enabled:he}),oe=A?ae:me;let ee={};P&&(S?ee=re.getParentProps():ie!==void 0&&(ee=re.getChildProps(ie)));const{checked:de=o,indeterminate:K=y,onCheckedChange:be,...ne}=ee,ce=X?.value,we=x.useRef(null),{getButtonProps:Ee,buttonRef:ve}=Kr({disabled:V,native:A}),Ce=X?.validation??Y,[ke,Se]=$a({controlled:ie!==void 0&&ce!==void 0&&!S?ce.includes(ie):de,default:d,name:"Checkbox",state:"checked"}),ge=P?!!de:ke,Te=P&&K||y;qc(we,me,ke,void 0,!X&&!V,j);const Oe=re?.registerChildId,Ne=x.useRef(null),Be=Ce.registerInput,Xe=X?ie:void 0,Rt=x.useCallback(lt=>Be(lt,{controlRef:we,value:Xe}),[Be,Xe]),Qt=Yr(b,Ne,S?void 0:Rt),Mt=fv(f,G,Ne,!A,ae);De(()=>{Ne.current&&(Ne.current.indeterminate=Te),X||z(ke)},[ke,Te,X,z]),Jr(ke,()=>{X||(M(J),L(ke!==Z.initialValue),Ce.change(ke))});const it=Gr({checked:ke,disabled:V,form:g,name:S?void 0:J,id:A?void 0:ae,required:E,ref:Qt,style:J?Kc:Ni,tabIndex:-1,type:"checkbox","aria-hidden":!0,onChange(lt){if(lt.nativeEvent.defaultPrevented)return;if(N){lt.preventDefault();return}const _t=lt.currentTarget.checked,Pn=Ve(Fn,lt.nativeEvent);if(w?.(_t,Pn),!Pn.isCanceled&&(be?.(_t,Pn),!Pn.isCanceled&&(Se(_t),ie!==void 0&&X!==void 0&&!S&&!P))){const Zt=_t?[...X.value,ie]:X.value.filter(Je=>Je!==ie);X.setValue(Zt,Pn)}},onClick(lt){lt.stopPropagation()},onFocus(){we.current?.focus()}},k!==void 0?{value:(X?ke&&k:k)||""}:ln,F,lt=>Ce.getValidationProps(V,lt));x.useEffect(()=>{if(!re||ie===void 0)return;const lt=re.disabledStatesRef.current;return lt.set(ie,V),()=>{lt.delete(ie)}},[re,V,ie]);const Un=x.useMemo(()=>({...Q,checked:ge,disabled:V,readOnly:N,required:E,indeterminate:Te}),[Q,ge,V,N,E,Te]),as=Yk(Un),Vn=bt("span",t,{state:Un,ref:[ve,we,r],props:[{id:oe,role:"checkbox","aria-checked":Te?"mixed":ge,"aria-readonly":N||void 0,"aria-required":E||void 0,"aria-labelledby":Mt,[C4]:S?"":void 0,onFocus(){V||U(!0)},onBlur(){const lt=Ne.current;lt&&(B(!0),U(!1),W==="onBlur"&&Ce.commit(X?ce:lt.checked))},onKeyDown(lt){if(lt.key!=="Enter"||(lt.preventBaseUIHandler(),lt.defaultPrevented))return;const _t=Ne.current?.form??null,Pn=lt.currentTarget,Zt=lt.nativeEvent,Je=lt.preventDefault,Tt=Zt.preventDefault;let Lt=!1;lt.preventDefault=()=>{Lt=!0,Je.call(lt)},Zt.preventDefault=()=>{Lt=!0,Tt.call(Zt)},Tt.call(Zt),bn(Pn).queueMicrotask(()=>{lt.preventDefault=Je,Zt.preventDefault=Tt,Lt||v4(_t)?.click()})},onClick(lt){if(N||V)return;lt.preventDefault();const _t=Ne.current;_t&&zc(_t,lt)}},I,ne,Ee,F,lt=>Ce.getValidationProps(V,lt)],stateAttributesMapping:as}),fs=Vn.props.id;return De(()=>{if(!(!Oe||S||ie===void 0||fs===void 0))return Oe(ie,fs)},[Oe,S,ie,fs]),s.jsxs(Xk.Provider,{value:Un,children:[Vn,!ke&&!X&&J&&!S&&R!==void 0&&s.jsx("input",{type:"hidden",form:g,name:J,value:R,disabled:V}),s.jsx("input",{...it,suppressHydrationWarning:!0})]})}),T4=x.forwardRef(function(t,r){const{render:o,className:c,style:d,keepMounted:f=!1,...p}=t,g=N4(),v=g.checked||g.indeterminate,{mounted:y,transitionStatus:b,setMounted:j}=yi(v),w=x.useRef(null),S={...g,transitionStatus:b};Wr({batch:!0,enabled:!v,open:v,ref:w,onComplete(){v||j(!1)}});const C={...Yk(g),...so},E=f||y,R=bt("span",t,{ref:[r,w],state:S,stateAttributesMapping:C,props:p});return E?R:null});function ea({className:e,...t}){return s.jsx(k4,{"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(T4,{"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 zv(e){return Array.isArray(e)?e.map(t=>zv(t)).join(","):e==null?"":String(e)}const Qk=new Map;function E4(e,t){const r=JSON.stringify({locale:zv(e),options:t}),o=Qk.get(r);if(o)return o;const c=new Intl.NumberFormat(e,t);return Qk.set(r,c),c}function Zk(e,t,r){return e==null?"":E4(t,r).format(e)}function Ci(e,t=Number.MIN_SAFE_INTEGER,r=Number.MAX_SAFE_INTEGER){return Math.max(t,Math.min(e,r))}function R4(e,t,r){return(e-t)*100/(r-t)}const Wk=x.createContext(void 0);function Jk(){const e=x.useContext(Wk);if(e===void 0)throw new Error(nn(51));return e}const A4="data-complete",O4="data-indeterminate",M4="data-progressing",Bv={status(e){return e==="progressing"?{[M4]:""}:e==="complete"?{[A4]:""}:e==="indeterminate"?{[O4]:""}:null}},D4=x.forwardRef(function(t,r){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 C="indeterminate",E=null,R=null,k="",A="indeterminate progress";if(g!=null&&Number.isFinite(g)){const _=R4(g,p,f);E=Ci(Number.isNaN(_)?0:_,0,100),R=Ci(g,p,f),C=R===f?"complete":"progressing",k=o?Zk(R,d,o):Zk(E/100,d,{style:"percent"}),A=k}const D=x.useMemo(()=>({status:C}),[C]),I={"aria-labelledby":S,"aria-valuemax":f,"aria-valuemin":p,"aria-valuenow":R??void 0,"aria-valuetext":c?c(k,g):A,role:"progressbar",children:s.jsxs(x.Fragment,{children:[b,s.jsx("span",{role:"presentation",style:Ni,children:"x"})]})},M=x.useMemo(()=>({formattedValue:k,percentageValue:E,setLabelId:N,state:D,value:g}),[k,E,N,D,g]),O=bt("div",t,{state:D,ref:r,props:[I,w],stateAttributesMapping:Bv});return s.jsx(Wk.Provider,{value:M,children:O})}),I4=x.forwardRef(function(t,r){const{render:o,className:c,style:d,...f}=t,{state:p}=Jk();return bt("div",t,{state:p,ref:r,props:f,stateAttributesMapping:Bv})}),P4=x.forwardRef(function(t,r){const{render:o,className:c,style:d,...f}=t,{percentageValue:p,state:g}=Jk(),v=p==null?{}:{insetInlineStart:0,height:"inherit",width:`${p}%`};return bt("div",t,{state:g,ref:r,props:[{style:v},f],stateAttributesMapping:Bv})});function qd({className:e,children:t,value:r,...o}){return s.jsxs(D4,{value:r,"data-slot":"progress",className:Ue("flex w-full flex-wrap items-center gap-3",e),...o,children:[t,s.jsx(_4,{children:s.jsx(L4,{})})]})}function _4({className:e,...t}){return s.jsx(I4,{"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 L4({className:e,...t}){return s.jsx(P4,{"data-slot":"progress-indicator",className:Ue("h-full rounded-[inherit] bg-primary transition-[width] duration-300 ease-out",e),...t})}const Hv=[];let Uv;function z4(){return Uv}function B4(e){Hv.push(e)}function zm(e){const t=(r,o)=>{const c=Ts(H4).current;let d;try{Uv=c;for(const f of Hv)f.before(c);d=e(r,o);for(const f of Hv)f.after(c);c.didInitialize=!0}finally{Uv=void 0}return d};return t.displayName=e.displayName||e.name,t}function e1(e){return x.forwardRef(zm(e))}function H4(){return{didInitialize:!1}}const t1=x.createContext(void 0);function Gd(e){const t=x.useContext(t1);if(t===void 0&&!e)throw new Error(nn(72));return t}function U4(e,t){return t!=null&&!ao(t)?0:typeof e=="function"?e():e}function ki(e,t,r){const o=U4(e,r);return typeof o=="number"?o:o?.[t]}function n1(e){return typeof e=="function"?e():e}function s1(e,t){return t||e==="click"||e==="mousedown"}function V4(e){return e?.includes("mouse")&&e!=="mousedown"}const r1=x.createContext({hasProvider:!1,timeoutMs:0,delayRef:{current:0},initialDelayRef:{current:0},timeout:new Zr,currentIdRef:{current:null},currentContextRef:{current:null}});function $4(e,t){e.current=t.current}function F4(e){const{children:t,delay:r,timeoutMs:o=0}=e,c=x.useRef(r),d=x.useRef(r),f=x.useRef(null),p=x.useRef(null),g=Xs();return De(()=>{if(d.current=r,!f.current){c.current=r;return}c.current={open:ki(c.current,"open"),close:ki(r,"close")}},[r,f,c,d]),s.jsx(r1.Provider,{value:x.useMemo(()=>({hasProvider:!0,delayRef:c,initialDelayRef:d,currentIdRef:f,timeoutMs:o,currentContextRef:p,timeout:g}),[o,g]),children:t})}function q4(e,t={open:!1}){const{open:r}=t,o="rootStore"in e?e.rootStore:e,c=o.useState("floatingId"),d=x.useContext(r1),{currentIdRef:f,delayRef:p,timeoutMs:g,initialDelayRef:v,currentContextRef:y,hasProvider:b,timeout:j}=d,[w,S]=x.useState(!1),N=x.useRef(r);return De(()=>{N.current=r},[r]),De(()=>{function C(){y.current?.setIsInstantPhase(!1),f.current=null,y.current=null,p.current=v.current,j.clear()}if(f.current&&!r&&f.current===c){if(S(!1),g){const E=c;return j.start(g,()=>{o.select("open")||f.current&&f.current!==E||C()}),()=>{(N.current||f.current!==E)&&j.clear()}}C()}},[r,c,f,p,g,v,y,j,o]),De(()=>{if(!r)return;const C=y.current,E=f.current;j.clear(),y.current={onOpenChange:o.setOpen,setIsInstantPhase:S},f.current=c,p.current={open:0,close:ki(v.current,"close")},E!==null&&E!==c?(S(!0),C?.setIsInstantPhase(!0),C?.onOpenChange(!1,Ve(Fn))):(S(!1),C?.setIsInstantPhase(!1))},[r,c,o,f,p,v,y,j]),De(()=>()=>{if(f.current===c){if(y.current=null,!N.current)return;f.current=null,$4(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 jt(e,t,r,o){return e.addEventListener(t,r,o),()=>{e.removeEventListener(t,r,o)}}function qa(...e){return()=>{for(let t=0;t{t.current=t.next}};return t}const Yc=x.forwardRef(function(t,r){const[o,c]=x.useState();De(()=>{gz&&hl&&c("button")},[]);const d={tabIndex:0,role:o};return s.jsx("span",{...t,ref:r,style:Ni,"aria-hidden":o?void 0:!0,...d,"data-base-ui-focus-guard":""})});function Kd(e){return`data-base-ui-${e}`}let Bm=0;function Hm(e,t={}){const{preventScroll:r=!1,sync:o=!1,shouldFocus:c}=t;cancelAnimationFrame(Bm);function d(){c&&!c()||e?.focus({preventScroll:r})}if(o)return d(),Bt;const f=requestAnimationFrame(d);return Bm=f,()=>{Bm===f&&(cancelAnimationFrame(f),Bm=0)}}const Vv={inert:new WeakMap,"aria-hidden":new WeakMap},a1="data-base-ui-inert",$v={inert:new WeakSet,"aria-hidden":new WeakSet};let Yd=new WeakMap,Fv=0;function K4(e){return $v[e]}function l1(e){return e?_c(e)?e.host:l1(e.parentNode):null}const o1=(e,t)=>t.map(r=>{if(e.contains(r))return r;const o=l1(r);return e.contains(o)?o:null}).filter(r=>r!=null),i1=e=>{const t=new Set;return e.forEach(r=>{let o=r;for(;o&&!t.has(o);)t.add(o),o=o.parentNode}),t},c1=(e,t,r)=>{const o=[],c=d=>{!d||r.has(d)||Array.from(d.children).forEach(f=>{_s(f)!=="script"&&(t.has(f)?c(f):o.push(f))})};return c(e),o};function Y4(e,t,r,o,{mark:c=!0}){let d=null;o?d="inert":r&&(d="aria-hidden");let f=null,p=null;const g=o1(t,e),v=c?c1(t,i1(g),new Set(g)):[],y=[],b=[];if(d){const j=Vv[d],w=K4(d);p=w,f=j;const S=o1(t,Array.from(t.querySelectorAll("[aria-live]"))),N=g.concat(S);c1(t,i1(N),new Set(N)).forEach(E=>{const R=E.getAttribute(d),k=R!==null&&R!=="false",A=(j.get(E)||0)+1;j.set(E,A),y.push(E),A===1&&k&&w.add(E),k||E.setAttribute(d,d==="inert"?"":"true")})}return c&&v.forEach(j=>{const w=(Yd.get(j)||0)+1;Yd.set(j,w),b.push(j),w===1&&j.setAttribute(a1,"")}),Fv+=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=(Yd.get(j)||0)-1;Yd.set(j,w),w||j.removeAttribute(a1)}),Fv-=1,Fv||(Vv.inert=new WeakMap,Vv["aria-hidden"]=new WeakMap,$v.inert=new WeakSet,$v["aria-hidden"]=new WeakSet,Yd=new WeakMap)}}function u1(e,t={}){const{ariaHidden:r=!1,inert:o=!1,mark:c=!0}=t,d=zt(e[0]).body;return Y4(e,d,r,o,{mark:c})}const X4=500,Q4={style:{transition:"none"}},d1="data-base-ui-click-trigger",f1={fallbackAxisSide:"none"},p1={fallbackAxisSide:"end"},Z4={clipPath:"inset(50%)",position:"fixed",top:0,left:0},m1=x.createContext(null),h1=()=>x.useContext(m1),W4=Kd("portal");function g1(e={}){const{ref:t,container:r,componentProps:o=ln,elementProps:c}=e,d=Pd(),p=h1()?.portalNode,[g,v]=x.useState(null),[y,b]=x.useState(null),j=Ie(C=>{C!==null&&b(C)}),w=x.useRef(null);De(()=>{if(r===null){w.current&&(w.current=null,b(null),v(null));return}const C=(r&&(Qb(r)?r:r.current))??p??document.body;if(C==null){w.current&&(w.current=null,b(null),v(null));return}w.current!==C&&(w.current=C,b(null),v(C))},[r,p]);const S=bt("div",o,{ref:[t,j],props:[{id:d,[W4]:""},c]}),N=g&&S?ys.createPortal(S,g):null;return{node:y,nodeId:x.isValidElement(S)?S.props.id:void 0,subtree:N}}const Um=x.forwardRef(function(t,r){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:r,componentProps:t,elementProps:v}),w=x.useRef(null),S=x.useRef(null),N=x.useRef(null),C=x.useRef(null),[E,R]=x.useState(null),k=x.useRef(!1),A=E?.modal,D=E?.open,I=!!E&&!E.modal&&E.open&&!!y;x.useEffect(()=>{if(!y||A)return;function O(_){y&&_.relatedTarget&&$c(_)&&(_.type==="focusin"?k.current&&(_k(y),k.current=!1):(Zz(y),k.current=!0))}return qa(jt(y,"focusin",O,!0),jt(y,"focusout",O,!0))},[y,A]),De(()=>{!y||D!==!0||!k.current||(_k(y),k.current=!1)},[D,y]);const M=x.useMemo(()=>({beforeOutsideRef:w,afterOutsideRef:S,beforeInsideRef:N,afterInsideRef:C,portalNode:y,setFocusManagerState:R}),[y]);return s.jsxs(x.Fragment,{children:[j,s.jsxs(m1.Provider,{value:M,children:[I&&y&&s.jsx(Yc,{"data-type":"outside",ref:w,onFocus:O=>{if($c(O,y))N.current?.focus();else{const _=E?E.domReference:null;Ik(_)?.focus()}}}),I&&y&&s.jsx("span",{role:g,"aria-owns":b,style:Z4}),y&&ys.createPortal(f,y),I&&y&&s.jsx(Yc,{"data-type":"outside",ref:S,onFocus:O=>{if($c(O,y))C.current?.focus();else{const _=E?E.domReference:null;Ov(_)?.focus(),E?.closeOnFocusOut&&E?.onOpenChange(!1,Ve(uo,O.nativeEvent))}}})]})]})});function x1(){const e=new Map;return{emit(t,r){e.get(t)?.forEach(o=>o(r))},on(t,r){e.has(t)||e.set(t,new Set),e.get(t).add(r)},off(t,r){e.get(t)?.delete(r)}}}class J4{constructor(){tn(this,"nodesRef",{current:[]});tn(this,"events",x1())}addNode(t){this.nodesRef.current.push(t)}removeNode(t){const r=this.nodesRef.current.findIndex(o=>o===t);r!==-1&&this.nodesRef.current.splice(r,1)}}const b1=x.createContext(null),v1=x.createContext(null),Xc=()=>x.useContext(b1)?.id||null,Ti=e=>{const t=x.useContext(v1);return e??t};function eB(e){const t=Pd(),r=Ti(e),o=Xc();return De(()=>{if(!t)return;const c={id:t,parentId:o};return r?.addNode(c),()=>{r?.removeNode(c)}},[r,t,o]),t}function tB(e){const{children:t,id:r}=e,o=Xc();return s.jsx(b1.Provider,{value:x.useMemo(()=>({id:r,parentId:o}),[r,o]),children:t})}function nB(e){const{children:t,externalTree:r}=e,o=Ts(()=>r??new J4).current;return s.jsx(v1.Provider,{value:o,children:t})}function sB(e,t){const r=bn(ns(e));return e instanceof r.KeyboardEvent?"keyboard":e instanceof r.FocusEvent?t||"keyboard":"pointerType"in e?e.pointerType||"keyboard":"touches"in e?"touch":e instanceof r.MouseEvent?t||(e.detail===0?"keyboard":"mouse"):""}const y1=20;let po=[];function qv(){po=po.filter(e=>e.deref()?.isConnected)}function j1(e){qv(),e&&_s(e)!=="body"&&(po.push(new WeakRef(e)),po.length>y1&&(po=po.slice(-y1)))}function w1(){return qv(),po[po.length-1]?.deref()}function rB(e){return e?Av(e)?e:Bd(e)[0]||e:null}function S1(e){if(e.hasAttribute("tabindex")&&!e.hasAttribute("data-tabindex")||!e.getAttribute("role")?.includes("dialog"))return;const r=Mk(e).filter(c=>{const d=c.getAttribute("data-tabindex")||"";return Av(c)||c.hasAttribute("data-tabindex")&&!d.startsWith("-")}),o=e.getAttribute("tabindex");r.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 Vm(e){const{context:t,children:r,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,C=N.useState("open"),E=N.useState("domReferenceElement"),R=N.useState("floatingElement"),{events:k,dataRef:A}=N.context,D=Ie(()=>A.current.floatingContext?.nodeId),I=c===!1,M=jv(E)&&I,O=qn(c),_=qn(d),L=qn(v),z=qn(C),U=Ti(w),B=h1(),Q=x.useRef(!1),W=x.useRef(!1),Z=x.useRef(!1),Y=x.useRef(null),q=x.useRef(""),G=x.useRef(""),$=x.useRef(null),F=x.useRef(null),X=Yr($,j,B?.beforeInsideRef),re=Yr(F,B?.afterInsideRef),P=Xs(),V=Xs(),J=Fc(),ie=B!=null,me=km(R),he=Ie((ee=me)=>ee?Bd(ee):[]),ae=Ie(()=>S?.().filter(ee=>ee!=null)??[]);x.useEffect(()=>{if(o||!p)return;function ee(K){K.key==="Tab"&&Ge(me,ar(zt(me)))&&he().length===0&&!M&&vs(K)}const de=zt(me);return jt(de,"keydown",ee)},[o,me,p,M,he]),x.useEffect(()=>{if(o||!C)return;const ee=zt(me);function de(){Z.current=!1}function K(ne){const ce=ns(ne),we=ae(),Ee=Ge(R,ce)||Ge(E,ce)||Ge(B?.portalNode,ce)||we.some(ve=>ve===ce||Ge(ve,ce));Z.current=!Ee,G.current=ne.pointerType||"keyboard",ce?.closest(`[${d1}]`)&&(W.current=!0,V.start(0,()=>{W.current=!1}))}function be(){G.current="keyboard"}return qa(jt(ee,"pointerdown",K,!0),jt(ee,"pointerup",de,!0),jt(ee,"pointercancel",de,!0),jt(ee,"keydown",be,!0),de)},[o,R,E,me,C,B,V,ae]),x.useEffect(()=>{if(o||!g)return;const ee=zt(me);function de(){W.current=!0,V.start(0,()=>{W.current=!1})}function K(we){const Ee=ns(we);Av(Ee)&&(Y.current=Ee)}function be(we){const Ee=we.relatedTarget,ve=we.currentTarget,Ce=ns(we);p&&Ee==null&&Ce!=null&&Ge(R,Ce)&&j1(Ce),queueMicrotask(()=>{const ke=D(),Se=N.context.triggerElements,ge=ae(),Te=Ee?.hasAttribute(Kd("focus-guard"))&&[$.current,F.current,B?.beforeInsideRef.current,B?.afterInsideRef.current,B?.beforeOutsideRef.current,B?.afterOutsideRef.current,vl(b),vl(y)].includes(Ee),Oe=!(Ge(E,Ee)||Ge(R,Ee)||Ge(Ee,R)||Ge(B?.portalNode,Ee)||ge.some(Ne=>Ne===Ee||Ge(Ne,Ee))||Se.hasMatchingElement(Ne=>Ge(Ne,Ee))||Te||U&&(ro(U.nodesRef.current,ke).find(Ne=>Ge(Ne.context?.elements.floating,Ee)||Ge(Ne.context?.elements.domReference,Ee))||jk(U.nodesRef.current,ke).find(Ne=>[Ne.context?.elements.floating,km(Ne.context?.elements.floating)].includes(Ee)||Ne.context?.elements.domReference===Ee)));if(ve===E&&me&&S1(me),f&&ve!==E&&!Mm(Ce)&&ar(ee)===ee.body){if(an(me)&&(me.focus(),f==="popup")){J.request(()=>{me.focus()});return}const Ne=he(),Be=Y.current,Xe=(Be&&Ne.includes(Be)?Be:null)||Ne[Ne.length-1]||me;an(Xe)&&Xe.focus()}if(A.current.insideReactTree){A.current.insideReactTree=!1;return}(M||!p)&&Ee&&Oe&&!W.current&&(M||Ee!==w1())&&(Q.current=!0,N.setOpen(!1,Ve(uo,we)))})}function ne(){Z.current||(A.current.insideReactTree=!0,P.start(0,()=>{A.current.insideReactTree=!1}))}const ce=an(E)?E:null;if(!(!R&&!ce))return qa(ce&&jt(ce,"focusout",be),ce&&jt(ce,"pointerdown",de),R&&jt(R,"focusin",K),R&&jt(R,"focusout",be),R&&B&&jt(R,"focusout",ne,!0))},[o,E,R,me,p,U,B,N,g,f,he,M,D,A,P,V,J,y,b,ae]),x.useEffect(()=>{if(o||!R||!C)return;const ee=Array.from(B?.portalNode?.querySelectorAll(`[${Kd("portal")}]`)||[]),K=(U?jk(U.nodesRef.current,D()):[]).find(ve=>jv(ve.context?.elements.domReference||null))?.context?.elements.domReference,ne=[...[R,...ee,$.current,F.current,B?.beforeOutsideRef.current,B?.afterOutsideRef.current,...ae()],K,vl(b),vl(y),M?E:null].filter(ve=>ve!=null),ce=u1(ne,{ariaHidden:p||M,mark:!1}),we=[R,...ee].filter(ve=>ve!=null),Ee=u1(we);return()=>{Ee(),ce()}},[C,o,E,R,p,B,M,U,D,y,b,ae]),De(()=>{if(!C||o||!an(me))return;q.current="",G.current="";const ee=zt(me),de=ar(ee);queueMicrotask(()=>{const K=O.current,be=typeof K=="function"?K(L.current||""):K;if(be===void 0||be===!1||Ge(me,de))return;let ce=null;const we=()=>(ce==null&&(ce=he(me)),ce[0]||me);let Ee;be===!0||be===null?Ee=we():Ee=vl(be),Ee=Ee||we();const ve=Ge(me,ar(ee));Hm(Ee,{preventScroll:Ee===me,shouldFocus(){if(!z.current)return!1;if(ve)return!0;const Ce=ar(ee);return!(Ce!==Ee&&Ge(me,Ce))}})})},[o,C,me,he,O,L,z]),De(()=>{if(o||!me)return;const ee=zt(me),de=ar(ee),K=L.current==null;j1(de);function be(ce){if(ce.open||(q.current=sB(ce.nativeEvent,G.current)),ce.reason===zs&&ce.nativeEvent.type==="mouseleave"&&(Q.current=!0),ce.reason===Lm)if(ce.nested)Q.current=!1;else if(Tm(ce.nativeEvent)||wv(ce.nativeEvent))Q.current=!1;else{let we=!1;zt(me).createElement("div").focus({get preventScroll(){return we=!0,!1}}),we?Q.current=!1:Q.current=!0}}k.on("openchange",be);function ne(ce){const we=_.current;let Ee=typeof we=="function"?we(ce):we;if(Ee===void 0||Ee===!1)return null;Ee===null&&(Ee=!0);const ve=E?.isConnected?E:null,Ce=de?.isConnected&&_s(de)!=="body"?de:null;let ke=K?Ce||ve:ve||Ce;return ke||(ke=w1()||null),typeof Ee=="boolean"?ke:vl(Ee)||ke||null}return()=>{k.off("openchange",be);const ce=ar(ee),we=ae(),Ee=Ge(R,ce)||we.some(Se=>Se===ce||Ge(Se,ce))||U&&ro(U.nodesRef.current,D(),!1).some(Se=>Ge(Se.context?.elements.floating,ce)),ve=_.current,Ce=q.current,ke=ne(Ce);queueMicrotask(()=>{const Se=rB(ke),ge=typeof ve!="boolean";if(ve&&!Q.current&&an(Se)&&(!(!ge&&Se!==ce&&ce!==ee.body)||Ee)){const Te={preventScroll:!0};Ce==="keyboard"&&(Te.focusVisible=!0),Se.focus(Te)}Q.current=!1})}},[o,R,me,_,L,k,U,E,D,ae]),De(()=>{if(!hl||C||!R)return;const ee=ar(zt(R));!an(ee)||!Cm(ee)||Ge(R,ee)&&ee.blur()},[C,R]),De(()=>{if(!(o||!B))return B.setFocusManagerState({modal:p,closeOnFocusOut:g,open:C,onOpenChange:N.setOpen,domReference:E}),()=>{B.setFocusManagerState(null)}},[o,B,p,C,N,g,E]),De(()=>{if(!(o||!me))return S1(me),()=>{queueMicrotask(qv)}},[o,me]);const oe=!o&&(p?!M:!0)&&(ie||p);return s.jsxs(x.Fragment,{children:[oe&&s.jsx(Yc,{"data-type":"inside",ref:X,onFocus:ee=>{if(p){const de=he();Hm(de[de.length-1])}else B?.portalNode&&(Q.current=!1,$c(ee,B.portalNode)?Ov(E)?.focus():vl(b??B.beforeOutsideRef)?.focus())}}),r,oe&&s.jsx(Yc,{"data-type":"inside",ref:re,onFocus:ee=>{p?Hm(he()[0]):B?.portalNode&&(g&&(Q.current=!0),$c(ee,B.portalNode)?Ik(E)?.focus():vl(y??B.afterOutsideRef)?.focus())}})]})}function $m(e,t={}){const{enabled:r=!0,event:o="click",toggle:c=!0,ignoreMouse:d=!1,stickIfOpen:f=!0,touchOpenDelay:p=0,reason:g=co}=t,v="rootStore"in e?e.rootStore:e,y=v.context.dataRef,b=x.useRef(void 0),j=Fc(),w=Xs(),S=x.useMemo(()=>{function N(E,R,k,A){const D=Ve(g,R,k);E&&A==="touch"&&p>0?w.start(p,()=>{v.setOpen(!0,D)}):v.setOpen(E,D)}function C(E,R,k){const A=y.current.openEvent,D=v.select("domReferenceElement")!==R;return E&&D||!E||!c?!0:A&&f?!k(A.type):!1}return{onPointerDown(E){b.current=ao(E.pointerType,!0)&&wv(E.nativeEvent)?"virtual":E.pointerType},onMouseDown(E){const R=b.current,k=E.nativeEvent,A=v.select("open");if(E.button!==0||o==="click"||ao(R,!0)&&d)return;const D=C(A,E.currentTarget,O=>O==="click"||O==="mousedown"),I=ns(k);if(Cm(I)){N(D,k,I,R);return}const M=E.currentTarget;j.request(()=>{N(D,k,M,R)})},onClick(E){if(o==="mousedown-only")return;const R=b.current;if(o==="mousedown"&&R){b.current=void 0;return}if(ao(R,!0)&&d)return;const k=v.select("open"),A=C(k,E.currentTarget,D=>D==="click"||D==="mousedown"||D==="keydown"||D==="keyup");N(A,E.nativeEvent,E.currentTarget,R)},onKeyDown(){b.current=void 0}}},[y,o,d,g,v,f,c,j,w,p]);return x.useMemo(()=>r?{reference:S}:ln,[r,S])}function aB(e,t){let r=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 r==null&&t.x&&f&&(r=d.x-t.x),o==null&&t.y&&p&&(o=d.y-t.y),b-=r||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 N1(e){return e!=null&&e.clientX!=null}function lB(e,t={}){const{enabled:r=!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)}),C=Ie((A,D,I)=>{v.current||g.current.openEvent&&!N1(g.current.openEvent)||c.set("positionReference",aB(I??p,{x:A,y:D,axis:o,dataRef:g,pointerType:b}))}),E=Ie(A=>{d?y.current||(C(A.clientX,A.clientY,A.currentTarget),S([])):C(A.clientX,A.clientY,A.currentTarget)}),R=ao(b)?f:d;x.useEffect(()=>{if(!r){N(p);return}if(!R)return;function A(){y.current?.(),y.current=null}const D=bn(f);function I(M){const O=ns(M);Ge(f,O)?A():C(M.clientX,M.clientY)}return!g.current.openEvent||N1(g.current.openEvent)?y.current=jt(D,"mousemove",I):N(p),A},[R,r,f,g,p,c,C,N,w]),x.useEffect(()=>()=>{c.set("positionReference",null)},[c]),x.useEffect(()=>{r&&!f&&(v.current=!1)},[r,f]),x.useEffect(()=>{!r&&d&&(v.current=!0)},[r,d]);const k=x.useMemo(()=>{function A(D){j(D.pointerType)}return{onPointerDown:A,onPointerEnter:A,onMouseMove:E,onMouseEnter:E}},[E]);return x.useMemo(()=>r?{reference:k,trigger:k}:{},[r,k])}function oB(){return!1}function iB(e){return{escapeKey:typeof e=="boolean"?e:e?.escapeKey??!1,outsidePress:typeof e=="boolean"?e:e?.outsidePress??!0}}function Xd(e,t={}){const{enabled:r=!0,escapeKey:o=!0,outsidePress:c=!0,outsidePressEvent:d="sloppy",referencePress:f=oB,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=Ti(g),N=Ie(typeof c=="function"?c:()=>!1),C=typeof c=="function"?N:c,E=C!==!1,R=Ie(()=>d),{escapeKey:k,outsidePress:A}=iB(p),D=x.useRef(!1),I=x.useRef(!1),M=x.useRef(!1),O=x.useRef(!1),_=x.useRef(!1),L=x.useRef(""),z=x.useRef(null),U=Xs(),B=Xs(),Q=Ie(()=>{B.clear(),j.current.insideReactTree=!1}),W=Ie(P=>{const V=j.current.floatingContext?.nodeId;return(S?ro(S.nodesRef.current,V):[]).some(ie=>ie.context?.open&&!ie.context.dataRef.current[P])}),Z=Ie(P=>yv(P,v.select("floatingElement"))||yv(P,v.select("domReferenceElement"))),Y=Ie(P=>{f()&&v.setOpen(!1,Ve(co,P.nativeEvent))}),q=Ie(P=>{if(!y||!r||!o||P.key!=="Escape"||_.current||!k&&W("__escapeKeyBubbles"))return;const V=Mz(P)?P.nativeEvent:P,J=Ve(Gc,V);v.setOpen(!1,J),J.isCanceled||P.preventDefault(),!k&&!J.isPropagationAllowed&&P.stopPropagation()}),G=Ie(()=>{j.current.insideReactTree=!0,B.start(0,Q)}),$=Ie(P=>{if(!y||!r||P.button!==0)return;const V=ns(P.nativeEvent);Ge(v.select("floatingElement"),V)&&(D.current||(D.current=!0,I.current=!1))}),F=Ie(P=>{!y||!r||(P.defaultPrevented||P.nativeEvent.defaultPrevented)&&D.current&&(I.current=!0)});x.useEffect(()=>{function P(V){V.open||(O.current=!1)}return w.on("openchange",P),()=>{w.off("openchange",P)}},[w]),x.useEffect(()=>{if(!y||!r)return y||(O.current=!1),Q;j.current.__escapeKeyBubbles=k,j.current.__outsidePressBubbles=A;const P=new Zr,V=new Zr,J=zt(b);function ie(){P.clear(),_.current=!0}function me(){P.start(hl?5:0,()=>{_.current=!1})}function he(){M.current=!0,V.start(0,()=>{M.current=!1})}function ae(){D.current=!1,I.current=!1}function oe(){const Oe=L.current,Ne=Oe==="pen"||!Oe?"mouse":Oe,Be=R(),Xe=typeof Be=="function"?Be():Be;return typeof Xe=="string"?Xe:Xe[Ne]}function ee(Oe){const Ne=oe();return Ne==="intentional"&&Oe.type!=="click"||Ne==="sloppy"&&Oe.type==="click"}function de(Oe){const Ne=j.current.floatingContext?.nodeId,Be=S&&ro(S.nodesRef.current,Ne).some(Xe=>yv(Oe,Xe.context?.elements.floating));return Z(Oe)||Be}function K(Oe){if(ee(Oe)){Oe.type!=="click"&&!Z(Oe)&&(V.clear(),M.current=!1),Q();return}if(j.current.insideReactTree){Q();return}const Ne=ns(Oe),Be=`[${Kd("inert")}]`,Xe=Ct(Ne)?Ne.getRootNode():null,Rt=Array.from((_c(Xe)?Xe:zt(v.select("floatingElement"))).querySelectorAll(Be)),Qt=v.context.triggerElements;if(Ne&&(Qt.hasElement(Ne)||Qt.hasMatchingElement(it=>Ge(it,Ne))))return;let Mt=Ct(Ne)?Ne:null;for(;Mt&&!Wl(Mt);){const it=Jl(Mt);if(Wl(it)||!Ct(it))break;Mt=it}if(!(Rt.length&&Ct(Ne)&&!Rz(Ne)&&!Ge(Ne,v.select("floatingElement"))&&Rt.every(it=>!Ge(Mt,it)))){if(an(Ne)&&!("touches"in Oe)){const it=Wl(Ne),Un=gr(Ne),as=/auto|scroll/,Vn=it||as.test(Un.overflowX),fs=it||as.test(Un.overflowY),lt=Vn&&Ne.clientWidth>0&&Ne.scrollWidth>Ne.clientWidth,_t=fs&&Ne.clientHeight>0&&Ne.scrollHeight>Ne.clientHeight,Pn=Un.direction==="rtl",Zt=_t&&(Pn?Oe.offsetX<=Ne.offsetWidth-Ne.clientWidth:Oe.offsetX>Ne.clientWidth),Je=lt&&Oe.offsetY>Ne.clientHeight;if(Zt||Je)return}if(!de(Oe)){if(oe()==="intentional"){if(Oe.detail!==0&&!Tm(Oe)&&!O.current)return;if(M.current){V.clear(),M.current=!1;return}}typeof C=="function"&&!C(Oe)||W("__outsidePressBubbles")||(v.setOpen(!1,Ve(Lm,Oe)),Q())}}}function be(Oe){oe()!=="sloppy"||Oe.pointerType==="touch"||!v.select("open")||!r||Z(Oe)||K(Oe)}function ne(Oe){if(oe()!=="sloppy"||!v.select("open")||!r||Z(Oe))return;const Ne=Oe.touches[0];Ne&&(z.current={startTime:Date.now(),startX:Ne.clientX,startY:Ne.clientY,dismissOnTouchEnd:!1,dismissOnMouseDown:!0},U.start(1e3,()=>{z.current&&(z.current.dismissOnTouchEnd=!1,z.current.dismissOnMouseDown=!1)}))}function ce(Oe,Ne){const Be=ns(Oe);if(!Be)return;const Xe=jt(Be,Oe.type,()=>{Ne(Oe),Xe()})}function we(Oe){L.current="touch",ce(Oe,ne)}function Ee(Oe){U.clear(),Oe.type==="pointerdown"&&(Oe.button===0&&(O.current=!0),L.current=Oe.pointerType),!(Oe.type==="mousedown"&&z.current&&!z.current.dismissOnMouseDown)&&ce(Oe,Ne=>{Ne.type==="pointerdown"?be(Ne):K(Ne)})}function ve(Oe){if(Oe.type==="pointercancel"&&(O.current=!1),!D.current)return;const Ne=I.current;if(ae(),oe()==="intentional"){if(Oe.type==="pointercancel"){Ne&&he();return}if(!de(Oe)){if(Ne){he();return}typeof C=="function"&&!C(Oe)||(V.clear(),M.current=!0,Q())}}}function Ce(Oe){if(oe()!=="sloppy"||!z.current||Z(Oe))return;const Ne=Oe.touches[0];if(!Ne)return;const Be=Math.abs(Ne.clientX-z.current.startX),Xe=Math.abs(Ne.clientY-z.current.startY),Rt=Math.sqrt(Be*Be+Xe*Xe);Rt>5&&(z.current.dismissOnTouchEnd=!0),Rt>10&&(K(Oe),U.clear(),z.current=null)}function ke(Oe){ce(Oe,Ce)}function Se(Oe){oe()!=="sloppy"||!z.current||Z(Oe)||(z.current.dismissOnTouchEnd&&K(Oe),U.clear(),z.current=null)}function ge(Oe){ce(Oe,Se)}const Te=qa(o&&qa(jt(J,"keydown",q),jt(J,"compositionstart",ie),jt(J,"compositionend",me)),E&&qa(jt(J,"click",Ee,!0),jt(J,"pointerdown",Ee,!0),jt(J,"pointerup",ve,!0),jt(J,"pointercancel",ve,!0),jt(J,"mousedown",Ee,!0),jt(J,"mouseup",ve,!0),jt(J,"touchstart",we,{capture:!0,passive:!0}),jt(J,"touchmove",ke,{capture:!0,passive:!0}),jt(J,"touchend",ge,{capture:!0,passive:!0})));return()=>{Te(),P.clear(),V.clear(),ae(),M.current=!1,Q()}},[j,b,o,E,C,y,r,k,A,q,Q,R,W,Z,S,v,U]);const X=x.useMemo(()=>({onKeyDown:q,onPointerDown:Y,onClick:Y}),[q,Y]),re=x.useMemo(()=>({onKeyDown:q,onPointerDown:F,onMouseDown:F,onClickCapture:G,onMouseDownCapture(P){G(),$(P)},onPointerDownCapture(P){G(),$(P)},onMouseUpCapture:G,onTouchEndCapture:G,onTouchMoveCapture:G}),[q,G,$,F]);return x.useMemo(()=>r?{reference:X,floating:re,trigger:X}:{},[r,X,re])}function C1(e,t,r){let{reference:o,floating:c}=e;const d=Qr(t),f=Cv(t),p=Nv(f),g=Xr(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=bl(t);return S&&(w[f]+=j*(S==="end"?1:-1)*(r&&v?-1:1)),w}async function cB(e,t){var r;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}=lo(t,e),S=Ck(w),C=p[j?b==="floating"?"reference":"floating":b],E=zd(await d.getClippingRect({element:(r=await(d.isElement==null?void 0:d.isElement(C)))==null||r?C:C.contextElement||await(d.getDocumentElement==null?void 0:d.getDocumentElement(p.floating)),boundary:v,rootBoundary:y,strategy:g})),R=b==="floating"?{x:o,y:c,width:f.floating.width,height:f.floating.height}:f.reference,k=await(d.getOffsetParent==null?void 0:d.getOffsetParent(p.floating)),A=await(d.isElement==null?void 0:d.isElement(k))&&await(d.getScale==null?void 0:d.getScale(k))||{x:1,y:1},D=zd(d.convertOffsetParentRelativeRectToViewportRelativeRect?await d.convertOffsetParentRelativeRectToViewportRelativeRect({elements:p,rect:R,offsetParent:k,strategy:g}):R);return{top:(E.top-D.top+S.top)/A.y,bottom:(D.bottom-E.bottom+S.bottom)/A.y,left:(E.left-D.left+S.left)/A.x,right:(D.right-E.right+S.right)/A.x}}const uB=50,dB=async(e,t,r)=>{const{placement:o="bottom",strategy:c="absolute",middleware:d=[],platform:f}=r,p=f.detectOverflow?f:{...f,detectOverflow:cB},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}=C1(v,o,g),j=o,w=0;const S={};for(let N=0;NQ<=0)){var z,U;const Q=(((z=d.flip)==null?void 0:z.index)||0)+1,W=M[Q];if(W&&(!(b==="alignment"?R!==Qr(W):!1)||L.every(q=>Qr(q.placement)===R?q.overflows[0]>0:!0)))return{data:{index:Q,overflows:L},reset:{placement:W}};let Z=(U=L.filter(Y=>Y.overflows[0]<=0).sort((Y,q)=>Y.overflows[1]-q.overflows[1])[0])==null?void 0:U.placement;if(!Z)switch(w){case"bestFit":{var B;const Y=(B=L.filter(q=>{if(I){const G=Qr(q.placement);return G===R||G==="y"}return!0}).map(q=>[q.placement,q.overflows.filter(G=>G>0).reduce((G,$)=>G+$,0)]).sort((q,G)=>q[1]-G[1])[0])==null?void 0:B[0];Y&&(Z=Y);break}case"initialPlacement":Z=p;break}if(c!==Z)return{reset:{placement:Z}}}return{}}}},k1=new Set(["left","top"]);async function pB(e,t){const{placement:r,platform:o,elements:c}=e,d=await(o.isRTL==null?void 0:o.isRTL(c.floating)),f=Xr(r),p=bl(r),g=Qr(r)==="y",v=k1.has(f)?-1:1,y=d&&g?-1:1,b=lo(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 mB=function(e){return e===void 0&&(e=0),{name:"offset",options:e,async fn(t){var r,o;const{x:c,y:d,placement:f,middlewareData:p}=t,g=await pB(t,e);return f===((r=p.offset)==null?void 0:r.placement)&&(o=p.arrow)!=null&&o.alignmentOffset?{}:{x:c+g.x,y:d+g.y,data:{...g,placement:f}}}}},hB=function(e){return e===void 0&&(e={}),{name:"shift",options:e,async fn(t){const{x:r,y:o,placement:c,platform:d}=t,{mainAxis:f=!0,crossAxis:p=!1,limiter:g={fn:R=>{let{x:k,y:A}=R;return{x:k,y:A}}},...v}=lo(e,t),y={x:r,y:o},b=await d.detectOverflow(t,v),j=Qr(c),w=Sv(j);let S=y[w],N=y[j];const C=(R,k)=>wk(k+b[R==="y"?"top":"left"],k,k-b[R==="y"?"bottom":"right"]);f&&(S=C(w,S)),p&&(N=C(j,N));const E=g.fn({...t,[w]:S,[j]:N});return{...E,data:{x:E.x-r,y:E.y-o,enabled:{[w]:f,[j]:p}}}}}},gB=function(e){return e===void 0&&(e={}),{options:e,fn(t){var r,o;const{x:c,y:d,placement:f,rects:p,middlewareData:g}=t,{offset:v=0,mainAxis:y=!0,crossAxis:b=!0}=lo(e,t),j={x:c,y:d},w=Qr(f),S=Sv(w);let N=j[S],C=j[w];const E=lo(v,t),R=typeof E=="number"?{mainAxis:E,crossAxis:0}:{mainAxis:(r=E.mainAxis)!=null?r:0,crossAxis:(o=E.crossAxis)!=null?o:0};if(y){const D=S==="y"?"height":"width",I=p.reference[S]-p.floating[D]+R.mainAxis,M=p.reference[S]+p.reference[D]-R.mainAxis;NM&&(N=M)}if(b){var k,A;const D=S==="y"?"width":"height",I=k1.has(Xr(f)),M=p.reference[w]-p.floating[D]+(I&&((k=g.offset)==null?void 0:k[w])||0)+(I?0:R.crossAxis),O=p.reference[w]+p.reference[D]+(I?0:((A=g.offset)==null?void 0:A[w])||0)-(I?R.crossAxis:0);CO&&(C=O)}return{[S]:N,[w]:C}}}},xB=function(e){return e===void 0&&(e={}),{name:"size",options:e,async fn(t){const{placement:r,rects:o,platform:c,elements:d}=t,{apply:f=()=>{},...p}=lo(e,t),g=await c.detectOverflow(t,p),v=Xr(r),y=bl(r),b=Qr(r)==="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 C=w-g.top-g.bottom,E=j-g.left-g.right,R=Vc(w-g[S],C),k=Vc(j-g[N],E),A=t.middlewareData.shift,D=!A;let I=R,M=k;A!=null&&A.enabled.x&&(M=E),A!=null&&A.enabled.y&&(I=C),D&&!y&&(b?M=j-2*gl(g.left,g.right):I=w-2*gl(g.top,g.bottom)),await f({...t,availableWidth:M,availableHeight:I});const O=await c.getDimensions(d.floating);return j!==O.width||w!==O.height?{reset:{rects:!0}}:{}}}};function T1(e){const t=gr(e);let r=parseFloat(t.width)||0,o=parseFloat(t.height)||0;const c=an(e),d=c?e.offsetWidth:r,f=c?e.offsetHeight:o,p=Em(r)!==d||Em(o)!==f;return p&&(r=d,o=f),{width:r,height:o,$:p}}function Gv(e){return Ct(e)?e:e.contextElement}function Qc(e){const t=Gv(e);if(!an(t))return xl(1);const r=t.getBoundingClientRect(),{width:o,height:c,$:d}=T1(t);let f=(d?Em(r.width):r.width)/o,p=(d?Em(r.height):r.height)/c;return(!f||!Number.isFinite(f))&&(f=1),(!p||!Number.isFinite(p))&&(p=1),{x:f,y:p}}const bB=xl(0);function E1(e){const t=bn(e);return!Jb()||!t.visualViewport?bB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function vB(e,t,r){return t===void 0&&(t=!1),!!r&&t&&r===bn(e)}function Ei(e,t,r,o){t===void 0&&(t=!1),r===void 0&&(r=!1);const c=e.getBoundingClientRect(),d=Gv(e);let f=xl(1);t&&(o?Ct(o)&&(f=Qc(o)):f=Qc(e));const p=vB(d,r,o)?E1(d):xl(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=bn(d),w=Ct(o)?bn(o):o;let S=j,N=ev(S);for(;N&&w!==S;){const C=Qc(N),E=N.getBoundingClientRect(),R=gr(N),k=E.left+(N.clientLeft+parseFloat(R.paddingLeft))*C.x,A=E.top+(N.clientTop+parseFloat(R.paddingTop))*C.y;g*=C.x,v*=C.y,y*=C.x,b*=C.y,g+=k,v+=A,S=bn(N),N=ev(S)}}return zd({width:y,height:b,x:g,y:v})}function Fm(e,t){const r=hm(e).scrollLeft;return t?t.left+r:Ei(fl(e)).left+r}function R1(e,t){const r=e.getBoundingClientRect(),o=r.left+t.scrollLeft-Fm(e,r),c=r.top+t.scrollTop;return{x:o,y:c}}function yB(e){let{elements:t,rect:r,offsetParent:o,strategy:c}=e;const d=c==="fixed",f=fl(o),p=t?mm(t.floating):!1;if(o===f||p&&d)return r;let g={scrollLeft:0,scrollTop:0},v=xl(1);const y=xl(0),b=an(o);if((b||!d)&&((_s(o)!=="body"||Md(f))&&(g=hm(o)),b)){const w=Ei(o);v=Qc(o),y.x=w.x+o.clientLeft,y.y=w.y+o.clientTop}const j=f&&!b&&!d?R1(f,g):xl(0);return{width:r.width*v.x,height:r.height*v.y,x:r.x*v.x-g.scrollLeft*v.x+y.x+j.x,y:r.y*v.y-g.scrollTop*v.y+y.y+j.y}}function jB(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function wB(e){const t=hm(e),r=e.ownerDocument.body,o=gl(e.scrollWidth,e.clientWidth,r.scrollWidth,r.clientWidth),c=gl(e.scrollHeight,e.clientHeight,r.scrollHeight,r.clientHeight);let d=-t.scrollLeft+Fm(e);const f=-t.scrollTop;return gr(r).direction==="rtl"&&(d+=gl(e.clientWidth,r.clientWidth)-o),{width:o,height:c,x:d,y:f}}const SB=25;function NB(e,t,r){r===void 0&&(r="viewport");const o=r==="layoutViewport",c=bn(e),d=fl(e),f=c.visualViewport;let p=d.clientWidth,g=d.clientHeight,v=0,y=0;if(f){const j=!Jb()||t==="fixed";o?j||(v=-f.offsetLeft,y=-f.offsetTop):(p=f.width,g=f.height,j&&(v=f.offsetLeft,y=f.offsetTop))}if(Fm(d)<=0){const j=d.ownerDocument,w=j.body,S=getComputedStyle(w),N=j.compatMode==="CSS1Compat"&&parseFloat(S.marginLeft)+parseFloat(S.marginRight)||0,C=Math.abs(d.clientWidth-w.clientWidth-N),E=getComputedStyle(d).scrollbarGutter==="stable both-edges"?C/2:C;E<=SB&&(p-=E)}return{width:p,height:g,x:v,y}}function CB(e,t){const r=Ei(e,!0,t==="fixed"),o=r.top+e.clientTop,c=r.left+e.clientLeft,d=Qc(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 A1(e,t,r){let o;if(t==="viewport"||t==="layoutViewport")o=NB(e,r,t);else if(t==="document")o=wB(fl(e));else if(Ct(t))o=CB(t,r);else{const c=E1(e);o={x:t.x-c.x,y:t.y-c.y,width:t.width,height:t.height}}return zd(o)}function kB(e,t){const r=t.get(e);if(r)return r;let o=Lc(e,[],!1).filter(p=>Ct(p)&&_s(p)!=="body"),c=null;const d=gr(e).position==="fixed";let f=d?Jl(e):e;for(;Ct(f)&&!Wl(f);){const p=gr(f),g=Wb(f),v=c?c.position:d?"fixed":"";!g&&(v==="fixed"||v==="absolute"&&p.position==="static")?o=o.filter(b=>b!==f):c=p,f=Jl(f)}return t.set(e,o),o}function TB(e){let{element:t,boundary:r,rootBoundary:o,strategy:c}=e;const f=[...r==="clippingAncestors"?mm(t)?[]:kB(t,this._c):[].concat(r),o],p=A1(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)}M=!1}try{o=new IntersectionObserver(O,{...I,root:d.ownerDocument})}catch{o=new IntersectionObserver(O,I)}o.observe(e)}const g=bn(e),v=()=>p(r);return g.addEventListener("resize",v),p(!0),()=>{g.removeEventListener("resize",v),f()}}function P1(e,t,r,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=Gv(e),y=c||d?[...v?Lc(v):[],...t?Lc(t):[]]:[];y.forEach(E=>{c&&E.addEventListener("scroll",r),d&&E.addEventListener("resize",r)});const b=v&&p?MB(v,r,d):null;let j=-1,w=null;f&&(w=new ResizeObserver(E=>{let[R]=E;R&&R.target===v&&w&&t&&(w.unobserve(t),cancelAnimationFrame(j),j=requestAnimationFrame(()=>{var k;(k=w)==null||k.observe(t)})),r()}),v&&!g&&w.observe(v),t&&w.observe(t));let S,N=g?Ei(e):null;g&&C();function C(){const E=Ei(e);N&&!I1(N,E)&&r(),N=E,S=requestAnimationFrame(C)}return r(),()=>{var E;y.forEach(R=>{c&&R.removeEventListener("scroll",r),d&&R.removeEventListener("resize",r)}),b?.(),(E=w)==null||E.disconnect(),w=null,g&&cancelAnimationFrame(S)}}const DB=mB,IB=hB,PB=fB,_B=xB,LB=gB,zB=(e,t,r)=>{const o=new Map,c=r??{},d={...D1,...c.platform,_c:o};return dB(e,t,{...c,platform:d})};var BB=typeof document<"u",HB=function(){},qm=BB?x.useLayoutEffect:HB;function Gm(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 r,o,c;if(e&&t&&typeof e=="object"){if(Array.isArray(e)){if(r=e.length,r!==t.length)return!1;for(o=r;o--!==0;)if(!Gm(e[o],t[o]))return!1;return!0}if(c=Object.keys(e),r=c.length,r!==Object.keys(t).length)return!1;for(o=r;o--!==0;)if(!{}.hasOwnProperty.call(t,c[o]))return!1;for(o=r;o--!==0;){const d=c[o];if(!(d==="_owner"&&e.$$typeof)&&!Gm(e[d],t[d]))return!1}return!0}return e!==e&&t!==t}function _1(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function L1(e,t){const r=_1(e);return Math.round(t*r)/r}function Yv(e){const t=x.useRef(e);return qm(()=>{t.current=e}),t}function UB(e){e===void 0&&(e={});const{placement:t="bottom",strategy:r="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:r,placement:t,middlewareData:{},isPositioned:!1}),[j,w]=x.useState(o);Gm(j,o)||w(o);const[S,N]=x.useState(null),[C,E]=x.useState(null),R=x.useCallback(q=>{q!==I.current&&(I.current=q,N(q))},[]),k=x.useCallback(q=>{q!==M.current&&(M.current=q,E(q))},[]),A=d||S,D=f||C,I=x.useRef(null),M=x.useRef(null),O=x.useRef(y),_=g!=null,L=Yv(g),z=Yv(c),U=Yv(v),B=x.useCallback(()=>{if(!I.current||!M.current)return;const q={placement:t,strategy:r,middleware:j};z.current&&(q.platform=z.current),zB(I.current,M.current,q).then(G=>{const $={...G,isPositioned:U.current!==!1};Q.current&&!Gm(O.current,$)&&(O.current=$,ys.flushSync(()=>{b($)}))})},[j,t,r,z,U]);qm(()=>{v===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,b(q=>({...q,isPositioned:!1})))},[v]);const Q=x.useRef(!1);qm(()=>(Q.current=!0,()=>{Q.current=!1}),[]),qm(()=>{if(A&&(I.current=A),D&&(M.current=D),A&&D){if(L.current)return L.current(A,D,B);B()}},[A,D,B,L,_]);const W=x.useMemo(()=>({reference:I,floating:M,setReference:R,setFloating:k}),[R,k]),Z=x.useMemo(()=>({reference:A,floating:D}),[A,D]),Y=x.useMemo(()=>{const q={position:r,left:0,top:0};if(!Z.floating)return q;const G=L1(Z.floating,y.x),$=L1(Z.floating,y.y);return p?{...q,transform:"translate("+G+"px, "+$+"px)",..._1(Z.floating)>=1.5&&{willChange:"transform"}}:{position:r,left:G,top:$}},[r,p,Z.floating,y.x,y.y]);return x.useMemo(()=>({...y,update:B,refs:W,elements:Z,floatingStyles:Y}),[y,B,W,Z,Y])}const VB=(e,t)=>{const r=DB(e);return{name:r.name,fn:r.fn,options:[e,t]}},$B=(e,t)=>{const r=IB(e);return{name:r.name,fn:r.fn,options:[e,t]}},FB=(e,t)=>({fn:LB(e).fn,options:[e,t]}),qB=(e,t)=>{const r=PB(e);return{name:r.name,fn:r.fn,options:[e,t]}},GB=(e,t)=>{const r=_B(e);return{name:r.name,fn:r.fn,options:[e,t]}};var Xv={exports:{}},Qv={};var z1;function KB(){if(z1)return Qv;z1=1;var e=Od();function t(b,j){return b===j&&(b!==0||1/b===1/j)||b!==b&&j!==j}var r=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,C=S[1];return d(function(){N.value=w,N.getSnapshot=j,g(N)&&C({inst:N})},[b,w,j]),c(function(){return g(N)&&C({inst:N}),b(function(){g(N)&&C({inst:N})})},[b]),f(w),w}function g(b){var j=b.getSnapshot;b=b.value;try{var w=j();return!r(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 Qv.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:y,Qv}var B1;function H1(){return B1||(B1=1,Xv.exports=KB()),Xv.exports}var Zv=H1(),Wv={exports:{}},Jv={};var U1;function YB(){if(U1)return Jv;U1=1;var e=Od(),t=H1();function r(v,y){return v===y&&(v!==0||1/v===1/y)||v!==v&&y!==y}var o=typeof Object.is=="function"?Object.is:r,c=t.useSyncExternalStore,d=e.useRef,f=e.useEffect,p=e.useMemo,g=e.useDebugValue;return Jv.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(!R){if(R=!0,k=I,I=j(I),w!==void 0&&N.hasValue){var M=N.value;if(w(M,I))return A=M}return A=I}if(M=A,o(k,I))return M;var O=j(I);return w!==void 0&&w(M,O)?(k=I,M):(k=I,A=O)}var R=!1,k,A,D=b===void 0?null:b;return[function(){return E(y())},D===null?void 0:function(){return E(D())}]},[y,b,j,w]);var C=c(v,S[0],S[1]);return f(function(){N.hasValue=!0,N.value=C},[C]),g(C),C},Jv}var V1;function XB(){return V1||(V1=1,Wv.exports=YB()),Wv.exports}var QB=XB();const ZB=ov(19)?JB:eH;function $1(e,t,r,o,c){return ZB(e,t,r,o,c)}function WB(e,t,r,o,c){const d=x.useCallback(()=>t(e.getSnapshot(),r,o,c),[e,t,r,o,c]);return Zv.useSyncExternalStore(e.subscribe,d,d)}B4({before(e){e.syncIndex=0,e.didInitialize||(e.syncTick=1,e.syncHooks=[],e.didChangeStore=!0,e.getSnapshot=()=>{let t=!1;for(let r=0;r0&&(e.didChangeStore&&(e.didChangeStore=!1,e.subscribe=t=>{const r=new Set;for(const c of e.syncHooks)r.add(c.store);const o=[];for(const c of r)o.push(c.subscribe(t));return()=>{for(const c of o)c()}}),Zv.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot))}});function JB(e,t,r,o,c){const d=z4();if(!d)return WB(e,t,r,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,r)||!Object.is(p.a2,o)||!Object.is(p.a3,c))&&(p.store!==e&&(d.didChangeStore=!0),p.store=e,p.selector=t,p.a1=r,p.a2=o,p.a3=c,p.value=t(e.getSnapshot(),r,o,c))):(p={store:e,selector:t,a1:r,a2:o,a3:c,value:t(e.getSnapshot(),r,o,c)},d.syncHooks.push(p)),p.value}function eH(e,t,r,o,c){return QB.useSyncExternalStoreWithSelector(e.subscribe,e.getSnapshot,e.getSnapshot,d=>t(d,r,o,c))}class tH{constructor(t){tn(this,"subscribe",t=>(this.listeners.add(t),()=>{this.listeners.delete(t)}));tn(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 r=this.updateTick;for(const o of this.listeners){if(r!==this.updateTick)return;o(t)}}update(t){for(const r in t)if(!Object.is(this.state[r],t[r])){this.setState({...this.state,...t});return}}set(t,r){Object.is(this.state[t],r)||this.setState({...this.state,[t]:r})}notifyAll(){const t={...this.state};this.setState(t)}use(t,r,o,c){return $1(this,t,r,o,c)}}class Zc extends tH{constructor(t,r={},o){super(t),this.context=r,this.selectors=o}useSyncedValue(t,r){x.useDebugValue(t);const o=this;De(()=>{o.state[t]!==r&&o.set(t,r)},[o,t,r])}useSyncedValueWithCleanup(t,r){const o=this;De(()=>(o.state[t]!==r&&o.set(t,r),()=>{o.set(t,void 0)}),[o,t,r])}useSyncedValues(t){const r=this,o=Object.values(t);De(()=>{r.update(t)},[r,...o])}useControlledProp(t,r){x.useDebugValue(t);const o=this,c=r!==void 0;De(()=>{c&&!Object.is(o.state[t],r)&&o.setState({...o.state,[t]:r})},[o,t,r,c])}select(t,r,o,c){const d=this.selectors[t];return d(this.state,r,o,c)}useState(t,r,o,c){return x.useDebugValue(t),$1(this,this.selectors[t],r,o,c)}useContextCallback(t,r){x.useDebugValue(t);const o=Ie(r??Bt);this.context[t]=o}useStateSetter(t){const r=x.useRef(void 0);return r.current===void 0&&(r.current=o=>{this.set(t,o)}),r.current}observe(t,r){let o;typeof t=="function"?o=t:o=this.selectors[t];let c=o(this.state);return r(c,c,this),this.subscribe(d=>{const f=o(d);if(!Object.is(c,f)){const p=c;c=f,r(f,p,this)}})}}const nH={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 ey extends Zc{constructor(r){const{syncOnly:o,nested:c,onOpenChange:d,triggerElements:f,...p}=r;super({...p,positionReference:p.referenceElement,domReferenceElement:p.referenceElement},{onOpenChange:d,dataRef:{current:{}},events:x1(),nested:c,triggerElements:f},nH);tn(this,"syncOpenEvent",(r,o)=>{(!r||!this.state.open||o!=null&&Dz(o))&&(this.context.dataRef.current.openEvent=r?o:void 0)});tn(this,"dispatchOpenChange",(r,o)=>{this.syncOpenEvent(r,o.event);const c={open:r,reason:o.reason,nativeEvent:o.event,nested:this.context.nested,triggerElement:o.trigger};this.context.events.emit("openchange",c)});tn(this,"setOpen",(r,o)=>{if(this.syncOnly){this.context.onOpenChange?.(r,o);return}this.dispatchOpenChange(r,o),this.context.onOpenChange?.(r,o)});this.syncOnly=o}}function sH(e){const{popupStore:t,treatPopupAsFloatingElement:r=!1,floatingRootContext:o,floatingId:c,nested:d,onOpenChange:f}=e,p=t.useState("open"),g=t.useState("activeTriggerElement"),v=t.useState(r?"popupElement":"positionerElement"),y=t.context.triggerElements,b=f,j=x.useRef(null);o===void 0&&j.current===null&&(j.current=new ey({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};Ct(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 Qd={tabIndex:-1,[mv]:""};function F1(e){return t=>t==="touch"?e.current:!0}function ty(e,t=!1){const r=Pd(),o=Xc()!=null,c=Ts(()=>e(r,o)).current;return sH({popupStore:c,treatPopupAsFloatingElement:t,floatingRootContext:c.state.floatingRootContext,floatingId:r,nested:o,onOpenChange:c.setOpen}),c}function ny({handle:e,store:t}){return De(()=>e.attachStore(t),[e,t]),null}function q1(e){const t=e.context.triggerElements.size;e.select("open")&&e.state.triggerCount!==t&&e.set("triggerCount",t)}function rH(e,t){const r=x.useRef(null);return Ie(o=>{const c=r.current;if(c!==null){if(c.element===o&&c.store===t&&c.id===e)return;r.current=null;const d=c.store;d.context.triggerElements.getById(c.id)===c.element&&(d.context.triggerElements.delete(c.id),q1(d))}o!==null&&e!==void 0&&(r.current={store:t,id:e,element:o},t.context.triggerElements.add(e,o),q1(t))})}function sy(e,t,r,o=!1){let c=e.preventUnmountingOnClose;t?c=!1:o&&(c=!0);const d=r?.id??null;let f=e.activeTriggerId,p=e.activeTriggerElement;return(d||t)&&(f=d,p=r??null),{open:t,preventUnmountingOnClose:c,activeTriggerId:f,activeTriggerElement:p}}function G1(e){let t=!1;return e.preventUnmountOnClose=()=>{t=!0},()=>t}function aH(e,t,r,o={}){const c=r.reason,d=c===zs,f=t&&c===_m,p=!t&&(c===co||c===Gc),g=G1(r);if(e.context.onOpenChange?.(t,r),r.isCanceled)return;o.onBeforeDispatch?.(),e.state.floatingRootContext.dispatchOpenChange(t,r);const v=()=>{const y=sy(e.state,t,r.trigger,g()),b={...o.extraState,...y};f?b.instantType="focus":p?b.instantType="dismiss":d&&(b.instantType=void 0),e.update(b)};d?ys.flushSync(v):v()}function K1(e,t,r,o){const c=r.useState("isMountedByTrigger",e),d=rH(e,r),f=Ie(g=>{const v=r.select("open"),y=r.select("activeTriggerId");if(y===e){const b={activeTriggerElement:g,...v?o:null};r.update(b);return}if(y==null&&v){const b={activeTriggerId:e??null,activeTriggerElement:g,...o};r.update(b)}}),p=Ie(g=>{d(g),g&&f(g)});return De(()=>(p(t.current),()=>p(null)),[p,t,r,e]),De(()=>{if(c){const g={activeTriggerElement:t.current,...o};r.update(g)}},[c,r,t,...Object.values(o)]),{registerTrigger:p,isMountedByThisTrigger:c}}function ry(e,t={}){const{closeOnActiveTriggerUnmount:r=!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&&r&&queueMicrotask(()=>{if(e.select("open")&&e.select("activeTriggerId")===b&&!e.context.triggerElements.getById(b)){const j=Ve(Fn);e.setOpen(!1,j),j.isCanceled||e.update({activeTriggerId:null,activeTriggerElement:null})}})},[c,e,d,f,p,r])}function ay(e,t,r,o){const{mounted:c,setMounted:d,transitionStatus:f}=yi(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}),r?.(),t.context.onOpenChangeComplete?.(!1)});return Wr({enabled:c&&!e&&!g,open:e,ref:t.context.popupRef,onComplete(){e||v()}}),{forceUnmount:v,transitionStatus:f}}function ly(e,t){e.useSyncedValues(t),De(()=>()=>{e.update({activeTriggerProps:ln,inactiveTriggerProps:ln,popupProps:ln})},[e])}function Y1(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 Km{constructor(){this.idMap=new Map}add(t,r){this.idMap.set(t,r)}delete(t){this.idMap.delete(t)}hasElement(t){for(const r of this.idMap.values())if(r===t)return!0;return!1}hasMatchingElement(t){for(const r of this.idMap.values())if(t(r))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 oy(e,t,r=!1){return{open:!1,openProp:void 0,mounted:!1,transitionStatus:void 0,floatingRootContext:new ey({open:!1,transitionStatus:void 0,floatingElement:null,referenceElement:null,triggerElements:e,floatingId:t,syncOnly:!0,nested:r,onOpenChange:void 0}),floatingId:t,triggerCount:0,preventUnmountingOnClose:!1,payload:void 0,activeTriggerId:null,activeTriggerElement:null,triggerIdProp:void 0,popupElement:null,positionerElement:null,activeTriggerProps:ln,inactiveTriggerProps:ln,popupProps:ln}}const Zd=e=>e.triggerIdProp??e.activeTriggerId,iy=e=>e.openProp??e.open,X1=e=>(e.popupElement?.id??e.floatingId)||void 0;function Q1(e,t){return t!==void 0&&iy(e)&&Zd(e)===t}function lH(e,t){return Q1(e,t)?!0:t!==void 0&&iy(e)&&Zd(e)==null&&e.triggerCount===1}const cy={open:iy,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:Zd,activeTriggerElement:e=>e.mounted?e.activeTriggerElement:null,popupId:X1,isTriggerActive:(e,t)=>t!==void 0&&Zd(e)===t,isOpenedByTrigger:(e,t)=>Q1(e,t),isMountedByTrigger:(e,t)=>t!==void 0&&Zd(e)===t&&e.mounted,triggerProps:(e,t)=>t?e.activeTriggerProps:e.inactiveTriggerProps,triggerPopupId:(e,t)=>lH(e,t)?X1(e):void 0,popupProps:e=>e.popupProps,popupElement:e=>e.popupElement,positionerElement:e=>e.positionerElement};function Z1(e){const t=x.useCallback(o=>e===void 0?Bt:e.subscribeStore(o),[e]),r=x.useCallback(()=>e===void 0?void 0:e.store,[e]);return Zv.useSyncExternalStore(t,r,()=>e?.serverStore)}function W1(e){const{open:t=!1,onOpenChange:r,elements:o={}}=e,c=Pd(),d=Xc()!=null,f=Ts(()=>new ey({open:t,transitionStatus:void 0,onOpenChange:r,referenceElement:o.reference??null,floatingElement:o.floating??null,triggerElements:new Km,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=Ct(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=r,f.context.nested=d,f}function oH(e){return iH(e,e.rootContext)}function iH(e,t){const{nodeId:r,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),C=Ti(o),E=x.useMemo(()=>({reference:c,floating:d,domReference:f}),[c,d,f]),R=UB({...e,elements:{...E,...v&&{reference:v}}}),k=Ct(b)?b:null,A=w===void 0?t.state.floatingElement:w;t.useSyncedValue("referenceElement",b??null),t.useSyncedValue("domReferenceElement",b===void 0?f:k),t.useSyncedValue("floatingElement",A);const D=x.useCallback(z=>{const U=Ct(z)?{getBoundingClientRect:()=>z.getBoundingClientRect(),getClientRects:()=>z.getClientRects(),contextElement:z}:z;y(U),R.refs.setReference(U)},[R.refs]),I=x.useCallback(z=>{(Ct(z)||z===null)&&(N.current=z,j(z)),(Ct(R.refs.reference.current)||R.refs.reference.current===null||z!==null&&!Ct(z))&&R.refs.setReference(z)},[R.refs,j]),M=x.useCallback(z=>{S(z),R.refs.setFloating(z)},[R.refs]),O=x.useMemo(()=>({...R.refs,setReference:I,setFloating:M,setPositionReference:D,domReference:N}),[R.refs,I,M,D]),_=x.useMemo(()=>({...R.elements,domReference:f}),[R.elements,f]),L=x.useMemo(()=>({...R,dataRef:t.context.dataRef,open:p,onOpenChange:t.setOpen,events:t.context.events,floatingId:g,refs:O,elements:_,nodeId:r,rootStore:t}),[R,O,_,r,t,p,g]);return De(()=>{f&&(N.current=f)},[f]),De(()=>{t.context.dataRef.current.floatingContext=L;const z=C?.nodesRef.current.find(U=>U.id===r);z&&(z.context=L)}),x.useMemo(()=>({...R,context:L,refs:O,elements:_,rootStore:t}),[R,O,_,L,t])}const uy=gk&&hl;function cH(e,t={}){const{enabled:r=!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=Xs();x.useEffect(()=>{const j=c.select("domReferenceElement");if(!r)return;const w=bn(j);function S(){const E=c.select("domReferenceElement");!c.select("open")&&an(E)&&E===ar(zt(E))&&(p.current=!0,g.current=E)}function N(){v.current=!0}function C(){v.current=!1}return qa(jt(w,"blur",S),uy&&jt(w,"keydown",N,!0),uy&&jt(w,"pointerdown",C,!0))},[c,r]),x.useEffect(()=>{if(!r)return;function j(w){if(w.reason===co||w.reason===Gc){const S=c.select("domReferenceElement");Ct(S)&&(g.current=S,p.current=!0)}}return d.on("openchange",j),()=>{d.off("openchange",j)}},[d,r,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=ns(w.nativeEvent);if(Ct(N)){if(uy&&!w.relatedTarget){if(!v.current&&!Cm(N))return}else if(!Oz(N))return}const C=Nm(w.relatedTarget,c.context.triggerElements),{nativeEvent:E,currentTarget:R}=w,k=typeof o=="function"?o():o;if(c.select("open")&&C||k===0||k===void 0){c.setOpen(!0,Ve(_m,E,R));return}y.start(k,()=>{p.current||c.setOpen(!0,Ve(_m,E,R))})},onBlur(w){j();const S=w.relatedTarget,N=w.nativeEvent,C=Ct(S)&&S.hasAttribute(Kd("focus-guard"))&&S.getAttribute("data-type")==="outside";y.start(0,()=>{const E=c.select("domReferenceElement"),R=ar(zt(E));!S&&R===E||Ge(f.current.floatingContext?.refs.floating.current,R)||Ge(E,R)||C||Nm(S??R,c.context.triggerElements)||c.setOpen(!1,Ve(_m,N))})}}},[f,o,c,y]);return x.useMemo(()=>r?{reference:b,trigger:b}:{},[r,b])}class dy{constructor(){tn(this,"dispose",()=>{this.openChangeTimeout.clear(),this.restTimeout.clear()});tn(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 Zr,this.restTimeout=new Zr,this.handleCloseOptions=void 0}static create(){return new dy}}const Ym=new WeakMap;function Xm(e){if(!e.performedPointerEventsMutation)return;const t=e.pointerEventsScopeElement;t&&Ym.get(t)===e&&(e.pointerEventsScopeElement?.style.removeProperty("pointer-events"),e.pointerEventsReferenceElement?.style.removeProperty("pointer-events"),e.pointerEventsFloatingElement?.style.removeProperty("pointer-events"),Ym.delete(t)),e.performedPointerEventsMutation=!1,e.pointerEventsScopeElement=null,e.pointerEventsReferenceElement=null,e.pointerEventsFloatingElement=null}function J1(e,t){const{scopeElement:r,referenceElement:o,floatingElement:c}=t,d=Ym.get(r);d&&d!==e&&Xm(d),Xm(e),e.performedPointerEventsMutation=!0,e.pointerEventsScopeElement=r,e.pointerEventsReferenceElement=o,e.pointerEventsFloatingElement=c,Ym.set(r,e),r.style.pointerEvents="none",o.style.pointerEvents="auto",c.style.pointerEvents="auto"}function fy(e){const t=e.context.dataRef.current,r=Ts(()=>t.hoverInteractionState??dy.create()).current;return t.hoverInteractionState||(t.hoverInteractionState=r),Mv(t.hoverInteractionState.disposeEffect),t.hoverInteractionState}function eT(e,t={}){const{enabled:r=!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=Ti(),b=Xc(),j=fy(d),w=Xs(),S=Ie(()=>s1(v.current.openEvent?.type,j.interactedInside)),N=Ie(()=>V4(v.current.openEvent?.type)),C=Ie(()=>{Xm(j)});De(()=>{f||(j.pointerType=void 0,j.restTimeoutPending=!1,j.interactedInside=!1,C())},[f,j,C]),x.useEffect(()=>C,[C]),De(()=>{if(r&&f&&j.handleCloseOptions?.blockPointerEvents&&N()&&Ct(g)&&p){const E=g,R=p,k=zt(p),A=y?.nodesRef.current.find(O=>O.id===b)?.context?.elements.floating;A&&(A.style.pointerEvents="");const D=j.pointerEventsScopeElement!==R?j.pointerEventsScopeElement:null,I=A!==R?A:null,M=j.handleCloseOptions?.getScope?.()??D??I??E.closest("[data-rootownerid]")??k.body;return J1(j,{scopeElement:M,referenceElement:E,floatingElement:R}),()=>{C()}}},[r,f,g,p,j,N,y,b,C]),x.useEffect(()=>{if(!r)return;function E(){return!!(y&&b&&ro(y.nodesRef.current,b).length>0)}function R(O){const _=ki(o,"close",j.pointerType),L=()=>{d.setOpen(!1,Ve(zs,O)),y?.events.emit("floating.closed",O)};_?j.openChangeTimeout.start(_,L):(j.openChangeTimeout.clear(),L())}function k(O){const _=ns(O);if(!Az(_)){j.interactedInside=!1;return}j.interactedInside=_?.closest("[aria-haspopup]")!=null}function A(){j.openChangeTimeout.clear(),w.clear(),y?.events.off("floating.closed",I),C()}function D(O){if(E()&&y){y.events.on("floating.closed",I);return}if(Nm(O.relatedTarget,d.context.triggerElements))return;const _=v.current.floatingContext?.nodeId??c,L=O.relatedTarget;if(!(y&&_&&Ct(L)&&ro(y.nodesRef.current,_,!1).some(U=>Ge(U.context?.elements.floating,L)))){if(j.handler){j.handler(O);return}C(),N()&&!S()&&R(O)}}function I(O){!y||!b||E()||w.start(0,()=>{y.events.off("floating.closed",I),d.setOpen(!1,Ve(zs,O)),y.events.emit("floating.closed",O)})}const M=p;return qa(M&&jt(M,"mouseenter",A),M&&jt(M,"mouseleave",D),M&&jt(M,"pointerdown",k,!0),()=>{y?.events.off("floating.closed",I)})},[r,p,d,v,o,c,N,S,C,j,y,b,w])}const uH={current:null};function tT(e,t={}){const{enabled:r=!0,delay:o=0,handleClose:c=null,mouseOnly:d=!1,restMs:f=0,move:p=!0,triggerElementRef:g=uH,externalTree:v,isActiveTrigger:y=!0,getHandleCloseContext:b,isClosing:j,shouldOpen:w,guardStaleOpen:S=!1}=t,N="rootStore"in e?e.rootStore:e,{dataRef:C,events:E}=N.context,R=Ti(v),k=fy(N),A=x.useRef(!1),D=qn(c),I=qn(o),M=qn(f),O=qn(r),_=qn(w),L=qn(j),z=Ie(()=>s1(C.current.openEvent?.type,k.interactedInside)),U=Ie(()=>_.current?.()!==!1),B=Ie((Z,Y,q)=>{const G=N.context.triggerElements;if(G.hasElement(Y))return!Z||!Ge(Z,Y);if(!Ct(q))return!1;const $=q;return G.hasMatchingElement(F=>Ge(F,$))&&(!Z||!Ge(Z,$))}),Q=Ie(()=>{if(!k.handler)return;zt(N.select("domReferenceElement")).removeEventListener("mousemove",k.handler),k.handler=void 0}),W=Ie(()=>{Xm(k)});return y&&(k.handleCloseOptions=c?.__options),x.useEffect(()=>Q,[Q]),x.useEffect(()=>{if(!r)return;function Z(Y){Y.open?A.current=!1:(A.current=Y.reason===zs,Q(),k.openChangeTimeout.clear(),k.restTimeout.clear(),k.blockMouseMove=!0,k.restTimeoutPending=!1)}return E.on("openchange",Z),()=>{E.off("openchange",Z)}},[r,E,k,Q]),x.useEffect(()=>{if(!r)return;function Z(X,re=!0){const P=ki(I.current,"close",k.pointerType);P?k.openChangeTimeout.start(P,()=>{N.setOpen(!1,Ve(zs,X)),R?.events.emit("floating.closed",X)}):re&&(k.openChangeTimeout.clear(),N.setOpen(!1,Ve(zs,X)),R?.events.emit("floating.closed",X))}const Y=g.current??(y?N.select("domReferenceElement"):null);if(!Ct(Y))return;function q(X){if(k.openChangeTimeout.clear(),k.blockMouseMove=!1,d&&!ao(k.pointerType))return;const re=n1(M.current),P=ki(I.current,"open",k.pointerType),V=ns(X),J=X.currentTarget??null,ie=N.select("domReferenceElement");let me=J;if(Ct(V)&&!N.context.triggerElements.hasElement(V)){for(const ce of N.context.triggerElements.elements())if(Ge(ce,V)){me=ce;break}}Ct(J)&&Ct(ie)&&!N.context.triggerElements.hasElement(J)&&Ge(J,ie)&&(me=ie);const he=me==null?!1:B(ie,me,V),ae=N.select("open"),oe=L.current?.()??N.select("transitionStatus")==="ending",ee=!ae&&oe&&A.current,de=!he&&Ct(me)&&Ct(ie)&&Ge(ie,me)&&ee,K=re>0&&!P,be=he&&(ae||ee)||de,ne=!ae||he;if(be){U()&&N.setOpen(!0,Ve(zs,X,me));return}K||(P?k.openChangeTimeout.start(P,()=>{ne&&U()&&N.setOpen(!0,Ve(zs,X,me))}):ne&&U()&&N.setOpen(!0,Ve(zs,X,me)))}function G(X){if(z()){W();return}Q();const re=N.select("domReferenceElement"),P=zt(re);k.restTimeout.clear(),k.restTimeoutPending=!1;const V=C.current.floatingContext??b?.();if(Nm(X.relatedTarget,N.context.triggerElements))return;if(D.current&&V){N.select("open")||k.openChangeTimeout.clear();const ie=g.current;k.handler=D.current({...V,tree:R,x:X.clientX,y:X.clientY,onClose(){W(),Q(),O.current&&!z()&&ie===N.select("domReferenceElement")&&Z(X,!0)}}),P.addEventListener("mousemove",k.handler),k.handler(X);return}(k.pointerType!=="touch"||!Ge(N.select("floatingElement"),X.relatedTarget))&&Z(X)}function $(X){Ge(Y,X.relatedTarget)||(k.openChangeTimeout.clear(),k.restTimeout.clear(),k.restTimeoutPending=!1)}const F=S?jt(Y,"mouseout",$):void 0;return p?qa(jt(Y,"mousemove",q,{once:!0}),jt(Y,"mouseenter",q),jt(Y,"mouseleave",G),F):qa(jt(Y,"mouseenter",q),jt(Y,"mouseleave",G),F)},[Q,W,C,I,N,r,D,k,y,B,z,d,p,M,g,R,O,b,L,U,S]),x.useMemo(()=>{if(!r)return;function Z(Y){k.pointerType=Y.pointerType}return{onPointerDown:Z,onPointerEnter:Z,onMouseMove(Y){const{nativeEvent:q}=Y,G=Y.currentTarget,$=N.select("domReferenceElement"),F=N.select("open"),X=B($,G,Y.target);if(d&&!ao(k.pointerType))return;if(F&&X&&k.handleCloseOptions?.blockPointerEvents){const V=N.select("floatingElement");if(V){const J=k.handleCloseOptions?.getScope?.()??G.ownerDocument.body;J1(k,{scopeElement:J,referenceElement:G,floatingElement:V})}}const re=n1(M.current);if(F&&!X||re===0||!X&&k.restTimeoutPending&&Y.movementX**2+Y.movementY**2<2)return;k.restTimeout.clear();function P(){if(k.restTimeoutPending=!1,z())return;const V=N.select("open");!k.blockMouseMove&&(!V||X)&&U()&&N.setOpen(!0,Ve(zs,q,G))}k.pointerType==="touch"?ys.flushSync(()=>{P()}):X&&F?P():(k.restTimeoutPending=!0,k.restTimeout.start(re,P))}}},[r,k,z,B,d,N,M,U])}const dH="Escape";function nT(e){return hl&&e.movementX===0&&e.movementY===0}function Qm(e,t,r){switch(e){case"vertical":return t;case"horizontal":return r;default:return t||r}}function Zm(e,t){return Qm(t,e===hv||e===Sm,e===xi||e===bi)}function py(e,t,r){return Qm(t,e===Sm,r?e===xi:e===bi)||e==="Enter"||e===" "||e===""}function fH(e,t,r){return Qm(t,r?e===xi:e===bi,e===Sm)}function pH(e,t,r,o){const c=r?e===bi:e===xi,d=e===hv;return t==="both"||t==="horizontal"&&o?e===dH:Qm(t,c,d)}function sT(e,t){const{listRef:r,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:C="vertical",parentOrientation:E,id:R,resetOnPointerLeave:k=!0,externalTree:A,grid:D}=t,I=D!=null,M="rootStore"in e?e.rootStore:e,O=M.useState("open"),_=M.useState("floatingElement"),L=M.useState("domReferenceElement"),z=M.context.dataRef,U=km(_),B=jv(L),Q=qn(U),W=Xc(),Z=Ti(A),Y=x.useRef(j),q=x.useRef(f??-1),G=x.useRef(null),$=x.useRef(!0),F=Ie(ge=>{c(q.current===-1?null:q.current,ge)}),X=x.useRef(!!_),re=x.useRef(O),P=x.useRef(!1),V=x.useRef(!1),J=x.useRef(null),ie=qn(N),me=qn(O),he=qn(f),ae=qn(k),oe=Fc(),ee=Fc(),de=Ie(()=>{function ge(Be){b?Z?.events.emit("virtualfocus",Be):J.current=Hm(Be,{sync:P.current,preventScroll:!0})}const Te=r.current[q.current],Oe=V.current;Te&&ge(Te),(P.current?Be=>Be():Be=>oe.request(Be))(()=>{const Be=r.current[q.current]||Te;if(!Be)return;Te||ge(Be),Ee&&(Oe||!$.current)&&Be.scrollIntoView?.({block:"nearest",inline:"nearest"})})});De(()=>{z.current.orientation=C},[z,C]),De(()=>{d&&(O&&_?(q.current=f??-1,Y.current&&f!=null&&(V.current=!0,F())):X.current&&(q.current=-1,F()))},[d,O,_,f,F]),De(()=>{if(d){if(!O){P.current=!1;return}if(_)if(o==null){if(P.current=!1,he.current!=null)return;if(X.current&&(q.current=-1,de()),(!re.current||!X.current)&&Y.current&&(G.current!=null||Y.current===!0&&G.current==null)){let ge=0;const Te=()=>{r.current[0]==null?(ge<2&&(ge?Ne=>ee.request(Ne):queueMicrotask)(Te),ge+=1):(q.current=G.current==null||py(G.current,C,y)||v?Om(r):Tv(r),G.current=null,F())};Te()}}else oo(r.current,o)||(q.current=o,de(),V.current=!1)}},[d,O,_,o,he,v,r,C,y,F,de,ee]),De(()=>{if(!d||_||!Z||b||!X.current)return;const ge=Z.nodesRef.current,Te=ge.find(Be=>Be.id===W)?.context?.elements.floating,Oe=ar(zt(L??Te??null)),Ne=ge.some(Be=>Be.context&&Ge(Be.context.elements.floating,Oe));Te&&!Ne&&$.current&&Te.focus({preventScroll:!0})},[d,_,L,Z,W,b]),De(()=>{re.current=O,X.current=!!_}),De(()=>{O||(G.current=null,Y.current=j)},[O,j]);const K=o!=null,be=Ie(ge=>{if(!me.current)return;const Te=r.current.indexOf(ge.currentTarget);Te!==-1&&(q.current!==Te||o!==Te)&&(q.current=Te,F(ge))}),ne=Ie(()=>E??Z?.nodesRef.current.find(ge=>ge.id===W)?.context?.dataRef?.current.orientation),ce=Ie(()=>Om(r,ie.current)),we=Ie(ge=>{if($.current=!1,P.current=!0,ge.which===229||!me.current&&ge.currentTarget===Q.current)return;if(v&&pH(ge.key,C,y,I)){Zm(ge.key,ne())||vs(ge),M.setOpen(!1,Ve(Pv,ge.nativeEvent)),an(L)&&(b?Z?.events.emit("virtualfocus",L):L.focus());return}const Te=q.current,Oe=Om(r,N),Ne=Tv(r,N);if(B||(ge.key==="Home"&&(vs(ge),q.current=Oe,F(ge)),ge.key==="End"&&(vs(ge),q.current=Ne,F(ge))),D!=null){const Be=D(ge,q.current,r,C,g,y,N,Oe,Ne);if(Be!=null&&(q.current=Be,F(ge)),C==="both")return}if(Zm(ge.key,C)){if(vs(ge),O&&!b&&ar(ge.currentTarget.ownerDocument)===ge.currentTarget){q.current=py(ge.key,C,y)?Oe:Ne,F(ge);return}py(ge.key,C,y)?g?Te>=Ne?p&&Te!==r.current.length?q.current=-1:(P.current=!1,q.current=Oe):q.current=Es(r.current,{startingIndex:Te,disabledIndices:N}):q.current=Math.min(Ne,Es(r.current,{startingIndex:Te,disabledIndices:N})):g?Te<=Oe?p&&Te!==-1?q.current=r.current.length:(P.current=!1,q.current=Ne):q.current=Es(r.current,{startingIndex:Te,decrement:!0,disabledIndices:N}):q.current=Math.max(Oe,Es(r.current,{startingIndex:Te,decrement:!0,disabledIndices:N})),oo(r.current,q.current)&&(q.current=-1),F(ge)}}),Ee=x.useMemo(()=>({onFocus(Te){P.current=!0,be(Te)},onClick:({currentTarget:Te})=>Te.focus({preventScroll:!0}),onMouseMove(Te){nT(Te)||(P.current=!0,V.current=!1,w&&be(Te))},onPointerLeave(Te){if(!me.current||!$.current||Te.pointerType==="touch")return;P.current=!0;const Oe=Te.relatedTarget;if(!(!w||r.current.includes(Oe))&&ae.current&&(J.current?.(),J.current=null,q.current=-1,F(Te),!b)){const Ne=Q.current,Be=ar(zt(Ne));Ne&&Ge(Ne,Be)&&Ne.focus({preventScroll:!0})}}}),[be,me,Q,w,r,F,ae,b]),ve=x.useMemo(()=>b&&O&&K&&{"aria-activedescendant":`${R}-${o}`},[b,O,K,R,o]),Ce=x.useMemo(()=>({...B?{}:ve,onKeyDown(ge){if(ge.key==="Tab"&&ge.shiftKey&&O&&!b){const Te=ns(ge.nativeEvent);if(Te&&!Ge(Q.current,Te))return;vs(ge),M.setOpen(!1,Ve(uo,ge.nativeEvent)),an(L)&&L.focus();return}we(ge)},onPointerMove(ge){nT(ge)||($.current=!0)}}),[ve,we,Q,B,M,O,b,L]),ke=x.useMemo(()=>{function ge(Ne){M.setOpen(!0,Ve(Pv,Ne.nativeEvent,Ne.currentTarget))}function Te(Ne){j==="auto"&&Tm(Ne.nativeEvent)&&(Y.current=!b)}function Oe(Ne){Y.current=j,j==="auto"&&wv(Ne.nativeEvent)&&(Y.current=!0)}return{onKeyDown(Ne){const Be=M.select("open");$.current=!1;const Xe=Ne.key.startsWith("Arrow"),Rt=fH(Ne.key,ne(),y),Qt=Zm(Ne.key,C),Mt=(v?Rt:Qt)||Ne.key==="Enter"||Ne.key.trim()==="";if(b&&Be)return we(Ne);if(!(!Be&&!S&&Xe)){if(Mt){const it=Zm(Ne.key,ne());G.current=v&&it?null:Ne.key}if(v){Rt&&(vs(Ne),Be?(q.current=ce(),F(Ne)):ge(Ne));return}Qt&&(he.current!=null&&(q.current=he.current),vs(Ne),!Be&&S?ge(Ne):we(Ne),Be&&F(Ne))}},onFocus(Ne){M.select("open")&&!b&&(q.current=-1,F(Ne))},onPointerDown:Oe,onPointerEnter:Oe,onMouseDown:Te,onClick:Te}},[we,j,ce,v,F,M,S,C,ne,y,he,b]),Se=x.useMemo(()=>({...ve,...ke}),[ve,ke]);return x.useMemo(()=>d?{reference:Se,floating:Ce,item:Ee,trigger:ke}:{},[d,Se,Ce,ke,Ee])}function rT(e,t){const{listRef:r,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=Xs(),S=x.useRef(""),N=x.useRef(y??c??-1),C=x.useRef(null),E=Ie(A=>{function D(Q){return o?.current[Q]}function I(Q){const W=D(Q);return W&&!Mm(W)||W?.matches(":disabled")?!1:f==null||!io(Er,Q,f)}function M(Q,W,Z=0){if(Q.length===0)return-1;const Y=(Z%Q.length+Q.length)%Q.length,q=W.toLowerCase();for(let G=0;G0&&A.key===" "&&(vs(A),p?.(!0)),S.current.length>0&&S.current[0]!==" "&&M(O,S.current)===-1&&A.key!==" "&&p?.(!1),O==null||A.key.length!==1||A.ctrlKey||A.metaKey||A.altKey)return;j&&A.key!==" "&&(vs(A),p?.(!0));const _=S.current==="";_&&(N.current=y??c??-1),O.every((Q,W)=>Q&&I(W)?Q[0]?.toLowerCase()!==Q[1]?.toLowerCase():!0)&&S.current===A.key&&(S.current="",N.current=C.current),S.current+=A.key,w.start(v,()=>{S.current="",N.current=C.current,p?.(!1)});const U=((_?y??c??-1:N.current)??0)+1,B=M(O,S.current,U);B!==-1?(d?.(B),C.current=B):A.key!==" "&&(S.current="",p?.(!1))}),R=Ie(A=>{const D=A.relatedTarget,I=b.select("domReferenceElement"),M=b.select("floatingElement");Ge(I,D)||Ge(M,D)||(w.clear(),S.current="",N.current=C.current,p?.(!1))});De(()=>{!j&&y!==null||(w.clear(),C.current=null,S.current!==""&&(S.current=""))},[j,y,w]);const k=x.useMemo(()=>({onKeyDown:E,onBlur:R}),[E,R]);return x.useMemo(()=>g?{reference:k,floating:k}:{},[g,k])}const aT=.1,mH=aT*aT,hn=.5;function Wm(e,t,r,o,c,d){return o>=t!=d>=t&&e<=(c-r)*(t-o)/(d-o)+r}function Jm(e,t,r,o,c,d,f,p,g,v){let y=!1;return Wm(e,t,r,o,c,d)&&(y=!y),Wm(e,t,c,d,f,p)&&(y=!y),Wm(e,t,f,p,g,v)&&(y=!y),Wm(e,t,g,v,r,o)&&(y=!y),y}function hH(e,t,r){return e>=r.x&&e<=r.x+r.width&&t>=r.y&&t<=r.y+r.height}function eh(e,t,r,o,c,d){const f=Math.min(r,c),p=Math.max(r,c),g=Math.min(o,d),v=Math.max(o,d);return e>=f&&e<=p&&t>=g&&t<=v}function lT(e={}){const{blockPointerEvents:t=!1}=e,r=new Zr,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 C(R,k){const A=performance.now(),D=A-N;if(w===null||S===null||D===0)return w=R,S=k,N=A,!1;const I=R-w,M=k-S,O=I*I+M*M,_=D*D*mH;return w=R,S=k,N=A,O<_}function E(){r.clear(),g()}return function(k){r.clear();const A=p.domReference,D=p.floating;if(!A||!D||b==null||c==null||d==null)return;const{clientX:I,clientY:M}=k,O=ns(k),_=k.type==="mouseleave",L=Ge(D,O),z=Ge(A,O);if(L&&(j=!0,!_))return;if(z&&(j=!1,!_)){j=!0;return}if(_&&Ct(k.relatedTarget)&&Ge(D,k.relatedTarget))return;function U(){return!!(y&&ro(y.nodesRef.current,v).length>0)}function B(){U()||E()}if(U())return;const Q=A.getBoundingClientRect(),W=D.getBoundingClientRect(),Z=c>W.right-W.width/2,Y=d>W.bottom-W.height/2,q=W.width>Q.width,G=W.height>Q.height,$=(q?Q:W).left,F=(q?Q:W).right,X=(G?Q:W).top,re=(G?Q:W).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){B();return}let P=!1;switch(b){case"top":P=eh(I,M,$,Q.top+1,F,W.bottom-1);break;case"bottom":P=eh(I,M,$,W.top+1,F,Q.bottom-1);break;case"left":P=eh(I,M,W.right-1,re,Q.left+1,X);break;case"right":P=eh(I,M,Q.right-1,re,W.left+1,X);break}if(P)return;if(j&&!hH(I,M,Q)){B();return}if(!_&&C(I,M)){B();return}let V=!1;switch(b){case"top":{const J=q?hn/2:hn*4,ie=q||Z?c+J:c-J,me=q?c-J:Z?c+J:c-J,he=d+hn+1,ae=Z||q?W.bottom-hn:W.top,oe=Z?q?W.bottom-hn:W.top:W.bottom-hn;V=Jm(I,M,ie,he,me,he,W.left,ae,W.right,oe);break}case"bottom":{const J=q?hn/2:hn*4,ie=q||Z?c+J:c-J,me=q?c-J:Z?c+J:c-J,he=d-hn,ae=Z||q?W.top+hn:W.bottom,oe=Z?q?W.top+hn:W.bottom:W.top+hn;V=Jm(I,M,ie,he,me,he,W.left,ae,W.right,oe);break}case"left":{const J=G?hn/2:hn*4,ie=G||Y?d+J:d-J,me=G?d-J:Y?d+J:d-J,he=c+hn+1,ae=Y||G?W.right-hn:W.left,oe=Y?G?W.right-hn:W.left:W.right-hn;V=Jm(I,M,ae,W.top,oe,W.bottom,he,ie,he,me);break}case"right":{const J=G?hn/2:hn*4,ie=G||Y?d+J:d-J,me=G?d-J:Y?d+J:d-J,he=c-hn,ae=Y||G?W.left+hn:W.right,oe=Y?G?W.left+hn:W.right:W.left+hn;V=Jm(I,M,he,ie,he,me,ae,W.top,oe,W.bottom);break}}V?j||r.start(40,B):B()}};return o.__options={...e,blockPointerEvents:t},o}const gH={...cy,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 xH extends Zc{constructor(r,o,c){const d=new Km;super(bH(r,d,o,c),vH(d),gH);tn(this,"setOpen",(r,o)=>{aH(this,r,o,{extraState:{openChangeReason:o.reason}})})}cancelPendingOpen(r){this.state.floatingRootContext.dispatchOpenChange(!1,Ve(co,r))}}function bH(e,t,r,o=!1){return{...oy(t,r,o),disabled:!1,instantType:void 0,isInstantPhase:!1,trackCursorAxis:"none",disableHoverablePopup:!1,openChangeReason:null,closeOnClick:!0,closeDelay:0,adaptiveOrigin:void 0,...e}}function vH(e){return{popupRef:x.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerElements:e}}const yH=zm(function(t){const{disabled:r=!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=ty((z,U)=>new xH({open:o,openProp:c,activeTriggerId:j,triggerIdProp:b},z,U));S.useControlledProp("openProp",c),S.useControlledProp("triggerIdProp",b),S.useContextCallback("onOpenChange",g),S.useContextCallback("onOpenChangeComplete",v);const N=S.useState("open"),C=!r&&N,E=S.useState("activeTriggerId"),R=S.useState("mounted"),k=S.useState("payload");S.useSyncedValues({trackCursorAxis:f,disableHoverablePopup:d,disabled:r}),ry(S,{closeOnActiveTriggerUnmount:!0});const{forceUnmount:A,transitionStatus:D}=ay(C,S),I=S.useState("isInstantPhase"),M=S.useState("instantType"),O=S.useState("lastOpenChangeReason"),_=x.useRef(null);De(()=>{N&&r&&S.setOpen(!1,Ve(r4))},[N,r,S]),De(()=>{D==="ending"&&O===Fn||D!=="ending"&&I?(M!=="delay"&&(_.current=M),S.set("instantType","delay")):_.current!==null&&(S.set("instantType",_.current),_.current=null)},[D,I,O,M,S]),De(()=>{C&&E==null&&S.set("payload",void 0)},[S,E,C]),x.useImperativeHandle(p,()=>({unmount:A,close:()=>S.setOpen(!1,Ve(_v))}),[A,S]);const L=C||R||!r&&f!=="none";return s.jsxs(t1.Provider,{value:S,children:[y&&s.jsx(ny,{handle:y,store:S}),L&&s.jsx(jH,{store:S,disabled:r,trackCursorAxis:f}),typeof w=="function"?w({payload:k}):w]})});function jH({store:e,disabled:t,trackCursorAxis:r}){const o=e.useState("floatingRootContext"),c=Xd(o,{enabled:!t,referencePress:()=>e.select("closeOnClick")}),d=lB(o,{enabled:!t&&r!=="none",axis:r==="none"?void 0:r}),f=x.useMemo(()=>Gr(d.reference,c.reference),[d.reference,c.reference]);return ly(e,{activeTriggerProps:f,inactiveTriggerProps:f,popupProps:c.floating??ln}),null}const oT=x.createContext(void 0);function wH(){return x.useContext(oT)}const SH=600,iT="data-base-ui-tooltip-trigger";function cT(e){if("composedPath"in e){const r=e.composedPath();for(let o=0;oC.select("transitionStatus")==="ending",shouldOpen(){return!$.current}}),ie=cH(A,{enabled:!Z}).reference,me=de=>{const K=$.current,be=cT(de),ne=V(be),ce=D.current,we=ce&&be&&Ge(ce,be);if(ne&&C.select("open")&&C.select("lastOpenChangeReason")===zs){C.setOpen(!1,Ve(zs,de));return}if(K&&!ne&&we&&!Y.current&&!C.select("open")&&ce&&ao(X.current)){const Ee=()=>{!$.current&&!Y.current&&!C.select("open")&&C.setOpen(!0,Ve(zs,de,ce))},ve=re();ve===0?(F.clear(),Ee()):F.start(ve,Ee)}},he=C.useState("triggerProps",O);return bt("button",t,{state:{open:k},ref:[r,M,D],props:[J,ie,O||q!=="none"?he:void 0,{onMouseOver(de){me(de.nativeEvent)},onFocus(de){P(cT(de.nativeEvent))&&de.preventBaseUIHandler()},onMouseLeave(){$.current=!1,F.clear(),X.current=void 0},onPointerEnter(de){X.current=de.pointerType},onPointerDown(de){X.current=de.pointerType,C.set("closeOnClick",y),y&&!C.select("open")&&C.cancelPendingOpen(de.nativeEvent)},onClick(de){y&&!C.select("open")&&C.cancelPendingOpen(de.nativeEvent)},id:E,[vv]:Z?"":void 0,[iT]:Z?void 0:""},w],stateAttributesMapping:gv})}),uT=x.createContext(void 0);function kH(){const e=x.useContext(uT);if(e===void 0)throw new Error(nn(70));return e}const TH=x.forwardRef(function(t,r){const{children:o,container:c,className:d,render:f,style:p,...g}=t,{node:v,subtree:y}=g1({container:c,ref:r,componentProps:t,elementProps:g});return!y&&!v?null:s.jsxs(x.Fragment,{children:[y,v&&ys.createPortal(o,v)]})}),EH=x.forwardRef(function(t,r){const{keepMounted:o=!1,...c}=t;return Gd().useState("mounted")||o?s.jsx(uT.Provider,{value:o,children:s.jsx(TH,{ref:r,...c})}):null}),dT=x.createContext(void 0);function fT(){const e=x.useContext(dT);if(e===void 0)throw new Error(nn(71));return e}const RH=x.createContext(void 0);function Wd(){return x.useContext(RH)?.direction??"ltr"}const AH=e=>({name:"arrow",options:e,async fn(t){const{x:r,y:o,placement:c,rects:d,platform:f,elements:p,middlewareData:g}=t,{element:v,padding:y=0,offsetParent:b="real"}=lo(e,t)||{};if(v==null)return{};const j=Ck(y),w={x:r,y:o},S=Cv(c),N=Nv(S),C=await f.getDimensions(v),E=S==="y",R=E?"top":"left",k=E?"bottom":"right",A=E?"clientHeight":"clientWidth",D=d.reference[N]+d.reference[S]-w[S]-d.floating[N],I=w[S]-d.reference[S],M=b==="real"?await f.getOffsetParent?.(v):p.floating;let O=p.floating[A]||d.floating[N];(!O||!await f.isElement?.(M))&&(O=p.floating[A]||d.floating[N]);const _=D/2-I/2,L=O/2-C[N]/2-1,z=Math.min(j[R],L),U=Math.min(j[k],L),B=z,Q=O-C[N]-U,W=O/2-C[N]/2+_,Z=wk(B,W,Q),Y=!g.arrow&&bl(c)!=null&&W!==Z&&d.reference[N]/2-(W{const{name:r,fn:o}=AH(e);return{name:r,fn:o,options:[e,t]}},MH={name:"hide",async fn(e){const{width:t,height:r,x:o,y:c}=e.rects.reference,d=t===0&&r===0&&o===0&&c===0,f=await e.platform.detectOverflow(e,{elementContext:"reference"});return{data:{referenceHidden:f.top-r>=0||f.right-t>=0||f.bottom-r>=0||f.left-t>=0||d}}}},DH={sideX:"left",sideY:"top"},IH="--available-width",PH="--available-height",_H="--anchor-width",LH="--anchor-height",zH="--transform-origin",pT=IH,mT=PH;function hT(e,t,r){const o=e==="inline-start"||e==="inline-end";return{top:"top",right:o?r?"inline-start":"inline-end":"right",bottom:"bottom",left:o?r?"inline-end":"inline-start":"left"}[t]}function gT(e,t,r){const{rects:o,placement:c}=e;return{side:hT(t,Xr(c),r),align:bl(c)||"center",anchor:{width:o.reference.width,height:o.reference.height},positioner:{width:o.floating.width,height:o.floating.height}}}function th(e){return BH(e,oH)}function BH(e,t){const{anchor:r,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:C,collisionAvoidance:E,shift:R,nodeId:k,adaptiveOrigin:A,lazyFlip:D=!1,externalTree:I}=e,[M,O]=x.useState(null);!C&&M!==null&&O(null);const _=E.side||"flip",L=E.align||"flip",z=E.fallbackAxisSide||"end",U=R?.crossAxis??!1,B=R?.rootBoundary,Q=typeof r=="function"?r:void 0,W=Ie(Q),Z=Q?W:r,Y=qn(r),q=qn(C),$=Wd()==="rtl",F=M||{top:"top",right:"right",bottom:"bottom",left:"left","inline-end":$?"left":"right","inline-start":$?"right":"left"}[c],X=f==="center"?F:`${F}-${f}`;let re=v;typeof re=="number"?re={top:re,right:re,bottom:re,left:re}:re&&(re={top:re.top||0,right:re.right||0,bottom:re.bottom||0,left:re.left||0});const P=1,V=c==="bottom"?P:0,J=c==="top"?P:0,ie=c==="right"?P:0,me=c==="left"?P:0,he={boundary:g==="clipping-ancestors"?"clippingAncestors":g,padding:re},ae=x.useRef(null),oe=qn(d),ee=qn(p),de=typeof d!="function"?d:0,K=typeof p!="function"?p:0,be=[];w&&be.push(w),be.push(VB(Je=>{const Tt=gT(Je,c,$),Lt=typeof oe.current=="function"?oe.current(Tt):oe.current,Yn=typeof ee.current=="function"?ee.current(Tt):ee.current;return{mainAxis:Lt,crossAxis:Yn,alignmentAxis:Yn}},[de,K,$,c]));const ne=L==="none"&&_!=="shift",ce=!ne&&(y||U||_==="shift"),we=_==="none"?null:qB({...he,padding:{top:re.top+P+V,right:re.right+P+me,bottom:re.bottom+P+J,left:re.left+P+ie},mainAxis:!U&&_==="flip",crossAxis:L==="flip"?"alignment":!1,fallbackAxisSideDirection:z}),Ee=ne?null:$B({...he,rootBoundary:B,mainAxis:L!=="none",crossAxis:ce,limiter:y||U?void 0:FB(Je=>{if(!ae.current)return{};const{width:Tt,height:Lt}=ae.current.getBoundingClientRect(),Yn=Qr(Xr(Je.placement)),_n=Yn==="y"?Tt:Lt,Ln=Yn==="y"?re.left+re.right:re.top+re.bottom;return{offset:_n/2+Ln/2}})},[he,y,U,B,re,L]);_==="shift"||L==="shift"||f==="center"?be.push(Ee,we):be.push(we,Ee),be.push(GB({...he,apply({elements:{floating:Je},availableWidth:Tt,availableHeight:Lt,rects:Yn}){if(!q.current)return;const _n=Je.style;_n.setProperty(pT,`${Tt}px`),_n.setProperty(mT,`${Lt}px`);const Ln=bn(Je).devicePixelRatio||1,{x:Cn,y:Gt,width:Jn,height:St}=Yn.reference,ht=(Math.round((Cn+Jn)*Ln)-Math.round(Cn*Ln))/Ln,vt=(Math.round((Gt+St)*Ln)-Math.round(Gt*Ln))/Ln;_n.setProperty(_H,`${ht}px`),_n.setProperty(LH,`${vt}px`)}}),OH(Je=>({element:ae.current||zt(Je.elements.floating).createElement("div"),padding:ae.current?b:0,offsetParent:"floating"}),[b]),{name:"transformOrigin",fn(Je){const{elements:{floating:Tt},middlewareData:Lt,placement:Yn,platform:_n,rects:Ln,y:Cn}=Je,Gt=Xr(Yn),Jn=bl(Yn),St=Qr(Gt)==="y",ht=ae.current,vt=typeof d=="function"?d(gT(Je,c,$)):d;let yt;if(!ht&&Jn&&Math.abs(St?Lt.shift?.x||0:Lt.shift?.y||0)<=1)yt=Jn==="start"===(St&&_n.isRTL?.(Tt)===!0)?"100%":"0%";else{const nr=St?Lt.arrow?.x||0:Lt.arrow?.y||0,Ir=St?ht?.clientWidth||0:ht?.clientHeight||0;yt=`${nr+Ir/2}px`}let jr=Gt==="top"||Gt==="left"?`calc(100% + ${vt}px)`:`${-vt}px`;return ce&&St&&Math.abs(Lt.shift?.y||0)>vt&&(jr=`${Ln.reference.y+Ln.reference.height/2-Cn}px`),Tt.style.setProperty(zH,St?`${yt} ${jr}`:`${jr} ${yt}`),{}}},MH,A),De(()=>{!C&&N&&N.update({referenceElement:null,floatingElement:null,domReferenceElement:null,positionReference:null})},[C,N]);const ve=x.useMemo(()=>({ancestorScroll:!j,elementResize:!j&&typeof ResizeObserver<"u",layoutShift:!j&&typeof IntersectionObserver<"u"}),[j]),{refs:Ce,elements:ke,x:Se,y:ge,middlewareData:Te,update:Oe,placement:Ne,context:Be,isPositioned:Xe,floatingStyles:Rt}=t({rootContext:N,open:S?C:void 0,placement:X,middleware:be,strategy:o,whileElementsMounted:S?void 0:(...Je)=>P1(...Je,ve),nodeId:k,externalTree:I}),{sideX:Qt,sideY:Mt}=Te.adaptiveOrigin||DH,it=Xe?o:"fixed",Un=x.useMemo(()=>{let Je;return Xe?A?Je={position:it,[Qt]:Se,[Mt]:ge}:Je={...Rt,position:it}:Je={position:it,top:0,left:0},Je[pT]="100vw",Je[mT]="100vh",Xe||(Je.opacity=0),Je},[A,it,Qt,Se,Mt,ge,Rt,Xe]),as=x.useRef(null);De(()=>{if(!C)return;const Je=Y.current,Tt=typeof Je=="function"?Je():Je,Yn=(xT(Tt)?Tt.current:Tt)||null||null;Yn!==as.current&&(Ce.setPositionReference(Yn),as.current=Yn)},[C,Ce,Z,Y]),x.useEffect(()=>{if(!C)return;const Je=Y.current;typeof Je!="function"&&xT(Je)&&Je.current!==as.current&&(Ce.setPositionReference(Je.current),as.current=Je.current)},[C,Ce,Z,Y]),x.useEffect(()=>{if(S&&C&&ke.reference&&ke.floating)return P1(ke.reference,ke.floating,Oe,ve)},[S,C,ke,Oe,ve]);const Vn=Xr(Ne),fs=hT(c,Vn,$),lt=bl(Ne)||"center",_t=!!Te.hide?.referenceHidden;De(()=>{D&&C&&Xe&&Vn!==F&&O(Vn)},[D,C,Xe,Vn,F]);const Pn=x.useMemo(()=>({position:"absolute",top:Te.arrow?.y,left:Te.arrow?.x}),[Te.arrow]),Zt=Te.arrow?.centerOffset!==0;return x.useMemo(()=>({positionerStyles:Un,arrowStyles:Pn,arrowRef:ae,arrowUncentered:Zt,side:fs,align:lt,physicalSide:Vn,anchorHidden:_t,refs:Ce,context:Be,isPositioned:Xe,update:Oe}),[Un,Pn,ae,Zt,fs,lt,Vn,_t,Ce,Be,Xe,Oe])}function xT(e){return e!=null&&"current"in e}function Jd(e){return e==="starting"?Q4:ln}function nh(e,t,{styles:r,transitionStatus:o,props:c,refs:d,hidden:f,inert:p=!1}){const g={...r};return p&&(g.pointerEvents="none"),bt("div",e,{state:t,ref:d,props:[{role:"presentation",hidden:f,style:g},Jd(o),c],stateAttributesMapping:Uc})}const HH=x.forwardRef(function(t,r){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:C=p1,style:E,...R}=t,k=Gd(),A=kH(),D=k.useState("open"),I=k.useState("mounted"),M=k.useState("trackCursorAxis"),O=k.useState("disableHoverablePopup"),_=k.useState("floatingRootContext"),L=k.useState("instantType"),z=k.useState("transitionStatus"),U=k.useState("adaptiveOrigin"),B=th({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:C,adaptiveOrigin:U}),Q=x.useMemo(()=>({open:D,side:B.side,align:B.align,anchorHidden:B.anchorHidden,instant:M!=="none"?"tracking-cursor":L}),[D,B.side,B.align,B.anchorHidden,M,L]),W=nh(t,Q,{styles:B.positionerStyles,transitionStatus:z,props:R,refs:[r,k.useStateSetter("positionerElement")],hidden:!I,inert:!D||M==="both"||O});return s.jsx(dT.Provider,{value:B,children:W})}),UH=x.forwardRef(function(t,r){const{render:o,className:c,style:d,...f}=t,p=Gd(),{side:g,align:v}=fT(),y=p.useState("open"),b=p.useState("instantType"),j=p.useState("transitionStatus"),w=p.useState("popupProps"),S=p.useState("floatingRootContext"),N=p.useState("disabled"),C=p.useState("closeDelay");Wr({open:y,ref:p.context.popupRef,onComplete(){y&&p.context.onOpenChangeComplete?.(!0)}}),eT(S,{enabled:!N,closeDelay:C});const E=p.useStateSetter("popupElement");return bt("div",t,{state:{open:y,side:g,align:v,instant:b,transitionStatus:j},ref:[r,p.context.popupRef,E],props:[Qd,w,Jd(j),f],stateAttributesMapping:bv})}),VH=x.forwardRef(function(t,r){const{render:o,className:c,style:d,...f}=t,p=Gd(),{arrowRef:g,side:v,align:y,arrowUncentered:b,arrowStyles:j}=fT(),w=p.useState("open"),S=p.useState("instantType");return bt("div",t,{state:{open:w,side:v,align:y,uncentered:b,instant:S},ref:[r,g],props:[{style:j,"aria-hidden":!0},f],stateAttributesMapping:Uc})}),$H=function(t){const{delay:r,closeDelay:o,timeout:c=400}=t,d=x.useMemo(()=>({open:r,close:o}),[r,o]);return s.jsx(oT.Provider,{value:r,children:s.jsx(F4,{delay:d,timeoutMs:c,children:t.children})})};function sh(e){return ov(19)?e:e?"true":void 0}function FH(e){const[t,r]=x.useState({current:e,previous:null});return Object.is(e,t.current)||r({current:e,previous:t.current}),t.previous}function qH(e){return s.jsx($H,{"data-slot":"tooltip-provider",...e})}function Ri(e){return s.jsx(yH,{"data-slot":"tooltip",...e})}function Ai(e){return s.jsx(CH,{"data-slot":"tooltip-trigger",...e})}function Oi({className:e,sideOffset:t=8,side:r="top",children:o,...c}){return s.jsx(EH,{children:s.jsx(HH,{sideOffset:t,side:r,className:"z-[35]",children:s.jsx(UH,{"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 GH({className:e,...t}){return s.jsx(VH,{className:Ue("size-2 rotate-45 rounded-[1px] bg-primary","data-[side=top]:-bottom-1 data-[side=bottom]:-top-1",e),...t})}const bT=x.createContext(void 0);function Wc(e){const t=x.useContext(bT);if(!e&&t===void 0)throw new Error(nn(27));return t}const vT=x.forwardRef(function(t,r){const{render:o,className:c,style:d,forceRender:f=!1,...p}=t,g=Wc(),v=g.useState("open"),y=g.useState("nested"),b=g.useState("mounted"),j=g.useState("transitionStatus");return bt("div",t,{state:{open:v,transitionStatus:j},ref:[g.context.backdropRef,r],stateAttributesMapping:bv,props:[{role:"presentation",hidden:!b,style:{userSelect:"none",WebkitUserSelect:"none"}},p],enabled:f||!y})}),yT=x.forwardRef(function(t,r){const{render:o,className:c,style:d,disabled:f=!1,nativeButton:p=!0,...g}=t,v=Wc(),y=v.useState("open"),{getButtonProps:b,buttonRef:j}=Kr({disabled:f,native:p}),w={disabled:f};function S(N){y&&v.setOpen(!1,Ve(Iv,N.nativeEvent))}return bt("button",t,{state:w,ref:[r,j],props:[{onClick:S},g,b]})}),jT=x.createContext(void 0);function KH(){const e=x.useContext(jT);if(e===void 0)throw new Error(nn(26));return e}const my="ArrowUp",hy="ArrowDown",gy="ArrowLeft",xy="ArrowRight",by="Home",vy="End",rh=new Set([my,hy,gy,xy,by,vy]),wT="Shift",YH=[wT,"Control","Alt","Meta"];function XH(e){return an(e)&&e.tagName==="INPUT"}function ST(e){return!!(XH(e)&&e.selectionStart!=null||an(e)&&e.tagName==="TEXTAREA")}function NT(e,t,r,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=CT(e,t,"top"),v=ah(e),y=ah(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 CT(e,t,r){const o=r==="left"?"offsetLeft":"offsetTop";let c=0;for(;t.offsetParent&&(c+=t[o],t.offsetParent!==e);)t=t.offsetParent;return c}function ah(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 QH="--nested-dialogs",ZH="data-nested-dialog-open",WH={...Uc,...so,nestedDialogOpen(e){return e?{[ZH]:""}:null}},kT=x.forwardRef(function(t,r){const{render:o,className:c,style:d,finalFocus:f,initialFocus:p,...g}=t,v=Wc(),y=v.useState("descriptionElementId"),b=v.useState("disablePointerDismissal"),j=v.useState("floatingRootContext"),w=v.useState("popupProps"),S=v.useState("modal"),N=v.useState("mounted"),C=v.useState("nested"),E=v.useState("nestedOpenDialogCount"),R=v.useState("open"),k=v.useState("openMethod"),A=v.useState("titleElementId"),D=v.useState("transitionStatus"),I=v.useState("role"),M=j.useState("floatingId");KH(),Wr({open:R,ref:v.context.popupRef,onComplete(){R&&v.context.onOpenChangeComplete?.(!0)}});const O=p===void 0?F1(v.context.popupRef):p,_=E>0,L=v.useStateSetter("popupElement"),U=bt("div",t,{state:{open:R,nested:C,transitionStatus:D,nestedDialogOpen:_},props:[w,{id:M,"aria-labelledby":A,"aria-describedby":y,role:I,...Qd,hidden:!N,onKeyDown(B){rh.has(B.key)&&B.stopPropagation()},style:{[QH]:E}},g],ref:[r,v.context.popupRef,L],stateAttributesMapping:WH});return s.jsx(Vm,{context:j,openInteractionType:k,disabled:!N,closeOnFocusOut:!b,initialFocus:O,returnFocus:f,modal:S!==!1,restoreFocus:"popup",children:U})}),lh=x.forwardRef(function(t,r){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:r,role:"presentation","data-base-ui-inert":"",...c,style:{position:"fixed",inset:0,userSelect:"none",WebkitUserSelect:"none",clipPath:d}})}),TT=x.forwardRef(function(t,r){const{keepMounted:o=!1,...c}=t,d=Wc(),f=d.useState("mounted"),p=d.useState("modal"),g=d.useState("open");return f||o?s.jsx(jT.Provider,{value:o,children:s.jsxs(Um,{ref:r,...c,children:[f&&p===!0&&s.jsx(lh,{ref:d.context.internalBackdropRef,inert:sh(!g)}),t.children]})}):null});let ET={},RT={},AT="";function oh(e,t){return Md(e)?e:t}function OT(e,t,r){return/hidden|clip/.test(e.getComputedStyle(oh(t,r)).overflowY)}function JH(e){if(typeof document>"u")return!1;const t=zt(e);return bn(t).innerWidth-t.documentElement.clientWidth>0}function eU(e){if(!(typeof CSS<"u"&&CSS.supports&&CSS.supports("scrollbar-gutter","stable"))||typeof document>"u")return!1;const r=zt(e),o=r.documentElement,c=r.body,d=oh(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 tU(e){const t=zt(e),r=t.documentElement,o=t.body,c=oh(r,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 nU(e){const t=zt(e),r=t.documentElement,o=t.body,c=bn(r);let d=0,f=0,p=!1;const g=Va.create();if(hl&&(c.visualViewport?.scale??1)!==1)return()=>{};function v(){const w=c.getComputedStyle(r),S=c.getComputedStyle(o),E=(w.scrollbarGutter||"").includes("both-edges")?"stable both-edges":"stable";d=r.scrollTop,f=r.scrollLeft,ET={scrollbarGutter:r.style.scrollbarGutter,overflowY:r.style.overflowY,overflowX:r.style.overflowX},AT=r.style.scrollBehavior,RT={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 R=r.scrollHeight>r.clientHeight,k=r.scrollWidth>r.clientWidth,A=w.overflowY==="scroll"||S.overflowY==="scroll",D=w.overflowX==="scroll"||S.overflowX==="scroll",I=Math.max(0,c.innerWidth-o.clientWidth),M=Math.max(0,c.innerHeight-o.clientHeight),O=parseFloat(S.marginTop)+parseFloat(S.marginBottom),_=parseFloat(S.marginLeft)+parseFloat(S.marginRight),L=oh(r,o);if(p=eU(e),p){r.style.scrollbarGutter=E,L.style.overflowY="hidden",L.style.overflowX="hidden";return}Object.assign(r.style,{scrollbarGutter:E,overflowY:"hidden",overflowX:"hidden"}),(R||A)&&(r.style.overflowY="scroll"),(k||D)&&(r.style.overflowX="scroll"),Object.assign(o.style,{position:"relative",height:O||M?`calc(100dvh - ${O+M}px)`:"100dvh",width:_||I?`calc(100vw - ${_+I}px)`:"100vw",boxSizing:"border-box",overflowY:"hidden",overflowX:"hidden",scrollBehavior:"unset"}),o.scrollTop=d,o.scrollLeft=f,r.setAttribute("data-base-ui-scroll-locked",""),r.style.scrollBehavior="unset"}function y(){Object.assign(r.style,ET),Object.assign(o.style,RT),p||(r.scrollTop=d,r.scrollLeft=f,r.removeAttribute("data-base-ui-scroll-locked"),r.style.scrollBehavior=AT)}function b(){y(),g.request(v)}v();const j=jt(c,"resize",b);return()=>{g.cancel(),y(),typeof c.removeEventListener=="function"&&j()}}class sU{constructor(){tn(this,"lockCount",0);tn(this,"restore",null);tn(this,"timeoutLock",Zr.create());tn(this,"timeoutUnlock",Zr.create());tn(this,"release",()=>{this.lockCount-=1,this.lockCount===0&&this.restore&&this.timeoutUnlock.start(0,this.unlock)});tn(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 r=zt(t),o=r.documentElement,c=r.body,d=bn(o);if(OT(d,o,c)){const p=new d.MutationObserver(()=>{OT(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=Ld||!JH(t);this.restore=f?tU(t):nU(t)}}const rU=new sU;function MT(e=!0,t=null){De(()=>{if(e)return rU.acquire(t)},[e,t])}function aU({store:e,parentContext:t,isDrawer:r}){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=Xd(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=ns(S);if(j&&!c){if(d){const C=e.context.internalBackdropRef.current,E=e.context.backdropRef.current;return C||E?C===N||E===N||Ge(N,f)&&!N?.hasAttribute("data-base-ui-portal"):!0}return!0}return!1},escapeKey:j});return MT(o&&d===!0,f),e.useContextCallback("onNestedDialogOpen",(S,N)=>{v(S),b(N)}),De(()=>(t?.onNestedDialogOpen&&(o?t.onNestedDialogOpen(g+1,y+(r?1:0)):t.onNestedDialogOpen(0,0)),()=>{t?.onNestedDialogOpen&&o&&t.onNestedDialogOpen(0,0)}),[r,o,g,y,t]),ly(e,{activeTriggerProps:w.reference,inactiveTriggerProps:w.trigger,popupProps:w.floating,nestedOpenDialogCount:g,nestedOpenDrawerCount:y}),null}const lU={...cy,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 oU extends Zc{constructor(r,o,c){const d=new Km,f=iU(r,d,o,c);super(f,cU(d),lU);tn(this,"setOpen",(r,o)=>{o.preventUnmountOnClose=()=>{this.set("preventUnmountingOnClose",!0)},!r&&o.trigger==null&&this.state.activeTriggerId!=null&&(o.trigger=this.state.activeTriggerElement??void 0),this.context.onOpenChange?.(r,o),!o.isCanceled&&(this.state.floatingRootContext.dispatchOpenChange(r,o),this.update(sy(this.state,r,o.trigger)))})}}function iU(e,t,r,o=!1){return{...oy(t,r,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 cU(e){return{popupRef:x.createRef(),backdropRef:x.createRef(),internalBackdropRef:x.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:e,onOpenChange:void 0,onOpenChangeComplete:void 0}}function DT(e,t){const{children:r,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,C=S||p,E=S?"alertdialog":"dialog",R=Wc(!0),k=R!=null,A={modal:N,disablePointerDismissal:C,nested:k,role:E},D=ty((z,U)=>new oU({open:c,openProp:o,activeTriggerId:j,triggerIdProp:b,...A},z,U),!0);D.useControlledProp("openProp",o),D.useControlledProp("triggerIdProp",b),D.useSyncedValues(A),D.useContextCallback("onOpenChange",d),D.useContextCallback("onOpenChangeComplete",f);const I=D.useState("open"),M=D.useState("mounted"),O=D.useState("payload");Y1(D,I),ry(D);const{forceUnmount:_}=ay(I,D);x.useImperativeHandle(v,()=>({unmount:_,close:()=>D.setOpen(!1,Ve(_v))}),[_,D]);const L=I||M;return s.jsxs(bT.Provider,{value:D,children:[y&&s.jsx(ny,{handle:y,store:D}),L&&s.jsx(aU,{store:D,parentContext:R?.context,isDrawer:w}),typeof r=="function"?r({payload:O}):r]})}const uU=zm(function(t){return DT("dialog",t)}),IT=x.forwardRef(function(t,r){const{render:o,className:c,style:d,id:f,...p}=t,g=Wc(),v=ja(f);return g.useSyncedValueWithCleanup("titleElementId",v),bt("h2",t,{ref:r,props:[{id:v},p]})});function dU(e){const t=x.useRef(""),r=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:r}}function PT(e,t){const r=Ie((d,f)=>{(typeof e=="function"?e():e)||t(f||(Ld?"touch":""))}),{onClick:o,onPointerDown:c}=dU(r);return x.useMemo(()=>({onClick:o,onPointerDown:c}),[o,c])}function _T(e){const[t,r]=x.useState(null),o=PT(e,r);return Jr(e,c=>{c&&!e&&r(null)}),x.useMemo(()=>({openMethod:t,triggerProps:o}),[t,o])}function Kt(e){return s.jsx(uU,{"data-slot":"dialog",...e})}function fU(e){return s.jsx(TT,{"data-slot":"dialog-portal",...e})}const $t=e=>s.jsx(IT,{"data-slot":"dialog-title",...e});function pU({className:e,...t}){return s.jsx(vT,{"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 Yt({className:e,children:t,showCloseButton:r=!0,keepMounted:o=!1,overlayForceRender:c=!1,...d}){return s.jsxs(fU,{keepMounted:o,children:[s.jsx(pU,{forceRender:c}),s.jsxs(kT,{"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,r&&s.jsxs(yT,{"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:fo("关闭")})]})]})]})}function Ft({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 Ht({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 sn({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 zn({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 mU(e){return DT("alert-dialog",e)}const hU=mU,gU=TT,xU=e=>s.jsx(IT,{"data-slot":"alert-dialog-title",...e});function bU({className:e,...t}){return s.jsx(vT,{"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 vU({className:e,children:t,showCloseButton:r=!1,...o}){return s.jsxs(gU,{children:[s.jsx(bU,{}),s.jsxs(kT,{"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,r&&s.jsxs(yT,{"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:fo("关闭")})]})]})]})}function yU({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 jU({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 wU({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 SU({className:e,tone:t="danger",...r}){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),...r})}function yy({className:e,containerClassName:t,...r}){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),...r})})}function LT({className:e,...t}){return s.jsx("thead",{"data-slot":"table-header",className:Ue(e),...t})}function jy({className:e,...t}){return s.jsx("tbody",{"data-slot":"table-body",className:Ue(e),...t})}function yl({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 zT({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 vn({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 NU="data-checked",CU="data-unchecked",wy={checked(e){return e?{[NU]:""}:{[CU]:""}},...so,...gi},Sy="data-composite-item-active",BT=x.createContext({register:()=>{},unregister:()=>{},subscribeMapChange:()=>()=>{},nextIndexRef:{current:0}});function kU(){return x.useContext(BT)}function Ny(e={}){const{guess:t,label:r,metadata:o,textRef:c,index:d}=e,{register:f,unregister:p,subscribeMapChange:g,nextIndexRef:v}=kU(),y=x.useRef(-1),[b,j]=x.useState(d==null&&t?()=>{if(y.current===-1){const C=v.current;v.current+=1,y.current=C}return y.current}:-1),w=d??b,S=x.useRef(null),N=x.useCallback(C=>{const E=S.current;E&&p(E),S.current=C,C&&f(C,{metadata:o??null,index:d??null,label:r,textRef:c})},[d,f,p,o,r,c]);return De(()=>{if(d==null)return g(C=>{const E=S.current?C.get(S.current)?.index:null;E!=null&&j(E)})},[d,g]),{ref:N,index:w}}function TU(e={}){const{highlightItemOnHover:t,highlightedIndex:r,onHighlightedIndexChange:o}=_C(),{ref:c,index:d}=Ny(e),f=r===d,p=x.useRef(null),g=Yr(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 HT(e){const{render:t,className:r,style:o,state:c=ln,props:d=Er,refs:f=Er,metadata:p,stateAttributesMapping:g,tag:v="div",...y}=e,{compositeProps:b,compositeRef:j}=TU({metadata:p});return bt(v,e,{state:c,ref:[j,...f],props:[b,...d,y],stateAttributesMapping:g})}const UT=x.createContext(void 0);function EU(){return x.useContext(UT)}function ih(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}const VT=x.createContext(void 0);function RU(){const e=x.useContext(VT);if(e===void 0)throw new Error(nn(52));return e}const $T=x.forwardRef(function(t,r){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=EU(),{disabled:C,readOnly:E,required:R,form:k,checkedValue:A,touched:D=!1,validation:I,name:M,setCheckedValue:O=Bt,setTouched:_=Bt,registerInputRef:L=Bt}=N??{},{setTouched:z,setFilled:U,state:B,disabled:Q}=ya(),W=Lk(),{labelId:Z,getDescriptionProps:Y}=ml(),q=Q||W.disabled||C||d,G=E||f,$=R||p,F=k,X=N?A===v:v==="",re=x.useRef(null),P=x.useRef(null),V=I?.registerInput,J=x.useCallback(ke=>V?.(ke,{controlRef:re,value:void 0}),[V]),ie=Yr(y,P,L,J);De(()=>{P.current?.checked&&U(!0)},[U]),De(()=>{if(P.current){if(q&&X){L(null);return}L(P.current)}},[X,q,L]);const me=ja(),he=no({id:j}),ae=b?void 0:he,oe=fv(g,Z,P,!b,ae),ee={role:"radio","aria-checked":X,"aria-labelledby":oe,[Sy]:X?"":void 0,id:b?he:me,onKeyDown(ke){ke.key==="Enter"&&ke.preventDefault()},onClick(ke){if(ke.defaultPrevented||q||G)return;ke.preventDefault();const Se=P.current;Se&&zc(Se,ke)},onFocus(ke){ke.defaultPrevented||q||G||!D||(P.current?.click(),_(!1))}},{getButtonProps:de,buttonRef:K}=Kr({disabled:q,native:b,composite:!1}),be={type:"radio",ref:ie,form:F,id:ae,name:M,tabIndex:-1,style:M?Kc:Ni,"aria-hidden":!0,...v!==void 0?{value:ih(v)}:ln,disabled:q,checked:X,required:$,readOnly:G,onChange(ke){if(ke.nativeEvent.defaultPrevented||q||G||v===void 0)return;const Se=Ve(Fn,ke.nativeEvent);O(v,Se),!Se.isCanceled&&z(!0)},onClick(ke){ke.stopPropagation()},onFocus(){re.current?.focus()}},ne=x.useMemo(()=>({...B,required:$,disabled:q,readOnly:G,checked:X}),[B,q,G,X,$]),ce=ne,we=N!==void 0,Ee=[r,re,K],ve=[ee,S,de,Y,I?ke=>I.getValidationProps(q,ke):ln],Ce=bt("span",t,{enabled:!we,state:ne,ref:Ee,props:ve,stateAttributesMapping:wy});return s.jsxs(VT.Provider,{value:ce,children:[we?s.jsx(HT,{tag:"span",render:o,className:c,style:w,state:ne,refs:Ee,props:ve,stateAttributesMapping:wy}):Ce,s.jsx("input",{...be,suppressHydrationWarning:!0})]})}),AU=x.forwardRef(function(t,r){const{render:o,className:c,style:d,keepMounted:f=!1,...p}=t,g=RU(),v=g.checked,{mounted:y,transitionStatus:b,setMounted:j}=yi(v),w={...g,transitionStatus:b},S=x.useRef(null),N=f||y,C=bt("span",t,{ref:[r,S],state:w,props:p,stateAttributesMapping:wy});return Wr({batch:!0,enabled:!v,open:v,ref:S,onComplete(){v||j(!1)}}),N?C:null});function Cy(e){const{children:t,elementsRef:r,labelsRef:o,onMapChange:c}=e,d=Ie(c),[,f]=x.useState(!1),p=Ts(MU).current,g=Ts(OU).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(D=>!D))}),S=Ie((D,I)=>{g.set(D,I),w()}),N=Ie(D=>{g.delete(D),w()}),C=Ie(D=>{const I=new Map;return r.current.length=0,o&&(o.current.length=0),D.forEach(M=>{I.set(M.element,{...M.registration.metadata??{},index:M.index}),r.current[M.index]=M.element,o&&(o.current[M.index]=M.registration.label!==void 0?M.registration.label:M.registration.textRef?.current?.textContent??M.element.textContent)}),v.current=r.current.length,I});function E(D){if(j.current?.disconnect(),j.current=null,typeof MutationObserver!="function"||D.length<2)return;const I=new MutationObserver(O=>{if(!PU(O))return;let _=null;for(const L of D)if(L.isConnected){if(_&&FT(_,L)>0){I.disconnect(),w();return}_=L}});j.current=I;const M=new Set;for(let O=1;OI.observe(O,{childList:!0}))}const R=Ie(()=>{const[D,I]=DU(g),M=C(D),O=b.current,_=!O||O.length!==D.length||D.some((L,z)=>{const U=O[z];return L.index!==U.index||L.element!==U.element||L.registration.index!==U.registration.index||L.registration.metadata!==U.registration.metadata});E(I),b.current=D,y.current=!1,_&&(p.forEach(L=>L(M)),d(M))});De(()=>(!y.current&&b.current&&C(b.current),()=>{r.current=[],o&&(o.current=[])}),[r,o,C]),De(()=>{y.current&&R()}),De(()=>()=>{j.current?.disconnect(),y.current=!0},[]);const k=Ie(D=>(p.add(D),()=>{p.delete(D)})),A=x.useMemo(()=>({register:S,unregister:N,subscribeMapChange:k,nextIndexRef:v}),[S,N,k,v]);return s.jsx(BT.Provider,{value:A,children:t})}function OU(){return new Map}function MU(){return new Set}function DU(e){const t=new Set,r=[],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),r.push(g))});let c=0;return o.sort((d,f)=>FT(d.element,f.element)),o.forEach(d=>{for(;t.has(c);)c+=1;d.index=c,r.push(d),c+=1}),t.size>0&&r.sort((d,f)=>d.index-f.index),[r,o.map(d=>d.element)]}function IU(e,t){let r=e.parentElement;for(;r&&!r.contains(t);)r=r.parentElement;return r}function PU(e){for(const t of e)for(let r=0;r{if(A.current=R.current[z]??null,(p??S)(z),U){const B=R.current[z];NT(C.current,B,d,r)}}),M=Ie(z=>{if(z.size===0)return;if(k.current){const W=R.current,Z=W.indexOf(A.current);if(Z===-1){const Y=W[D];!Y||io(W,D,b)?I(LU(W,b)):A.current=Y}else Z!==D&&I(Z);return}k.current=!0;const U=Array.from(z.keys()),B=U.find(W=>W?.hasAttribute(Sy))??null,Q=B?z.get(B)?.index??-1:-1;if(Q!==-1)I(Q);else if(io(U,D,b)){const W=Es(U,{disabledIndices:b});oo(U,W)||I(W)}NT(C.current,B,d,r)});De(()=>{if(b==null||f!=null||!k.current)return;const z=R.current;if(io(z,D,b)){const U=Es(z,{disabledIndices:b});oo(z,U)||I(U)}},[b,f,D,R,I]);const O=Ie((z,U,B)=>c?c(z,U,B,R):B),_=Ie(z=>{const U=z.key===by||z.key===vy;if(!rh.has(z.key)||!v&&U||zU(z,j)||!C.current)return;const Q=d==="rtl",W=Q?gy:xy,Z=Q?xy:gy,Y=r==="vertical"?hy:W,q=r==="vertical"?my:Z,G=ns(z.nativeEvent);if(G!=null&&ST(G)&&!qT(G)){const V=G.selectionStart,J=G.selectionEnd,ie=G.value;if(V==null||z.shiftKey||V!==J||z.key!==q&&V0)return}let $=D;const F=Om(R,b),X=Tv(R,b);o!=null&&($=o({disabledIndices:b,elementsRef:R,event:z,highlightedIndex:D,loopFocus:t,maxIndex:X,minIndex:F,onLoop:O,orientation:r,rtl:Q}));const re=r!=="vertical"&&z.key===W||r!=="horizontal"&&z.key===hy,P=r!=="vertical"&&z.key===Z||r!=="horizontal"&&z.key===my;v&&(z.key===by?$=F:z.key===vy&&($=X)),$===D&&(re||P)&&(t&&$===X&&re?($=F,c&&($=c(z,D,$,R))):t&&$===F&&P?($=X,c&&($=c(z,D,$,R))):$=Es(R.current,{startingIndex:$,decrement:P,disabledIndices:b})),$!==D&&!oo(R.current,$)&&(y&&z.stopPropagation(),(N||U||re||P)&&z.preventDefault(),I($,!0),queueMicrotask(()=>{R.current[$]?.focus()}))});return{props:{ref:E,onFocus(z){const U=C.current,B=ns(z.nativeEvent);!U||B==null||!ST(B)||B.setSelectionRange(0,B.value.length)},onKeyDown:_},highlightedIndex:D,onHighlightedIndexChange:I,elementsRef:R,onMapChange:M,relayKeyboardEvent:_}}function LU(e,t){let r=-1;for(let o=0;o({highlightedIndex:_,onHighlightedIndexChange:L,highlightItemOnHover:A,relayKeyboardEvent:B}),[_,L,A,B]);return s.jsx(PC.Provider,{value:W,children:s.jsx(Cy,{elementsRef:z,onMapChange:Z=>{N?.(Z),U(Z)},children:Q})})}const HU=[wT],GT=x.forwardRef(function(t,r){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,...C}=t,{setTouched:E,setFocused:R,validationMode:k,name:A,disabled:D,state:I,validation:M,setDirty:O,setFilled:_,validityData:L}=ya(),{labelId:z}=ml(),{clearErrors:U,elementRef:B}=Hc(),Q=az(!0),W=D||d,Z=A??j,Y=ja(S),[q,G]=$a({controlled:v,default:y,name:"RadioGroup",state:"value"}),[$,F]=x.useState(!1),X=Ie((K,be)=>{g?.(K,be),!be.isCanceled&&G(K)}),re=M.getInputControl,P=x.useMemo(()=>({get current(){return re()}}),[re]),V=x.useRef(null),J=x.useRef(null);function ie(K){let be;return w&&(typeof w=="function"?be=w(K):w.current=K),V.current=K,be}const me=Ie(K=>{if(!K||K.disabled)return;J.current||(J.current=K);const be=V.current,ne=K.checked||be==null||be.disabled?ie(K):void 0;return()=>{J.current===K&&(J.current=null),V.current===K?ne?(ne(),V.current=null):ie(null):ne?.()}}),he=Ie(()=>{const K=B.current;if(!K)return q??null;for(const be of M.registeredInputs.keys())if(be.checked&&Wz(be,K))return q??null;return null});qc(P,Y,q??null,he,!W,j),Jr(q,()=>{U(Z),O(q!==L.initialValue),_(q!=null),M.change(q);const K=J.current;q==null&&K&&!K.disabled&&ie(K)});const ae=z??Q?.legendId,oe={...I,disabled:W??!1,required:p??!1,readOnly:f??!1},ee=x.useMemo(()=>({checkedValue:q,disabled:W,form:b,validation:M,name:Z,readOnly:f,registerInputRef:me,required:p,setCheckedValue:X,setTouched:F,touched:$}),[q,W,b,M,Z,f,me,p,X,F,$]),de={id:S,role:"radiogroup","aria-required":p||void 0,"aria-disabled":W||void 0,"aria-readonly":f||void 0,"aria-labelledby":ae,onFocus(){R(!0)},onBlur(K){Ge(K.currentTarget,K.relatedTarget)||(E(!0),R(!1),k==="onBlur"&&M.commit(q))},onKeyDownCapture(K){K.key.startsWith("Arrow")&&(F(!0),R(!0))}};return s.jsx(UT.Provider,{value:ee,children:s.jsx(BU,{render:o,className:c,style:N,state:oe,props:[de,C,K=>M.getValidationProps(W??!1,K)],refs:[r],stateAttributesMapping:gi,enableHomeAndEndKeys:!1,modifierKeys:HU})})});function ch({className:e,...t}){return s.jsx(GT,{"data-slot":"radio-group",className:Ue("flex flex-col gap-2",e),...t})}function Mi({className:e,...t}){return s.jsx($T,{"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(AU,{"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 KT(e){const t=x.useRef(!0);t.current&&(t.current=!1,e())}const YT=x.createContext(void 0),XT=x.createContext(void 0),QT=x.createContext(void 0);function mo(){const e=x.useContext(YT);if(e===void 0)throw new Error(nn(60));return e}function ky(){const e=x.useContext(XT);if(e===void 0)throw new Error(nn(101));return e}function ZT(){const e=x.useContext(QT);if(e===void 0)throw new Error(nn(61));return e}function UU(e,t,r=Object.is){const{length:o}=e;if(o!==t.length)return!1;for(let c=0;cObject.is(e,t);function ta(e,t,r){return e==null||t==null?Object.is(e,t):r(e,t)}function WT(e,t,r){return Array.isArray(e)&&Array.isArray(t)?!UU(e,t,(o,c)=>ta(o,c,r)):e!==t}function dh(e,t,r){return e?e.some(o=>o===void 0?!1:ta(t,o,r)):!1}function Jc(e,t,r){return e?e.findIndex(o=>o===void 0?!1:ta(o,t,r)):-1}function VU(e,t){if(t!==uh)return o=>dh(e,o,t);const r=new Set(e);return r.delete(void 0),o=>r.has(o)&&(o!==0||e.some(c=>Object.is(o,c)))}function ef(e,t,r,o){const c=o&&Array.isArray(t)?e.findIndex(VU(t,r)):Jc(e,t,r);return c===-1?null:c}function JT(e,t,r,o,c,d){return dh(o,t,c)?d!=null&&e>d&&dh(o,r[d],c)?d:e:e===d?ef(r,o,c,!0):d}function eE(e,t,r){return e.filter(o=>!ta(t,o,r))}function $U(e){return typeof e=="object"&&e!=null&&Array.isArray(e.items)}function Ty(e){return $U(e?.[0])}function fh(e){return Ty(e)?e.flatMap(t=>t.items):e}function tE(e){if(!Array.isArray(e))return e!=null&&"null"in e;const t=e;if(Ty(t)){for(const r of t)for(const o of r.items)if(o&&o.value==null&&o.label!=null)return!0;return!1}for(const r of t)if(r&&r.value==null&&r.label!=null)return!0;return!1}function ho(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 ih(e)}function wa(e,t){return t&&e!=null?t(e)??"":e&&typeof e=="object"&&"value"in e&&"label"in e?ih(e.value):ih(e)}function nE(e,t,r){function o(){return ho(e,r)}if(r&&e!=null)return r(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=fh(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 FU(e,t,r){return e.reduce((o,c,d)=>(d>0&&o.push(", "),o.push(s.jsx(x.Fragment,{children:nE(c,t,r)},d)),o),[])}const qU={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:r,itemToStringValue:o}=e;return t==null?!1:r&&Array.isArray(t)?t.length>0:wa(t,o)!==""},hasNullItemLabel:(e,t)=>t?tE(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 r=e.isItemEqualToValue,o=e.value;return e.multiple?Array.isArray(o)&&o.some(c=>ta(t,c,r)):ta(t,o,r)},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},jl=1;function sE(e,t){return Math.max(0,e-t)}function GU(e,t){if(t<=0)return 0;const r=Ci(e,0,t),o=r,c=t-r,d=o<=jl,f=c<=jl;return d&&f?o<=c?0:t:d?0:f?t:r}function KU(e){const{id:t,value:r,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:C,onOpenChangeComplete:E,items:R,multiple:k=!1,itemToStringLabel:A,itemToStringValue:D,isItemEqualToValue:I=uh,highlightItemOnHover:M=!0,children:O}=e,{clearErrors:_}=Hc(),{setDirty:L,setTouched:z,setFocused:U,validityData:B,setFilled:Q,name:W,disabled:Z,validation:Y,validationMode:q}=ya(),G=no({id:t}),$=Z||b,F=W??g,[X,re]=$a({controlled:r,default:k?o??Er:o,name:"Select",state:"value"}),[P,V]=$a({controlled:d,default:f,name:"Select",state:"open"}),J=x.useRef([]),ie=x.useRef([]),me=x.useRef(null),he=x.useRef(null),ae=x.useRef(0),oe=x.useRef(null),ee=x.useRef([]),de=x.useRef(!1),K=x.useRef(null),be=x.useRef(null),ne=x.useRef({allowSelectedMouseUp:!1,allowUnselectedMouseUp:!1,dragY:0}),ce=x.useRef(!1),we=x.useRef(X),{mounted:Ee,setMounted:ve,transitionStatus:Ce}=yi(P),{openMethod:ke,triggerProps:Se}=_T(P),ge=Ts(()=>new Zc({id:G,labelId:void 0,modal:S,multiple:k,itemToStringLabel:A,itemToStringValue:D,isItemEqualToValue:I,value:X,open:P,mounted:Ee,transitionStatus:Ce,items:R,forceMount:!1,openMethod:null,activeIndex:null,selectedIndex:null,popupProps:ln,triggerProps:ln,triggerElement:null,positionerElement:null,listElement:null,popupSide:null,scrollUpArrowVisible:!1,scrollDownArrowVisible:!1,hasScrollArrows:!1},{setValue:Bt,setOpen:Bt,handleScrollArrowVisibility:Bt,onOpenChangeComplete:Bt,listRef:J,popupRef:me,scrollHandlerRef:he,scrollArrowsMountedCountRef:ae,valueRef:oe,valuesRef:ee,labelsRef:ie,typingRef:de,selectionRef:ne,firstItemTextRef:K,selectedItemTextRef:be,alignItemWithTriggerActiveRef:ce,initialValueRef:we},qU)).current,Te=ge.useState("activeIndex"),Oe=ge.useState("selectedIndex"),Ne=ge.useState("triggerElement"),Be=ge.useState("positionerElement"),Xe=FH(ke),Rt=ke??Xe,Qt=x.useMemo(()=>k?"":wa(X,D),[k,X,D]),Mt=x.useMemo(()=>k&&Array.isArray(X)?X.map(ht=>wa(ht,D)):wa(X,D),[k,X,D]),it=qn(Ne),Un=Ie(()=>Mt);qc(it,G,X,Un,!$,g);const as=k?Array.isArray(X)&&X.length>0:X!=null&&Qt!=="";De(()=>{Q(as)},[as,Q]),De(function(){const vt=ef(ee.current,X,I,k);vt===null&&(be.current=null),!P&&ge.set("selectedIndex",vt)},[k,P,X,I,ge]),Jr(X,()=>{_(F),L(WT(X,B.initialValue,I)),Y.change(X)});const Vn=Ie((ht,vt)=>{p?.(ht,vt),!vt.isCanceled&&(V(ht),!ht&&(vt.reason===uo||vt.reason===Lm)&&(z(!0),U(!1),q==="onBlur"&&Y.commit(X)))}),fs=Ie(()=>{ve(!1),ge.update({activeIndex:null,openMethod:null,scrollUpArrowVisible:!1,scrollDownArrowVisible:!1}),E?.(!1)});Wr({enabled:!N,open:P,ref:me,onComplete(){P||fs()}}),x.useImperativeHandle(N,()=>({unmount:fs}),[fs]);const lt=Ie((ht,vt)=>{c?.(ht,vt),!vt.isCanceled&&re(ht)}),_t=Ie(ht=>{const vt=sE(ht.scrollHeight,ht.clientHeight),yt=GU(ht.scrollTop,vt),jr=yt>0,nr=ytqT(J.current[ht]),onMatch(ht){P?ge.set("activeIndex",ht):lt(ee.current[ht],Ve(Fn))},onTyping(ht){de.current=ht}}),Yn=x.useMemo(()=>Gr(Lt.reference,Tt.reference,Je.reference,Zt.reference,Se),[Zt.reference,Lt.reference,Tt.reference,Je.reference,Se]),_n=x.useMemo(()=>Gr(Qd,Lt.floating,Tt.floating,Je.floating),[Lt.floating,Tt.floating,Je.floating]),Ln=Tt.item??ln;ge.useContextCallback("setValue",lt),ge.useContextCallback("setOpen",Vn),ge.useContextCallback("handleScrollArrowVisibility",_t),ge.useContextCallback("onOpenChangeComplete",E),KT(()=>{ge.update({popupProps:_n,triggerProps:Yn})}),ge.useSyncedValues({id:G,modal:S,multiple:k,value:X,open:P,mounted:Ee,transitionStatus:Ce,popupProps:_n,triggerProps:Yn,items:R,itemToStringLabel:A,itemToStringValue:D,isItemEqualToValue:I,openMethod:Rt});const Cn=x.useMemo(()=>({disabled:$,readOnly:j,required:w,multiple:k,highlightItemOnHover:M,itemProps:Ln}),[$,j,w,k,M,Ln]),Gt=Yr(C,Y.inputRef),Jn=k?void 0:F,St=x.useMemo(()=>!k||!Array.isArray(X)||!F?null:X.map(ht=>{const vt=wa(ht,D);return s.jsx("input",{type:"hidden",form:v,name:F,value:vt,disabled:$},vt)}),[k,X,v,F,D,$]);return s.jsxs(YT.Provider,{value:ge,children:[s.jsx(XT.Provider,{value:Cn,children:s.jsx(QT.Provider,{value:Pn,children:O})}),s.jsx("input",{...Y.getValidationProps($,{onFocus(){ge.state.triggerElement?.focus({focusVisible:!0})},onChange(ht){if(ht.nativeEvent.defaultPrevented||$||j)return;const vt=ht.currentTarget.value,yt=Ve(Fn,ht.nativeEvent);function jr(){if(k)return;const nr=vt.toLowerCase();let Ir=ee.current.findIndex(Ja=>wa(Ja,D).toLowerCase()===nr||ho(Ja,A).toLowerCase()===nr);Ir===-1&&(Ir=ee.current.findIndex((Ja,Jt)=>{const ac=ie.current[Jt];return ac!=null&&ac.toLowerCase()===nr}));const gn=ee.current[Ir];gn!=null&<(gn,yt)}ge.set("forceMount",!0),queueMicrotask(jr)}}),id:G&&Jn==null?`${G}-hidden-input`:void 0,form:v,name:Jn,autoComplete:y,value:Qt,disabled:$,required:w&&!(k&&as),readOnly:j,ref:Gt,style:F?Kc:Ni,tabIndex:-1,"aria-hidden":!0,suppressHydrationWarning:!0}),St]})}function rE(e,t){return e??t}const ph=5;function aE(e,t){const r=YU(t);return e.clientX>=r.left-ph&&e.clientX<=r.right+ph&&e.clientY>=r.top-ph&&e.clientY<=r.bottom+ph}function YU(e){const t=e.getBoundingClientRect(),r=bn(e);if(pv)return t;const o=r.getComputedStyle(e,"::before"),c=r.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 XU="data-popup-side",QU=400,ZU={...xv,...gi,popupSide:e=>e?{[XU]:e}:null,value:()=>null},WU=x.forwardRef(function(t,r){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}=ya(),{labelId:C}=ml(),E=mo(),{readOnly:R,required:k,disabled:A}=ky(),D=N||A||f,I=E.useState("open"),M=E.useState("mounted"),O=E.useState("value"),_=E.useState("triggerProps"),L=E.useState("positionerElement"),z=E.useState("listElement"),U=E.useState("popupSide"),B=E.useState("id"),Q=E.useState("labelId"),W=E.useState("hasSelectedValue"),Z=M&&L?U:null,Y=d??B,q=rE(C,Q);no({id:d});const G=qn(L),$=x.useRef(null),{getButtonProps:F,buttonRef:X}=Kr({disabled:D,native:p}),re=E.useStateSetter("triggerElement"),P=Xs(),V=Xs(),J=Xs();x.useEffect(()=>{if(I)return J.start(QU,()=>{E.context.selectionRef.current.allowUnselectedMouseUp=!0,E.context.selectionRef.current.allowSelectedMouseUp=!0}),()=>{J.clear()};E.context.selectionRef.current={allowSelectedMouseUp:!1,allowUnselectedMouseUp:!1,dragY:0},V.clear()},[I,E,V,J]);const ie=Gr(_,{id:Y,role:"combobox","aria-expanded":I,"aria-haspopup":"listbox","aria-controls":I?z?.id??km(L)?.id:void 0,"aria-labelledby":q,"aria-readonly":R||void 0,"aria-required":k||void 0,tabIndex:D?-1:0,onFocus(ae){b(!0),I&&E.context.alignItemWithTriggerActiveRef.current&&E.context.setOpen(!1,Ve(Fn,ae.nativeEvent)),P.start(0,()=>{E.set("forceMount",!0)})},onBlur(ae){Ge(L,ae.relatedTarget)||(y(!0),b(!1),j==="onBlur"&&w.commit(O))},onMouseDown(ae){if(I)return;const oe=zt(ae.currentTarget);function ee(de){if(!$.current)return;const K=de.target;Ge($.current,K)||Ge(G.current,K)||aE(de,$.current)||E.context.setOpen(!1,Ve(Fk,de))}V.start(0,()=>{oe.addEventListener("mouseup",ee,{once:!0})})}},v,F),me=w.getValidationProps(D,ie);me.role="combobox";const he={...S,open:I,disabled:D,value:O,readOnly:R,popupSide:Z,placeholder:!W};return bt("button",t,{ref:[r,$,X,re],state:he,stateAttributesMapping:ZU,props:me})}),JU={value:()=>null},eV=x.forwardRef(function(t,r){const{className:o,render:c,children:d,placeholder:f,style:p,...g}=t,v=mo(),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),C={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=FU(y,b,j):E=nE(y,b,j),bt("span",t,{state:C,ref:[r,v.context.valueRef],props:[{children:E},g],stateAttributesMapping:JU})}),tV=x.forwardRef(function(t,r){const{render:o,className:c,style:d,...f}=t,v={open:mo().useState("open")};return bt("span",t,{state:v,ref:r,props:[{"aria-hidden":!0,children:"▼"},f],stateAttributesMapping:gv})}),nV=x.forwardRef(function(t,r){const o=mo(),c=o.useState("mounted"),d=o.useState("forceMount");return c||d?s.jsx(Um,{ref:r,...t}):null}),lE=x.createContext(void 0);function sV(){const e=x.useContext(lE);if(!e)throw new Error(nn(59));return e}function mh(e,t){e&&Object.assign(e.style,t)}const rV={position:"relative",maxHeight:"100%",overflowX:"hidden",overflowY:"auto"},aV=20;function Ey(e,t,r,o){const[c,d]=x.useState(!1);De(()=>{if(!e||!t||r==null){d(!1);return}const f=zt(r).documentElement.clientWidth,p=r.offsetWidth;d(f>0&&p>0&&p>=f-aV)},[e,t,r]),MT(e&&(!t||c),o)}const lV={position:"fixed"},oV=x.forwardRef(function(t,r){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:C=!0,collisionAvoidance:E=f1,style:R,...k}=t,A=mo(),D=ZT(),I=A.useState("open"),M=A.useState("mounted"),O=A.useState("modal"),_=A.useState("value"),L=A.useState("openMethod"),z=A.useState("positionerElement"),U=A.useState("triggerElement"),B=A.useState("isItemEqualToValue"),Q=A.useState("transitionStatus"),W=x.useRef(null),Z=x.useRef(null),[Y,q]=x.useState(C),G=M&&Y&&L!=="touch";!M&&Y!==C&&q(C),x.useImperativeHandle(A.context.alignItemWithTriggerActiveRef,()=>G),Ey((G||O)&&I,L==="touch",z,U);const $=th({anchor:o,floatingRootContext:D,positionMethod:f,mounted:M,side:p,sideOffset:v,align:g,alignOffset:y,arrowPadding:w,collisionBoundary:b,collisionPadding:j,sticky:S,disableAnchorTracking:N??G,collisionAvoidance:E,keepMounted:!0}),F=G?"none":$.side,X=G?lV:$.positionerStyles,re={open:I,side:F,align:$.align,anchorHidden:$.anchorHidden};De(()=>{A.set("popupSide",$.side)},[A,$.side]);const P=A.useStateSetter("positionerElement"),V=nh(t,re,{styles:X,transitionStatus:Q,props:k,refs:[r,P],hidden:!M,inert:!I}),J=x.useRef(0),ie=Ie(he=>{if(A.context.valuesRef.current.length===0)return;const ae=J.current;J.current=he.size;const oe=Ve(Fn);if(ae!==0&&!A.state.multiple&&_!==null&&Jc(A.context.valuesRef.current,_,B)===-1){const de=A.context.initialValueRef.current,be=de!=null&&Jc(A.context.valuesRef.current,de,B)!==-1?de:null;A.context.setValue(be,oe),be===null&&(A.set("selectedIndex",null),A.context.selectedItemTextRef.current=null)}if(ae!==0&&A.state.multiple&&Array.isArray(_)){const ee=_.filter(de=>Jc(A.context.valuesRef.current,de,B)!==-1);ee.length!==_.length&&(A.context.setValue(ee,oe),ee.length===0&&(A.set("selectedIndex",null),A.context.selectedItemTextRef.current=null))}if(I&&G){A.update({scrollUpArrowVisible:!1,scrollDownArrowVisible:!1});const ee={height:""};mh(z,ee),mh(A.context.popupRef.current,ee)}}),me=x.useMemo(()=>({...$,side:F,alignItemWithTriggerActive:G,setControlledAlignItemWithTrigger:q,scrollUpArrowRef:W,scrollDownArrowRef:Z}),[$,F,G,q]);return s.jsx(Cy,{elementsRef:A.context.listRef,labelsRef:A.context.labelsRef,onMapChange:ie,children:s.jsxs(lE.Provider,{value:me,children:[M&&O&&s.jsx(lh,{inert:sh(!I),cutout:U}),V]})})}),hh="base-ui-disable-scrollbar",oE={className:hh,getElement(e){return s.jsx("style",{nonce:e,href:hh,precedence:"base-ui:low",children:`.${hh}{scrollbar-width:none}.${hh}::-webkit-scrollbar{display:none}`})}},iV=x.createContext(void 0);function iE(e){return x.useContext(iV)}const cV=x.createContext(void 0),uV={disableStyleElements:!1};function dV(){return x.useContext(cV)??uV}const cE="--transform-origin",fV={...Uc,...so},pV=x.forwardRef(function(t,r){const{render:o,className:c,style:d,finalFocus:f,...p}=t,g=mo(),{multiple:v,readOnly:y,highlightItemOnHover:b}=ky(),j=ZT(),{side:w,align:S,alignItemWithTriggerActive:N,isPositioned:C,setControlledAlignItemWithTrigger:E}=sV(),R=iE()!=null,k=Wd(),{nonce:A,disableStyleElements:D}=dV(),I=g.useState("id"),M=g.useState("open"),O=g.useState("openMethod"),_=g.useState("mounted"),L=g.useState("popupProps"),z=g.useState("transitionStatus"),U=g.useState("triggerElement"),B=g.useState("positionerElement"),Q=g.useState("listElement"),W=x.useRef(!1),Z=x.useRef(!1),Y=x.useRef({}),q=Fc(),G=Ie(re=>{if(!B||!g.context.popupRef.current||!Z.current)return;const P=B.style.top==="0px",V=B.style.bottom==="0px";if(W.current||!N||!P&&!V){g.context.handleScrollArrowVisibility(re);return}const J=dE(B),ie=tf(B.getBoundingClientRect().height,"y",J),me=zt(B),he=bn(B),ae=he.getComputedStyle(B),oe=parseFloat(ae.marginTop),ee=parseFloat(ae.marginBottom),de=uE(he.getComputedStyle(g.context.popupRef.current)),K=Math.min(me.documentElement.clientHeight-oe-ee,de),be=re.scrollTop,ne=gh(re);let ce=null;const we=ke=>{B.style.height=`${ke}px`},Ee=P?ne-be:be,ve=Math.min(ie+Ee,K);if(Ee<=jl){const ke=Ci(Ee,0,K-ie);ke>0&&we(ie+ke),re.scrollTop=P?ne:0,K-(ie+ke)<=jl&&(W.current=!0),g.context.handleScrollArrowVisibility(re);return}if(K-ve>jl)ce=P?1/0:0;else if(V&&bejl&&(re.scrollTop=ke)}Ce>=K-jl&&(W.current=!0),g.context.handleScrollArrowVisibility(re)});x.useImperativeHandle(g.context.scrollHandlerRef,()=>G,[G]),Wr({open:M,ref:g.context.popupRef,onComplete(){M&&g.context.onOpenChangeComplete(!0)}});const $={open:M,transitionStatus:z,side:w,align:S};De(()=>{!B||!g.context.popupRef.current||Object.keys(Y.current).length||(Y.current={top:B.style.top||"0",left:B.style.left||"0",right:B.style.right,height:B.style.height,bottom:B.style.bottom,minHeight:B.style.minHeight,maxHeight:B.style.maxHeight,marginTop:B.style.marginTop,marginBottom:B.style.marginBottom})},[g,B]),De(()=>{M||N||(Z.current=!1,W.current=!1,mh(B,Y.current))},[M,N,B]),De(()=>{const re=g.context.popupRef.current;if(!M||!U||!B||!re||N&&!C||g.state.transitionStatus==="ending")return;if(Z.current=!0,re.style.removeProperty(cE),!N){q.request(()=>g.context.handleScrollArrowVisibility(Q||re));return}const P=mV(re);try{let V=g.context.selectedItemTextRef.current;V?.isConnected||(V=!g.select("hasSelectedValue")&&g.context.firstItemTextRef.current?.isConnected?g.context.firstItemTextRef.current:null);const J=g.context.valueRef.current,ie=bn(B),me=ie.getComputedStyle(B),he=ie.getComputedStyle(re),ae=zt(U),oe=dE(U),ee=xh(U.getBoundingClientRect(),oe),de=xh(B.getBoundingClientRect(),oe),K=ee.height,be=Q||re,ne=be.scrollHeight,ce=parseFloat(he.borderBottomWidth),we=parseFloat(me.marginTop)||10,Ee=parseFloat(me.marginBottom)||10,ve=parseFloat(me.minHeight)||100,Ce=uE(he),ke=5,Se=5,ge=20,Te=ae.documentElement.clientHeight-we-Ee,Oe=ae.documentElement.clientWidth,Ne=Te-ee.bottom+K;let Be,Xe=k==="rtl"?ee.right-de.width:ee.left,Rt=0;if(V&&J){const Zt=xh(J.getBoundingClientRect(),oe);Be=xh(V.getBoundingClientRect(),oe),Xe=de.left+(k==="rtl"?Zt.right-Be.right:Zt.left-Be.left);const Je=Zt.top-ee.top+Zt.height/2;Rt=Be.top-de.top+Be.height/2-Je}const Qt=Ne+Rt+Ee+ce;let Mt=Math.min(Te,Qt);const it=Te-we-Ee,Un=Qt-Mt,as=Oe-Se;B.style.left=`${Ci(Xe,ke,as-de.width)}px`,B.style.height=`${Mt}px`,B.style.maxHeight="none",B.style.marginTop=`${we}px`,B.style.marginBottom=`${Ee}px`,re.style.height="100%";const Vn=gh(be),fs=Un>=Vn-jl;fs&&(Mt=Math.min(Te,de.height)-(Un-Vn));const lt=ee.topTe-ge||Math.ceil(Mt)+jl=it?"0":`${Zt}px`,B.style.height=`${Mt}px`,be.scrollTop=gh(be)}else B.style.bottom="0",be.scrollTop=Un;if(Be){const Zt=de.top,Je=de.height,Tt=Be.top+Be.height/2,Lt=Ci(Je>0?(Tt-Zt)/Je*100:50,0,100);re.style.setProperty(cE,`50% ${Lt}%`)}(Pn===Te||Mt>=Ce)&&(W.current=!0),g.context.handleScrollArrowVisibility(be),b&&g.state.selectedIndex===null&&g.state.activeIndex===null&&g.context.listRef.current[0]!=null&&g.set("activeIndex",0)}finally{P()}},[g,M,B,U,N,E,q,Q,b,k,C]),x.useEffect(()=>{if(!N||!B||!M)return;const re=bn(B);function P(V){g.context.setOpen(!1,Ve(a4,V))}return jt(re,"resize",P)},[g,N,B,M]);const F={...Q?{role:"presentation"}:{role:"listbox","aria-multiselectable":v||void 0,"aria-readonly":y||void 0,id:`${I}-list`},onKeyDown(re){R&&rh.has(re.key)&&re.stopPropagation()},onScroll(re){Q||G(re.currentTarget)},...N&&{style:Q?{height:"100%"}:rV},className:!Q&&N?oE.className:void 0},X=bt("div",t,{ref:[r,g.context.popupRef],state:$,stateAttributesMapping:fV,props:[L,F,Jd(z),p]});return s.jsxs(x.Fragment,{children:[!D&&oE.getElement(A),s.jsx(Vm,{context:j,modal:!1,disabled:!_,openInteractionType:O,returnFocus:f,restoreFocus:!0,children:X})]})});function uE(e){const t=e.maxHeight;return t.endsWith("px")&&parseFloat(t)||1/0}function gh(e){return sE(e.scrollHeight,e.clientHeight)}function dE(e){return D1.getScale(e)}function tf(e,t,r){return e/r[t]}function xh(e,t){return zd({x:tf(e.x,"x",t),y:tf(e.y,"y",t),width:tf(e.width,"x",t),height:tf(e.height,"y",t)})}const fE=[["transform","none"],["scale","1"],["translate","0 0"]];function mV(e){const{style:t}=e,r={};for(const[o,c]of fE)r[o]=t.getPropertyValue(o),t.setProperty(o,c,"important");return()=>{for(const[o]of fE){const c=r[o];c?t.setProperty(o,c):t.removeProperty(o)}}}const pE=x.createContext(void 0);function Ry(){const e=x.useContext(pE);if(!e)throw new Error(nn(57));return e}const hV=x.memo(x.forwardRef(function(t,r){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=Ny({guess:!0,label:p,textRef:b}),w=mo(),{itemProps:S,multiple:N,disabled:C,readOnly:E}=ky(),R=C||g,k=w.useState("isActive",j.index),A=w.useState("open"),D=w.useState("isSelected",f),I=w.useState("isSelectedByFocus",j.index),M=w.useState("isItemEqualToValue"),O=j.index,_=x.useRef(null);De(()=>{const $=w.context.valuesRef.current;return $[O]=f,()=>{delete $[O]}},[O,f,w]),De(()=>{const $=w.state.value,F=w.state.selectedIndex;let X=F,re;N&&Array.isArray($)?(X=JT(O,f,w.context.valuesRef.current,$,M,F),re=X===O,O===F&&!re&&(w.context.selectedItemTextRef.current=null)):(re=$!==void 0&&ta(f,$,M),re&&(X=O)),w.set("selectedIndex",X),re&&b.current&&(w.context.selectedItemTextRef.current=b.current)},[O,N,M,w,f]);const L=x.useRef("mouse"),z=x.useRef(!1),{getButtonProps:U,buttonRef:B}=Kr({disabled:R,focusableWhenDisabled:!0,native:v,composite:!0}),Q={disabled:R,selected:D,highlighted:k};function W($){if(C||E)return;const F=w.state.value;if(N){const X=Array.isArray(F)?F:[],re=D?eE(X,f,M):[...X,f];w.context.setValue(re,Ve(Ud,$))}else w.context.setValue(f,Ve(Ud,$)),w.context.setOpen(!1,Ve(Ud,$))}function Z(){w.context.selectionRef.current.dragY=0}const Y={role:"option","aria-selected":D,tabIndex:A&&k?0:-1,onKeyDown($){w.set("activeIndex",O),$.key===" "&&w.context.typingRef.current&&$.preventDefault()},onClick($){const F=L.current!=="touch",X=$.nativeEvent.pointerType,re=F&&Tm($.nativeEvent)&&(X!==void 0||k),P=F&&!re&&!z.current;z.current=!1,!(R||P)&&W($.nativeEvent)},onPointerEnter($){L.current=$.pointerType},onPointerMove($){if($.pointerType==="mouse"&&$.buttons===1){const F=w.context.selectionRef.current;F.dragY+=$.movementY,F.dragY**2>=64&&(F.allowUnselectedMouseUp=!0)}},onPointerDown($){L.current=$.pointerType,z.current=!0,Z()},onMouseUp(){if(Z(),R||L.current==="touch"||z.current)return;const $=!w.context.selectionRef.current.allowSelectedMouseUp&&D,F=!w.context.selectionRef.current.allowUnselectedMouseUp&&!D;$||F||(z.current=!0,_.current?.click(),z.current=!1)}},q=bt("div",t,{ref:[B,r,j.ref,_],state:Q,props:[S,Y,y,U]}),G=x.useMemo(()=>({selected:D,index:O,textRef:b,selectedByFocus:I}),[D,O,b,I]);return s.jsx(pE.Provider,{value:G,children:q})})),gV=x.forwardRef(function(t,r){const{selected:o}=Ry();return t.keepMounted||o?s.jsx(xV,{...t,ref:r}):null}),xV=x.memo(x.forwardRef((e,t)=>{const{render:r,className:o,style:c,keepMounted:d,...f}=e,{selected:p}=Ry(),g=x.useRef(null),{transitionStatus:v,setMounted:y}=yi(p),j=bt("span",e,{ref:[t,g],state:{selected:p,transitionStatus:v},props:[{"aria-hidden":!0,children:"✔️"},f],stateAttributesMapping:so});return Wr({batch:!0,enabled:!p,open:p,ref:g,onComplete(){p||y(!1)}}),j})),bV=x.memo(x.forwardRef(function(t,r){const{index:o,textRef:c,selectedByFocus:d}=Ry(),f=mo(),{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 bt("div",t,{ref:[b,r,c],props:y})})),ct=KU,ut=eV;function dt({className:e,children:t,...r}){return s.jsxs(WU,{"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),...r,children:[t,s.jsx(tV,{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 ft({className:e,sideOffset:t=4,children:r,...o}){return s.jsx(nV,{children:s.jsx(oV,{sideOffset:t,className:"z-[35]",children:s.jsx(pV,{"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:r})})})}function Ye({className:e,children:t,...r}){return s.jsxs(hV,{"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),...r,children:[s.jsx(bV,{className:"min-w-0 flex-1 truncate",children:t}),s.jsx(gV,{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 Gn({options:e,value:t,onValueChange:r,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(k=>k.ready?{...k,ready:!1}:k);return}const N=w.getBoundingClientRect(),C=S.getBoundingClientRect(),E=C.left-N.left-w.clientLeft,R=C.width;v(k=>k.ready&&k.left===E&&k.width===R?k:{left:E,width:R,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(GT,{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=>r(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($T,{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 vV=x.createContext(void 0);function yV(){return x.useContext(vV)}const jV=x.forwardRef(function(t,r){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=ja(b||void 0),C=yV(),E=C?.value??[],R=(d||C?.disabled)??!1,[k,A]=$a({controlled:C?N!==void 0&&E.indexOf(N)>-1:g,default:c,name:"Toggle",state:"pressed"}),{getButtonProps:D,buttonRef:I}=Kr({disabled:R,native:j}),M={disabled:R,pressed:k},O=[I,r],_=[{"aria-pressed":k,onClick(U){const B=!k,Q=Ve(Fn,U.nativeEvent);p?.(B,Q),!Q.isCanceled&&(N&&C?.setGroupValue?.(N,B,Q),!Q.isCanceled&&A(B))}},S,D],L=bt("button",t,{enabled:!C,state:M,ref:O,props:_}),z=x.useMemo(()=>({disabled:R,focusableWhenDisabled:!1}),[R]);return C?s.jsx(HT,{tag:"button",render:v,className:o,style:w,metadata:z,state:M,refs:O,props:_}):L}),wV=Bc(["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 SV({className:e,variant:t,size:r,...o}){return s.jsx(jV,{"data-slot":"toggle",className:Ue(wV({variant:t,size:r}),e),...o})}function NV(e,t,r,o,c,d,f,p,g,v=2){const y=Vz(r.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 oo(r.current,y)?void 0:y}const mE=x.createContext(void 0),hE=x.createContext(void 0),gE=x.createContext(void 0),xE=x.createContext(!1),bE=x.createContext("");function Sa(){const e=x.useContext(mE);if(!e)throw new Error(nn(22));return e}function bh(){const e=x.useContext(hE);if(!e)throw new Error(nn(23));return e}function nf(){const e=x.useContext(gE);if(!e)throw new Error(nn(24));return e}function vE(){return x.useContext(bE)}function CV(){return x.useContext(xE)}const kV={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:r}=e;return t==null?!1:r==="multiple"&&Array.isArray(t)?t.length>0:!0},hasNullItemLabel:(e,t)=>t?tE(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 r=e.isItemEqualToValue,o=e.selectedValue;return Array.isArray(o)?o.some(c=>ta(t,c,r)):ta(t,o,r)},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 yE(e){return e==null?void 0:`${e}-popup`}function TV(e,t){return(r,o)=>r==null?!1:e.contains(r,o,t)}const jE=new Map;function EV(e={}){const t={usage:"search",sensitivity:"base",ignorePunctuation:!0,...e},r=`${zv(e.locale)}|${JSON.stringify(t)}`,o=jE.get(r);if(o)return o;const c=new Intl.Collator(e.locale,t),d={contains(f,p,g){if(!p)return!0;const v=ho(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=ho(f,g);return c.compare(v.slice(0,p.length),p)===0},endsWith(f,p,g){if(!p)return!0;const v=ho(f,g),y=p.length;return v.length>=y&&c.compare(v.slice(v.length-y),p)===0}};return jE.set(r,d),d}const RV=EV;function AV(e,t=!1){const{overflowY:r}=gr(e);return r!=="auto"&&r!=="scroll"?!1:t?e.clientHeight>0:e.scrollHeight>e.clientHeight}const wE=Symbol("none"),Ay={value:wE,index:-1};function OV(e,t,r){const o=e.get(t);if(o!==void 0||r===uh)return o;for(const[c,d]of e)if(ta(c,t,r))return d}function MV(e){const{id:t,onOpenChangeComplete:r,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:C=!1,inputRef:E,grid:R=!1,items:k,filteredItems:A,filter:D,filterQuery:I,openOnInputClick:M=!0,autoHighlight:O=!1,keepHighlight:_=!1,highlightItemOnHover:L=!0,loopFocus:z=!0,itemToStringLabel:U,itemToStringValue:B,isItemEqualToValue:Q=uh,virtualized:W=!1,inline:Z=!1,fillInputOnItemPress:Y=!0,modal:q=!1,limit:G=-1,autoComplete:$="list",formAutoComplete:F,locale:X,submitOnItemClick:re=!1}=e,{clearErrors:P}=Hc(),{setDirty:V,validityData:J,setFilled:ie,name:me,disabled:he,setTouched:ae,setFocused:oe,validationMode:ee,validation:de}=ya(),K=Wd(),be=no({id:t}),ne=RV({locale:X}),ce=Array.isArray(k)?null:k;if(ce&&typeof ce.label!="function")throw new Error(nn(100));const we=ce?ce.data:k,Ee=ce?.value,ve=Ee?void 0:we,Ce=x.useMemo(()=>{if(!A||!Ee)return;const Me=fh(A),_e=Me.map(Ee);let at;return{values:_e,findItem(Ut,kn){if(!at){at=new Map;for(let dn=0;dn<_e.length;dn+=1)at.has(_e[dn])||at.set(_e[dn],Me[dn])}return OV(at,Ut,kn)}}},[A,Ee]),ke=x.useMemo(()=>ce?Me=>ce.label(Me,Q,_e=>{const at=Ce?.findItem(_e,Q);return at!=null?ce.itemLabel(at):ho(_e,U)}):U,[ce,U,Ce,Q]),Se=x.useMemo(()=>ce?Object.assign(Me=>ce.itemLabel(Me),{selected:Me=>ho(Me,ke)}):U,[ce,ke,U]);function ge(Me){return ho(Me,ke)}const[Te,Oe]=x.useState(!1),[Ne,Be]=x.useState(null),Xe=x.useRef(Ne),Rt=x.useRef([]),Qt=x.useRef([]),Mt=x.useRef(null),it=x.useRef(null),Un=x.useRef(null),as=x.useRef(null),Vn=x.useRef(null),fs=x.useRef(!0),lt=x.useRef(!1),_t=x.useRef(null),Pn=x.useRef(null),Zt=x.useRef(null),Je=x.useRef(Ay),Tt=x.useRef(null),Lt=x.useRef([]),Yn=x.useRef(null),_n=he||S,Ln=me??j,Cn=y==="multiple",Gt=y==="single",Jn=p!==void 0||f!==void 0,St=we!==void 0,ht=A!==void 0;let vt;O==="always"?vt="always":vt=O?"input-change":!1;const[yt,jr]=$a({controlled:c,default:Cn?o??Er:o,name:"Combobox",state:"selectedValue"}),nr=x.useMemo(()=>D===null?()=>!0:D!==void 0?D:TV(ne,Se),[D,ne,Se]),Ir=Ts(()=>Jn?f??"":Gt?ge(yt):"").current,[gn,Ja]=$a({controlled:p,default:Ir,name:"Combobox",state:"inputValue"}),[Jt,ac]=$a({controlled:g,default:v,name:"Combobox",state:"open"}),kx=Ty(we),ur=!Jt&&Ne!==null?Ne:String(gn).trim(),Oa=Gt?ge(yt):"",Po=Gt&&!Te&&ur!==""&&Oa.length===ur.length&&ne.contains(Oa,ur),_o=Po?"":I??ur,xp=St&&ht&&Po&&(!ce||ce.hasValue(yt,Q)),lc=x.useMemo(()=>we?fh(we):Er,[we]),Lo=x.useMemo(()=>{if(A&&!xp)return A;if(!we)return Er;if(kx){const _e=we,at=[];let Ut=0;for(const kn of _e){if(G>-1&&Ut>=G)break;const dn=G>-1?G-Ut:1/0,Tn=_o===""?kn.items.slice(0,dn):[];if(_o!=="")for(const ls of kn.items){if(Tn.length>=dn)break;nr(ls,_o,Se)&&Tn.push(ls)}if(Tn.length>0){const ls={...kn,items:Tn};at.push(ls),Ut+=Tn.length}}return at}if(_o==="")return G>-1?lc.slice(0,G):lc;const Me=[];for(const _e of lc){if(G>-1&&Me.length>=G)break;nr(_e,_o,Se)&&Me.push(_e)}return Me},[A,xp,we,kx,_o,G,nr,Se,lc]),Ss=x.useMemo(()=>{if(Ce&&Lo===A)return Ce.values;const Me=fh(Lo);return Ee?Me.map(_e=>Ee(_e)):Me},[Lo,A,Ce,Ee]),Ze=Ts(()=>{let Me=null;return Z&&Jt&&St&&y!=="none"&&(Me=ef(Ss,yt,Q,Cn)),new Zc({id:be,labelId:void 0,selectedValue:yt,open:Jt,items:ve,selectionMode:y,name:Ln,form:w,disabled:_n,readOnly:N,required:C,grid:R,virtualized:W,openOnInputClick:M,itemToStringLabel:ke,isItemEqualToValue:Q,modal:q,autoHighlight:vt,submitOnItemClick:re,hasInputValue:Jn,mounted:!1,forceMounted:!1,transitionStatus:"idle",inline:Z,activeIndex:null,selectedIndex:Me,popupProps:{},listProps:{},inputProps:{},triggerProps:{},itemProps:ln,positionerElement:null,listElement:null,popupId:void 0,triggerElement:null,inputElement:null,inputGroupElement:null,popupSide:null,openMethod:null,inputInsidePopup:!0,inputOwnsFormValue:y==="none"},{onOpenChangeComplete:Bt,setOpen:Bt,setInputValue:Bt,setSelectedValue:Bt,setIndices:Bt,handleSelection:Bt,forceMount:Bt,requestSubmit:Bt,listRef:Rt,labelsRef:Qt,popupRef:Mt,emptyRef:Vn,inputRef:it,startDismissRef:Un,endDismissRef:as,keyboardActiveRef:fs,chipsContainerRef:_t,clearRef:Pn,valuesRef:Lt,pointerDownItemRef:Yn,selectionEventRef:Zt},kV)}).current,Ml=y==="none"?gn:yt,Tx=x.useMemo(()=>y==="none"?Ml:Array.isArray(yt)?yt.map(Me=>wa(Me,B)):wa(yt,B),[Ml,B,y,yt]),Ma=Ie(b),Ns=Ie(r),$s=Ze.useState("activeIndex"),zo=Ze.useState("selectedIndex"),oc=Ze.useState("positionerElement"),Ex=Ze.useState("listElement"),ic=Ze.useState("triggerElement"),cc=Ze.useState("inputElement"),uc=Ze.useState("inputGroupElement"),Cs=Ze.useState("inline"),sr=Ze.useState("inputInsidePopup"),Dl=Ze.useState("inputOwnsFormValue"),Il=Gt&&!sr&&gn===Oa,dc=qn(ic),{mounted:Bo,setMounted:ps,transitionStatus:bp}=yi(Jt),{openMethod:Rx,triggerProps:vp}=_T(Jt),Pl=Ie(()=>Tx);qc(sr?dc:it,be,Ml,Pl,!_n,j);const _l=Ie(()=>{we?Qt.current=Ss.map(ge):Ze.set("forceMounted",!0)}),Ho=Ie((Me,_e,at)=>{if(_e===-1){if(Je.current===Ay)return;Je.current=Ay}else Je.current={value:Me,index:_e};Ma(Me,l4(at,void 0,{index:_e}))}),Pr=Ie(Me=>{const _e={};Me.activeIndex!==void 0&&(_e.activeIndex=Me.activeIndex),Me.selectedIndex!==void 0&&(_e.selectedIndex=Me.selectedIndex),Ze.update(_e);const at=Me.activeIndex;if(at===void 0)return;const Ut=Me.type||Fn;at===null?Ho(void 0,-1,Ut):Ho(Lt.current[at],at,Ut)}),_r=Ie((Me,_e)=>{if(e.onInputValueChange?.(Me,_e),!_e.isCanceled){if(lt.current=_e.reason===Fa,_e.reason===Vd){Jt&&Ne!==null&&Be(null);const at=_e.event,Ut=at.inputType;if(at.type==="compositionend"||Ut!=null&&Ut!==""&&Ut!=="insertReplacementText"){const dn=Me.trim()!=="";dn&&Oe(!0),Tt.current={hasQuery:dn};const Tn=Ze.state.listElement;if(!Ze.state.virtualized&&Tn){const ls=Mt.current;for(const wr of Lc(Tn.firstElementChild??Tn)){if(!an(wr)||(ls?!Ge(ls,wr):wr.getAttribute("role")==="dialog"))break;if(AV(wr)){wr.scrollTop=0;break}}}dn&&vt&&Ze.state.activeIndex==null&&(Jt||Cs)&&Ze.set("activeIndex",0)}}else _e.reason===Fa&&Me===""&&Ze.state.inputInsidePopup&&(Tt.current={hasQuery:!1,selection:!0});Ja(Me)}}),Ax=Ie(Me=>{const _e=!Me&&sr&&!Cs&&gn!==""&&(String(gn).trim()===Ne||gn===Oa);!Me&&(_e||gn===""||Il)&&Oe(!1),Be(null),_e&&_r("",Ve(Fa))}),Et=Ie((Me,_e)=>{if(Jt!==Me&&(_e.reason===Gc&&St&&Ss.length===0&&!Vn.current&&_e.allowPropagation(),e.onOpenChange?.(Me,_e),!_e.isCanceled&&(Me&&Ne!==null&&Ax(_e.reason===Vd),!Me&&Te&&(Gt?(Cs||Be(ur),ur===""&&Oe(!1)):Cn&&(Cs||Be(ur),sr&&Pr({activeIndex:null}),(!sr||Cs)&&_r("",Ve(Fa,_e.event,void 0,{isItemPress:_e.reason===Ud})))),ac(Me),!Me&&sr&&(_e.reason===uo||_e.reason===Lm)&&(ae(!0),oe(!1),ee==="onBlur")))){const at=y==="none"?gn:yt;de.commit(at)}}),fc=Ie((Me,_e)=>{if(d?.(Me,_e),_e.isCanceled)return;jr(Me),(y==="none"&&Mt.current&&Y||Gt&&!Ze.state.inputInsidePopup)&&_r(ge(Me),Ve(_e.reason,_e.event))}),$u=Ie((Me,_e)=>{const at=ns(Me),Ut=Zt.current??Me;Zt.current=null;const kn=Ve(Ud,Ut),dn=at?.closest("a")?.getAttribute("href");if(dn){dn.startsWith("#")&&Et(!1,kn);return}if(Cn){const Tn=Array.isArray(yt)?yt:[],ls=dh(Tn,_e,Q),wr=ls?eE(Tn,_e,Q):[...Tn,_e];if(fc(wr,kn),kn.isCanceled||!(it.current?it.current.value.trim()!=="":!1))return;if(Ze.state.inputInsidePopup){_r("",Ve(Fa,kn.event,void 0,{isItemPress:!0}));const zr=Tt.current;zr&&!ls&&(zr.toggledValue=_e)}else Et(!1,kn)}else{if(fc(_e,kn),kn.isCanceled)return;Et(!1,kn)}}),Fu=Ie(()=>{const Me=de.inputRef.current?.form??Ze.state.inputElement?.form;Me&&typeof Me.requestSubmit=="function"&&Me.requestSubmit()}),Lr=Ie(()=>{if(ps(!1),Ns?.(!1),Oe(!1),Be(null),Pr(y==="none"?{activeIndex:null,selectedIndex:null}:{activeIndex:null}),Cn&&it.current&&it.current.value!==""&&!lt.current&&_r("",Ve(Fa)),Gt)if(Ze.state.inputInsidePopup)it.current&&it.current.value!==""&&_r("",Ve(Fa));else{const Me=ge(yt);it.current&&it.current.value!==Me&&_r(Me,Ve(Me===""?Fa:Fn))}}),dr=x.useMemo(()=>Cs&&oc?{current:oc.closest('[role="dialog"]')}:Mt,[Cs,oc]);Wr({enabled:!e.actionsRef,open:Jt,ref:dr,onComplete(){Jt||Lr()}}),x.useImperativeHandle(e.actionsRef,()=>({unmount:Lr}),[Lr]),De(function(){const _e=Xe.current!==null&&Ne===null;if(Xe.current=Ne,Jt&&(!_e||!St)||(Jt||(Yn.current=null),y==="none"))return;const at=St?Ss:Lt.current;Pr({selectedIndex:ef(at,yt,Q,Cn)})},[Jt,Ne,yt,y,Cn,St,Ss,Q,Pr]),De(()=>{we&&(Lt.current=Ss,Rt.current.length=Ss.length)},[we,Ss]),De(()=>{const Me=Tt.current;if(Me){const ls=Jt||Cs||Ze.state.positionerElement?.hidden===!1;if(Me.hasQuery)vt&&ls&&Ze.set("activeIndex",0),Tt.current=null;else if(String(gn).trim()===""&&(Tt.current=null,ls)){const wr=Me.selection;vt==="always"&&!wr&&Ze.state.selectionMode==="none"&&Ze.set("activeIndex",0),queueMicrotask(()=>{if(!Ze.state.open&&!Ze.state.inline||it.current&&it.current.value.trim()!=="")return;const da=Ze.state.selectedValue,zr=Ze.state.selectionMode==="multiple";if(zr&&Array.isArray(da)?da.length>0:Ze.state.selectionMode!=="none"&&da!=null){const Ms=St||ht?Ss:Lt.current,Ia=Jc(Ms,Me.toggledValue,Ze.state.isItemEqualToValue);Ze.set("activeIndex",Ia!==-1?Ia:ef(Ms,da,Ze.state.isItemEqualToValue,zr))}else wr?Ze.set("activeIndex",null):vt==="always"&&Ze.set("activeIndex",0)})}}if(!Jt&&!Cs)return;const at=St||ht?Ss:Lt.current,Ut=Ze.state.activeIndex;if(Ut==null){if(vt==="always"&&at.length>0){Ze.set("activeIndex",0);return}Ho(void 0,-1,Fn);return}if(Ut>=at.length){Ho(void 0,-1,Fn),Ze.set("activeIndex",null);return}const kn=at[Ut],dn=Je.current.value,Tn=dn!==wE&&ta(kn,dn,Ze.state.isItemEqualToValue);(Je.current.index!==Ut||!Tn)&&Ho(kn,Ut,Fn)},[$s,vt,Ho,ht,St,Ss,Cs,Jt,Ze,gn]),De(()=>{if(y==="none"){ie(String(gn)!=="");return}ie(Cn?Array.isArray(yt)&&yt.length>0:yt!=null)},[ie,y,gn,yt,Cn]),x.useEffect(()=>{St&&vt&&Ss.length===0&&Pr({activeIndex:null})},[St,vt,Ss.length,Pr]);function Ox(){Jt&&ur!==""&&ur!==String(Ir)&&!Il&&Oe(!0)}function lS(){Jt&&Ne!==null&&Ax(!1)}let qu=!1;function yp(){!qu&&gn!==Oa&&(qu=!0,_r(Oa,Ve(Fn)))}function oS(){y!=="none"&&(P(Ln),V(WT(yt,J.initialValue,Q)),de.change(yt),Gt&&!Jn&&!sr&&yp())}function fr(){Gt&&!Jn&&!sr&&!Te&&yp()}function jp(){y==="none"&&(P(Ln),V(gn!==J.initialValue),de.change(gn))}Jr(ur,Ox),Jr(Jt,lS),Jr(yt,oS),Jr(Oa,fr),Jr(we,fr),Jr(gn,jp);const pc=W1({open:Cs?!0:Jt,onOpenChange:Et,elements:{reference:sr?ic:cc,floating:oc}}),Gu=R?"grid":"listbox",Da=Jt||Cs,wp=Da?"true":"false",mc=x.useMemo(()=>{const Me=cc?.tagName==="INPUT",_e=cc==null||Me,at=_e||Da,Ut=_e?{autoComplete:"off",spellCheck:"false",autoCorrect:"off",autoCapitalize:"none"}:{};return at&&(Ut.role="combobox",Ut["aria-expanded"]=wp,Ut["aria-haspopup"]=Gu,Ut["aria-controls"]=Da?Ex?.id:void 0,Ut["aria-autocomplete"]=N?"none":$),{reference:Ut,floating:{role:"presentation"}}},[cc,Da,wp,Gu,Ex?.id,$,N]),Ll=$m(pc,{enabled:!_n&&M,event:"mousedown-only",toggle:!1,touchOpenDelay:sr?0:100,reason:s4}),Ku=Xd(pc,{enabled:!_n&&!Cs,outsidePressEvent:{mouse:"sloppy",touch:"intentional"},bubbles:Cs?!0:void 0,outsidePress(Me){const _e=ns(Me);return!Ge(ic,_e)&&!Ge(Pn.current,_e)&&!Ge(_t.current,_e)&&!Ge(uc,_e)}}),zl=sT(pc,{enabled:!_n,id:be,listRef:Rt,activeIndex:$s,selectedIndex:zo,virtual:!0,loopFocus:z,allowEscape:z&&!vt,focusItemOnOpen:Te||y==="none"&&!vt?!1:"auto",focusItemOnHover:L,resetOnPointerLeave:!_,orientation:R?"horizontal":void 0,rtl:K==="rtl",disabledIndices:Er,grid:R?NV:void 0,onNavigate(Me,_e){!_e&&!Jt||bp==="ending"||Pr(_e?{activeIndex:Me,type:fs.current?Vk:$k}:{activeIndex:Me})}}),Sp=x.useMemo(()=>Gr(zl.reference,{onKeyDown(Me){R&&Ze.state.activeIndex==null&&(Me.key==="ArrowLeft"||Me.key==="ArrowRight")&&Me.preventBaseUIHandler()}},Ku.reference,Ll.reference,mc.reference),[zl.reference,Ku.reference,Ll.reference,mc.reference,R,Ze]),Yu=x.useMemo(()=>Gr(Qd,Ku.floating),[Ku.floating]),Mx=x.useMemo(()=>Gr(zl.floating,mc.floating),[zl.floating,mc.floating]),Dx=x.useMemo(()=>{const Me=zl.item;return Me?{...Me,onFocus:void 0}:ln},[zl.item]);Ze.useContextCallback("setOpen",Et),Ze.useContextCallback("setInputValue",_r),Ze.useContextCallback("setSelectedValue",fc),Ze.useContextCallback("setIndices",Pr),Ze.useContextCallback("handleSelection",$u),Ze.useContextCallback("forceMount",_l),Ze.useContextCallback("requestSubmit",Fu),Ze.useContextCallback("onOpenChangeComplete",r),KT(()=>{Ze.update({inline:Z,popupProps:Yu,listProps:Mx,inputProps:Sp,triggerProps:vp,itemProps:Dx})});const hc={id:be,selectedValue:yt,open:Jt,mounted:Bo,transitionStatus:bp,items:ve,inline:Z,popupProps:Yu,listProps:Mx,inputProps:Sp,triggerProps:vp,itemProps:Dx,openMethod:Rx,selectionMode:y,name:Ln,form:w,disabled:_n,readOnly:N,required:C,grid:R,virtualized:W,openOnInputClick:M,itemToStringLabel:ke,modal:q,autoHighlight:vt,isItemEqualToValue:Q,submitOnItemClick:re,hasInputValue:Jn};De(()=>{Ze.update({...hc,inputOwnsFormValue:y==="none"&&(Z||!Ze.state.inputInsidePopup)})},[Ze,...Object.values(hc)]);const ua=Yr(E,de.inputRef),Np=x.useMemo(()=>({query:ur,hasItems:St,filteredItems:Lo,flatFilteredValues:Ss}),[ur,St,Lo,Ss]),Cp=x.useMemo(()=>Array.isArray(Ml)?"":wa(Ml,B),[Ml,B]),Uo=Cn&&Array.isArray(yt)&&yt.length>0,el=Cn||y==="none"&&Dl?void 0:Ln,Ix=x.useMemo(()=>!Cn||!Array.isArray(yt)||!Ln?null:yt.map(Me=>{const _e=wa(Me,B);return s.jsx("input",{type:"hidden",form:w,name:Ln,value:_e,disabled:_n},_e)}),[Cn,yt,w,Ln,B,_n]),kp=s.jsxs(x.Fragment,{children:[e.children,s.jsx("input",{...de.getValidationProps(_n,{onFocus(){if(sr){ic?.focus();return}(it.current||ic)?.focus()},onChange(Me){if(Me.nativeEvent.defaultPrevented||_n||N)return;const _e=Me.currentTarget.value,at=_e.toLowerCase(),Ut=Ve(Fn,Me.nativeEvent),kn=()=>Lt.current.findIndex(Tn=>wa(Tn,B).toLowerCase()===at||ge(Tn).toLowerCase()===at);function dn(){if(Cn)return;if(y==="none"){_r(_e,Ut);return}let Tn=kn();Tn===-1&&(Tn=Lt.current.findIndex((wr,da)=>{const zr=Qt.current[da];return zr!=null&&zr.toLowerCase()===at}));const ls=Tn===-1?void 0:Lt.current[Tn];ls!=null&&fc?.(ls,Ut)}Gt&&(_l(),we&&kn()===-1&&Ze.set("forceMounted",!0)),queueMicrotask(dn)}}),id:be&&el==null?`${be}-hidden-input`:void 0,form:w,name:el,autoComplete:F,disabled:_n,required:C&&!Uo,readOnly:N,value:Cp,ref:ua,style:el?Kc:Ni,tabIndex:-1,"aria-hidden":!0,suppressHydrationWarning:!0}),Ix]});return s.jsx(mE.Provider,{value:Ze,children:s.jsx(hE.Provider,{value:pc,children:s.jsx(xE.Provider,{value:St,children:s.jsx(gE.Provider,{value:Np,children:s.jsx(bE.Provider,{value:gn,children:kp})})})})})}function DV(e){const{multiple:t=!1,defaultValue:r,value:o,onValueChange:c,autoComplete:d,...f}=e;return s.jsx(MV,{...f,selectionMode:t?"multiple":"single",selectedValue:o,defaultSelectedValue:r,onSelectedValueChange:c,formAutoComplete:d})}const IV="data-popup-side",PV="data-list-empty",SE={...xv,...gi,popupSide:e=>e?{[IV]:e}:null,listEmpty:e=>e?{[PV]:""}:null},_V=x.createContext(void 0);function LV(){return x.useContext(_V)}const NE=x.createContext(void 0);function Oy(e){const t=x.useContext(NE);if(t===void 0&&!e)throw new Error(nn(21));return t}const CE=x.forwardRef(function(t,r){const o=Sa(),{buttonRef:c,getButtonProps:d}=Kr({native:!1}),f=Yr(r,c);function p(v){o.context.setOpen(!1,Ve(Iv,v.nativeEvent,v.currentTarget))}const g=d({onClick:p});return s.jsx("span",{ref:f,...g,"aria-label":"Dismiss",tabIndex:void 0,style:Kc})});function kE(e){const t=e.useState("mounted"),r=e.useState("popupSide"),o=e.useState("positionerElement");return t&&o?r:null}function vh(){return nf().filteredItems.length===0}function zV(e){return e==="rtl"?["ArrowRight","ArrowLeft"]:["ArrowLeft","ArrowRight"]}function BV(e,t){const r=e>=t-1?t-2:e;return r>=0?r:void 0}function TE(e,t,r){const o=e.context.listRef.current[t];o&&(e.context.selectionEventRef.current=r,o.click(),e.context.selectionEventRef.current=null)}const HV=x.forwardRef(function(t,r){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}=ya(),{labelId:N}=ml(),C=LV(),R=!!Oy(!0),k=Sa(),A=vE(),D=Wd(),I=k.useState("required"),M=k.useState("disabled"),O=k.useState("readOnly"),_=k.useState("name"),L=k.useState("form"),z=k.useState("selectionMode"),U=k.useState("autoHighlight"),B=k.useState("inputProps"),Q=k.useState("triggerProps"),W=k.useState("open"),Z=k.useState("mounted"),Y=k.useState("selectedValue"),q=k.useState("id"),G=k.useState("inline"),$=k.useState("modal"),F=!!U,X=kE(k),re=y||M||d,P=vh(),V=R||G,J=!V||$,ie=ja(f??(V?void 0:q)),me=R?uk:v,[he,ae]=x.useState(null),oe=x.useRef(!1),ee=x.useRef(null),de=x.useRef(!1),K=z==="none"&&!R,be=Ie(Se=>{const ge=R||k.state.inline;ge&&!k.state.hasInputValue&&k.context.setInputValue("",Ve(Fn)),k.update({inputElement:Se,inputInsidePopup:ge,inputOwnsFormValue:K})}),ne=R?g:S.getValidationProps(re,g);function ce(){k.context.setIndices({activeIndex:null,selectedIndex:null,type:k.context.keyboardActiveRef.current?Vk:$k})}function we(){k.context.keyboardActiveRef.current=!1}const Ee={...me,open:W,disabled:re,readOnly:O,popupSide:X,listEmpty:P};function ve(Se){if(!C)return;let ge;const{highlightedChipIndex:Te}=C,Oe=C.chipsRef.current.length,[Ne,Be]=zV(D);return Te!==void 0?(Se.key===Ne?(Se.preventDefault(),Te>0?ge=Te-1:ge=void 0):Se.key===Be?(Se.preventDefault(),Te0&&(Se.preventDefault(),ge=Oe>0?Oe-1:void 0),ge)}const Ce=bt("input",t,{state:Ee,ref:[r,k.context.inputRef,be],props:[B,Q,{value:he??A,"aria-readonly":O||void 0,"aria-required":I||void 0,"aria-labelledby":N,disabled:re,readOnly:O,required:z==="none"?I:void 0,form:L,...K&&_&&{name:_},id:ie,onFocus(){if(j(!0),!G||!de.current)return;de.current=!1;const Se=ee.current;Se==null||!Object.hasOwn(k.context.valuesRef.current,Se)||k.context.setIndices({activeIndex:Se})},onBlur(){b(!0),j(!1);const Se=k.state.activeIndex;if(G&&Se!==null&&U!=="always"&&(ee.current=Se,de.current=!0,k.context.setIndices({activeIndex:null})),w==="onBlur"){const ge=z==="none"?A:Y;S.commit(ge)}},onCompositionStart(Se){wm||(oe.current=!0,ae(Se.currentTarget.value))},onCompositionEnd(Se){oe.current=!1;const ge=Se.currentTarget.value;ae(null),k.context.setInputValue(ge,Ve(Vd,Se.nativeEvent))},onChange(Se){const ge=Se.nativeEvent,Te=ge.inputType,Oe=!Te||Te==="insertReplacementText",Ne=oe.current||!Oe;function Be(Mt){O||re||!Mt||!Ne||(k.context.setOpen(!0,Ve(Vd,ge)),F||ce())}if(oe.current){const Mt=Se.currentTarget.value;ae(Mt),Mt===""&&!k.state.openOnInputClick&&!k.state.inputInsidePopup&&k.context.setOpen(!1,Ve(Fa,ge));const it=Mt.trim(),Un=F&&it!=="";Be(it),W&&k.state.activeIndex!==null&&!Un&&ce();return}const Xe=Ve(Vd,ge);if(k.context.setInputValue(Se.currentTarget.value,Xe),Xe.isCanceled)return;const Rt=Se.currentTarget.value==="",Qt=Ve(Fa,ge);Rt&&!k.state.inputInsidePopup&&(z==="single"&&k.context.setSelectedValue(null,Qt),k.state.openOnInputClick||k.context.setOpen(!1,Qt)),Be(Se.currentTarget.value.trim()),W&&k.state.activeIndex!==null&&!F&&ce()},onKeyDown(Se){if(Se.ctrlKey||Se.shiftKey||Se.altKey||Se.metaKey)return;if(k.context.keyboardActiveRef.current=!0,re||O){O&&Se.key==="Enter"&&W&&k.state.activeIndex!==null&&vs(Se);return}const ge=Se.currentTarget,Te=ge.scrollWidth-ge.clientWidth,Oe=D==="rtl";if(Se.key==="Home"){vs(Se);const Xe=xk&&Oe?ge.value.length:0;ge.setSelectionRange(Xe,Xe),ge.scrollLeft=0;return}if(Se.key==="End"){vs(Se);const Xe=xk&&Oe?0:ge.value.length;ge.setSelectionRange(Xe,Xe),ge.scrollLeft=Oe?-Te:Te;return}if(!Z&&Se.key==="Escape"){const Xe=z==="multiple"&&Array.isArray(Y)?Y.length===0:Y===null,Rt=Ve(Gc,Se.nativeEvent),Qt=z==="multiple"?[]:null;k.context.setInputValue("",Rt),k.context.setSelectedValue(Qt,Rt),!Xe&&!k.state.inline&&!Rt.isPropagationAllowed&&Se.stopPropagation();return}if(C&&Se.key==="Backspace"&&ge.value===""&&C.highlightedChipIndex===void 0&&Array.isArray(Y)&&Y.length>0){const Xe=C.chipsRef.current.length,Rt=Xe>0?Xe-1:Y.length-1,Qt=Y.filter((Mt,it)=>it!==Rt);ce(),k.context.setSelectedValue(Qt,Ve(Fn,Se.nativeEvent));return}const Ne=C?.highlightedChipIndex!==void 0,Be=ve(Se);if(C?.setHighlightedChipIndex(Be),Be!==void 0?C?.chipsRef.current[Be]?.focus():Ne&&k.context.inputRef.current?.focus(),Se.which!==229&&Se.key==="Enter"&&W){const Xe=k.state.activeIndex,Rt=Se.nativeEvent;if(Xe===null){if(G)return;k.context.setOpen(!1,Ve(Fn,Rt));return}vs(Se),TE(k,Xe,Rt)}},onPointerMove:we,onPointerDown:we},ne],stateAttributesMapping:SE}),ke=R?s.jsx(fk.Provider,{value:dk,children:Ce}):Ce;return s.jsxs(x.Fragment,{children:[W&&J&&s.jsx(CE,{ref:k.context.startDismissRef}),ke]})}),UV=x.forwardRef(function(t,r){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}=ya(),{labelId:C}=ml(),E=Sa(),R=E.useState("selectionMode"),k=E.useState("disabled"),A=E.useState("readOnly"),D=E.useState("required"),I=E.useState("positionerElement"),M=E.useState("listElement"),O=E.useState("popupId"),_=E.useState("triggerProps"),L=E.useState("inputInsidePopup"),z=E.useState("id"),U=E.useState("labelId"),B=E.useState("open"),Q=E.useState("selectedValue"),W=E.useState("activeIndex"),Z=E.useState("selectedIndex"),Y=E.useState("hasSelectedValue"),q=bh(),G=vE(),$=Xs(),F=b||k||f,X=vh(),re=kE(E);no({id:L?p:void 0});const P=L?p??z:p,V=rE(C,U);let J;B&&L?J=O??yE(z):B&&(J=M?.id);const ie=x.useRef("");function me(ne){ie.current=ne.pointerType}const{reference:he}=rT(q,{enabled:!B&&!A&&!k&&R==="single",listRef:E.context.labelsRef,activeIndex:W,selectedIndex:Z,onMatch(ne){const ce=E.context.valuesRef.current[ne];ce!==void 0&&E.context.setSelectedValue(ce,Ve(Fn))}}),{reference:ae}=$m(q,{enabled:!k,event:"mousedown"}),{buttonRef:oe,getButtonProps:ee}=Kr({native:d,disabled:F}),de={...y,readOnly:A,open:B,disabled:F,popupSide:re,listEmpty:X,placeholder:R==="none"?!1:!Y},K=Ie(ne=>{E.set("triggerElement",ne)});return bt("button",t,{ref:[r,oe,K],state:de,props:[_,ae,he,{id:P,tabIndex:L?0:-1,role:L?"combobox":void 0,"aria-expanded":B,"aria-haspopup":L?"dialog":"listbox","aria-controls":J,"aria-required":L&&D||void 0,"aria-readonly":L&&A||void 0,"aria-labelledby":V,onPointerDown:me,onPointerEnter:me,onFocus(){w(!0),!F&&$.start(0,E.context.forceMount)},onBlur(ne){if(!Ge(I,ne.relatedTarget)&&(j(!0),w(!1),S==="onBlur")){const ce=R==="none"?G:Q;N.commit(ce)}},onMouseDown(ne){if(F||(L||q.set("domReferenceElement",ne.currentTarget),E.context.forceMount(),ie.current!=="touch"&&(E.context.inputRef.current?.focus(),L||ne.preventDefault()),B))return;const ce=zt(ne.currentTarget);function we(Ee){const ve=E.state.triggerElement;if(!ve)return;const Ce=ns(Ee),ke=E.state.positionerElement,Se=E.state.listElement;Ge(ve,Ce)||Ge(ke,Ce)||Ge(Se,Ce)||aE(Ee,ve)||E.context.setOpen(!1,Ve(Fk,Ee))}L&&ce.addEventListener("mouseup",we,{once:!0})},onKeyDown(ne){(ne.key==="ArrowDown"||ne.key==="ArrowUp")&&(vs(ne),E.context.setOpen(!0,Ve(Pv,ne.nativeEvent)),E.context.inputRef.current?.focus())}},N.getValidationProps(F,v),ee],stateAttributesMapping:SE})}),VV=x.createContext(null);function $V(){return x.useContext(VV)}function FV(e){const{children:t}=e,{filteredItems:r}=nf(),o=$V(),c=o?o.items:r;return s.jsx(x.Fragment,{children:c.map(t)})}const qV=x.forwardRef(function(t,r){var o;const{render:c,className:d,style:f,children:p,...g}=t,v=Sa(),y=bh(),b=!!Oy(!0),{filteredItems:j,hasItems:w}=nf(),S=v.useState("selectionMode"),N=v.useState("grid"),C=v.useState("readOnly"),E=v.useState("listProps"),R=v.useState("virtualized"),k=v.useState("forceMounted"),A=S==="multiple",D=j.length===0,I=Ie(B=>{v.set("positionerElement",B)}),M=Ie(B=>{v.set("listElement",B)}),O=x.useMemo(()=>typeof p=="function"?o||(o=s.jsx(FV,{children:p})):p,[p]),_={empty:D},L=y.useState("floatingId"),z=bt("div",t,{state:_,ref:[r,M,b?null:I],props:[E,{children:O,tabIndex:-1,id:L,role:N?"grid":"listbox","aria-multiselectable":A?"true":void 0,"aria-readonly":!N&&C?!0:void 0,onKeyDown(B){if(!(v.state.disabled||v.state.readOnly)&&B.key==="Enter"){const Q=v.state.activeIndex;if(Q==null)return;vs(B),TE(v,Q,B.nativeEvent)}},onKeyDownCapture(){v.context.keyboardActiveRef.current=!0},onPointerMoveCapture(){v.context.keyboardActiveRef.current=!1}},g]});if(R)return z;const U=w&&!k?void 0:v.context.labelsRef;return s.jsx(Cy,{elementsRef:v.context.listRef,labelsRef:U,children:z})}),GV="⁠",KV=200;function YV(e){const t=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT);let r=null;for(;t.nextNode();){const o=t.currentNode;o.nodeValue!==""&&(r=o)}return r}function XV(){const e=Xs(),t=x.useRef(null);return x.useEffect(()=>{if(Ld)return;const r=t.current;if(r==null)return;const o=YV(r);if(o==null)return;const c=o.data,d=`${c}${GV}`;return o.nodeValue=d,e.start(KV,()=>{o.nodeValue===d&&(o.nodeValue=c)}),()=>{e.clear(),o.nodeValue===d&&(o.nodeValue=c)}},[t,e]),t}const EE=x.createContext(void 0);function QV(){const e=x.useContext(EE);if(e===void 0)throw new Error(nn(20));return e}const ZV=x.forwardRef(function(t,r){const{keepMounted:o=!1,...c}=t,d=Sa(),f=d.useState("mounted"),p=d.useState("forceMounted");return f||o||p?s.jsx(EE.Provider,{value:o,children:s.jsx(Um,{ref:r,...c})}):null}),WV=x.forwardRef(function(t,r){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:C=f1,style:E,...R}=t,k=Sa(),A=bh(),D=QV(),I=k.useState("modal"),M=k.useState("open"),O=k.useState("mounted"),_=k.useState("openMethod"),L=k.useState("positionerElement"),z=k.useState("triggerElement"),U=k.useState("inputElement"),B=k.useState("inputGroupElement"),Q=k.useState("inputInsidePopup"),W=k.useState("transitionStatus"),Z=vh(),q=th({anchor:d??(Q?z:B??U),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:D,collisionAvoidance:C,lazyFlip:!0});Ey(M&&I,_==="touch",L,z);const G={open:M,side:q.side,align:q.align,anchorHidden:q.anchorHidden,empty:Z};De(()=>{k.set("popupSide",q.side)},[k,q.side]);const $=Ie(X=>{k.set("positionerElement",X)}),F=nh(t,G,{styles:q.positionerStyles,transitionStatus:W,props:R,refs:[r,$],hidden:!O,inert:!M});return s.jsxs(NE.Provider,{value:q,children:[O&&I&&s.jsx(lh,{inert:sh(!M),cutout:B??U??z}),F]})}),JV={...Uc,...so},e6=x.forwardRef(function(t,r){const{render:o,className:c,style:d,initialFocus:f,finalFocus:p,...g}=t,v=Sa(),y=Oy(),b=bh(),j=v.useState("mounted"),w=v.useState("open"),S=v.useState("openMethod"),N=v.useState("popupProps"),C=v.useState("transitionStatus"),E=v.useState("inputInsidePopup"),R=v.useState("inputElement"),k=v.useState("modal"),A=v.useState("id"),D=vh(),I=g.id??(E?yE(A):void 0);De(()=>(v.set("popupId",v.context.popupRef.current?.id||I),()=>{v.set("popupId",void 0)}),[v,I]),Wr({open:w,ref:v.context.popupRef,onComplete(){w&&v.context.onOpenChangeComplete(!0)}});const M={open:w,side:y.side,align:y.align,anchorHidden:y.anchorHidden,transitionStatus:C,empty:D},O=bt("div",t,{state:M,ref:[r,v.context.popupRef],props:[N,{id:I,role:E?"dialog":"presentation",onFocus(B){const Q=ns(B.nativeEvent);S!=="touch"&&(Ge(v.state.listElement,Q)||Q===B.currentTarget)&&v.context.inputRef.current?.focus()}},Jd(C),g],stateAttributesMapping:JV}),L=f===void 0?E?B=>B==="touch"?v.context.popupRef.current:R:!1:f;let z;p!=null?z=p:z=E?void 0:!1;const U=!E||k;return s.jsx(Vm,{context:b,disabled:!j,modal:U,openInteractionType:S,initialFocus:L,returnFocus:z,getInsideElements:()=>[v.context.startDismissRef.current,v.context.endDismissRef.current],children:s.jsxs(x.Fragment,{children:[O,U&&s.jsx(CE,{ref:v.context.endDismissRef})]})})}),t6=x.forwardRef(function(t,r){const{render:o,className:c,style:d,...f}=t;return bt("span",t,{ref:r,props:[{"aria-hidden":!0,children:"▼"},f]})}),RE=x.createContext(void 0);function AE(){const e=x.useContext(RE);if(!e)throw new Error(nn(19));return e}const n6=x.createContext(!1);function s6(){return x.useContext(n6)}function OE(e){const{componentProps:t,forwardedRef:r,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=Ny({guess:!0,index:v,textRef:w}),N=Sa(),C=s6(),E=CV(),R=N.useState("selectionMode"),k=N.useState("disabled"),A=N.useState("readOnly"),D=N.useState("isItemEqualToValue"),I=k||y,M=R!=="none",O=v??c??S.index,_=O!==-1,L=N.useState("id"),z=N.useState("isActive",O),U=N.useState("isSelected",g),B=N.useState("itemProps"),Q=x.useRef(null),W=L!=null&&_?`${L}-${O}`:void 0,Z=U&&M;De(()=>{if(!(_&&(o||v!=null)))return;const V=N.context.listRef.current;return V[O]=Q.current,()=>{delete V[O]}},[_,o,O,v,N]),De(()=>{if(!_||E)return;const P=N.context.valuesRef.current;return P[O]=g,()=>{delete P[O]}},[_,E,O,g,N]),De(()=>{if(!_||E)return;const P=N.state.selectedValue;let V=N.state.selectedIndex;N.state.selectionMode==="multiple"&&Array.isArray(P)?V=JT(O,g,N.context.valuesRef.current,P,D,V):ta(g,P,D)&&(V=O),N.set("selectedIndex",V)},[_,E,N,O,g,D]);const{getButtonProps:Y,buttonRef:q}=Kr({disabled:I,focusableWhenDisabled:!0,native:b,composite:!0}),G={disabled:I,selected:Z,highlighted:z};function $(P){function V(){N.context.handleSelection(P,g)}N.state.submitOnItemClick?(ys.flushSync(V),N.context.requestSubmit()):V()}const F={id:W,role:C?"gridcell":"option","aria-selected":M?Z:void 0,tabIndex:void 0,onPointerDownCapture(P){P.isPrimary&&(N.context.pointerDownItemRef.current=P.currentTarget),P.preventDefault()},onMouseDown(P){P.preventDefault()},onClick(P){I||A||$(P.nativeEvent)},onMouseUp(P){const V=N.context.pointerDownItemRef.current===P.currentTarget;N.context.pointerDownItemRef.current=null,!(I||A||P.button!==0||V||!z)&&$(P.nativeEvent)}},X=bt("div",t,{ref:[q,r,S.ref,Q],state:G,props:[B,F,j,Y]}),re=x.useMemo(()=>({selected:Z,textRef:w}),[Z,w]);return s.jsx(RE.Provider,{value:re,children:X})}function r6(e){const{componentProps:t,forwardedRef:r}=e,c=Sa().useState("isItemEqualToValue"),{flatFilteredValues:d}=nf(),f=t.value??null,p=Jc(d,f,c);return s.jsx(OE,{componentProps:t,forwardedRef:r,virtualized:!0,indexFromFilter:p})}const a6=x.memo(x.forwardRef(function(t,r){const c=Sa().useState("virtualized");return c&&t.index==null?s.jsx(r6,{componentProps:t,forwardedRef:r}):s.jsx(OE,{componentProps:t,forwardedRef:r,virtualized:c,indexFromFilter:void 0})})),l6=x.forwardRef(function(t,r){const{selected:o}=AE();return t.keepMounted||o?s.jsx(o6,{...t,ref:r}):null}),o6=x.memo(x.forwardRef((e,t)=>{const{render:r,className:o,style:c,keepMounted:d,...f}=e,{selected:p}=AE(),g=x.useRef(null),{transitionStatus:v,setMounted:y}=yi(p),j=bt("span",e,{ref:[t,g],state:{selected:p,transitionStatus:v},props:[{"aria-hidden":!0,children:"✔️"},f],stateAttributesMapping:so});return Wr({batch:!0,enabled:!p,open:p,ref:g,onComplete(){p||y(!1)}}),j})),i6=x.forwardRef(function(t,r){const{render:o,className:c,style:d,children:f,...p}=t,{filteredItems:g}=nf(),v=Sa(),y=XV(),b=g.length===0?f:null;return bt("div",t,{ref:[r,v.context.emptyRef,y],props:[{children:b,role:"status","aria-live":"polite","aria-atomic":!0},p]})}),c6="、";function My({value:e,onValueChange:t,options:r,placeholder:o="",emptyHint:c=fo("没有匹配的选项"),searchPlaceholder:d=fo("搜索…"),disabled:f=!1,className:p,id:g,title:v,...y}){const b=x.useMemo(()=>r.filter(w=>e.includes(w.value)),[r,e]),j=b.length?b.map(w=>w.label).join(c6):o;return s.jsxs(DV,{items:r,multiple:!0,value:b,onValueChange:w=>t(w.map(S=>S.value)),isItemEqualToValue:(w,S)=>w?.value===S?.value,disabled:f,children:[s.jsxs(UV,{"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(t6,{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(ZV,{children:s.jsx(WV,{sideOffset:4,className:"z-[35]",children:s.jsxs(e6,{"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(HV,{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(i6,{children:s.jsx("div",{className:"px-2.5 py-3 text-[11.5px] leading-[1.5] text-muted-foreground",children:c})}),s.jsx(qV,{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain p-[5px]",children:w=>s.jsxs(a6,{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(l6,{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 ME=x.createContext(void 0);function sf(e){const t=x.useContext(ME);if(t===void 0&&!e)throw new Error(nn(47));return t}const u6={...cy,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 d6 extends Zc{constructor(r,o,c){const d=new Km;super(f6(r,d,o,c),p6(d),u6);tn(this,"setOpen",(r,o)=>{const c=o.reason===zs,d=o.reason===co&&o.event.detail===0,f=!r&&(o.reason===Gc||o.reason==null),p=G1(o),g=this.select("activeTriggerId");if(!r&&o.reason===Iv&&o.trigger==null&&g!=null&&(o.trigger=this.context.triggerElements.getById(g)??this.select("activeTriggerElement")??void 0),this.context.onOpenChange?.(r,o),o.isCanceled)return;this.state.floatingRootContext.dispatchOpenChange(r,o);const v=()=>{const b=sy(this.state,r,o.trigger,p());b.openChangeReason=o.reason,this.update(b)};c?(this.set("stickIfOpen",!0),this.context.stickIfOpenTimeout.start(X4,()=>{this.set("stickIfOpen",!1)}),ys.flushSync(v)):v();let y;d?y="click":f?y="dismiss":o.reason===uo&&(y="focus"),this.set("instantType",y)})}}function f6(e,t,r,o=!1){const c={...oy(t,r,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 p6(e){return{popupRef:x.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:x.createRef(),beforeContentFocusGuardRef:x.createRef(),stickIfOpenTimeout:new Zr,triggerElements:e}}const DE=zm(function({props:t}){const{children:r,open:o,defaultOpen:c=!1,onOpenChange:d,onOpenChangeComplete:f,modal:p=!1,handle:g,triggerId:v,defaultTriggerId:y=null}=t,b=h6(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),Y1(b,j),ry(b);const{forceUnmount:N}=ay(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,Ve(_v))}),[N,b]);const C=j||w;return s.jsxs(ME.Provider,{value:b,children:[g&&s.jsx(ny,{handle:g,store:b}),C&&s.jsx(g6,{store:b,modal:p}),typeof r=="function"?r({payload:S}):r]})});function m6(e){return sf(!0)?s.jsx(DE,{props:e}):s.jsx(nB,{children:s.jsx(DE,{props:e})})}function h6(e,t){const r=ty((o,c)=>new d6(t,o,c));return x.useEffect(()=>r.context.stickIfOpenTimeout.disposeEffect(),[r]),r}function g6({store:e,modal:t}){const r=e.useState("floatingRootContext"),o=Xd(r,{outsidePressEvent:{mouse:t==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}}),c=o.reference,d=o.floating;return ly(e,{activeTriggerProps:c,inactiveTriggerProps:c,popupProps:d}),null}const x6=300;function b6(e,t){const r=x.useRef(null);function o(d){ys.flushSync(()=>{e.setOpen(!1,Ve(uo,d.nativeEvent,d.currentTarget))}),Qz(r.current)?.focus()}function c(d){const f=e.select("positionerElement");if(f&&$c(d,f))e.context.beforeContentFocusGuardRef.current?.focus();else{ys.flushSync(()=>{e.setOpen(!1,Ve(uo,d.nativeEvent,d.currentTarget))});let p=Xz(e.context.triggerFocusTargetRef.current||t.current);for(;p!==null&&Ge(f,p);){const g=p;if(p=Ov(p),p===g)break}p?.focus()}}return{preFocusGuardRef:r,handlePreFocusGuardFocus:o,handleFocusTargetFocus:c}}const v6=e1(function(t,r){const{render:o,className:c,style:d,disabled:f=!1,nativeButton:p=!0,handle:g,payload:v,openOnHover:y=!1,delay:b=x6,closeDelay:j=0,id:w,...S}=t,N=sf(!0),E=Z1(g)??N;if(!E)throw new Error(nn(74));const R=ja(w),k=E.useState("isTriggerActive",R),A=E.useState("floatingRootContext"),D=E.useState("isOpenedByTrigger",R),I=E.useState("triggerPopupId",R),M=x.useRef(null),{registerTrigger:O,isMountedByThisTrigger:_}=K1(R,M,E,{payload:v,disabled:f,openOnHover:y,closeDelay:j}),L=E.useState("openChangeReason"),z=E.useState("stickIfOpen"),U=E.useState("openMethod"),B=E.useState("focusManagerModal"),Q=tT(A,{enabled:!f&&y&&(U!=="touch"||L!==co),mouseOnly:!0,move:!1,handleClose:lT(),restMs:b,delay:{close:j},triggerElementRef:M,isActiveTrigger:k,isClosing:()=>E.select("transitionStatus")==="ending"}),W=$m(A,{stickIfOpen:z}),Z=PT(()=>E.select("open"),ie=>{E.set("openMethod",ie)}),Y=E.useState("triggerProps",_),{getButtonProps:q,buttonRef:G}=Kr({disabled:f,native:p}),$={open(ie){return ie&&L===co?xv.open(ie):gv.open(ie)}},{preFocusGuardRef:F,handlePreFocusGuardFocus:X,handleFocusTargetFocus:re}=b6(E,M),V=bt("button",t,{state:{disabled:f,open:D},ref:[G,r,O,M],props:[W.reference,Q,Y,Z,{[d1]:"",id:R,"aria-haspopup":"dialog","aria-expanded":D,"aria-controls":I},S,q],stateAttributesMapping:$}),J=s.jsx(x.Fragment,{children:V},R);return _&&!B?s.jsxs(x.Fragment,{children:[s.jsx(Yc,{ref:F,onFocus:X}),J,s.jsx(Yc,{ref:E.context.triggerFocusTargetRef,onFocus:re})]}):J}),IE=x.createContext(void 0);function y6(){const e=x.useContext(IE);if(e===void 0)throw new Error(nn(45));return e}const j6=x.forwardRef(function(t,r){const{keepMounted:o=!1,...c}=t;return sf().useState("mounted")||o?s.jsx(IE.Provider,{value:o,children:s.jsx(Um,{ref:r,...c})}):null}),PE=x.createContext(void 0);function w6(){const e=x.useContext(PE);if(!e)throw new Error(nn(46));return e}const S6=x.forwardRef(function(t,r){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:C=!1,collisionAvoidance:E=p1,...R}=t,k=sf(),A=y6(),D=eB(),I=k.useState("floatingRootContext"),M=k.useState("mounted"),O=k.useState("open"),_=k.useState("openChangeReason"),L=k.useState("activeTriggerElement"),z=k.useState("modal"),U=k.useState("openMethod"),B=k.useState("positionerElement"),Q=k.useState("instantType"),W=k.useState("transitionStatus"),Z=k.useState("adaptiveOrigin"),Y=x.useRef(null),q=Uk(B),G=th({anchor:f,floatingRootContext:I,positionMethod:p,mounted:M,side:g,sideOffset:y,align:v,alignOffset:b,arrowPadding:S,collisionBoundary:j,collisionPadding:w,sticky:N,disableAnchorTracking:C,keepMounted:A,nodeId:D,collisionAvoidance:E,adaptiveOrigin:Z}),$=I.useState("domReferenceElement");De(()=>{const V=$,J=Y.current;if(V&&(Y.current=V),J&&V&&V!==J){k.set("instantType",void 0);const ie=new AbortController;return q(()=>{k.set("instantType","trigger-change")},ie.signal),()=>{ie.abort()}}},[$,q,k]);const F=z===!0&&_!==zs;Ey(O&&F,U==="touch",B,L);const X=k.useStateSetter("positionerElement"),re={open:O,side:G.side,align:G.align,anchorHidden:G.anchorHidden,instant:Q},P=nh(t,re,{styles:G.positionerStyles,transitionStatus:W,props:R,refs:[r,X],hidden:!M,inert:!O});return s.jsxs(PE.Provider,{value:G,children:[M&&F&&s.jsx(lh,{inert:sh(!O),cutout:L}),s.jsx(tB,{id:D,children:P})]})}),N6=x.createContext(void 0);function C6(){const[e,t]=x.useState(0),r=Ie(()=>(t(c=>c+1),()=>{t(c=>Math.max(0,c-1))}));return{context:x.useMemo(()=>({register:r}),[r]),hasClosePart:e>0}}const k6=x.forwardRef(function(t,r){const{render:o,className:c,style:d,initialFocus:f,finalFocus:p,...g}=t,v=sf(),y=w6(),b=iE()!=null,{context:j,hasClosePart:w}=C6(),S=v.useState("open"),N=v.useState("openMethod"),C=v.useState("instantType"),E=v.useState("transitionStatus"),R=v.useState("popupProps"),k=v.useState("titleElementId"),A=v.useState("descriptionElementId"),D=v.useState("modal"),I=v.useState("mounted"),M=v.useState("openChangeReason"),O=v.useState("activeTriggerElement"),_=v.useState("floatingRootContext"),L=_.useState("floatingId"),z=v.useState("disabled"),U=v.useState("openOnHover"),B=v.useState("closeDelay");Wr({open:S,ref:v.context.popupRef,onComplete(){S&&v.context.onOpenChangeComplete?.(!0)}}),eT(_,{enabled:U&&!z,closeDelay:B});const Q=f===void 0?F1(v.context.popupRef):f,W=D!==!1&&w;v.useSyncedValue("focusManagerModal",W);const Z=v.useStateSetter("popupElement"),Y={open:S,side:y.side,align:y.align,instant:C,transitionStatus:E},q=bt("div",t,{state:Y,ref:[r,v.context.popupRef,Z],props:[R,{id:L,role:"dialog",...Qd,"aria-labelledby":k,"aria-describedby":A,onKeyDown(G){b&&rh.has(G.key)&&G.stopPropagation()}},Jd(E),g],stateAttributesMapping:bv});return s.jsx(Vm,{context:_,openInteractionType:N,modal:W,disabled:!I||M===zs,initialFocus:Q,returnFocus:p,restoreFocus:"popup",previousFocusableElement:an(O)?O:void 0,nextFocusableElement:v.context.triggerFocusTargetRef,beforeContentFocusGuardRef:v.context.beforeContentFocusGuardRef,children:s.jsx(N6.Provider,{value:j,children:q})})});function rf(e){return s.jsx(m6,{"data-slot":"popover",...e})}function yh(e){return s.jsx(v6,{"data-slot":"popover-trigger",...e})}function af({className:e,sideOffset:t=6,align:r="start",side:o,alignOffset:c,collisionPadding:d=8,anchor:f,children:p,...g}){return s.jsx(j6,{children:s.jsx(S6,{className:"z-[35] outline-none",sideOffset:t,align:r,side:o,alignOffset:c,collisionPadding:d,anchor:f,children:s.jsx(k6,{"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 T6({page:e,pageCount:t,onPageChange:r,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:fo("第 {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:()=>r(p-1),children:fo("上一页")}),s.jsx(se,{type:"button",variant:"outline",size:"sm",disabled:o||p>=f,onClick:()=>r(p+1),children:fo("下一页")}),!d&&g]})}const E6=Bc(["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 eu({className:e,variant:t,active:r=!1,count:o,icon:c,trailing:d,children:f,...p}){return s.jsxs("button",{type:"button","data-slot":"nav-item","data-active":r?"":void 0,"aria-current":r?"true":void 0,className:Ue(E6({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]",r&&"text-inherit"),children:o})]})}function l(e,t){const r=typeof window<"u"?window.wbI18n:void 0;return r&&typeof r.t=="function"?r.t(e,t):e}function jh(e){if(e.source==="subscription"&&(e.port===null||e.port===void 0))return l("未分配端口");const t=e.resolved;return t?.protocol&&t.host&&t.port?`${String(t.protocol).toUpperCase()} ${t.host}:${t.port}`:t?.label||""}function lf(e){const t=e.name||e.id,o=[e.resolveError?l("解析失败"):jh(e),e.enabled===!1?l("已禁用"):""].filter(Boolean);return o.length?l("{name}({parts})",{name:t,parts:o.join(" · ")}):t}const Ga="pool:";function Pe(){return window}function He(e,t){Pe().wbApp?.toast?.(e,t)}function wl(e){const t=Pe().wbApp?.esc;return t?t(e):String(e??"").replace(/[&<>"']/g,r=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[r]||r)}function Bs(e){const t=Pe().wbApp?.formatTime;if(t)return t(e);const r=Number(e);return!Number.isFinite(r)||r<=0?"":new Date(r).toLocaleString("zh-CN")}function pt(e){return e instanceof Error?e.message:String(e)}function tu(e){if(e==null||e==="")return null;const t=Number(e);return Number.isFinite(t)?t:null}function Dy(e){const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const r=o=>String(o).padStart(2,"0");return`${r(t.getMonth()+1)}-${r(t.getDate())} ${r(t.getHours())}:${r(t.getMinutes())}`}function R6(e){return e==="积分"?l("积分"):e==="额度"?l("额度"):e}function A6(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=e,r=Array.isArray(t.credits)?t.credits:[],o=Date.now();return r.map(c=>{const d=String(c?.name||"").trim()||l("积分包"),f=String(c?.unit||"").trim(),p=tu(c?.total),g=tu(c?.used),v=tu(c?.remain),y=c?.unlimited===!0,b=tu(c?.grantAt),j=tu(c?.startAt),w=tu(c?.expireAt),S=c?.daily===!0,N=String(c?.grantReason||"").trim(),C=w!==null&&w>0&&w<=o,E=p!==null&&p>0,R=y?l("不限"):v!==null?E?l("剩 {remaining} / {total}",{remaining:v,total:p}):l("剩 {remaining}",{remaining:v}):g!==null?l("已用 {used}",{used:g}):"—",k=!y&&f&&R!=="—"?`${R} ${R6(f)}`:R,A=E&&v!==null?Math.max(0,Math.min(100,v/p*100)):null,D=v!==null&&v<=0||v===null&&g!==null&&E&&g>=p,I=!y&&!S&&(D||C),M=[];b!==null&&b>0?M.push(l("{time} 领取",{time:Dy(b)})):j!==null&&j>0&&M.push(l("{time} 生效",{time:Dy(j)})),S?M.push(l("每日重置")):w!==null&&w>0&&M.push(C?l("已过期"):l("{time} 到期",{time:Dy(w)})),N&&M.push(N);const O=C||v===0?"muted":A!==null&&A<20?"warn":v===null&&g===null&&!y?"muted":"ok",_=[d,k,b!==null&&b>0?l("领取 {time}",{time:Bs(b)}):j!==null&&j>0?l("生效 {time}",{time:Bs(j)}):"",w!==null&&w>0?C?l("已过期({time})",{time:Bs(w)}):l("到期 {time}",{time:Bs(w)}):"",S?l("每日重置(额度按周期回满,不是作废)"):"",N,A===null&&v!==null?l("上游未给总量,画不出剩余比例"):"",g!==null&&p!==null?l("已用 {used} / 共 {total}",{used:g,total:p}):""].filter(Boolean).join(" · ");return{name:d,view:k,tone:O,percent:A,window:M.length?M.join(" · "):null,title:_,spent:I}})}function _E({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":l("剩余 {percent}%",{percent:Math.round(e.percent)})})}):null]})}function LE({rows:e,subscriptionLine:t,variant:r,kind:o,title:c,children:d}){const[f,p]=x.useState(!1),[g,v]=x.useState(!1),y=e.filter(C=>!C.spent),b=e.filter(C=>C.spent),j=r==="pool"?`usage-toggle usage-pool-line ${o}`:`usage-toggle ${o}`,w=x.useRef(null),S=x.useCallback(C=>{w.current=C,C&&(C.scrollTop=0)},[]),N=x.useCallback(()=>w.current??null,[]);return x.useLayoutEffect(()=>{if(!g)return;const C=w.current?.querySelector(".usage-pop-spent .usage-pop-row");C instanceof HTMLElement&&C.scrollIntoView({block:"nearest"})},[g]),s.jsxs(rf,{open:f,onOpenChange:p,children:[s.jsxs(yh,{render:s.jsx("button",{type:"button",className:j,title:c,"aria-label":l("积分明细")}),children:[r==="pool"?d:s.jsx("span",{className:"val",children:d}),s.jsx("span",{className:"caret","aria-hidden":!0,children:"▾"})]}),s.jsx(af,{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:l("积分明细")}),y.map((C,E)=>s.jsx(_E,{row:C},`${C.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:l("展开或收起(默认收起)"),onClick:()=>v(C=>!C),children:[s.jsx("span",{className:"caret","aria-hidden":!0,children:"▾"}),s.jsx("span",{children:l("已用完 / 已过期")}),s.jsx("span",{className:"n",children:l("{count} 份",{count:b.length})})]}),g?b.map((C,E)=>s.jsx(_E,{row:C},`spent-${C.name}-${E}`)):null]}):null]})})]})}const nu="workbuddy",O6="raccoon",M6={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"}},D6={usage:!1,edition:!1,identifier:"userId",expiry:"tokenExpiresAt",emailAsName:!1};function Rn(e){const t=e?.provider;return typeof t=="string"&&t?t:nu}function lr(e){return e&&M6[e]||D6}function zE(e){const t=Array.isArray(e?.providers)?e.providers:[],r=Array.isArray(e?.accounts)?e.accounts:[],o=new Map;r.forEach(d=>{const f=Rn(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(nu,{id:nu,label:Pe().wbProviders?.labelOf?.(nu)||"WorkBuddy 国内版",count:0}),[...c.values()]}function wh(e){const t=lr(Rn(e)).identifier;return String(e?.[t]||"")}function BE(e){const t=Number(e)||0;return t<=0?0:t<1e11?t*1e3:t}function I6(e){const t=lr(Rn(e)).expiry;return BE(e?.[t])}function Na(e){return lr(Rn(e)).usage}const Iy=30,HE=86400,UE=60,VE=1800,$E=86400,FE=1,P6=95e5;function _6(e){return e==="codearts"?[{type:"token",action:"skip",threshold:P6,reset:"daily",enabled:!0}]:e==="cline-free"?[]:[{type:"balance",action:"skip",threshold:FE,enabled:!0}]}function qE(e){const t=e?.usageQuery;if(!t||typeof t!="object")return{enabled:!0,interval:UE};const r=t.enabled===void 0?!0:t.enabled===!0,o=Number(t.interval)||0,c=o>=Iy&&o<=HE;return{enabled:r,interval:r&&!c?UE:o}}function L6(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 r=Number(t.threshold);if(!Number.isFinite(r)||r<=0)return!1;if(t.type==="token"&&t.reset!=="daily"){const o=Number(t.period);if(!Number.isInteger(o)||o$E)return!1}return!0}function z6(e){const t=e?.lowBalance;if(!t||typeof t!="object"||!t.mode)return _6(Rn(e));const r=Number(t.threshold),o=Number.isFinite(r)&&r>0?r:FE;return t.mode!=="skip"&&t.mode!=="disable"?[]:[{type:"balance",action:t.mode,threshold:o,enabled:!0}]}function su(e){const t=e?.limiters;return Array.isArray(t)?t.filter(L6):z6(e)}function B6(e){return su(e).filter(t=>t.type==="token")}function H6(e,t){const r=t*1e3;return e-e%r}function GE(e){return e.reset==="daily"?0:e.period??0}function Py(e,t=Date.now()){if(e===0){const r=new Date(t);return r.setHours(0,0,0,0),r.getTime()}return H6(t,e)}function of(e,t,r=Date.now()){if(e.type!=="token")return null;const o=GE(e),c=(t||[]).find(d=>Number(d.kind)===o);return c&&Number(c.windowStart)===Py(o,r)?c:null}function Sh(e,t){const r=su(e).filter(f=>f.type==="balance"&&f.action==="skip"&&f.enabled!==!1&&f.threshold>0);if(!r.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)&&r.some(f=>dc.type==="token"&&c.action==="skip"&&c.enabled!==!1);if(!r.length||!t?.length)return!1;const o=Date.now();return r.some(c=>{const d=of(c,t,o);return d!==null&&Number(d.used)>=c.threshold})}function U6(e,t){return su(e).some(r=>{if(r.type!=="token"||r.action!=="disable"||r.enabled===!1)return!1;const o=of(r,t);return o!==null&&Number(o.used)>=r.threshold})}function Ly(e,t=Date.now()){const r=GE(e),o=Py(r,t),c=r===0?Math.max(0,Py(0,o+864e5+36e5)-t):Math.max(0,o+r*1e3-t);return{kind:r,startMs:o,remainingMs:c,daily:r===0}}function Nh(e,t){if(e<=0)return"";const r=Math.ceil(e/6e4);if(t){const o=Math.ceil(e/36e5);return o>=1?l("今日剩 {n} 小时",{n:o}):l("今日剩 {n} 分钟",{n:r})}return r>=1?l("剩 {n} 分钟",{n:r}):l("剩不到 1 分钟")}function Sl(e){const t=Number(e);if(!Number.isFinite(t))return"—";const r=window.wbUnits;return r?.formatTokens?r.formatTokens(t):String(Math.round(t))}function KE(e){return e>0&&e%3600===0?l("{n} 小时",{n:e/3600}):e>0&&e%60===0?l("{n} 分钟",{n:e/60}):l("{n} 秒",{n:e})}function cf(e){return e?.desktop===!0}function YE(e){return e?.chatSupported!==!1}function V6(e){return typeof e=="string"&&e.startsWith("custom-")}function $6(e){return l(e==="enterprise"?"企业":e==="ultimate"?"旗舰":"个人")}function Ch(e,t){const r=Number(e?.priority??100)-Number(t?.priority??100);return r!==0?r:(Number(e?.addedAt)||0)-(Number(t?.addedAt)||0)}function or(e){return e?.enabled!==!1}function uf(e,t=""){const r=e?.rateLimits||{},o=Date.now();return t?Number(r[t]?.resetAt)>o:Object.values(r).some(c=>Number(c?.resetAt)>o)}function XE(e){return e?.edition==="intl"?"intl":"cn"}function QE(e){return lr(Rn(e)).claim?e?.canClaim!==!1:!1}const ZE="coding-plan",go="start-plan";function kh(e){return!!lr(Rn(e)).planChannel}function zy(e){return kh(e)?String(e?.zcodePlan||"").trim()===go?go:ZE:""}function F6(e){return l(e===go?"活动套餐(Start Plan)":"编码套餐(Coding Plan)")}function WE(e){switch(String(e??"").trim()){case"pending":return l("待生效");case"active":return l("生效中");case"expired":return l("已过期");case"unknown":return l("状态未知");default:return String(e??"")}}function Th(e){const t=e?.claimPlans;if(!t||typeof t!="object"||Array.isArray(t))return[];const r=By();return Object.entries(t).filter(([,o])=>Number(o)>0&&By(Number(o))===r).map(([o])=>o)}function q6(e){return Th(e).length>0}function G6(e){const t=Th(e),r=t.length?l("({plans})",{plans:t.join(l("、"))}):"";return l("今天(北京时间 {day})已领取 {n} 份{names};还有其他可领套餐时,点这里可以继续领;活动按自然日发新套餐,明天可再领",{day:By(),n:t.length,names:r})}function K6(e){return!!lr(Rn(e)).usageDetail}function JE(e){return!!lr(Rn(e)).creditDetail}function eR(e){return/^free$/i.test(String(e??"").trim())}function Y6(e){const t=String(e??"").trim();return/^trial$/i.test(t)?l("试用版"):eR(t)?l("免费版"):t}function By(e=Date.now()){return new Date(e+8*3600*1e3).toISOString().slice(0,10)}function df(e,t,r){return uf(e)||Sh(e,t)||_y(e,r)}function tR(e,t){const r=String(t.q||"").trim().toLowerCase();return r?[ru(e),e?.name,e?.nickname,e?.email,wh(e),e?.id].some(c=>String(c||"").toLowerCase().includes(r)):!0}function nR(e,t){return t.provider==="all"||Rn(e)===t.provider}function Hy(e,t){return t.enabled==="all"?!0:t.enabled==="enabled"?or(e):!or(e)}function sR(e,t,r,o){if(t.limit==="all")return!0;if(!or(e))return!1;const c=df(e,r?.(e),o?.(e));return t.limit==="limited"?c:!c}function rR(e,t,r,o){return nR(e,t)&&Hy(e,t)&&sR(e,t,r,o)&&tR(e,t)}function X6(e,t,r,o){return(e||[]).filter(c=>rR(c,t,r,o))}function aR(e,t,r,o){const c=e||[],d=g=>c.filter(v=>nR(v,t)&&(g==="enabled"||Hy(v,t))&&tR(v,t)),f=d("enabled"),p=d("limit");return{enabledAll:f.length,enabled:f.filter(or).length,disabled:f.filter(g=>!or(g)).length,limitAll:p.length,normal:p.filter(g=>or(g)&&!df(g,r?.(g),o?.(g))).length,limited:p.filter(g=>or(g)&&df(g,r?.(g),o?.(g))).length}}function Uy(e){const t=e?.rateLimits;if(!t||typeof t!="object")return[];const r=Date.now();return Object.entries(t).map(([o,c])=>({model:o,...c&&typeof c=="object"?c:{}})).filter(o=>Number(o.resetAt)>r).sort((o,c)=>Number(o.resetAt)-Number(c.resetAt))}function Vy(e){const t=(e||[]).slice().sort(Ch),r=new Map;return t.forEach((o,c)=>r.set(o.id,{position:c+1,total:t.length})),r}function Q6(e,t,r,o){const c=(e||[]).slice().sort(Ch),d=[],f=new Map;for(const p of c){const g=Rn(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(or).length,disabled:v.filter(y=>!or(y)).length,limited:v.filter(y=>or(y)&&df(y,r?.(y),o?.(y))).length}})}function ru(e){if(!e)return"";const t=String(e.name||"").trim();if(e.nameCustom===!0&&t)return t;const r=String(e.email||"").trim();return lr(Rn(e)).emailAsName&&r?r:e?.nickname||t||wh(e)||e?.id||""}const $y="已限流",lR=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime();function Fy(e){const t=Number(e);if(!Number.isFinite(t)||t<=0||t<=Date.now())return $y;const r=new Date(t),o=r.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",hour12:!1}),c=Math.round((lR(r)-lR(new Date))/864e5);return c===0?l("今天 {clock}",{clock:o}):c===1?l("明天 {clock}",{clock:o}):l("{month}月{day}日 {clock}",{month:r.getMonth()+1,day:r.getDate(),clock:o})}function Z6(e){const t=Rn(e);if(!lr(t).edition)return"";const r=XE(e),o=e?.editionLabel,c=o||(r==="intl"?"国际版":"国内版");return(Pe().wbProviders?.labelOf?.(t)||"").includes(c)?"":o||l(r==="intl"?"国际版":"国内版")}function W6(e){return[YE(e)?null:{text:l("仅账号管理"),kind:"plain",title:l("该提供商的推理转发尚未接入,账号不参与转发")},V6(Rn(e))&&e.hasCredentials===!1?{text:l("未配置凭证"),kind:"bad",title:l("这条自定义账号既没有 API Key,也没有勾选「无需鉴权」:转发时会被跳过,该提供商下的模型也不会出现在模型列表里。去账号「设置」里补上 Key,或勾选「该上游无需鉴权」")}:null,e.proxy?.error?{text:l("代理异常"),kind:"bad",title:l("{error}(转发时会回退直连)",{error:e.proxy.error})}:null,zy(e)===go?{text:l("活动套餐"),kind:"plain",title:l("转发走活动套餐通道(zcode.z.ai 的 Anthropic 端点,用账号里领到的额度);在账号设置里可切回编码套餐")}:null].filter(t=>t!==null)}const oR="workbuddy-desktop-accounts-filters",iR="workbuddy-desktop-accounts-collapsed",cR="workbuddy-desktop-accounts-names-hidden";function J6(){const e={provider:"all",enabled:"all",limit:"all",q:""},t=Pe().wbFilterMemory?.load(oR,e)||e;return{provider:String(t.provider||"all"),enabled:String(t.enabled||"all"),limit:String(t.limit||"all"),q:""}}function e$(){try{const e=JSON.parse(localStorage.getItem(iR)||"[]");return new Set(Array.isArray(e)?e.map(t=>String(t)).filter(Boolean):[])}catch{return new Set}}function t$(){try{return localStorage.getItem(cR)==="1"}catch{return!1}}let on={version:0,filter:J6(),collapsed:e$(),selected:new Set,panels:new Map,connections:new Map,clash:null,dialog:null,namesHidden:t$(),usageBusy:!1,usageInflight:new Set};const qy=new Set;function uR(e){return qy.add(e),()=>{qy.delete(e)}}function Qs(){return on}function yn(e){on={...on,...e,version:on.version+1},qy.forEach(t=>t())}function xr(){yn({})}function Gy(){return Pe().wbApp?.getState?.()?.accounts}function Nl(){const e=Gy()?.accounts;return Array.isArray(e)?e:[]}function Ca(e){return Nl().find(t=>t.id===e)||null}function n$(e,t){const r=Q6(Nl(),c=>rR(c,on.filter,e,t),e,t);return{groups:r.filter(c=>c.accounts.length>0),allGroups:r}}function dR(){return zE(Gy())}function s$(e,t){return aR(Nl(),on.filter,e,t)}function r$(){return Vy(Nl())}function Eh(){Pe().wbFilterMemory?.save(oR,{provider:on.filter.provider,enabled:on.filter.enabled,limit:on.filter.limit})}function a$(e){on.filter.q!==e&&yn({filter:{...on.filter,q:e}})}function l$(e){const t=e||"all";on.filter.provider!==t&&(yn({filter:{...on.filter,provider:t}}),Eh())}function fR(e,t){const r={...on.filter,[e]:t};r.enabled==="disabled"&&r.limit!=="all"&&(r.limit="all"),yn({filter:r}),Eh()}function Rh(){return on.filter.provider!=="all"||on.filter.enabled!=="all"||on.filter.limit!=="all"||on.filter.q.trim()!==""}function pR(){yn({filter:{provider:"all",enabled:"all",limit:"all",q:""}}),Eh()}function o$(){const e=on.filter.provider;e!=="all"&&(dR().some(t=>t.id===e)||(yn({filter:{...on.filter,provider:"all"}}),Eh()))}function mR(e){try{localStorage.setItem(iR,JSON.stringify([...e]))}catch{}}function hR(e){const t=new Set(on.collapsed);t.has(e)?t.delete(e):t.add(e),mR(t),yn({collapsed:t})}function i$(e,t){const r=new Set(on.collapsed);for(const o of e)t?r.add(o):r.delete(o);mR(r),yn({collapsed:r})}function c$(e){return on.selected.has(e)}function u$(e,t){const r=new Set(on.selected);t?r.add(e):r.delete(e),yn({selected:r})}function gR(e,t){const r=new Set(on.selected);for(const o of e)t?r.add(o):r.delete(o);yn({selected:r})}function d$(){yn({selected:new Set})}function xR(e,t){return on.panels.get(e)?.has(t)===!0}function bR(e,t,r){if(!e)return;const o=new Map(on.panels),c=new Set(o.get(e)||[]);r?c.add(t):c.delete(t),c.size?o.set(e,c):o.delete(e),yn({panels:o})}function f$(e,t){const r=new Map(on.panels);for(const o of e){const c=new Set(r.get(o)||[]);c.add(t),r.set(o,c)}yn({panels:r})}function p$(){const e=!on.namesHidden;try{localStorage.setItem(cR,e?"1":"0")}catch{}yn({namesHidden:e})}function m$(e){return"*".repeat(Math.min(Math.max(e.length,4),12))}const vR="usage_not_configured",xo=new Map,ff=new Map;function na(e,t,r){xo.set(e,t),t!=null&&au(t)?ff.set(e,r):ff.delete(e)}function Ka(e){const t=xo.get(e.id);if(t===void 0)return;if(!au(t))return t;const r=Math.max(Number(e.addedAt)||0,Number(e.updatedAt)||0);return(ff.get(e.id)||0)>=r?t:void 0}const pf=new Map;let yR=0;function Cl(e){return e?pf.get(e.id)||[]:[]}function h$(e){const t=Number(e?.tokenAt)||0;if(!t||t===yR)return!1;const r=e?.tokenUsage;if(!r||typeof r!="object")return!1;yR=t;const o=new Map;for(const[d,f]of Object.entries(r)){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!==pf.size||[...o].some(([d,f])=>{const p=pf.get(d);return!p||p.length!==f.length||f.some((g,v)=>g.used!==p[v]?.used||g.windowStart!==p[v]?.windowStart)});pf.clear();for(const[d,f]of o)pf.set(d,f);return c}let Ah=null;async function jR(e={}){const t=Qs().clash;if(!e.force&&t)return t;Ah||(Ah=(async()=>{try{const o=await Pe().workbuddyDesktop?.getProxies?.();if(!o||typeof o!="object"||!o.clash)throw new Error(l("代理列表响应异常({type})",{type:typeof o}));return o.clash}finally{Ah=null}})());const r=await Ah;return yn({clash:r}),r}function g$(){yn({clash:null})}let mf=null,Oh=null;function x$(){return mf}async function wR(e={}){if(!e.force&&mf)return mf;Oh||(Oh=(async()=>{try{const r=await Pe().workbuddyDesktop?.getProxyPool?.();if(!r||typeof r!="object"||!Array.isArray(r.items))throw new Error(l("代理池响应异常({type})",{type:typeof r}));return r.items}finally{Oh=null}})());const t=await Oh;return mf=t,t}let Ky=null;function b$(){return Ky}let Mh=0,SR=!1;function v$(){if(!(mf||Date.now(){Mh=0,Ky=null,xr()}).catch(e=>{Ky=pt(e),xr()})}}function Dh(e){if(!Ca(e)){He(l("账号不存在,请刷新后重试"),"err");return}yn({dialog:{kind:"settings",id:e}})}function Ih(){yn({dialog:null})}function Yy(e,t="enable"){const r=(Array.isArray(e)?e:[]).filter(o=>Ca(o));if(!r.length){He(l("请先勾选要操作的账号"),"err");return}yn({dialog:{kind:"batch",ids:r,action:t}})}function y$(e){let t=!1;for(const f of[...xo.keys()])e.has(f)||(xo.delete(f),t=!0);for(const f of[...ff.keys()])e.has(f)||ff.delete(f);const r=new Map(Qs().panels);for(const f of[...r.keys()])e.has(f)||(r.delete(f),t=!0);const o=new Map(Qs().connections);for(const f of[...o.keys()])e.has(f)||(o.delete(f),t=!0);const c=new Set(Qs().usageInflight);for(const f of[...c])e.has(f)||(c.delete(f),t=!0);const d=new Set(Qs().selected);for(const f of[...d])e.has(f)||(d.delete(f),t=!0);t&&yn({panels:r,connections:o,usageInflight:c,selected:d})}const j$=2e3;function NR(e){return Qs().connections.get(e)||0}async function CR(){try{const e=await Pe().workbuddyDesktop?.getAccountConnections?.(),t=e?.counts&&typeof e.counts=="object"?e.counts:{},r=new Map;for(const[o,c]of Object.entries(t)){const d=Number(c)||0;d>0&&r.set(o,d)}return yn({connections:r}),!0}catch{return!1}}let kR=null;function w$(){kR||(kR=setInterval(()=>{document.hidden||Pe().wbApp?.currentPage!=="accounts"||CR()},j$))}function Xy(){return Nl().filter(e=>Na(e)&&e.available!==!1)}function au(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===vR}:null}function TR(e){return e.usage?e.usage:{error:e.error?String(e.error):l("余额响应为空"),code:e.code}}function ER(e){const t=Array.isArray(e?.results)?e.results:[],r=Number(e?.at)||Date.now();let o=0;for(const c of t)c?.id&&(na(String(c.id),TR(c),Number(c.at)||r),o++);return o&&(xr(),Pe().wbApp?.renderTopbarStatus?.()),o}let RR=!1;function S$(e){if(!JE(e))return!1;const t=Ka(e);return!t||typeof t!="object"||Array.isArray(t)||au(t)?!1:!Array.isArray(t.credits)}async function N$(){if(!RR){RR=!0;for(const e of Nl().filter(S$)){const t=xo.get(e.id);try{await hf(e.id)}catch{}const r=xo.get(e.id);t!==void 0&&(!r||au(r))&&na(e.id,t,Date.now()),xr()}}}let AR=0;async function C$(){try{const e=await Pe().workbuddyDesktop?.getBalancesSnapshot?.(),t=h$(e);t&&(xr(),Pe().wbApp?.renderTopbarStatus?.());const r=Number(e?.at)||0;return!r||r===AR||(AR=r,!ER(e))?t:(N$(),!0)}catch{return!1}}async function hf(e){const t=await Pe().workbuddyDesktop?.getAllBalances?.(e||void 0),r=Array.isArray(t?.results)?t.results:[],o=Date.now(),c=new Set;for(const d of r){if(!d?.id)continue;const f=String(d.id);e&&f!==e||(c.add(f),na(f,TR(d),o))}if(e)return c.has(e)||na(e,l("未返回余额数据"),o),xr(),t;for(const d of Xy())c.has(d.id)||na(d.id,l("未返回余额数据"),o);return xr(),t}async function OR(){if(Qs().usageBusy)return;const e=Xy();if(!e.length){He(l("暂无可查询余额的账号"),"err");return}yn({usageBusy:!0}),e.forEach(t=>na(t.id,null,Date.now())),xr();try{const t=(await hf(null))?.results||[],r=t.filter(f=>f.usage).length,o=t.filter(f=>f.code===vR).length,c=o?l("({n} 个未配置查询凭证)",{n:o}):"",d=t.length-r-o;He(r+o===t.length?l("✅ 已更新 {n} 个账号的余额{suffix}",{n:r,suffix:c}):l("已更新 {ok}/{total} 个账号,{failed} 个失败",{ok:r,total:t.length,failed:d}),d?"err":"ok")}catch(t){const r=pt(t);e.forEach(o=>na(o.id,l("查询失败:{message}",{message:r}),Date.now())),xr(),He(l("余额查询失败:{message}",{message:r}),"err")}finally{yn({usageBusy:!1})}}async function MR(e){if(Qs().usageInflight.has(e))return;const t=new Set(Qs().usageInflight);t.add(e),na(e,null,Date.now()),yn({usageInflight:t});try{await hf(e)}finally{const r=new Set(Qs().usageInflight);r.delete(e),yn({usageInflight:r})}}async function k$(e){if(!Qs().usageInflight.has(e))try{await MR(e);const t=au(xo.get(e));t?.notConfigured?He(t.message,"ok"):t?He(l("余额查询失败:{message}",{message:t.message}),"err"):He(l("✅ 已更新余额"))}catch(t){na(e,l("查询失败:{message}",{message:pt(t)}),Date.now()),xr(),He(l("余额查询失败:{message}",{message:pt(t)}),"err")}}async function Ph(e){if(e){const r=Ca(e);if(!r||!Na(r))return;try{await MR(e)}catch(o){na(e,l("查询失败:{message}",{message:pt(o)}),Date.now()),xr()}return}if(Qs().usageBusy)return;const t=Xy();if(t.length){yn({usageBusy:!0}),t.forEach(r=>na(r.id,null,Date.now())),xr();try{await hf(null)}catch(r){const o=pt(r);t.forEach(c=>na(c.id,l("查询失败:{message}",{message:o}),Date.now())),xr()}finally{yn({usageBusy:!1})}}}async function DR(e,t){try{await Pe().workbuddyDesktop?.updateAccount?.(e,{enabled:t}),await Pe().wbApp?.refresh?.(),He(l(t?"✅ 已启用":"✅ 已禁用"))}catch(r){He(l("操作失败:{message}",{message:pt(r)}),"err"),Pe().wbApp?.refresh?.()}}async function IR(e,t){if(!e.length)return!1;try{return await Pe().workbuddyDesktop?.reorderAccounts?.(e),He(t?l("✅ 已保存:{note}",{note:t}):l("✅ 顺序已保存")),await Pe().wbApp?.refresh?.(),!0}catch(r){return He(l("顺序未保存:{message}",{message:pt(r)}),"err"),Pe().wbApp?.refresh?.(),!1}}async function PR(e,t){if(e.length)try{await Pe().workbuddyDesktop?.batchAccounts?.({action:t?"enable":"disable",ids:e}),He(t?l("✅ 已启用 {n} 个账号",{n:e.length}):l("✅ 已禁用 {n} 个账号",{n:e.length})),await Pe().wbApp?.refresh?.()}catch(r){He(l("操作失败:{message}",{message:pt(r)}),"err"),Pe().wbApp?.refresh?.()}}async function T$(e,t){try{await Pe().workbuddyDesktop?.clearRateLimits?.(e,t||null),He(t?l("✅ 已清除 {model} 的限流标记",{model:t}):l("✅ 已清除该账号全部限流标记")),await Pe().wbApp?.refresh?.()}catch(r){He(l("清除失败:{message}",{message:pt(r)}),"err")}}async function E$(e,t,r){if(t===_R){Dh(e);return}if(t!==_h&&t!==r)try{const o=t===""?null:{source:"pool",proxyId:t.slice(Ga.length)},d=(await Pe().workbuddyDesktop?.updateAccount?.(e,{proxy:o}))?.changes,f=Array.isArray(d)&&d.length?d[0]:l("代理已更新");He(`✅ ${f}`)}catch(o){He(l("保存失败:{message}",{message:pt(o)}),"err")}finally{await Pe().wbApp?.refresh?.()}}const _h="__proxy_custom__",_R="__proxy_custom_edit__";function LR(e,t){const r=Ca(e);if(!r){He(l("账号不存在,请刷新后重试"),"err");return}const o=Pe().wbZcodePlans;if(!o?.open){He(l("套餐明细弹窗未加载,请重启应用后重试"),"err");return}o.open({id:e,name:t||r.name})}function R$(e,t,r=1){return{seat:t.get(e.id)||{position:1,total:1},rank:r,picked:c$(e.id),usageEntry:xo.get(e.id),limitsOpen:xR(e.id,"limits"),connections:NR(e.id)}}const A$={DEFAULT_PROVIDER_ID:nu,RACCOON_PROVIDER_ID:O6,providerOf:Rn,providerFeatures:lr,providerSummaries:zE,identifierOf:wh,tokenExpiryOf:I6,supportsUsage:Na,isDesktopAccount:cf,supportsChat:YE,byPriorityOrder:Ch,typeLabel:$6,isEnabled:or,isRateLimited:uf,isLimited:e=>df(e,e?Ka(e):void 0,Cl(e)),accountEdition:XE,supportsClaim:QE,matchEnabled:Hy,matchLimit:sR,visibleAccounts:X6,filterCounts:aR,positionMap:Vy,activeLimits:Uy,editionSuffix:Z6,formatResetText:Fy};function O$(){window.wbAccountsView={render:()=>xr(),refreshCaches:y$,openPanels:f$,syncConnections:CR,applyBalances:ER,syncBalancesSnapshot:C$,queryUsageFor:hf,queryAllUsage:OR,refreshUsageAfterCheckin:Ph,supportsUsage:Na,isDesktopAccount:cf,isEnabled:or,isRateLimited:uf},window.wbAccountsModel=A$,window.wbAccountPanel={open:Dh,close:Ih,openBatch:Yy,closeBatch:Ih,syncAddProvider:()=>Pe().wbAccountAddForms?.syncAddProvider?.(),invalidate:g$}}function M$(e){return e.type==="balance"?l("余额 < {threshold}",{threshold:e.threshold}):e.reset==="daily"?l("每日消耗 ≥ {count} Token(每天 0 点重置)",{count:Sl(e.threshold)}):l("每 {period}消耗 ≥ {count} Token",{period:KE(e.period??0),count:Sl(e.threshold)})}function D$(e){return e.action==="disable"?l("禁用该账号(需手动重新启用)"):l("跳过该账号(自动恢复)")}function I$(e){return`${Math.round(e.threshold).toLocaleString("en-US")} Token`}function P$(e,t){if(t.enabled===!1)return{text:l("已停用"),kind:"off"};if(t.type==="balance"){const v=Ka(e),y=Sh(e,v),b=v&&typeof v=="object"?v:null,j=b?b.totalLeft??b.available:void 0,w=j==null||j===""||b?.unlimited?"":l(" · 当前 {n}",{n:Number(j)});return y?{text:l("已跳过{current}",{current:w}),kind:"warn",title:l("余额低于阈值,转发时会跳过该账号(余额回升自动恢复)")}:{text:l("未触发{current}",{current:w}),kind:"ok"}}const r=Cl(e),o=of(t,r),c=o?o.used:0,d=Sl(t.threshold),f=t.reset==="daily"?l(" · 今日 {used} / {quota}",{used:Sl(c),quota:d}):l(" · 本周期 {used} / {quota}",{used:Sl(c),quota:d}),p=o?` · ${Nh(Ly(t).remainingMs,t.reset==="daily")}`:"";return o!==null&&c>=t.threshold?t.action==="disable"?e.enabled===!1?{text:l("已触发 · 账号已禁用"),kind:"danger",title:l("重置也不恢复,需手动启用")}:{text:l("已达上限{usage}",{usage:f}),kind:"warn",title:l("稍后由后台判定自动禁用")}:{text:l("已跳过{usage}{countdown}",{usage:f,countdown:p}),kind:"warn",title:l("窗口内已用 {used} / {limit} Token,转发时会跳过该账号(重置后自动恢复)",{used:Math.round(c).toLocaleString("en-US"),limit:Math.round(t.threshold).toLocaleString("en-US")})}:{text:l("未触发{usage}{countdown}",{usage:f,countdown:p}),kind:"ok",title:I$(t)}}function _$(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 zR(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 r=_$(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:r.value,periodUnit:r.unit}}function BR(e){const t=Number(e.thresholdInput);if(!Number.isFinite(t)||t<=0)return{error:l("限制阈值必须是大于 0 的数字")};if(e.type==="balance")return{rule:{type:"balance",action:e.action,threshold:t,enabled:!0}};const r=Math.round(e.tokenUnit==="wan"?t*1e4:t);if(e.reset==="daily")return{rule:{type:"token",action:e.action,threshold:r,reset:"daily",enabled:!0}};const o=Number(e.periodInput)*(e.periodUnit==="hours"?3600:60);if(!Number.isFinite(o)||o<=0)return{error:l("请填写重置周期")};const c=Math.round(o);return c$E?{error:l("重置周期必须是 30 分钟 ~ 24 小时")}:{rule:{type:"token",action:e.action,threshold:r,period:c,reset:"fixed",enabled:!0}}}function L$({account:e,target:t,onClose:r,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=BR(f);if("error"in b){d(b.error);return}o(b.rule,t.index)},y=()=>{if(f.type==="balance"){const R=Ka(e);if(R&&typeof R=="object"){const k=R;if(k.unlimited)return l("当前可用 ∞(不参与余额不足判定)");const A=k.totalLeft??k.available;if(A!=null&&A!=="")return l("当前余额 {n};与余额列同一数字口径,严格小于才触发(等于阈值仍可用)",{n:Number(A)})}return l("读数来自自动余额查询;与余额列同一数字口径,严格小于才触发(等于阈值仍可用)")}const b=BR(f);if(!("rule"in b))return"";const j=b.rule,w=of(j,Cl(e));if(!w)return j.reset==="daily"?l("窗口 = 今天 0 点起(本地时区),0 点重置即清零恢复;按账号在 requests 表聚合"):l("窗口对齐自然时间(整点 / 整 N 分钟一轮回),重置即清零恢复;按账号在 requests 表聚合");const S=Ly(j),N=Sl(w.used),C=Sl(j.threshold),E=j.reset==="daily"?l("今日已用"):l("本周期已用");return l("{scope} {used} / {quota} Token,{countdown}重置",{scope:E,used:N,quota:C,countdown:Nh(S.remainingMs,S.daily)})};return s.jsx(Kt,{open:!0,onOpenChange:b=>{b||r()},children:s.jsxs(Yt,{className:"w-[min(580px,calc(100vw-48px))]",showCloseButton:!0,children:[s.jsx(Ft,{children:s.jsx($t,{children:t.index>=0?l("编辑限制"):l("添加限制")})}),s.jsxs(Ht,{children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:l("限制类型")}),s.jsxs(ct,{value:f.type,onValueChange:b=>g({type:b,thresholdInput:""}),children:[s.jsx(dt,{className:"w-[150px]","aria-label":l("限制类型"),children:s.jsx(ut,{children:f.type==="balance"?l("余额"):l("Token 消耗")})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"balance",children:l("余额")}),s.jsx(Ye,{value:"token",children:l("Token 消耗")})]})]}),s.jsx("span",{className:"detail",children:l("余额沿用现有口径;Token 按重置方式内的累计消耗判定(切换类型会清空阈值)")})]}),f.type==="balance"?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:l("触发条件")}),s.jsx("span",{className:"detail",style:{fontSize:13},children:l("余额低于")}),s.jsx(Ke,{type:"number",min:0,step:1,className:"max-w-[120px]",placeholder:l("阈值"),value:f.thresholdInput,onChange:b=>g({thresholdInput:b.currentTarget.value})}),s.jsx("span",{className:"detail",style:{fontSize:13},children:l("时")})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:l("触发后")}),s.jsxs(ct,{value:f.action,onValueChange:b=>g({action:b}),children:[s.jsx(dt,{className:"min-w-[280px]","aria-label":l("触发动作"),children:s.jsx(ut,{children:f.action==="disable"?l("禁用该账号(需手动重新启用)"):l("跳过该账号(余额回升自动恢复)")})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"skip",children:l("跳过该账号(余额回升自动恢复)")}),s.jsx(Ye,{value:"disable",children:l("禁用该账号(需手动重新启用)")})]})]})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:l("重置方式")}),s.jsxs(ct,{value:f.reset,onValueChange:b=>g({reset:b}),children:[s.jsx(dt,{className:"w-[190px]","aria-label":l("重置方式"),children:s.jsx(ut,{children:f.reset==="daily"?l("自然日(每天 0 点)"):l("固定周期")})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"fixed",children:l("固定周期")}),s.jsx(Ye,{value:"daily",children:l("自然日(每天 0 点)")})]})]}),s.jsx("span",{className:"detail",children:l("有的账号过了 0 点额度就回来 —— 选「自然日」")})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:l("触发条件")}),f.reset==="daily"?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"detail",style:{fontSize:13},children:l("每日消耗 ≥")}),s.jsx(Ke,{type:"number",min:0,step:1,className:"max-w-[110px]",placeholder:l("阈值"),value:f.thresholdInput,onChange:b=>g({thresholdInput:b.currentTarget.value})}),s.jsxs(ct,{value:f.tokenUnit,onValueChange:b=>g({tokenUnit:b}),children:[s.jsx(dt,{className:"w-[92px]","aria-label":l("Token 单位"),children:s.jsx(ut,{children:f.tokenUnit==="wan"?l("万"):l("个")})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"wan",children:l("万")}),s.jsx(Ye,{value:"unit",children:l("个")})]})]}),s.jsx("span",{className:"detail",style:{fontSize:13},children:l("Token 时")})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"detail",style:{fontSize:13},children:l("每")}),s.jsx(Ke,{type:"number",min:1,step:1,className:"max-w-[90px]",placeholder:l("周期"),value:f.periodInput,onChange:b=>g({periodInput:b.currentTarget.value})}),s.jsxs(ct,{value:f.periodUnit,onValueChange:b=>g({periodUnit:b}),children:[s.jsx(dt,{className:"w-[92px]","aria-label":l("周期单位"),children:s.jsx(ut,{children:f.periodUnit==="hours"?l("小时"):l("分钟")})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"minutes",children:l("分钟")}),s.jsx(Ye,{value:"hours",children:l("小时")})]})]}),s.jsx("span",{className:"detail",style:{fontSize:13},children:l("内消耗 ≥")}),s.jsx(Ke,{type:"number",min:0,step:1,className:"max-w-[110px]",placeholder:l("阈值"),value:f.thresholdInput,onChange:b=>g({thresholdInput:b.currentTarget.value})}),s.jsxs(ct,{value:f.tokenUnit,onValueChange:b=>g({tokenUnit:b}),children:[s.jsx(dt,{className:"w-[92px]","aria-label":l("Token 单位"),children:s.jsx(ut,{children:f.tokenUnit==="wan"?l("万"):l("个")})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"wan",children:l("万")}),s.jsx(Ye,{value:"unit",children:l("个")})]})]}),s.jsx("span",{className:"detail",style:{fontSize:13},children:l("Token 时")})]})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:l("触发后")}),s.jsxs(ct,{value:f.action,onValueChange:b=>g({action:b}),children:[s.jsx(dt,{className:"min-w-[280px]","aria-label":l("触发动作"),children:s.jsx(ut,{children:f.action==="disable"?l("禁用该账号(需手动重新启用)"):l("跳过该账号(重置后自动恢复)")})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"skip",children:l("跳过该账号(重置后自动恢复)")}),s.jsx(Ye,{value:"disable",children:l("禁用该账号(需手动重新启用)")})]})]})]})]}),s.jsx("p",{className:"detail limiter-hint",children:y()}),c?s.jsx("p",{className:"detail text-destructive",children:c}):null]}),s.jsxs(sn,{children:[s.jsx(se,{variant:"outline",onClick:r,children:l("取消")}),s.jsx(se,{variant:"default",onClick:v,children:t.index>=0?l("保存规则"):l("添加规则")})]})]})})}function z$({account:e,draft:t,onChange:r}){const[o,c]=x.useState(null),d=()=>c({index:-1,draft:zR(null)}),f=y=>c({index:y,draft:zR(t[y])}),p=(y,b)=>{const j=[...t];b>=0?j[b]=y:j.push(y),r(j),c(null)},g=y=>{r(t.filter((b,j)=>j!==y)),o&&c(null)},v=(y,b)=>{const j=[...t];j[y]={...j[y],enabled:b},r(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=P$(e,y);return s.jsxs("div",{className:"limiter-rule","data-off":y.enabled===!1||void 0,children:[s.jsx(Rs,{checked:y.enabled!==!1,"aria-label":l("启用该规则"),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"?l("余额"):"Token"})," ",l("{cond} 时 → {action}",{cond:M$(y),action:D$(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:l("编辑")}),s.jsx(se,{variant:"ghost",onClick:()=>g(b),children:l("删除")})]})]},b)})}):s.jsx("p",{className:"detail mt-2.5",children:l("还没有限制规则:账号照常参与转发,余额与 Token 消耗都不设上限。")}),s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx(se,{variant:"outline",onClick:d,children:l("+ 添加限制")}),s.jsx("span",{className:"detail",children:l("可添加多条;同类规则也允许并存(例如一条按余额、两条不同重置方式的 Token)")})]}),s.jsx(L$,{account:e,target:o,onClose:()=>c(null),onSave:p})]})}function B$(e,t){const r=su(e);return JSON.stringify(t)===JSON.stringify(r)?null:{patch:{limiters:t}}}function H$(e){return su(e).map(t=>({...t}))}const U$={seconds:1,minutes:60,hours:3600};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"}:e>0?{value:String(e),unit:"seconds"}:{value:"5",unit:"minutes"}}function $$(e){const{enabled:t,interval:r}=qE(e),o=V$(t?r:0);return{enabled:t,intervalInput:o.value,unit:o.unit}}function F$(e,t){const r=Math.round(Number(t.intervalInput)*U$[t.unit]);if(t.enabled){if(!Number.isFinite(Number(t.intervalInput))||Number(t.intervalInput)<=0)return{error:l("请填写查询间隔")};if(rHE)return{error:l("查询间隔必须是 {min} 秒 ~ 24 小时",{min:Iy})}}const o={},c=qE(e);return(t.enabled!==c.enabled||t.enabled&&r!==c.interval)&&(o.usageQuery={enabled:t.enabled,interval:t.enabled?r:c.interval}),o.usageQuery?{patch:o}:null}function q$({account:e,draft:t,onChange:r}){const o=c=>r({...t,...c});return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"field-row mt-2.5",children:s.jsxs(tt,{className:"inline-flex cursor-pointer items-center gap-2.5 font-normal",children:[s.jsx(Rs,{checked:t.enabled,onCheckedChange:c=>o({enabled:c===!0}),"aria-label":l("自动查询余额")}),s.jsx("span",{className:"text-xs text-subtle",children:l("自动查询余额(按下面的间隔自动刷新余额列的读数)")})]})}),t.enabled?s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:"account-usage-interval",children:l("查询间隔")}),s.jsx(Ke,{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(ct,{value:t.unit,onValueChange:c=>o({unit:c}),children:[s.jsx(dt,{className:"w-[92px]","aria-label":l("间隔单位"),children:s.jsx(ut,{children:t.unit==="hours"?l("小时"):t.unit==="minutes"?l("分钟"):l("秒")})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"seconds",children:l("秒")}),s.jsx(Ye,{value:"minutes",children:l("分钟")}),s.jsx(Ye,{value:"hours",children:l("小时")})]})]}),s.jsx("span",{className:"detail",children:l("30 秒 ~ 24 小时;手动查询会顺延下一轮")})]}):null]})}const HR=64;function G$(e,t){const r=Rn(e);return t.filter(o=>o.id!==e.id&&Rn(o)===r)}const kl=999;function Lh(e){return ru(e)||e?.id||""}function UR(e){const t=e?.config?.source||e?.source,r=e?.config||null;return{mode:t==="pool"?"pool":t==="clash"?"clash":t==="custom"?"custom":"none",proxyId:t==="pool"?String(r?.proxyId||""):"",listenerUid:r?.source==="clash"||t==="clash"?String(r?.listenerUid||""):"",protocol:r?.protocol==="socks5"?"socks5":"http",host:r?.host||"",port:r?.port===void 0||r?.port===null?"":String(r.port),username:r?.username||"",password:r?.password||""}}function Qy(e){if(e.mode==="none")return null;if(e.mode==="pool"){if(!e.proxyId)throw new Error(l("请先选择已保存的代理"));return{source:"pool",proxyId:e.proxyId}}if(e.mode==="clash"){if(!e.listenerUid)throw new Error(l("请先选择 Clash Verge 出口"));return{source:"clash",listenerUid:e.listenerUid}}const t=e.host.trim(),r=Number(e.port);if(!t)throw new Error(l("请填写代理主机地址"));if(!Number.isInteger(r)||r<1||r>65535)throw new Error(l("代理端口必须是 1-65535 的整数"));return{source:"custom",protocol:e.protocol==="socks5"?"socks5":"http",host:t,port:r,username:e.username.trim(),password:e.password}}function VR(e){const t=e.profileActive===!1?l("(其他订阅,可能未生效)"):"",r=e.enabled===!1?l("(已在 Clash 中禁用)"):"";return`${e.name} :${e.port}${t}${r}`}function $R({draft:e,onChange:t,idPrefix:r}){const c=Qs().clash,d=Array.isArray(c?.options)?c.options:[],f=e.mode==="clash",[p,g]=x.useState(!1),[v,y]=x.useState(null),[b,j]=x.useState(null),[w,S]=x.useState(""),N=R=>t({...e,...R});x.useEffect(()=>{f&&jR().catch(()=>{})},[f]);const C=x.useCallback((R=!1)=>{S(""),wR({force:R}).then(k=>j(k)).catch(k=>{j([]),S(pt(k))})},[]);x.useEffect(()=>{e.mode==="pool"&&b===null&&C()},[e.mode,b,C]);async function E(){if(p)return;if(e.mode==="pool"){if(!e.proxyId){He(l("请先选择已保存的代理"),"err");return}g(!0),y(l("正在连接上游…"));try{const k=await Pe().workbuddyDesktop?.testProxyPoolItem?.(e.proxyId);y(k?.success?s.jsxs("span",{className:"text-success",children:[l("✅ 出口可用"),k.ip?l(" 出口 IP {ip}",{ip:wl(k.ip)}):"",k.durationMs!==void 0&&k.durationMs!==""?` ${wl(String(k.durationMs))}ms`:""]}):s.jsxs("span",{className:"text-destructive",children:["❌ ",wl(k?.error||l("连接失败"))]}))}catch(k){y(s.jsxs("span",{className:"text-destructive",children:["❌ ",wl(pt(k))]}))}finally{g(!1)}return}let R;try{R=Qy(e)}catch(k){He(pt(k),"err");return}g(!0),y(l("正在连接上游…"));try{const k=await Pe().workbuddyDesktop?.testProxy?.({proxy:R});k?.success?y(s.jsxs("span",{className:"text-success",children:[l("✅ 出口可用"),k.status!==void 0&&k.status!==""?` HTTP ${wl(String(k.status))}`:"",k.ip?l(" 出口 IP {ip}",{ip:wl(k.ip)}):"",k.durationMs!==void 0&&k.durationMs!==""?` ${wl(String(k.durationMs))}ms`:""]})):y(s.jsxs("span",{className:"text-destructive",children:["❌ ",wl(k?.error||l("连接失败"))]}))}catch(k){y(s.jsxs("span",{className:"text-destructive",children:["❌ ",wl(pt(k))]}))}finally{g(!1)}}return s.jsxs("div",{className:"flex flex-col",children:[s.jsxs(ch,{value:e.mode,onValueChange:R=>N({mode:R}),className:"flex-row flex-wrap items-center gap-5","aria-label":l("代理方式"),children:[s.jsxs(tt,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(Mi,{value:"none"}),l("无代理(直连)")]}),s.jsxs(tt,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(Mi,{value:"pool"}),l("已保存的代理")]}),f?s.jsxs(tt,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(Mi,{value:"clash"}),"Clash Verge"]}):null,s.jsxs(tt,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(Mi,{value:"custom"}),l("自定义")]})]}),e.mode==="pool"?s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:`${r}-pool-exit`,children:l("代理")}),s.jsxs(ct,{value:e.proxyId,disabled:!b?.length,onValueChange:R=>N({proxyId:String(R)}),children:[s.jsx(dt,{id:`${r}-pool-exit`,className:"min-w-[220px]",children:s.jsx(ut,{children:b?.find(R=>R.id===e.proxyId)?lf(b.find(R=>R.id===e.proxyId)):b===null?l("正在读取…"):b.length?l("请选择代理"):l("还没有保存的代理")})}),s.jsx(ft,{children:(b??[]).map(R=>s.jsx(Ye,{value:R.id,children:lf(R)},R.id))})]}),s.jsx(se,{variant:"outline",size:"sm",onClick:()=>C(!0),children:l("重新读取")})]}),s.jsx("div",{className:"detail mt-1.5",children:w?l("读取失败:{error}",{error:w}):b===null?l("正在读取代理列表…"):b.length?l("地址与端口由「网络代理」页管理:那边改一次、测一次,所有引用它的账号一起生效"):l("「网络代理」页还没有出口 —— 去那里新增,或点「同步 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:`${r}-clash-exit`,children:l("出口")}),s.jsxs(ct,{value:e.listenerUid,disabled:!d.length,onValueChange:R=>N({listenerUid:String(R)}),children:[s.jsx(dt,{id:`${r}-clash-exit`,className:"min-w-[220px]",children:s.jsx(ut,{children:d.find(R=>String(R.uid)===e.listenerUid)?VR(d.find(R=>String(R.uid)===e.listenerUid)):c?.available===!1?l("未检测到 Clash Verge"):d.length?l("请选择出口"):l("没有可用出口")})}),s.jsx(ft,{children:d.map(R=>s.jsx(Ye,{value:String(R.uid),children:VR(R)},String(R.uid)))})]}),s.jsx(se,{variant:"outline",size:"sm",onClick:()=>{jR({force:!0}).then(()=>He(l("✅ 已重新读取 Clash Verge 配置"))).catch(R=>He(l("读取失败:{error}",{error:pt(R)}),"err"))},children:l("重新读取")})]}),s.jsx("div",{className:"detail mt-1.5",children:c===null?l("正在读取 Clash Verge 配置…"):c.available===!1?c.error?l("不可用:{error}",{error:c.error}):l("未检测到 Clash Verge 配置"):d.length?l("读取自 {dir};端口由 Clash Verge 管理,这里实时同步",{dir:c.dir||"Clash Verge"}):l("Clash Verge 里还没有配置混合监听器或节点端口")}),s.jsxs("p",{className:"detail mt-1.5",children:[l("这是既有配置(直接引用 Clash 出口,不经过代理池)。推荐改用上面的"),s.jsx("b",{children:l("「已保存的代理」")}),l(":到「网络代理」页点「同步 Clash Verge」把出口导进池后即可选 —— 那样能集中测试、也能被多个账号共用。")]})]}):null,e.mode==="custom"?s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:`${r}-protocol`,children:l("协议")}),s.jsxs(ct,{value:e.protocol,onValueChange:R=>N({protocol:R}),children:[s.jsx(dt,{id:`${r}-protocol`,className:"min-w-[110px]",children:s.jsx(ut,{children:e.protocol==="socks5"?"SOCKS5":"HTTP"})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"http",children:"HTTP"}),s.jsx(Ye,{value:"socks5",children:"SOCKS5"})]})]}),s.jsx("label",{htmlFor:`${r}-host`,className:"ml-2",children:l("主机")}),s.jsx(Ke,{id:`${r}-host`,className:"min-w-[140px]",placeholder:"127.0.0.1",value:e.host,onChange:R=>N({host:R.currentTarget.value})}),s.jsx("label",{htmlFor:`${r}-port`,children:l("端口")}),s.jsx(Ke,{id:`${r}-port`,type:"number",min:1,max:65535,className:"max-w-[110px]",placeholder:"7890",value:e.port,onChange:R=>N({port:R.currentTarget.value})})]}),s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:`${r}-user`,children:l("用户名")}),s.jsx(Ke,{id:`${r}-user`,placeholder:l("可选"),autoComplete:"off",value:e.username,onChange:R=>N({username:R.currentTarget.value})}),s.jsx("label",{htmlFor:`${r}-pass`,children:l("密码")}),s.jsx(Ke,{id:`${r}-pass`,type:"password",placeholder:l("可选"),autoComplete:"new-password",value:e.password,onChange:R=>N({password:R.currentTarget.value})})]})]}):null,s.jsxs("div",{className:"field-row mt-3",children:[s.jsx(se,{variant:"outline",size:"sm",disabled:p,onClick:()=>{E()},children:l(p?"测试中…":"测试出口")}),s.jsx("span",{className:"detail",children:v})]})]})}function K$({plan:e,hasJwt:t,onChange:r}){const o=F6(e),[c,d]=x.useState(null);return x.useEffect(()=>{if(e!==go)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:l("使用套餐")}),s.jsxs(ct,{value:e,onValueChange:f=>r(String(f)),children:[s.jsx(dt,{id:"account-plan-channel",className:"min-w-[220px]",children:s.jsx(ut,{children:o})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:ZE,children:l("编码套餐(Coding Plan)— 走开放平台端点,用自己订阅的额度")}),s.jsx(Ye,{value:go,children:l("活动套餐(Start Plan)— 走官方活动端点,用活动里领到的额度")})]})]}),e===go&&!t?s.jsx("span",{className:"detail text-destructive",children:l("该账号没有套餐登录态(jwt),活动套餐会失败:请重新登录该账号")}):null,e===go?s.jsxs("span",{className:"detail",title:l("活动套餐的推理端点要求每条请求带一个阿里云验证码令牌;令牌由本应用在后台静默铸造,界面关闭时无法铸造"),children:[l("验证码令牌:{counts}",{counts:c?`${c.ready} / ${c.target||3}`:l("读取中…")}),c&&c.ready===0?l("(库存为空,正在补;补不上时转发会失败)"):""]}):null]})}function Y$({configured:e,value:t,onChange:r,onClear:o,clearBusy:c}){return s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:"account-balance-token-input",children:l("余额查询凭证")}),s.jsx(Ke,{id:"account-balance-token-input",className:"min-w-[220px]",placeholder:l(e?"已配置,留空则不修改":"一般不用填"),title:l("积分查询已复用转发用的登录凭证,这里通常留空即可。只有旧版本填过、或从旧代理导入过凭证时才有值"),value:t,onChange:d=>r(d.currentTarget.value)}),e?s.jsx(se,{variant:"outline",size:"sm",disabled:c,onClick:o,title:l("清除已配置的余额查询凭证"),children:l("清除")}):null]})}function X$({hasApiKey:e,noAuth:t,value:r,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:l("API Key")}),s.jsx(Ke,{id:"account-api-key-input",type:"password",autoComplete:"new-password",className:"min-w-[220px]",disabled:t,placeholder:e?l("已配置,留空则不修改"):"sk-…",title:l("上游的 API Key。留空 = 不修改(改凭证不会换账号 id);要清掉已配的凭证用右边的「清除」"),value:r,onChange:p=>o(p.currentTarget.value)}),e&&!t?s.jsx(se,{variant:"outline",size:"sm",disabled:f,onClick:d,title:l("清除已配置的 API Key(转发时会因缺少凭证被跳过)"),children:l("清除")}):null]}),s.jsx("div",{className:"field-row mt-2.5",children:s.jsxs(tt,{className:"inline-flex cursor-pointer items-center gap-2.5 font-normal",children:[s.jsx(ea,{checked:t,"aria-label":l("该上游无需鉴权"),onCheckedChange:p=>c(p===!0)}),s.jsx("span",{className:"text-xs text-subtle",children:l("该上游无需鉴权(转发与拉取模型都不发送鉴权头)")})]})}),s.jsxs("p",{className:"detail",children:[l("上游本来不要凭证时(本地 Ollama、OpenCode Zen 的免费档)勾上这一项:账号会被正常选路;只把 Key 留空"),s.jsx("strong",{children:l("又不勾")}),l("会被当成「未配置凭证」而跳过。")]})]})}function Q$({provider:e,name:t,protocol:r,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:l("OpenAI 兼容")},{value:"anthropic",label:"Anthropic"}],j=b.find(w=>w.value===r)?.label||r;return s.jsxs(zn,{children:[s.jsx("h3",{children:l("提供商")}),s.jsxs("p",{children:[l("这一栏改的是"),s.jsx("strong",{children:l("「{name}」本身",{name:e.name||e.id})}),l("(名下 {count} 个账号共用)",{count:c}),l("改协议 / Base URL 会改变它们的转发方式,正在进行的请求可能失败;模型清单与映射在「模型管理」页。")]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:"account-provider-name",children:l("名称")}),s.jsx(Ke,{id:"account-provider-name",maxLength:HR,className:"min-w-[220px]",placeholder:l("提供商显示名,1~{max} 个字符",{max:HR}),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:l("协议")}),s.jsxs(ct,{value:r,onValueChange:w=>p(String(w)),children:[s.jsx(dt,{id:"account-provider-protocol",className:"min-w-[180px]",children:s.jsx(ut,{children:j})}),s.jsx(ft,{children:b.map(w=>s.jsx(Ye,{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:l("Base URL")}),s.jsx(Ke,{id:"account-provider-baseurl",className:"min-w-[260px]",placeholder:l("OpenAI 兼容填到 /v1;Anthropic 填根地址"),value:o,onChange:w=>g(w.currentTarget.value)})]}),s.jsx("div",{className:"field-row mt-2.5",children:s.jsxs(tt,{className:"inline-flex cursor-pointer items-center gap-2.5 font-normal",children:[s.jsx(ea,{checked:d==="opencode","aria-label":l("伪装 OpenCode 官方客户端"),onCheckedChange:w=>v(w===!0?"opencode":"")}),s.jsx("span",{className:"text-xs text-subtle",children:l("伪装 OpenCode 官方客户端(OpenCode Zen 免费档要它才放行)")})]})}),s.jsxs("p",{className:"detail",children:[l("开启后,网关按 OpenCode 官方 CLI 的形状发请求:没填 Key 的账号用匿名凭证"),s.jsx("code",{children:"public"}),l("、补官方会话头、请求体补两个占位工具(上游免费档的三道校验)。"),s.jsx("strong",{children:l("它会改写请求体")}),l(",只对 OpenCode Zen 这类上游有意义,别的家请关掉。")]}),s.jsxs("div",{className:"field-row mt-3",children:[s.jsx(se,{variant:"destructive",onClick:y,children:l("删除提供商")}),s.jsx("span",{className:"detail",children:l("级联删除名下全部账号,不可恢复")})]})]})}function Z$({id:e,onClose:t}){const r=Ca(e),[o,c]=x.useState(r?.enabled!==!1),[d,f]=x.useState(r?.name||""),[p,g]=x.useState(()=>UR(r?.proxy)),[v,y]=x.useState(""),[b,j]=x.useState(()=>zy(r)),[w,S]=x.useState(!1),[N,C]=x.useState(""),[E,R]=x.useState(null),[k,A]=x.useState(""),[D,I]=x.useState("chat_completions"),[M,O]=x.useState(""),[_,L]=x.useState(""),[z,U]=x.useState(""),[B,Q]=x.useState(r?.noAuth===!0),[W,Z]=x.useState(()=>$$(r)),[Y,q]=x.useState(()=>H$(r)),[G,$]=x.useState("basic"),[F,X]=x.useState(()=>String(Number(r?.maxConcurrent)||0));if(x.useEffect(()=>{let K=!0;R(null);const be=Ca(e);return be?(Promise.resolve(Pe().wbCustomProvidersUi?.find?.(Rn(be))).then(ne=>{!K||!ne||(R(ne),A(ne.name||""),I(ne.protocol||"chat_completions"),O(ne.baseUrl||""),L(typeof ne.clientEmulation=="string"?ne.clientEmulation:""))}).catch(()=>{}),()=>{K=!1}):()=>{K=!1}},[e]),!r)return s.jsx(Kt,{open:!0,onOpenChange:K=>{K||t()},children:s.jsxs(Yt,{children:[s.jsx(Ft,{children:s.jsx($t,{children:l("账号设置")})}),s.jsx(Ht,{children:s.jsx("p",{className:"detail",children:l("账号不存在,请刷新后重试。")})}),s.jsxs(sn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:l("关闭")})]})]})});const re=r,P=G$(re,Nl()),V=Rn(re)==="catpaw",J=Rn(re).startsWith("custom-");async function ie(){if(!w){S(!0);try{await Pe().workbuddyDesktop?.updateAccount?.(e,{balanceToken:null}),y(""),He(l("✅ 已清除余额查询凭证")),await Pe().wbApp?.refresh?.()}catch(K){He(l("清除失败:{error}",{error:pt(K)}),"err")}finally{S(!1)}}}async function me(){if(!w){S(!0);try{await Pe().workbuddyDesktop?.updateAccount?.(e,{apiKey:null}),U(""),He(l("✅ 已清除 API Key(该账号现在没有凭证,转发会被跳过)")),await Pe().wbApp?.refresh?.()}catch(K){He(l("清除失败:{error}",{error:pt(K)}),"err")}finally{S(!1)}}}function he(){if(!J)return null;const K=z.trim(),be={};return K?be.apiKey=K:B!==(re.noAuth===!0)&&(be.noAuth=B),Object.keys(be).length?be:null}function ae(){if(!E)return null;const K=k.trim(),be=M.trim();if(!K)return{error:l("请填写提供商名称")};if(!be)return{error:l("请填写提供商的 Base URL")};const ne=typeof E.clientEmulation=="string"?E.clientEmulation:"";return E.name===K&&E.protocol===D&&E.baseUrl===be&&ne===_?null:{id:E.id,name:K,protocol:D,baseUrl:be,clientEmulation:_}}async function oe(){if(w)return;let K;try{K=Qy(p)}catch(Se){He(pt(Se),"err");return}const be=ae();if(be&&"error"in be){C(s.jsx("span",{className:"text-destructive",children:be.error}));return}const ne=Na(re)?F$(re,W):null;if(ne&&"error"in ne){C(s.jsx("span",{className:"text-destructive",children:ne.error}));return}const ce=B$(re,Y),we=he()||{},Ee=Number(F);if(!Number.isFinite(Ee)||Ee<0){He(l("并发上限必须是 0~{max} 的整数",{max:kl}),"err");return}const ve=Math.min(kl,Math.round(Ee)),Ce=Number(re.maxConcurrent)||0,ke=ve!==Ce?{maxConcurrent:ve}:{};S(!0);try{const Se=V&&v.trim()?{balanceToken:v.trim()}:{},ge=kh(re)&&b!==zy(re)?{zcodePlan:b}:{};if(await Pe().workbuddyDesktop?.updateAccount?.(e,{name:d.trim()||re.name,enabled:o,proxy:K,...Se,...ge,...we,...ke,...ne&&"patch"in ne?ne.patch:{},...ce&&"patch"in ce?ce.patch:{}}),be)try{await Pe().wbCustomProvidersUi?.update?.(be)}catch(Te){C(s.jsx("span",{className:"text-destructive",children:l("账号已保存,但提供商未更新:{error}",{error:pt(Te)})})),await Pe().wbApp?.refresh?.(),S(!1);return}t(),He(l("✅ 账号设置已保存"));try{await Pe().wbApp?.refresh?.()}catch{}}catch(Se){C(s.jsx("span",{className:"text-destructive",children:pt(Se)})),He(l("保存失败:{error}",{error:pt(Se)}),"err")}finally{S(!1)}}const ee=Number(lr(Rn(re)).concurrencyDefault)||0,de=V||J||kh(re);return s.jsx(Kt,{open:!0,onOpenChange:K=>{K||w||t()},children:s.jsxs(Yt,{className:"w-[min(900px,calc(100vw-48px))]",children:[s.jsx(Ft,{children:s.jsx($t,{children:l("账号设置 · {name}",{name:Lh(r)})})}),s.jsx(Ht,{className:"p-0",children:s.jsxs("div",{className:"acct-dlg",children:[s.jsx("aside",{className:"prov-rail acct-dlg-rail","aria-label":l("账号设置分组"),children:s.jsxs("div",{className:"rail-scroll",children:[s.jsx("div",{className:"rail-label",children:l("账号设置")}),[["basic",l("基本")],...de?[["credential",l("凭证与套餐")]]:[],...Na(re)?[["query",l("查询设置")],["limiter",l("限制器")]]:[],["network",l("网络")]].map(([K,be])=>s.jsx(eu,{active:G===K,title:be,className:"shadow-none",onClick:()=>$(K),children:be},K))]})}),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:l("基本")}),s.jsx("p",{children:l("这条账号是谁、排第几、能不能接请求。")})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:l("启用")}),s.jsx(Rs,{checked:o,onCheckedChange:c,"aria-label":l("启用该账号")}),s.jsx("span",{className:"detail",children:l("关闭则不参与转发(余额查询照常,见「查询设置」)")})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:"account-name-input",children:l("备注名")}),s.jsx(Ke,{id:"account-name-input",maxLength:100,placeholder:l("账号显示名称"),className:"max-w-[280px]",value:d,onChange:K=>f(K.currentTarget.value)})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:l("转发顺序")}),s.jsx("span",{className:"detail",children:l("在列表里拖:拖分组带调整整组顺位,拖行首把手调整组内先后(顺序由拖拽表达,不再填数字)")})]}),s.jsxs("div",{className:"field-row",children:[s.jsx("label",{htmlFor:"account-conc-input",children:l("并发上限")}),s.jsx(Ke,{id:"account-conc-input",type:"number",min:0,max:kl,step:1,className:"max-w-[110px]",value:F,onChange:K=>X(K.currentTarget.value)}),s.jsx("span",{className:"detail",children:ee>0?l("0 = 按本家默认 {default}",{default:ee}):l("0 = 不限")})]}),s.jsx("p",{className:"detail acct-dlg-hint",children:ee>0?l("并发上限 受上游硬顶约束,达到上限的账号跳过、请求转给其他账号(原列表 ⋯ 菜单的「并发上限」入口已并入这里)"):l("并发上限 0~{max};达到上限的账号跳过、请求转给其他账号(原列表 ⋯ 菜单的「并发上限」入口已并入这里)",{max:kl})})]}):null,G==="credential"&&de?s.jsxs("div",{children:[s.jsxs("div",{className:"acct-dlg-pane-head",children:[s.jsx("h3",{children:l("凭证与套餐")}),s.jsx("p",{children:l("这一段按提供商出现:有什么配什么。")})]}),V?s.jsx(Y$,{configured:r.hasBalanceToken===!0,value:v,onChange:y,clearBusy:w,onClear:()=>{ie()}}):null,J?s.jsx(X$,{hasApiKey:re.hasApiKey===!0,noAuth:B,value:z,onValue:U,onToggleNoAuth:Q,onClear:()=>{me()},clearBusy:w}):null,kh(re)?s.jsx(K$,{plan:b,hasJwt:r.canClaim===!0,onChange:j}):null,E?s.jsx(Q$,{provider:E,count:P.length+1,name:k,protocol:D,baseUrl:M,emulation:_,onName:A,onProtocol:I,onBaseUrl:O,onEmulation:L,onRemove:()=>{w||Promise.resolve(Pe().wbCustomProvidersUi?.remove?.(E.id)).then(K=>{K&&t()})}}):null]}):null,G==="query"&&Na(re)?s.jsxs("div",{children:[s.jsxs("div",{className:"acct-dlg-pane-head",children:[s.jsx("h3",{children:l("查询设置")}),s.jsx("p",{children:l("余额列读数的自动刷新;也是「限制器」余额规则的数据来源。")})]}),s.jsx(q$,{account:re,draft:W,onChange:Z})]}):null,G==="limiter"&&Na(re)?s.jsxs("div",{children:[s.jsxs("div",{className:"acct-dlg-pane-head",children:[s.jsx("h3",{children:l("限制器")}),s.jsx("p",{children:l("按规则限制该账号参与转发:没有规则(或全部停用)= 不限制;跳过档自动恢复,禁用档需手动启用。")})]}),s.jsx(z$,{account:re,draft:Y,onChange:q})]}):null,G==="network"?s.jsxs("div",{children:[s.jsxs("div",{className:"acct-dlg-pane-head",children:[s.jsx("h3",{children:l("网络")}),s.jsx("p",{children:l("这条账号访问上游走哪条线路。")})]}),s.jsx($R,{draft:p,onChange:g,idPrefix:"account-proxy"}),r.proxy?.error?s.jsx("p",{className:"detail text-destructive",children:l("当前代理不可用:{error}(转发时会回退直连)",{error:r.proxy.error})}):null]}):null]})]})}),s.jsxs(sn,{children:[s.jsx("div",{className:"detail mr-auto",style:{minHeight:18},children:N}),s.jsx(se,{variant:"outline",disabled:w,onClick:t,children:l("取消")}),s.jsx(se,{variant:"default",disabled:w,onClick:()=>{oe()},children:l(w?"保存中…":"保存")})]})]})})}const W$=[{value:"enable",label:l("启用")},{value:"disable",label:l("禁用")},{value:"proxy",label:l("修改代理")},{value:"concurrency",label:l("设置并发上限")},{value:"remove",label:l("删除")}];function J$({ids:e,action:t,onClose:r}){const[o,c]=x.useState(t),[d,f]=x.useState(()=>UR(null)),[p,g]=x.useState(""),[v,y]=x.useState(!1),[b,j]=x.useState(""),w=e.map(R=>Ca(R)).filter(R=>R!==null),S=w.reduce((R,k)=>Math.max(R,Number(lr(Rn(k)).concurrencyDefault)||0),0);function N(R){return Promise.resolve(Pe().wbConfirm?.ask?.({title:l("删除选中的账号"),html:l("确定删除选中的 {count} 个账号?此操作不可恢复,账号的登录态会一并移除。",{count:R}),okText:l("删除"),okClass:"danger"})??!1)}async function C(){if(v)return;if(!e.length){He(l("没有选中的账号"),"err");return}let R;if(o==="proxy")try{R=Qy(d)}catch(A){He(pt(A),"err");return}let k;if(o==="concurrency"){const A=Number(p.trim());if(!p.trim()||!Number.isFinite(A)||A<0){He(l("并发上限必须是 0~{max} 的整数",{max:kl}),"err");return}k=Math.min(kl,Math.round(A))}if(!(o==="remove"&&!await N(e.length))){if(o==="disable"||o==="remove"){const A=new Set(e);if(!Nl().filter(I=>I.enabled!==!1&&!A.has(I.id)).length){const I=l(o==="remove"?"删除":"禁用");if(!await Promise.resolve(Pe().wbConfirm?.ask?.({title:l("全部启用中的账号将被{what}",{what:I}),html:l("这会{what}所有启用中的账号,转发将不可用。确定继续?",{what:I}),okText:I,okClass:o==="remove"?"danger":"primary"})??!1))return}}y(!0),j("");try{const A={action:o,ids:e};o==="proxy"&&(A.proxy=R),o==="concurrency"&&(A.maxConcurrent=k);const D=await Pe().workbuddyDesktop?.batchAccounts?.(A),I=(D?.ok||[]).filter(z=>z.changes?.length).length,M=(D?.removed||[]).length,O=D?.failed||[],_=o==="remove"?M:I,L={enable:l("启用"),disable:l("禁用"),proxy:l("修改代理"),concurrency:l("设置并发上限"),remove:l("删除")}[o]||o;if(O.length){const z=O.slice(0,3).map(U=>Lh(Ca(String(U.id)))||U.id).join(l("、"));He(l("{verb}完成:成功 {ok} 个,失败 {fail} 个({detail}{more})",{verb:L,ok:_,fail:O.length,detail:z,more:O.length>3?l(" 等"):""}),"err"),j(s.jsxs("span",{className:"text-destructive",children:[l("失败 {count} 个:",{count:O.length}),O.map(U=>`${Lh(Ca(String(U.id)))||U.id}(${U.error})`).join(l(";"))]}))}else He(l("✅ {verb}完成:共 {count} 个账号",{verb:L,count:_})),r();await Pe().wbApp?.refresh?.()}catch(A){j(s.jsx("span",{className:"text-destructive",children:pt(A)})),He(l("批量操作失败:{error}",{error:pt(A)}),"err")}finally{y(!1)}}}const E={enable:l("启用"),disable:l("禁用"),proxy:l("修改代理"),concurrency:l("设置并发上限"),remove:l("删除")}[o]||o;return s.jsx(Kt,{open:!0,onOpenChange:R=>{R||v||r()},children:s.jsxs(Yt,{children:[s.jsx(Ft,{children:s.jsx($t,{children:l("批量操作 · 已选 {count} 个账号",{count:e.length})})}),s.jsxs(Ht,{children:[s.jsxs(zn,{children:[s.jsx("h3",{children:l("将作用于以下账号")}),s.jsx("p",{style:{maxHeight:84,overflowY:"auto"},children:w.map(R=>Lh(R)).join(l("、"))})]}),s.jsxs(zn,{children:[s.jsx("h3",{children:l("操作")}),s.jsx(ch,{value:o,onValueChange:c,className:"flex-row flex-wrap items-center gap-5","aria-label":l("批量动作"),children:W$.map(R=>s.jsxs(tt,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(Mi,{value:R.value}),R.label]},R.value))}),o==="proxy"?s.jsx("div",{className:"mt-2.5",children:s.jsx($R,{draft:d,onChange:f,idPrefix:"batch-proxy"})}):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:l("并发上限")}),s.jsx(Ke,{id:"batch-conc-input",type:"number",min:0,max:kl,step:1,className:"max-w-[110px]",placeholder:l("不限"),value:p,onChange:R=>g(R.currentTarget.value)}),s.jsx("span",{className:"detail",children:l("0 = 不限")})]}),s.jsx("p",{className:"detail acct-dlg-hint",children:S>0?l("并发上限 0~{max};有上游硬顶的家(如 CodeArts)以它的硬顶为准;达到上限的账号会被跳过、请求转给其他账号",{max:kl}):l("并发上限 0~{max};达到上限的账号会被跳过、请求转给其他账号",{max:kl})})]}):null]}),s.jsx("div",{className:"detail",style:{minHeight:18},children:b})]}),s.jsxs(sn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:v,onClick:r,children:l("取消")}),s.jsx(se,{variant:o==="remove"?"destructive":"default",disabled:v,onClick:()=>{C()},children:v?l("执行中…"):l("执行({action})",{action:E})})]})]})})}function eF(){const e=Qs();return e.dialog?e.dialog.kind==="settings"?s.jsx(Z$,{id:e.dialog.id,onClose:Ih},e.dialog.id):s.jsx(J$,{ids:e.dialog.ids,action:e.dialog.action,onClose:Ih},e.dialog.ids.join(",")):null}var Zy={exports:{}},gf={},Wy={exports:{}},Jy={};var FR;function tF(){return FR||(FR=1,(function(e){function t(Z,Y){var q=Z.length;Z.push(Y);e:for(;0>>1,$=Z[G];if(0>>1;Gc(re,q))P<$&&0>c(V,re)?(Z[G]=V,Z[P]=q,G=P):(Z[G]=re,Z[X]=q,G=X);else if(P<$&&0>c(V,q))Z[G]=V,Z[P]=q,G=P;else break e}}return Y}function c(Z,Y){var q=Z.sortIndex-Y.sortIndex;return q!==0?q:Z.id-Y.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,C=!1,E=typeof setTimeout=="function"?setTimeout:null,R=typeof clearTimeout=="function"?clearTimeout:null,k=typeof setImmediate<"u"?setImmediate:null;function A(Z){for(var Y=r(v);Y!==null;){if(Y.callback===null)o(v);else if(Y.startTime<=Z)o(v),Y.sortIndex=Y.expirationTime,t(g,Y);else break;Y=r(v)}}function D(Z){if(N=!1,A(Z),!S)if(r(g)!==null)S=!0,I||(I=!0,U());else{var Y=r(v);Y!==null&&W(D,Y.startTime-Z)}}var I=!1,M=-1,O=5,_=-1;function L(){return C?!0:!(e.unstable_now()-_Z&&L());){var G=b.callback;if(typeof G=="function"){b.callback=null,j=b.priorityLevel;var $=G(b.expirationTime<=Z);if(Z=e.unstable_now(),typeof $=="function"){b.callback=$,A(Z),Y=!0;break t}b===r(g)&&o(g),A(Z)}else o(g);b=r(g)}if(b!==null)Y=!0;else{var F=r(v);F!==null&&W(D,F.startTime-Z),Y=!1}}break e}finally{b=null,j=q,w=!1}Y=void 0}}finally{Y?U():I=!1}}}var U;if(typeof k=="function")U=function(){k(z)};else if(typeof MessageChannel<"u"){var B=new MessageChannel,Q=B.port2;B.port1.onmessage=z,U=function(){Q.postMessage(null)}}else U=function(){E(z,0)};function W(Z,Y){M=E(function(){Z(e.unstable_now())},Y)}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(Z){Z.callback=null},e.unstable_forceFrameRate=function(Z){0>Z||125G?(Z.sortIndex=q,t(v,Z),r(g)===null&&Z===r(v)&&(N?(R(M),M=-1):N=!0,W(D,q-G))):(Z.sortIndex=$,t(g,Z),S||w||(S=!0,I||(I=!0,U()))),Z},e.unstable_shouldYield=L,e.unstable_wrapCallback=function(Z){var Y=j;return function(){var q=j;j=Y;try{return Z.apply(this,arguments)}finally{j=q}}}})(Jy)),Jy}var qR;function nF(){return qR||(qR=1,Wy.exports=tF()),Wy.exports}var GR;function sF(){if(GR)return gf;GR=1;var e=nF(),t=Od(),r=Hk();function o(n){var a="https://react.dev/errors/"+n;if(1be||(n.current=K[be],K[be]=null,be--)}function we(n,a){be++,K[be]=n.current,n.current=a}var Ee=ne(null),ve=ne(null),Ce=ne(null),ke=ne(null);function Se(n,a){switch(we(Ce,a),we(ve,n),we(Ee,null),a.nodeType){case 9:case 11:n=(n=a.documentElement)&&(n=n.namespaceURI)?HL(n):0;break;default:if(n=a.tagName,a=a.namespaceURI)a=HL(a),n=UL(a,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}ce(Ee),we(Ee,n)}function ge(){ce(Ee),ce(ve),ce(Ce)}function Te(n){var a=n.memoizedState;a!==null&&(Td._currentValue=a.memoizedState,we(ke,n)),a=Ee.current;var i=UL(a,n.type);a!==i&&(we(ve,n),we(Ee,i))}function Oe(n){ve.current===n&&(ce(Ee),ce(ve)),ke.current===n&&(ce(ke),Td._currentValue=de)}var Ne,Be;function Xe(n){if(Ne===void 0)try{throw Error()}catch(i){var a=i.stack.trim().match(/\n( *(at )?)/);Ne=a&&a[1]||"",Be=-1fl in fi?Xte(fi,fl,{enumerable:!0,configurable:!0,writable:!0,value:Wl}):fi[fl]=Wl;var sn=(fi,fl,Wl)=>Qte(fi,typeof fl!="symbol"?fl+"":fl,Wl);(function(){"use strict";function fi(e,t){for(var a=0;ao[c]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}function fl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Wl={exports:{}},Ad={};var Ak;function V3(){if(Ak)return Ad;Ak=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 Ad.Fragment=t,Ad.jsx=a,Ad.jsxs=a,Ad}var Ok;function F3(){return Ok||(Ok=1,Wl.exports=V3()),Wl.exports}var s=F3(),Jb={exports:{}},ot={};var Mk;function $3(){if(Mk)return ot;Mk=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(P){return P===null||typeof P!="object"?null:(P=w&&P[w]||P["@@iterator"],typeof P=="function"?P:null)}var N={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},k=Object.assign,E={};function R(P,V,J){this.props=P,this.context=V,this.refs=E,this.updater=J||N}R.prototype.isReactComponent={},R.prototype.setState=function(P,V){if(typeof P!="object"&&typeof P!="function"&&P!=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,P,V,"setState")},R.prototype.forceUpdate=function(P){this.updater.enqueueForceUpdate(this,P,"forceUpdate")};function C(){}C.prototype=R.prototype;function A(P,V,J){this.props=P,this.context=V,this.refs=E,this.updater=J||N}var D=A.prototype=new C;D.constructor=A,k(D,R.prototype),D.isPureReactComponent=!0;var I=Array.isArray;function M(){}var O={H:null,A:null,T:null,S:null},_=Object.prototype.hasOwnProperty;function L(P,V,J){var ie=J.ref;return{$$typeof:e,type:P,key:V,ref:ie!==void 0?ie:null,props:J}}function z(P,V){return L(P.type,V,P.props)}function U(P){return typeof P=="object"&&P!==null&&P.$$typeof===e}function B(P){var V={"=":"=0",":":"=2"};return"$"+P.replace(/[=:]/g,function(J){return V[J]})}var Q=/\/+/g;function W(P,V){return typeof P=="object"&&P!==null&&P.key!=null?B(""+P.key):V.toString(36)}function Z(P){switch(P.status){case"fulfilled":return P.value;case"rejected":throw P.reason;default:switch(typeof P.status=="string"?P.then(M,M):(P.status="pending",P.then(function(V){P.status==="pending"&&(P.status="fulfilled",P.value=V)},function(V){P.status==="pending"&&(P.status="rejected",P.reason=V)})),P.status){case"fulfilled":return P.value;case"rejected":throw P.reason}}throw P}function Y(P,V,J,ie,me){var he=typeof P;(he==="undefined"||he==="boolean")&&(P=null);var ae=!1;if(P===null)ae=!0;else switch(he){case"bigint":case"string":case"number":ae=!0;break;case"object":switch(P.$$typeof){case e:case t:ae=!0;break;case y:return ae=P._init,Y(ae(P._payload),V,J,ie,me)}}if(ae)return me=me(P),ae=ie===""?"."+W(P,0):ie,I(me)?(J="",ae!=null&&(J=ae.replace(Q,"$&/")+"/"),Y(me,V,J,"",function(de){return de})):me!=null&&(U(me)&&(me=z(me,J+(me.key==null||P&&P.key===me.key?"":(""+me.key).replace(Q,"$&/")+"/")+ae)),V.push(me)),1;ae=0;var oe=ie===""?".":ie+":";if(I(P))for(var ee=0;ee"u"?!1:e instanceof ShadowRoot||e instanceof vn(e).ShadowRoot}function Md(e){const{overflow:t,overflowX:a,overflowY:o,display:c}=gr(e);return/auto|scroll|overlay|hidden|clip/.test(t+o+a)&&c!=="inline"&&c!=="contents"}function G3(e){return/^(table|td|th)$/.test(zs(e))}function gm(e){try{if(e.matches(":popover-open"))return!0}catch{}try{return e.matches(":modal")}catch{return!1}}const K3=/transform|translate|scale|rotate|perspective|filter/,Y3=/paint|layout|strict|content/,pi=e=>!!e&&e!=="none";let tv;function nv(e){const t=kt(e)?gr(e):e;return pi(t.transform)||pi(t.translate)||pi(t.scale)||pi(t.rotate)||pi(t.perspective)||!sv()&&(pi(t.backdropFilter)||pi(t.filter))||K3.test(t.willChange||"")||Y3.test(t.contain||"")}function X3(e){let t=eo(e);for(;on(t)&&!Jl(t);){if(nv(t))return t;if(gm(t))return null;t=eo(t)}return null}function sv(){return tv==null&&(tv=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),tv}function Jl(e){return/^(html|body|#document)$/.test(zs(e))}function gr(e){return vn(e).getComputedStyle(e)}function xm(e){return kt(e)?{scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}:{scrollLeft:e.scrollX,scrollTop:e.scrollY}}function eo(e){if(zs(e)==="html")return e;const t=e.assignedSlot||e.parentNode||_c(e)&&e.host||pl(e);return _c(t)?t.host:t}function Ik(e){const t=eo(e);return Jl(t)?(e.ownerDocument||e).body:on(t)&&Md(t)?t:Ik(t)}function Lc(e,t,a){var o;t===void 0&&(t=[]),a===void 0&&(a=!0);const c=Ik(e),d=c===((o=e.ownerDocument)==null?void 0:o.body),f=vn(c);if(d){const p=rv(f);return t.concat(f,f.visualViewport||[],Md(c)?c:[],p&&a?Lc(p):[])}else return t.concat(c,Lc(c,[],a))}function rv(e){return e.parent&&Object.getPrototypeOf(e.parent)?e.frameElement:null}const av={...q3},Pk={};function Os(e,t){const a=x.useRef(Pk);return a.current===Pk&&(a.current=e(t)),a}const lv=av.useInsertionEffect,Q3=lv&&lv!==av.useLayoutEffect?lv:e=>e();function Ie(e){const t=Os(Z3).current;return t.next=e,Q3(t.effect),t.trampoline}function Z3(){const e={next:void 0,callback:W3,trampoline:(...t)=>e.callback?.(...t),effect:()=>{e.callback=e.next}};return e}function W3(){}const De=typeof document<"u"?x.useLayoutEffect:()=>{};function ov(e,t){if(e&&!t)return e;if(!e&&t)return t;if(e||t)return{...e,...t}}const iv={};function Kr(e,t,a,o,c){if(!a&&!o&&!c&&!e)return bm(t);let d=bm(e);return t&&(d=Dd(d,t)),a&&(d=Dd(d,a)),o&&(d=Dd(d,o)),c&&(d=Dd(d,c)),d}function J3(e){if(e.length===0)return iv;if(e.length===1)return bm(e[0]);let t=bm(e[0]);for(let a=1;a=65&&c<=90&&(typeof t=="function"||typeof t>"u")}function cv(e){return typeof e=="function"}function Lk(e,t){return cv(e)?e(t):e??iv}function n5(e,t){return t?e?(...a)=>{const o=a[0];if(Hk(o)){const d=o;vm(d);const f=t(...a);return d.baseUIHandlerPrevented||e?.(...a),f}const c=t(...a);return e?.(...a),c}:zk(t):e}function zk(e){return e&&((...t)=>{const a=t[0];return Hk(a)&&vm(a),e(...t)})}function vm(e){return e.preventBaseUIHandler=()=>{e.baseUIHandlerPrevented=!0},e}function Bk(e,t){return t?e?t+" "+e:t:e}function Hk(e){return e!=null&&typeof e=="object"&&"nativeEvent"in e}function s5(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 rn=s5("https://base-ui.com/production-error","Base UI"),Uk=x.createContext(void 0);function Vk(e=!1){const t=x.useContext(Uk);if(t===void 0&&!e)throw new Error(rn(16));return t}function r5(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 Ut(e){return e?.ownerDocument||document}function zc(e,t,{detail:a=0}={}){e.dispatchEvent(new(vn(e)).PointerEvent("click",{bubbles:!0,cancelable:!0,composed:!0,detail:a,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,altKey:t.altKey,metaKey:t.metaKey}))}function Yr(e={}){const{disabled:t=!1,focusableWhenDisabled:a,tabIndex:o=0,native:c=!0,composite:d}=e,f=x.useRef(null),p=Vk(!0),g=d??p!==void 0,{props:v}=r5({focusableWhenDisabled:a,disabled:t,composite:g,tabIndex:o,isNativeButton:c}),y=x.useCallback(()=>{const w=f.current;uv(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:R,...C}=w;return Kr({onClick(A){if(t){A.preventDefault();return}S?.(A)},onMouseDown(A){t||N?.(A)},onKeyDown(A){if(t||(vm(A),E?.(A),A.baseUIHandlerPrevented))return;const D=A.target===A.currentTarget,I=A.currentTarget,M=uv(I),O=!c&&a5(I),_=D&&(c?M:!O),L=A.key==="Enter",z=A.key===" ",U=I.getAttribute("role"),B=U?.startsWith("menuitem")||U==="option"||U==="gridcell";if(D&&g&&z){if(A.defaultPrevented&&B)return;A.preventDefault(),(!c||M)&&(A.preventBaseUIHandler(),zc(I,A));return}if(!_||c||!z&&!L){D&&O&&z&&A.preventDefault();return}A.defaultPrevented||(A.preventDefault(),L&&(A.preventBaseUIHandler(),zc(I,A)))},onKeyUp(A){if(!t){if(vm(A),k?.(A),A.target===A.currentTarget&&c&&g&&uv(A.currentTarget)&&A.key===" "){A.preventDefault();return}A.baseUIHandlerPrevented||A.target===A.currentTarget&&!c&&!g&&!A.defaultPrevented&&A.key===" "&&(A.preventBaseUIHandler(),zc(A.currentTarget,A))}},onPointerDown(A){if(t){A.preventDefault();return}R?.(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 uv(e){return on(e)&&e.tagName==="BUTTON"}function a5(e){return on(e)&&e.tagName==="A"&&!!e.href}function Xr(e,t,a,o){const c=Os(Fk).current;return o5(c,e,t,a,o)&&$k(c,[e,t,a,o]),c.callback}function l5(e){const t=Os(Fk).current;return i5(t,e)&&$k(t,e),t.callback}function Fk(){return{callback:null,cleanup:null,refs:[]}}function o5(e,t,a,o,c){return e.refs[0]!==t||e.refs[1]!==a||e.refs[2]!==o||e.refs[3]!==c}function i5(e,t){return e.refs.length!==t.length||e.refs.some((a,o)=>a!==t[o])}function $k(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 qk(e){if(!x.isValidElement(e))return null;const t=e,a=t.props;return(dv(19)?a?.ref:t.ref)??null}function Vt(){}const Er=Object.freeze([]),cn=Object.freeze({});function u5(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 d5(e,t){return typeof e=="function"?e(t):e}function f5(e,t){return typeof e=="function"?e(t):e}function bt(e,t,a={}){let o=t.render;a.enabled!==!1&&(o=g5(o));const c=p5(t,a,o);if(a.enabled===!1)return null;const d=a.state??cn;return x5(e,o,c,d)}function p5(e,t,a){const{className:o,style:c}=e,{state:d=cn,ref:f,props:p,stateAttributesMapping:g,enabled:v=!0}=t,y=v?d5(o,d):void 0,b=v?f5(c,d):void 0,j=v?u5(d,g):cn,w=v&&p?m5(p):void 0,S=v?ov(j,w)??{}:cn;return typeof document<"u"&&(v?Array.isArray(f)?S.ref=l5([S.ref,qk(a),...f]):S.ref=Xr(S.ref,qk(a),f):Xr(null,null)),v?(y!==void 0&&(S.className=Bk(S.className,y)),b!==void 0&&(S.style=ov(S.style,b)),S):cn}function m5(e){return Array.isArray(e)?J3(e):Kr(void 0,e)}const h5=Symbol.for("react.lazy");function g5(e){if(e?.$$typeof!==h5)return e;const t=x.Children.toArray(e)[0];return x.isValidElement(t)?t:e}function x5(e,t,a,o){if(t){if(typeof t=="function")return t(a,o);const c=Kr(a,t.props);return c.ref=a.ref,x.cloneElement(t,c)}if(e&&typeof e=="string")return b5(e,a);throw new Error(rn(8))}function b5(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 v5=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}=Yr({disabled:d,focusableWhenDisabled:f,native:p});return bt("button",t,{state:{disabled:d},ref:[a,b],props:[v,y]})});function Gk(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,Xk=Kk,Bc=(e,t)=>a=>{var o;if(t?.variants==null)return Xk(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=Yk(y)||Yk(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 Xk(e,f,g,a?.class,a?.className)},y5=(e,t)=>{const a=new Array(e.length+t.length);for(let o=0;o({classGroupId:e,validator:t}),Qk=(e=new Map,t=null,a)=>({nextPart:e,validators:t,classGroupId:a}),ym="-",Zk=[],w5="arbitrary..",S5=e=>{const t=k5(e),{conflictingClassGroups:a,conflictingClassGroupModifiers:o}=e;return{getClassGroupId:f=>{if(f.startsWith("[")&&f.endsWith("]"))return N5(f);const p=f.split(ym),g=p[0]===""&&p.length>1?1:0;return Wk(p,g,t)},getConflictingClassGroupIds:(f,p)=>{if(p){const g=o[f],v=a[f];return g?v?y5(v,g):g:v||Zk}return a[f]||Zk}}},Wk=(e,t,a)=>{if(e.length-t===0)return a.classGroupId;const c=e[t],d=a.nextPart.get(c);if(d){const v=Wk(e,t+1,d);if(v)return v}const f=a.validators;if(f===null)return;const p=t===0?e.join(ym):e.slice(t).join(ym),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?w5+o:void 0})(),k5=e=>{const{theme:t,classGroups:a}=e;return C5(a,t)},C5=(e,t)=>{const a=Qk();for(const o in e){const c=e[o];fv(c,a,o,t)}return a},fv=(e,t,a,o)=>{const c=e.length;for(let d=0;d{if(typeof e=="string"){E5(e,t,a);return}if(typeof e=="function"){R5(e,t,a,o);return}A5(e,t,a,o)},E5=(e,t,a)=>{const o=e===""?t:Jk(t,e);o.classGroupId=a},R5=(e,t,a,o)=>{if(O5(e)){fv(e(o),t,a,o);return}t.validators===null&&(t.validators=[]),t.validators.push(j5(a,e))},A5=(e,t,a,o)=>{const c=Object.entries(e),d=c.length;for(let f=0;f{let a=e;const o=t.split(ym),c=o.length;for(let d=0;d"isThemeGetter"in e&&e.isThemeGetter===!0,M5=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)}}},pv="!",eC=":",D5=[],tC=(e,t,a,o,c)=>({modifiers:e,hasImportantModifier:t,baseClassName:a,maybePostfixModifierPosition:o,isExternal:c}),I5=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 tC(d,w,j,S)};if(t){const c=t+eC,d=o;o=f=>f.startsWith(c)?d(f.slice(c.length)):tC(D5,!1,f,void 0,!0)}if(a){const c=o;o=d=>a({className:d,parseClassName:c})}return o},P5=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}},_5=e=>({cache:M5(e.cacheSize),parseClassName:I5(e),sortModifiers:P5(e),postfixLookupClassGroupIds:L5(e),...S5(e)}),L5=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(z5);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,R;if(E){const M=N.substring(0,k);R=o(M);const O=R&&f[R]?o(N):void 0;O&&O!==R&&(R=O,E=!1)}else R=o(N);if(!R){if(!E){v=b+(v.length>0?" "+v:v);continue}if(R=o(N),!R){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+pv:C,D=A+R;if(p.indexOf(D)>-1)continue;p.push(D);const I=c(R,E);for(let M=0;M0?" "+v:v)}return v},H5=(...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=_5(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=B5(g,a);return c(g,y),y};return d=f,(...g)=>d(H5(...g))},V5=[],ws=e=>{const t=a=>a[e]||V5;return t.isThemeGetter=!0,t.themeKey=e,t},sC=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,rC=/^\((?:(\w[\w-]*):)?(.+)\)$/i,F5=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,$5=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,q5=/\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$/,G5=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix|color|light-dark)\(.+\)$/,K5=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Y5=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,to=e=>F5.test(e),wt=e=>!!e&&!Number.isNaN(Number(e)),Va=e=>!!e&&Number.isInteger(Number(e)),mv=e=>e.endsWith("%")&&wt(e.slice(0,-1)),ml=e=>$5.test(e),aC=()=>!0,X5=e=>q5.test(e)&&!G5.test(e),hv=()=>!1,Q5=e=>K5.test(e),Z5=e=>Y5.test(e),W5=e=>!qe(e)&&!Ge(e),J5=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)),ez=e=>no(e,dC,hv),qe=e=>sC.test(e),mi=e=>no(e,fC,X5),lC=e=>no(e,iz,wt),tz=e=>no(e,mC,aC),nz=e=>no(e,pC,hv),oC=e=>no(e,cC,hv),sz=e=>no(e,uC,Z5),jm=e=>no(e,hC,Q5),Ge=e=>rC.test(e),Id=e=>hi(e,fC),rz=e=>hi(e,pC),iC=e=>hi(e,cC),az=e=>hi(e,dC),lz=e=>hi(e,uC),wm=e=>hi(e,hC,!0),oz=e=>hi(e,mC,!0),no=(e,t,a)=>{const o=sC.exec(e);return o?o[1]?t(o[1]):a(o[2]):!1},hi=(e,t,a=!1)=>{const o=rC.exec(e);return o?o[1]?t(o[1]):a:!1},cC=e=>e==="position"||e==="percentage",uC=e=>e==="image"||e==="url",dC=e=>e==="length"||e==="size"||e==="bg-size",fC=e=>e==="length",iz=e=>e==="number",pC=e=>e==="family-name",mC=e=>e==="number"||e==="weight",hC=e=>e==="shadow",cz=U5(()=>{const e=ws("color"),t=ws("font"),a=ws("text"),o=ws("font-weight"),c=ws("tracking"),d=ws("leading"),f=ws("breakpoint"),p=ws("container"),g=ws("spacing"),v=ws("radius"),y=ws("shadow"),b=ws("inset-shadow"),j=ws("text-shadow"),w=ws("drop-shadow"),S=ws("blur"),N=ws("perspective"),k=ws("aspect"),E=ws("ease"),R=ws("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"],D=()=>[...A(),Ge,qe],I=()=>["auto","hidden","clip","visible","scroll"],M=()=>["auto","contain","none"],O=()=>[Ge,qe,g],_=()=>[to,"full","auto",...O()],L=()=>[Va,"none","subgrid",Ge,qe],z=()=>["auto",{span:["full",Va,Ge,qe]},Va,Ge,qe],U=()=>[Va,"auto",Ge,qe],B=()=>["auto","min","max","fr",Ge,qe],Q=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],W=()=>["start","end","center","stretch","center-safe","end-safe"],Z=()=>["auto",...O()],Y=()=>[to,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...O()],q=()=>[p,to,"screen","full","dvw","lvw","svw","min","max","fit",...O()],G=()=>[to,"screen","full","lh","dvh","lvh","svh","min","max","fit",...O()],F=()=>[e,Ge,qe],$=()=>[...A(),iC,oC,{position:[Ge,qe]}],X=()=>["no-repeat",{repeat:["","x","y","space","round"]}],re=()=>["auto","cover","contain",az,ez,{size:[Ge,qe]}],P=()=>[mv,Id,mi],V=()=>["","none","full",v,Ge,qe],J=()=>["",wt,Id,mi],ie=()=>["solid","dashed","dotted","double"],me=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],he=()=>[wt,mv,iC,oC],ae=()=>["","none",S,Ge,qe],oe=()=>["none",wt,Ge,qe],ee=()=>["none",wt,Ge,qe],de=()=>[wt,Ge,qe],K=()=>[to,"full",...O()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[ml],breakpoint:[ml],color:[aC],container:[ml],"drop-shadow":[ml],ease:["in","out","in-out"],font:[W5],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[ml],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[ml],shadow:[ml],spacing:["px",wt],text:[ml],"text-shadow":[ml],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",to,qe,Ge,k]}],container:["container"],"container-type":[{"@container":["","normal","size",Ge,qe]}],"container-named":[J5],columns:[{columns:[wt,"auto",qe,Ge,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:D()}],overflow:[{overflow:I()}],"overflow-x":[{"overflow-x":I()}],"overflow-y":[{"overflow-y":I()}],overscroll:[{overscroll:M()}],"overscroll-x":[{"overscroll-x":M()}],"overscroll-y":[{"overscroll-y":M()}],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:[Va,"auto",Ge,qe]}],basis:[{basis:[to,"full","auto",p,...O()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[wt,to,"auto","initial","none",qe]}],grow:[{grow:["",wt,Ge,qe]}],shrink:[{shrink:["",wt,Ge,qe]}],order:[{order:[Va,"first","last","none",Ge,qe]}],"grid-cols":[{"grid-cols":L()}],"col-start-end":[{col:z()}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":L()}],"row-start-end":[{row:z()}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":B()}],"auto-rows":[{"auto-rows":B()}],gap:[{gap:O()}],"gap-x":[{"gap-x":O()}],"gap-y":[{"gap-y":O()}],"justify-content":[{justify:[...Q(),"normal"]}],"justify-items":[{"justify-items":[...W(),"normal"]}],"justify-self":[{"justify-self":["auto",...W()]}],"align-content":[{content:["normal",...Q()]}],"align-items":[{items:[...W(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...W(),{baseline:["","last"]}]}],"place-content":[{"place-content":Q()}],"place-items":[{"place-items":[...W(),"baseline"]}],"place-self":[{"place-self":["auto",...W()]}],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:Z()}],mx:[{mx:Z()}],my:[{my:Z()}],ms:[{ms:Z()}],me:[{me:Z()}],mbs:[{mbs:Z()}],mbe:[{mbe:Z()}],mt:[{mt:Z()}],mr:[{mr:Z()}],mb:[{mb:Z()}],ml:[{ml:Z()}],"space-x":[{"space-x":O()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":O()}],"space-y-reverse":["space-y-reverse"],size:[{size:Y()}],"inline-size":[{inline:["auto",...q()]}],"min-inline-size":[{"min-inline":["auto",...q()]}],"max-inline-size":[{"max-inline":["none",...q()]}],"block-size":[{block:["auto",...G()]}],"min-block-size":[{"min-block":["auto",...G()]}],"max-block-size":[{"max-block":["none",...G()]}],w:[{w:[p,"screen",...Y()]}],"min-w":[{"min-w":[p,"screen","none",...Y()]}],"max-w":[{"max-w":[p,"screen","none","prose",{screen:[f]},...Y()]}],h:[{h:["screen","lh",...Y()]}],"min-h":[{"min-h":["screen","lh","none",...Y()]}],"max-h":[{"max-h":["screen","lh","none",...Y()]}],"font-size":[{text:["base",a,Id,mi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[o,oz,tz]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",mv,qe]}],"font-family":[{font:[rz,nz,t]}],"font-features":[{"font-features":[qe]}],"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,Ge,qe]}],"line-clamp":[{"line-clamp":[wt,"none",Ge,lC]}],leading:[{leading:["none",d,...O()]}],"list-image":[{"list-image":["none",Ge,qe]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",Ge,qe]}],"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:[...ie(),"wavy"]}],"text-decoration-thickness":[{decoration:[wt,"from-font","auto",Ge,mi]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[wt,"auto",Ge,qe]}],"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:[Va,Ge,qe]}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Ge,qe]}],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",Ge,qe]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:$()}],"bg-repeat":[{bg:X()}],"bg-size":[{bg:re()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},Va,Ge,qe],radial:["",Ge,qe],conic:["",Va,Ge,qe]},lz,sz]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:P()}],"gradient-via-pos":[{via:P()}],"gradient-to-pos":[{to:P()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:V()}],"rounded-s":[{"rounded-s":V()}],"rounded-e":[{"rounded-e":V()}],"rounded-t":[{"rounded-t":V()}],"rounded-r":[{"rounded-r":V()}],"rounded-b":[{"rounded-b":V()}],"rounded-l":[{"rounded-l":V()}],"rounded-ss":[{"rounded-ss":V()}],"rounded-se":[{"rounded-se":V()}],"rounded-ee":[{"rounded-ee":V()}],"rounded-es":[{"rounded-es":V()}],"rounded-tl":[{"rounded-tl":V()}],"rounded-tr":[{"rounded-tr":V()}],"rounded-br":[{"rounded-br":V()}],"rounded-bl":[{"rounded-bl":V()}],"border-w":[{border:J()}],"border-w-x":[{"border-x":J()}],"border-w-y":[{"border-y":J()}],"border-w-s":[{"border-s":J()}],"border-w-e":[{"border-e":J()}],"border-w-bs":[{"border-bs":J()}],"border-w-be":[{"border-be":J()}],"border-w-t":[{"border-t":J()}],"border-w-r":[{"border-r":J()}],"border-w-b":[{"border-b":J()}],"border-w-l":[{"border-l":J()}],"divide-x":[{"divide-x":J()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":J()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...ie(),"hidden","none"]}],"divide-style":[{divide:[...ie(),"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:[...ie(),"none","hidden"]}],"outline-offset":[{"outline-offset":[wt,Ge,qe]}],"outline-w":[{outline:["",wt,Id,mi]}],"outline-color":[{outline:F()}],shadow:[{shadow:["","inner","none",y,wm,jm]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":["none",b,wm,jm]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:J()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[wt,mi]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":J()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":["none",j,wm,jm]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[wt,Ge,qe]}],"mix-blend":[{"mix-blend":[...me(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":me()}],"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":[wt]}],"mask-image-linear-from-pos":[{"mask-linear-from":he()}],"mask-image-linear-to-pos":[{"mask-linear-to":he()}],"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":he()}],"mask-image-t-to-pos":[{"mask-t-to":he()}],"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":he()}],"mask-image-r-to-pos":[{"mask-r-to":he()}],"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":he()}],"mask-image-b-to-pos":[{"mask-b-to":he()}],"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":he()}],"mask-image-l-to-pos":[{"mask-l-to":he()}],"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":he()}],"mask-image-x-to-pos":[{"mask-x-to":he()}],"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":he()}],"mask-image-y-to-pos":[{"mask-y-to":he()}],"mask-image-y-from-color":[{"mask-y-from":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"mask-image-radial":[{"mask-radial":[Ge,qe]}],"mask-image-radial-from-pos":[{"mask-radial-from":he()}],"mask-image-radial-to-pos":[{"mask-radial-to":he()}],"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":[wt]}],"mask-image-conic-from-pos":[{"mask-conic-from":he()}],"mask-image-conic-to-pos":[{"mask-conic-to":he()}],"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:$()}],"mask-repeat":[{mask:X()}],"mask-size":[{mask:re()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",Ge,qe]}],filter:[{filter:["","none",Ge,qe]}],blur:[{blur:ae()}],brightness:[{brightness:[wt,Ge,qe]}],contrast:[{contrast:[wt,Ge,qe]}],"drop-shadow":[{"drop-shadow":["","none",w,wm,jm]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:["",wt,Ge,qe]}],"hue-rotate":[{"hue-rotate":[wt,Ge,qe]}],invert:[{invert:["",wt,Ge,qe]}],saturate:[{saturate:[wt,Ge,qe]}],sepia:[{sepia:["",wt,Ge,qe]}],"backdrop-filter":[{"backdrop-filter":["","none",Ge,qe]}],"backdrop-blur":[{"backdrop-blur":ae()}],"backdrop-brightness":[{"backdrop-brightness":[wt,Ge,qe]}],"backdrop-contrast":[{"backdrop-contrast":[wt,Ge,qe]}],"backdrop-grayscale":[{"backdrop-grayscale":["",wt,Ge,qe]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[wt,Ge,qe]}],"backdrop-invert":[{"backdrop-invert":["",wt,Ge,qe]}],"backdrop-opacity":[{"backdrop-opacity":[wt,Ge,qe]}],"backdrop-saturate":[{"backdrop-saturate":[wt,Ge,qe]}],"backdrop-sepia":[{"backdrop-sepia":["",wt,Ge,qe]}],"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",Ge,qe]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[wt,"initial",Ge,qe]}],ease:[{ease:["linear","initial",E,Ge,qe]}],delay:[{delay:[wt,Ge,qe]}],animate:[{animate:["none",R,Ge,qe]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[N,Ge,qe]}],"perspective-origin":[{"perspective-origin":D()}],rotate:[{rotate:oe()}],"rotate-x":[{"rotate-x":oe()}],"rotate-y":[{"rotate-y":oe()}],"rotate-z":[{"rotate-z":oe()}],scale:[{scale:ee()}],"scale-x":[{"scale-x":ee()}],"scale-y":[{"scale-y":ee()}],"scale-z":[{"scale-z":ee()}],"scale-3d":["scale-3d"],skew:[{skew:de()}],"skew-x":[{"skew-x":de()}],"skew-y":[{"skew-y":de()}],transform:[{transform:[Ge,qe,"","none","gpu","cpu"]}],"transform-origin":[{origin:D()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:K()}],"translate-x":[{"translate-x":K()}],"translate-y":[{"translate-y":K()}],"translate-z":[{"translate-z":K()}],"translate-none":["translate-none"],zoom:[{zoom:[Va,Ge,qe]}],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",Ge,qe]}],"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",Ge,qe]}],fill:[{fill:["none",...F()]}],"stroke-w":[{stroke:[wt,Id,mi,lC]}],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 Ve(...e){return cz(Kk(e))}const uz=Bc(["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(v5,{className:Ve(uz({variant:t,size:a}),e),...o})}const dz="data-valid",fz="data-invalid",pz={badInput:!1,customError:!1,patternMismatch:!1,rangeOverflow:!1,rangeUnderflow:!1,stepMismatch:!1,tooLong:!1,tooShort:!1,typeMismatch:!1,valid:null,valueMissing:!1},gC={valid:null,touched:!1,dirty:!1,filled:!1,focused:!1},mz={disabled:!1,...gC},gi={valid(e){return e===null?null:e?{[dz]:""}:{[fz]:""}}},xC={invalid:void 0,name:void 0,validityData:{state:pz,errors:[],error:"",value:"",initialValue:null},setValidityData:Vt,disabled:void 0,setTouched:Vt,setDirty:Vt,setFilled:Vt,setFocused:Vt,validationMode:"onSubmit",shouldValidateOnChange:()=>!1,state:mz,registerFieldControl:Vt,validation:{getValidationProps:(e,t=cn)=>t,inputRef:{current:null},registeredInputs:new Map,registerInput:Vt,getInputControl:()=>null,commit:async()=>{},change:Vt}},bC=x.createContext(xC);function wa(e=!0){const t=x.useContext(bC);if(t.setValidityData===Vt&&!e)throw new Error(rn(28));return t}const hz=x.createContext(void 0);function gz(e=!1){const t=x.useContext(hz);if(!t&&!e)throw new Error(rn(86));return t}const xz=x.createContext({elementRef:{current:null},formRef:{current:{fields:new Map}},errors:{},clearErrors:Vt,validationMode:"onSubmit",submitCountRef:{current:0}});function Hc(){return x.useContext(xz)}let vC=0;function bz(e,t="mui"){const[a,o]=x.useState(e),c=e||a;return x.useEffect(()=>{a==null&&(vC+=1,o(`${t}-${vC}`))},[a,t]),c}const yC=av.useId;function Pd(e,t){if(yC!==void 0){const a=yC();return e??(t?`${t}-${a}`:a)}return bz(e,t)}function Sa(e){return Pd(e,"base-ui")}const vz=x.createContext({controlId:void 0,registerControlId:Vt,resetControlId:Vt,labelId:void 0,setLabelId:Vt,messageIds:[],setMessageIds:Vt,getDescriptionProps:e=>e});function hl(){return x.useContext(vz)}function gv(e,t,a,o=!0,c){const[d,f]=x.useState(),p=Sa(c?`${c}-label`:void 0),g=e??t??d;return De(()=>{const v=e||t||!o?void 0:yz(a.current,p);d!==v&&f(v)}),g}function yz(e,t){const a=jz(e);if(a)return!a.id&&t&&(a.id=t),a.id||void 0}function jz(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 so(e={}){const{id:t,enabled:a=!0}=e,{controlId:o,registerControlId:c,resetControlId:d}=hl(),f=Sa(),p=Os(()=>Symbol()),g=x.useRef(!1),v=x.useRef(!1),y=Ie(()=>{!g.current||c===Vt||(g.current=!1,c(p.current,void 0))});return De(()=>{if(!a||c===Vt){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 wz(){return typeof navigator>"u"?{userAgent:"",platform:"",maxTouchPoints:0}:{userAgent:navigator.userAgent,platform:navigator.platform??"",maxTouchPoints:navigator.maxTouchPoints??0}}const{userAgent:Sz,platform:Nz,maxTouchPoints:kz}=wz(),Sm=Sz.toLowerCase(),_d=Nz.toLowerCase(),Ld=/^i(os$|p)/.test(_d)||_d==="macintel"&&kz>1,jC="android",Nm=_d===jC||Sm.includes(jC),wC=!Ld&&_d.startsWith("mac");_d.startsWith("win");const Cz=wC||Ld,gl=typeof CSS<"u"&&!!CSS.supports?.("-webkit-backdrop-filter:none"),SC=!gl&&Sm.includes("firefox");!gl&&Sm.includes("chrom");const Tz=Cz,xv=/jsdom|happydom/.test(Sm);function ar(e){let t=e.activeElement;for(;t?.shadowRoot?.activeElement!=null;)t=t.shadowRoot.activeElement;return t}function Ke(e,t){if(!e||!t)return!1;const a=t.getRootNode?.();if(e.contains(t))return!0;if(a&&_c(a)){let o=t;for(;o;){if(e===o)return!0;o=o.parentNode||o.host}}return!1}function os(e){return"composedPath"in e?e.composedPath()[0]??e.target:e.target}const bv="data-base-ui-focusable",NC="input:not([type='hidden']):not([disabled]),[contenteditable]:not([contenteditable='false']),textarea:not([disabled])",xi="ArrowLeft",bi="ArrowRight",vv="ArrowUp",km="ArrowDown",kC="data-starting-style",Ez="data-ending-style",Rz={[kC]:""},Az={[Ez]:""},ro={transitionStatus(e){return e==="starting"?Rz:e==="ending"?Az:null}},Oz="data-open",Mz="data-closed",Dz="data-anchor-hidden",CC="data-popup-open",Iz="data-pressed",Pz={[CC]:""},_z={[CC]:"",[Iz]:""},Lz={[Oz]:""},zz={[Mz]:""},Bz={[Dz]:""},yv={open(e){return e?Pz:null}},jv={open(e){return e?_z:null}},Uc={open(e){return e?Lz:zz},anchorHidden(e){return e?Bz:null}},wv={...Uc,...ro},Sv="data-trigger-disabled";function Cm(e,t){if(!kt(e))return!1;const a=e;if(t.hasElement(a))return!a.hasAttribute(Sv);for(const[,o]of t.entries())if(Ke(o,a))return!o.hasAttribute(Sv);return!1}function Nv(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 Hz(e){return e.matches("html,body")}function Tm(e){return on(e)&&e.matches(NC)}function Uz(e){return e?.closest(`button,a[href],[role="button"],select,[tabindex]:not([tabindex="-1"]),${NC}`)!=null}function kv(e){return e?e.getAttribute("role")==="combobox"&&Tm(e):!1}function Vz(e){if(!e||xv)return!0;try{return e.matches(":focus-visible")}catch{return!0}}function Em(e){return e?e.hasAttribute(bv)?e:e.querySelector(`[${bv}]`)||e:null}function ao(e,t,a=!0){return e.filter(c=>c.parentId===t).flatMap(c=>[...!a||c.context?.open?[c]:[],...ao(e,c.id,a)])}function TC(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 Ss(e){e.preventDefault(),e.stopPropagation()}function Fz(e){return"nativeEvent"in e}function Rm(e){return e.pointerType===""&&e.isTrusted?!0:Nm&&e.pointerType?e.type==="click"&&e.buttons===1:e.detail===0&&!e.pointerType}function Cv(e){return xv?!1:!Nm&&e.width===0&&e.height===0||Nm&&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 lo(e,t){const a=["mouse","pen"];return t||a.push("",void 0),a.includes(e)}function $z(e){const t=e.type;return t==="click"||t==="mousedown"||t==="keydown"||t==="keyup"}const Vc=Math.min,xl=Math.max,Am=Math.round,vi=Math.floor,bl=e=>({x:e,y:e}),qz={left:"right",right:"left",bottom:"top",top:"bottom"};function EC(e,t,a){return xl(e,Vc(t,a))}function oo(e,t){return typeof e=="function"?e(t):e}function Qr(e){return e.split("-")[0]}function vl(e){return e.split("-")[1]}function Tv(e){return e==="x"?"y":"x"}function Ev(e){return e==="y"?"height":"width"}function Zr(e){const t=e[0];return t==="t"||t==="b"?"y":"x"}function Rv(e){return Tv(Zr(e))}function Gz(e,t,a){a===void 0&&(a=!1);const o=vl(e),c=Rv(e),d=Ev(c);let f=c==="x"?o===(a?"end":"start")?"right":"left":o==="start"?"bottom":"top";return t.reference[d]>t.floating[d]&&(f=Om(f)),[f,Om(f)]}function Kz(e){const t=Om(e);return[Av(e),t,Av(t)]}function Av(e){return e.includes("start")?e.replace("start","end"):e.replace("end","start")}const RC=["left","right"],AC=["right","left"],Yz=["top","bottom"],Xz=["bottom","top"];function Qz(e,t,a){switch(e){case"top":case"bottom":return a?t?AC:RC:t?RC:AC;case"left":case"right":return t?Yz:Xz;default:return[]}}function Zz(e,t,a,o){const c=vl(e);let d=Qz(Qr(e),a==="start",o);return c&&(d=d.map(f=>f+"-"+c),t&&(d=d.concat(d.map(Av)))),d}function Om(e){const t=Qr(e);return qz[t]+e.slice(t.length)}function Wz(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 OC(e){return typeof e!="number"?Wz(e):{top:e,right:e,bottom:e,left:e}}function zd(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 Mm(e,t,a){return Math.floor(e/t)!==a}function io(e,t){return t<0||t>=e.length}function Dm(e,t){return Ms(e.current,{disabledIndices:t})}function Ov(e,t){return Ms(e.current,{decrement:!0,startingIndex:e.current.length,disabledIndices:t})}function Ms(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&&co(e,d,o));return d}function Jz(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===vv?w="up":t.key===km&&(w="down"),w){const S=[],N=[];let k=!1,E=0;{let _=null,L=-1;e.forEach((z,U)=>{if(z==null)return;E+=1;const B=z.closest('[role="row"]');B&&(k=!0),(B!==_||L===-1)&&(_=B,L+=1,S[L]=[]),S[L].push(U),N[U]=L})}let R=!1,C=0;if(k)for(const _ of S){const L=_.length;L>C&&(C=L),L!==f&&(R=!0)}const A=R&&E{if(!R||y===-1)return;const L=N[y];if(L==null)return;const z=S[L].indexOf(y),U=_==="up"?-1:1;for(let B=L+U,Q=0;Q=S.length){if(!o||A)return;if(B=B<0?S.length-1:0,c){const Z=Math.min(z,S[B].length-1),Y=S[B][Z]??S[B][0],q=c(t,y,Y);B=N[q]??B}}const W=S[B];for(let Z=Math.min(z,W.length-1);Z>=0;Z-=1){const Y=W[Z];if(!co(e,Y,p))return Y}}},M=_=>{if(!A||y===-1)return;const L=y%D,z=_==="up"?-D:D,U=v-v%D,B=vi(v/D)+1;for(let Q=y-L+z,W=0;Wv){if(!o)return;Q=Q<0?U:0}const Z=Math.min(Q+D-1,v);for(let Y=Math.min(Q+L,Z);Y>=Q;Y-=1)if(!co(e,Y,p))return Y}};b&&Ss(t);const O=I(w)??M(w);if(O!==void 0)j=O;else if(y===-1)j=w==="up"?v:g;else if(j=Ms(e,{startingIndex:y,amount:D,decrement:w==="up",disabledIndices:p}),o){if(w==="up"&&(y-D_?z:z-D,c&&(j=c(t,y,j))}w==="down"&&y+D>v&&(j=Ms(e,{startingIndex:y%D-D,amount:D,disabledIndices:p}),c&&(j=c(t,y,j)))}io(e,j)&&(j=y)}if(a==="both"){const S=vi(y/f);t.key===(d?xi:bi)&&(b&&Ss(t),y%f!==f-1?(j=Ms(e,{startingIndex:y,disabledIndices:p}),o&&Mm(j,f,S)&&(j=Ms(e,{startingIndex:y-y%f-1,disabledIndices:p}),c&&(j=c(t,y,j)))):o&&(j=Ms(e,{startingIndex:y-y%f-1,disabledIndices:p}),c&&(j=c(t,y,j))),Mm(j,f,S)&&(j=y)),t.key===(d?bi:xi)&&(b&&Ss(t),y%f!==0?(j=Ms(e,{startingIndex:y,decrement:!0,disabledIndices:p}),o&&Mm(j,f,S)&&(j=Ms(e,{startingIndex:y+(f-y%f),decrement:!0,disabledIndices:p}),c&&(j=c(t,y,j)))):o&&(j=Ms(e,{startingIndex:y+(f-y%f),decrement:!0,disabledIndices:p}),c&&(j=c(t,y,j))),Mm(j,f,S)&&(j=y));const N=vi(v/f)===S;io(e,j)&&(o&&N?(j=t.key===(d?bi:xi)?v:Ms(e,{startingIndex:y-y%f-1,disabledIndices:p}),c&&(j=c(t,y,j))):j=y)}return j}function co(e,t,a){if(typeof a=="function"?a(t):a?.includes(t)??!1)return!0;const c=e[t];return c?!Im(c)||c.matches(":disabled")?!0:!a&&(c.hasAttribute("disabled")||c.getAttribute("aria-disabled")==="true"):!1}function e4(e){return e.visibility==="hidden"||e.visibility==="collapse"}function Im(e,t=e?gr(e):null){return!e||!e.isConnected||!t||e4(t)?!1:typeof e.checkVisibility=="function"?e.checkVisibility():t.display!=="none"&&t.display!=="contents"}const t4='a[href],button,input,select,textarea,summary,details,iframe,object,embed,[tabindex],[contenteditable]:not([contenteditable="false"]),audio[controls],video[controls]';function n4(e){const t=e.assignedSlot;if(t)return t;if(e.parentElement)return e.parentElement;const a=e.getRootNode();return _c(a)?a.host:null}function Mv(e){for(const t of Array.from(e.children))if(zs(t)==="summary")return t;return null}function s4(e,t){const a=Mv(t);return!!a&&(e===a||Ke(a,e))}function MC(e){const t=e?zs(e):"";return e!=null&&e.matches(t4)&&(t!=="summary"||e.parentElement!=null&&zs(e.parentElement)==="details"&&Mv(e.parentElement)===e)&&(t!=="details"||Mv(e)==null)&&(t!=="input"||e.type!=="hidden")}function DC(e){if(!MC(e)||!e.isConnected||e.matches(":disabled"))return!1;for(let t=e;t;t=n4(t)){const a=t!==e,o=zs(t)==="slot";if(t.hasAttribute("inert")||a&&zs(t)==="details"&&!t.open&&!s4(e,t)||t.hasAttribute("hidden")||!o&&!r4(t,a))return!1}return!0}function r4(e,t){const a=gr(e);return t?a.display!=="none":Im(e,a)}function IC(e){const t=e.tabIndex;if(t<0){const a=zs(e);if(a==="details"||a==="audio"||a==="video"||on(e)&&e.isContentEditable)return 0}return t}function Dv(e){if(zs(e)!=="input")return null;const t=e;return t.type==="radio"&&t.name!==""?t:null}function a4(e,t){const a=Dv(e);if(!a)return!0;const o=t.find(c=>{const d=Dv(c);return d?.name===a.name&&d.form===a.form&&d.checked});return o?o===a:t.find(c=>{const d=Dv(c);return d?.name===a.name&&d.form===a.form})===a}function PC(e){if(on(e)&&zs(e)==="slot"){const t=e.assignedElements({flatten:!0});if(t.length>0)return t}return on(e)&&e.shadowRoot?Array.from(e.shadowRoot.children):Array.from(e.children)}function _C(e,t){PC(e).forEach(a=>{MC(a)&&t.push(a),_C(a,t)})}function LC(e,t,a){PC(e).forEach(o=>{on(o)&&o.matches(t)&&a.push(o),LC(o,t,a)})}function Iv(e){return DC(e)&&IC(e)>=0}function zC(e){const t=[];return _C(e,t),t.filter(DC)}function Bd(e){const t=zC(e);return t.filter(a=>IC(a)>=0&&a4(a,t))}function BC(e,t){const a=Bd(e),o=a.length;if(o===0)return;const c=ar(Ut(e)),d=a.indexOf(c),f=d===-1?t===1?0:o-1:d+t;return a[f]}function Pv(e){return BC(Ut(e).body,1)||e}function HC(e){return BC(Ut(e).body,-1)||e}function UC(e,t){if(!e)return null;const a=Bd(Ut(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 l4(e){return UC(e,1)}function o4(e){return UC(e,-1)}function Fc(e,t){const a=t||e.currentTarget,o=e.relatedTarget;return!o||!Ke(a,o)}function i4(e){Bd(e).forEach(a=>{a.dataset.tabindex=a.getAttribute("tabindex")||"",a.setAttribute("tabindex","-1")})}function VC(e){const t=[];LC(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 _v(e){x.useEffect(e,Er)}const Hd=0;class Wr{constructor(){sn(this,"currentId",Hd);sn(this,"clear",()=>{this.currentId!==Hd&&(clearTimeout(this.currentId),this.currentId=Hd)});sn(this,"disposeEffect",()=>this.clear)}static create(){return new Wr}start(t,a){this.clear(),this.currentId=setTimeout(()=>{this.currentId=Hd,a()},t)}isStarted(){return this.currentId!==Hd}}function Qs(){const e=Os(Wr.create).current;return _v(e.disposeEffect),e}function c4(e,t){return e.matches(":disabled")?!1:!t||e.form===t?!0:e.form===null&&!e.hasAttribute("form")}const u4=x.createContext({disabled:!1});function FC(){return x.useContext(u4)}var Lv={exports:{}},Bs={};var $C;function d4(){if($C)return Bs;$C=1;var e=Od();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(),Lv.exports=d4(),Lv.exports}var Ns=GC();const Pm=null;class f4{constructor(){sn(this,"callbacks",[]);sn(this,"callbacksCount",0);sn(this,"nextId",1);sn(this,"startId",1);sn(this,"isScheduled",!1);sn(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 _m=new f4;class Fa{constructor(){sn(this,"currentId",Pm);sn(this,"cancel",()=>{this.currentId!==Pm&&(_m.cancel(this.currentId),this.currentId=Pm)});sn(this,"disposeEffect",()=>this.cancel)}static create(){return new Fa}static request(t){return _m.request(t)}static cancel(t){return _m.cancel(t)}request(t){this.cancel(),this.currentId=_m.request(()=>{this.currentId=Pm,t()})}}function $c(){const e=Os(Fa.create).current;return _v(e.disposeEffect),e}function yl(e){return e==null?e:"current"in e?e.current:e}let Lm=null;function p4(e){if(!Lm){const t=[];Lm=t,queueMicrotask(()=>{Lm=null,Ns.flushSync(()=>{for(const a of t)a()})})}Lm.push(e)}function KC(e,t=!1,a=!1){const o=$c();return Ie((c,d=null)=>{o.cancel();const f=yl(e);if(f==null)return;const p=f,g=()=>{if(!a){Ns.flushSync(c);return}p4(()=>{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=kC;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 Jr(e){const{enabled:t=!0,open:a,ref:o,batch:c=!1,onComplete:d}=e,f=Ie(d),p=KC(o,a,c);x.useEffect(()=>{if(!t)return;const g=new AbortController;return p(f,g.signal),()=>{g.abort()}},[t,a,f,p])}function yi(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=Fa.request(()=>{d("ending")});return()=>{Fa.cancel(g)}}},[e,f,c,a]),De(()=>{if(!e||t)return;const g=Fa.request(()=>{d(void 0)});return()=>{Fa.cancel(g)}},[t,e]),De(()=>{if(!e||!t)return;e&&f&&c!=="idle"&&d("starting");const g=Fa.request(()=>{d("idle")});return()=>{Fa.cancel(g)}},[t,e,f,c]),{mounted:f,setMounted:p,transitionStatus:c}}function $a({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 qc(e,t,a,o,c=!0,d){const{registerFieldControl:f}=wa(),p=Os(()=>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 ea(e,t){const a=x.useRef(e),o=Ie(t);De(()=>{a.current!==e&&o(a.current),a.current=e},[e,o])}const Kn="none",uo="trigger-press",Hs="trigger-hover",zm="trigger-focus",Bm="outside-press",Ud="item-press",zv="close-press",Vd="input-change",qa="input-clear",m4="input-press",fo="focus-out",Gc="escape-key",Bv="list-navigation",YC="keyboard",XC="pointer",QC="cancel-open",h4="disabled",Hv="imperative-action",g4="window-resize";function Fe(e,t,a,o){let c=!1,d=!1;const f=o??cn;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 x4(e,t,a){const o=a??cn;return{reason:e,event:t??new Event("base-ui"),...o}}const b4=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:R,validityData:C,setFocused:A,setFilled:D,validationMode:I,validation:M}=wa(),{clearErrors:O,elementRef:_,submitCountRef:L}=Hc(),z=k||g,U=N??f,B={...S,disabled:z},{labelId:Q}=hl(),W=so({id:d}),[Z]=$a({controlled:p,default:y,name:"FieldControl",state:"value"}),Y=p!==void 0,q=Y?Z:void 0,G=q==null?void 0:String(q),F=Ie(()=>M.inputRef.current?.value);qc(M.inputRef,W,G,F,!z,f),De(()=>{const P=G??M.inputRef.current?.value;P!==void 0&&D(P!=="")},[G,M.inputRef,D]),ea(G,()=>{G!==void 0&&(O(U),R(G!==(C.initialValue??"")),M.change(G))});const $=x.useRef(null),X=Qs();return De(()=>{b&&$.current===ar(Ut($.current))&&A(!0)},[b,A]),bt("input",t,{ref:[a,$],state:B,props:[{id:W,disabled:z,name:U,ref:M.inputRef,"aria-labelledby":Q,autoFocus:b,...Y?{value:q}:{defaultValue:y},onChange(P){const V=P.currentTarget.value,J=Fe(Kn,P.nativeEvent);v?.(V,J),!Y&&(R(V!==(C.initialValue??"")),D(V!==""),!P.nativeEvent.defaultPrevented&&!J.isCanceled&&(O(U),M.change(V)))},onFocus(){A(!0)},onBlur(P){if(E(!0),A(!1),I==="onBlur"){const V=P.currentTarget.value;M.commit(V),Y&&queueMicrotask(()=>{const J=M.inputRef.current?.value;J!==void 0&&J!==V&&J!==(C.initialValue??"")&&M.commit(J)})}},onKeyDown(P){if(P.currentTarget.tagName==="INPUT"&&P.key==="Enter"){E(!0);const V=P.currentTarget.value,J=P.currentTarget.form;if(J&&J===_.current&&!P.defaultPrevented){const ie=P.currentTarget,me=L.current;X.start(0,()=>{L.current===me&&M.commit(ie.value)})}else M.commit(V)}}},w,P=>M.getValidationProps(z,P)],stateAttributesMapping:gi})}),v4=x.forwardRef(function(t,a){return s.jsx(b4,{ref:a,...t})});function Ye({className:e,type:t,ref:a,...o}){return s.jsx(v4,{ref:a,type:t,"data-slot":"input",className:Ve("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 Fd({className:e,...t}){return s.jsx("textarea",{"data-slot":"textarea",className:Ve("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 ji({className:e,...t}){return s.jsx("div",{"data-slot":"input-group",role:"group",className:Ve("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 y4=Bc(["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 wi({className:e,align:t="inline-start",...a}){return s.jsx("div",{role:"group","data-slot":"input-group-addon","data-align":t,className:Ve(y4({align:t}),e),onClick:o=>{o.target.closest("button")||o.currentTarget.parentElement?.querySelector("input")?.focus()},...a})}const j4=Bc("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 w4({className:e,type:t="button",variant:a="ghost",size:o="xs",...c}){return s.jsx(se,{type:t,"data-size":o,variant:a,className:Ve(j4({size:o}),e),...c})}function Si({className:e,...t}){return s.jsx(Ye,{"data-slot":"input-group-control",className:Ve("flex-1 rounded-none border-0 bg-transparent shadow-none focus:border-0 focus:shadow-none",e),...t})}function S4(e){return bt(e.defaultTagName??"div",e,e)}const N4=Bc("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 S4({render:o,defaultTagName:"span",props:Kr({"data-slot":"badge"},c,{className:Ve(N4({variant:t,shape:a}),e)})})}function Uv({className:e,...t}){return s.jsx("span",{className:Ve("size-1.5 flex-none rounded-full bg-current",e),...t})}function po(e,t){if(typeof window>"u")return e;const a=window.wbI18n;return a?a.t(e,t)??e:e}function $d({className:e,...t}){return s.jsx("svg",{"data-slot":"spinner",role:"status","aria-label":po("加载中"),viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",className:Ve("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 st({className:e,...t}){return s.jsx("label",{"data-slot":"label",className:Ve("flex items-center gap-[6px] text-[11.5px] text-muted-foreground",e),...t})}const ZC={clipPath:"inset(50%)",overflow:"hidden",whiteSpace:"nowrap",border:0,padding:0,width:1,height:1,margin:-1},Ni={...ZC,position:"fixed",top:0,left:0},Kc={...ZC,position:"absolute"},WC=x.createContext(void 0);function k4(){const e=x.useContext(WC);if(e===void 0)throw new Error(rn(63));return e}const C4="data-checked",T4="data-unchecked",JC={...gi,checked(e){return e?{[C4]:""}:{[T4]:""}}},E4=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:R,style:C,...A}=t,{clearErrors:D}=Hc(),{state:I,setTouched:M,setDirty:O,validityData:_,setFilled:L,setFocused:z,validationMode:U,disabled:B,name:Q,validation:W}=wa(),{labelId:Z}=hl(),Y=B||N,q=Q??y,G=x.useRef(null),F=Xr(G,v,W.inputRef),$=x.useRef(null),X=Sa(),re=so({id:g}),P=b?void 0:re,[V,J]=$a({controlled:o,default:!!d,name:"Switch",state:"checked"});qc($,X,V,void 0,!Y,y),De(()=>{L(V)},[V,L]),ea(V,()=>{D(q),O(V!==_.initialValue),W.change(V)});const{getButtonProps:ie,buttonRef:me}=Yr({disabled:Y,native:b}),he=gv(f,Z,G,!b,P),ae={id:b?re:X,role:"switch","aria-checked":V,"aria-readonly":w||void 0,"aria-required":S||void 0,"aria-labelledby":he,onFocus(){Y||z(!0)},onBlur(){const K=G.current;!K||Y||(M(!0),z(!1),U==="onBlur"&&W.commit(K.checked))},onClick(K){if(w||Y)return;K.preventDefault();const be=G.current;be&&zc(be,K)}},oe={...W.getValidationProps(Y),checked:V,disabled:Y,form:p,id:P,name:q,required:S,style:q?Kc:Ni,tabIndex:-1,type:"checkbox","aria-hidden":!0,ref:F,onChange(K){if(K.nativeEvent.defaultPrevented)return;if(w){K.preventDefault();return}const be=K.currentTarget.checked,ne=Fe(Kn,K.nativeEvent);j?.(be,ne),!ne.isCanceled&&J(be)},onClick(K){K.stopPropagation()},onFocus(){$.current?.focus()},...R!==void 0?{value:R}:cn},ee=x.useMemo(()=>({...I,checked:V,disabled:Y,readOnly:w,required:S}),[I,V,Y,w,S]),de=bt("span",t,{state:ee,ref:[a,$,me],props:[ae,A,ie,K=>W.getValidationProps(Y,K)],stateAttributesMapping:JC});return s.jsxs(WC.Provider,{value:ee,children:[de,!V&&q&&E!==void 0&&s.jsx("input",{type:"hidden",form:p,name:q,value:E,disabled:Y}),s.jsx("input",{...oe,suppressHydrationWarning:!0})]})}),R4=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t,p=k4();return bt("span",t,{state:p,ref:a,stateAttributesMapping:JC,props:f})});function ps({className:e,size:t="default",...a}){const o=t==="sm";return s.jsx(E4,{"data-slot":"switch",className:Ve("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(R4,{"data-slot":"switch-thumb",className:Ve("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 A4(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 O4="data-checked",M4="data-unchecked";function e1(e){return{checked(t){return e.indeterminate?{}:t?{[O4]:""}:{[M4]:""}},...gi}}const D4=x.createContext(void 0);function I4(){return x.useContext(D4)}const t1=x.createContext(void 0);function P4(){const e=x.useContext(t1);if(e===void 0)throw new Error(rn(14));return e}const _4="data-parent",L4=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:R,value:C,nativeButton:A=!1,style:D,...I}=t,{clearErrors:M}=Hc(),{disabled:O,name:_,setDirty:L,setFilled:z,setFocused:U,setTouched:B,state:Q,validationMode:W,validityData:Z,validation:Y}=wa(),q=FC(),{labelId:G,registerControlId:F,getDescriptionProps:$}=hl(),X=I4(),re=X?.allValues===void 0?void 0:X.parent,P=re!==void 0,V=O||q.disabled||X?.disabled||p,J=_??j,ie=C??J,me=Sa(),he=X?.registerControlId!==F,ae=so({id:v||void 0,enabled:he}),oe=A?ae:me;let ee={};P&&(S?ee=re.getParentProps():ie!==void 0&&(ee=re.getChildProps(ie)));const{checked:de=o,indeterminate:K=y,onCheckedChange:be,...ne}=ee,ce=X?.value,we=x.useRef(null),{getButtonProps:Ee,buttonRef:ve}=Yr({disabled:V,native:A}),ke=X?.validation??Y,[Ce,Se]=$a({controlled:ie!==void 0&&ce!==void 0&&!S?ce.includes(ie):de,default:d,name:"Checkbox",state:"checked"}),ge=P?!!de:Ce,Te=P&&K||y;qc(we,me,Ce,void 0,!X&&!V,j);const Oe=re?.registerChildId,Ne=x.useRef(null),Be=ke.registerInput,Qe=X?ie:void 0,Rt=x.useCallback(lt=>Be(lt,{controlRef:we,value:Qe}),[Be,Qe]),Wt=Xr(b,Ne,S?void 0:Rt),Dt=gv(f,G,Ne,!A,ae);De(()=>{Ne.current&&(Ne.current.indeterminate=Te),X||z(Ce)},[Ce,Te,X,z]),ea(Ce,()=>{X||(M(J),L(Ce!==Z.initialValue),ke.change(Ce))});const ct=Kr({checked:Ce,disabled:V,form:g,name:S?void 0:J,id:A?void 0:ae,required:E,ref:Wt,style:J?Kc:Ni,tabIndex:-1,type:"checkbox","aria-hidden":!0,onChange(lt){if(lt.nativeEvent.defaultPrevented)return;if(N){lt.preventDefault();return}const Bt=lt.currentTarget.checked,Ln=Fe(Kn,lt.nativeEvent);if(w?.(Bt,Ln),!Ln.isCanceled&&(be?.(Bt,Ln),!Ln.isCanceled&&(Se(Bt),ie!==void 0&&X!==void 0&&!S&&!P))){const Jt=Bt?[...X.value,ie]:X.value.filter(tt=>tt!==ie);X.setValue(Jt,Ln)}},onClick(lt){lt.stopPropagation()},onFocus(){we.current?.focus()}},C!==void 0?{value:(X?Ce&&C:C)||""}:cn,$,lt=>ke.getValidationProps(V,lt));x.useEffect(()=>{if(!re||ie===void 0)return;const lt=re.disabledStatesRef.current;return lt.set(ie,V),()=>{lt.delete(ie)}},[re,V,ie]);const $n=x.useMemo(()=>({...Q,checked:ge,disabled:V,readOnly:N,required:E,indeterminate:Te}),[Q,ge,V,N,E,Te]),us=e1($n),qn=bt("span",t,{state:$n,ref:[ve,we,a],props:[{id:oe,role:"checkbox","aria-checked":Te?"mixed":ge,"aria-readonly":N||void 0,"aria-required":E||void 0,"aria-labelledby":Dt,[_4]:S?"":void 0,onFocus(){V||U(!0)},onBlur(){const lt=Ne.current;lt&&(B(!0),U(!1),W==="onBlur"&&ke.commit(X?ce:lt.checked))},onKeyDown(lt){if(lt.key!=="Enter"||(lt.preventBaseUIHandler(),lt.defaultPrevented))return;const Bt=Ne.current?.form??null,Ln=lt.currentTarget,Jt=lt.nativeEvent,tt=lt.preventDefault,Tt=Jt.preventDefault;let Ht=!1;lt.preventDefault=()=>{Ht=!0,tt.call(lt)},Jt.preventDefault=()=>{Ht=!0,Tt.call(Jt)},Tt.call(Jt),vn(Ln).queueMicrotask(()=>{lt.preventDefault=tt,Jt.preventDefault=Tt,Ht||A4(Bt)?.click()})},onClick(lt){if(N||V)return;lt.preventDefault();const Bt=Ne.current;Bt&&zc(Bt,lt)}},I,ne,Ee,$,lt=>ke.getValidationProps(V,lt)],stateAttributesMapping:us}),gs=qn.props.id;return De(()=>{if(!(!Oe||S||ie===void 0||gs===void 0))return Oe(ie,gs)},[Oe,S,ie,gs]),s.jsxs(t1.Provider,{value:$n,children:[qn,!Ce&&!X&&J&&!S&&R!==void 0&&s.jsx("input",{type:"hidden",form:g,name:J,value:R,disabled:V}),s.jsx("input",{...ct,suppressHydrationWarning:!0})]})}),z4=x.forwardRef(function(t,a){const{render:o,className:c,style:d,keepMounted:f=!1,...p}=t,g=P4(),v=g.checked||g.indeterminate,{mounted:y,transitionStatus:b,setMounted:j}=yi(v),w=x.useRef(null),S={...g,transitionStatus:b};Jr({batch:!0,enabled:!v,open:v,ref:w,onComplete(){v||j(!1)}});const k={...e1(g),...ro},E=f||y,R=bt("span",t,{ref:[a,w],state:S,stateAttributesMapping:k,props:p});return E?R:null});function ta({className:e,...t}){return s.jsx(L4,{"data-slot":"checkbox",className:Ve("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(z4,{"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 Vv(e){return Array.isArray(e)?e.map(t=>Vv(t)).join(","):e==null?"":String(e)}const n1=new Map;function B4(e,t){const a=JSON.stringify({locale:Vv(e),options:t}),o=n1.get(a);if(o)return o;const c=new Intl.NumberFormat(e,t);return n1.set(a,c),c}function s1(e,t,a){return e==null?"":B4(t,a).format(e)}function ki(e,t=Number.MIN_SAFE_INTEGER,a=Number.MAX_SAFE_INTEGER){return Math.max(t,Math.min(e,a))}function H4(e,t,a){return(e-t)*100/(a-t)}const r1=x.createContext(void 0);function a1(){const e=x.useContext(r1);if(e===void 0)throw new Error(rn(51));return e}const U4="data-complete",V4="data-indeterminate",F4="data-progressing",Fv={status(e){return e==="progressing"?{[F4]:""}:e==="complete"?{[U4]:""}:e==="indeterminate"?{[V4]:""}:null}},$4=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,R=null,C="",A="indeterminate progress";if(g!=null&&Number.isFinite(g)){const _=H4(g,p,f);E=ki(Number.isNaN(_)?0:_,0,100),R=ki(g,p,f),k=R===f?"complete":"progressing",C=o?s1(R,d,o):s1(E/100,d,{style:"percent"}),A=C}const D=x.useMemo(()=>({status:k}),[k]),I={"aria-labelledby":S,"aria-valuemax":f,"aria-valuemin":p,"aria-valuenow":R??void 0,"aria-valuetext":c?c(C,g):A,role:"progressbar",children:s.jsxs(x.Fragment,{children:[b,s.jsx("span",{role:"presentation",style:Ni,children:"x"})]})},M=x.useMemo(()=>({formattedValue:C,percentageValue:E,setLabelId:N,state:D,value:g}),[C,E,N,D,g]),O=bt("div",t,{state:D,ref:a,props:[I,w],stateAttributesMapping:Fv});return s.jsx(r1.Provider,{value:M,children:O})}),q4=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t,{state:p}=a1();return bt("div",t,{state:p,ref:a,props:f,stateAttributesMapping:Fv})}),G4=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 bt("div",t,{state:g,ref:a,props:[{style:v},f],stateAttributesMapping:Fv})});function qd({className:e,children:t,value:a,...o}){return s.jsxs($4,{value:a,"data-slot":"progress",className:Ve("flex w-full flex-wrap items-center gap-3",e),...o,children:[t,s.jsx(K4,{children:s.jsx(Y4,{})})]})}function K4({className:e,...t}){return s.jsx(q4,{"data-slot":"progress-track",className:Ve("relative flex h-1.5 w-full items-center overflow-x-hidden overflow-y-hidden rounded-pill bg-surface-3",e),...t})}function Y4({className:e,...t}){return s.jsx(G4,{"data-slot":"progress-indicator",className:Ve("h-full rounded-[inherit] bg-primary transition-[width] duration-300 ease-out",e),...t})}const $v=[];let qv;function X4(){return qv}function Q4(e){$v.push(e)}function Hm(e){const t=(a,o)=>{const c=Os(Z4).current;let d;try{qv=c;for(const f of $v)f.before(c);d=e(a,o);for(const f of $v)f.after(c);c.didInitialize=!0}finally{qv=void 0}return d};return t.displayName=e.displayName||e.name,t}function l1(e){return x.forwardRef(Hm(e))}function Z4(){return{didInitialize:!1}}const o1=x.createContext(void 0);function Gd(e){const t=x.useContext(o1);if(t===void 0&&!e)throw new Error(rn(72));return t}function W4(e,t){return t!=null&&!lo(t)?0:typeof e=="function"?e():e}function Ci(e,t,a){const o=W4(e,a);return typeof o=="number"?o:o?.[t]}function i1(e){return typeof e=="function"?e():e}function c1(e,t){return t||e==="click"||e==="mousedown"}function J4(e){return e?.includes("mouse")&&e!=="mousedown"}const u1=x.createContext({hasProvider:!1,timeoutMs:0,delayRef:{current:0},initialDelayRef:{current:0},timeout:new Wr,currentIdRef:{current:null},currentContextRef:{current:null}});function eB(e,t){e.current=t.current}function tB(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:Ci(c.current,"open"),close:Ci(a,"close")}},[a,f,c,d]),s.jsx(u1.Provider,{value:x.useMemo(()=>({hasProvider:!0,delayRef:c,initialDelayRef:d,currentIdRef:f,timeoutMs:o,currentContextRef:p,timeout:g}),[o,g]),children:t})}function nB(e,t={open:!1}){const{open:a}=t,o="rootStore"in e?e.rootStore:e,c=o.useState("floatingId"),d=x.useContext(u1),{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:Ci(v.current,"close")},E!==null&&E!==c?(S(!0),k?.setIsInstantPhase(!0),k?.onOpenChange(!1,Fe(Kn))):(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,eB(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 jt(e,t,a,o){return e.addEventListener(t,a,o),()=>{e.removeEventListener(t,a,o)}}function Ga(...e){return()=>{for(let t=0;t{t.current=t.next}};return t}const Yc=x.forwardRef(function(t,a){const[o,c]=x.useState();De(()=>{Tz&&gl&&c("button")},[]);const d={tabIndex:0,role:o};return s.jsx("span",{...t,ref:a,style:Ni,"aria-hidden":o?void 0:!0,...d,"data-base-ui-focus-guard":""})});function Kd(e){return`data-base-ui-${e}`}let Um=0;function Vm(e,t={}){const{preventScroll:a=!1,sync:o=!1,shouldFocus:c}=t;cancelAnimationFrame(Um);function d(){c&&!c()||e?.focus({preventScroll:a})}if(o)return d(),Vt;const f=requestAnimationFrame(d);return Um=f,()=>{Um===f&&(cancelAnimationFrame(f),Um=0)}}const Gv={inert:new WeakMap,"aria-hidden":new WeakMap},d1="data-base-ui-inert",Kv={inert:new WeakSet,"aria-hidden":new WeakSet};let Yd=new WeakMap,Yv=0;function rB(e){return Kv[e]}function f1(e){return e?_c(e)?e.host:f1(e.parentNode):null}const p1=(e,t)=>t.map(a=>{if(e.contains(a))return a;const o=f1(a);return e.contains(o)?o:null}).filter(a=>a!=null),m1=e=>{const t=new Set;return e.forEach(a=>{let o=a;for(;o&&!t.has(o);)t.add(o),o=o.parentNode}),t},h1=(e,t,a)=>{const o=[],c=d=>{!d||a.has(d)||Array.from(d.children).forEach(f=>{zs(f)!=="script"&&(t.has(f)?c(f):o.push(f))})};return c(e),o};function aB(e,t,a,o,{mark:c=!0}){let d=null;o?d="inert":a&&(d="aria-hidden");let f=null,p=null;const g=p1(t,e),v=c?h1(t,m1(g),new Set(g)):[],y=[],b=[];if(d){const j=Gv[d],w=rB(d);p=w,f=j;const S=p1(t,Array.from(t.querySelectorAll("[aria-live]"))),N=g.concat(S);h1(t,m1(N),new Set(N)).forEach(E=>{const R=E.getAttribute(d),C=R!==null&&R!=="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=(Yd.get(j)||0)+1;Yd.set(j,w),b.push(j),w===1&&j.setAttribute(d1,"")}),Yv+=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=(Yd.get(j)||0)-1;Yd.set(j,w),w||j.removeAttribute(d1)}),Yv-=1,Yv||(Gv.inert=new WeakMap,Gv["aria-hidden"]=new WeakMap,Kv.inert=new WeakSet,Kv["aria-hidden"]=new WeakSet,Yd=new WeakMap)}}function g1(e,t={}){const{ariaHidden:a=!1,inert:o=!1,mark:c=!0}=t,d=Ut(e[0]).body;return aB(e,d,a,o,{mark:c})}const lB=500,oB={style:{transition:"none"}},x1="data-base-ui-click-trigger",b1={fallbackAxisSide:"none"},v1={fallbackAxisSide:"end"},iB={clipPath:"inset(50%)",position:"fixed",top:0,left:0},y1=x.createContext(null),j1=()=>x.useContext(y1),cB=Kd("portal");function w1(e={}){const{ref:t,container:a,componentProps:o=cn,elementProps:c}=e,d=Pd(),p=j1()?.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&&(ev(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=bt("div",o,{ref:[t,j],props:[{id:d,[cB]:""},c]}),N=g&&S?Ns.createPortal(S,g):null;return{node:y,nodeId:x.isValidElement(S)?S.props.id:void 0,subtree:N}}const Fm=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}=w1({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,R]=x.useState(null),C=x.useRef(!1),A=E?.modal,D=E?.open,I=!!E&&!E.modal&&E.open&&!!y;x.useEffect(()=>{if(!y||A)return;function O(_){y&&_.relatedTarget&&Fc(_)&&(_.type==="focusin"?C.current&&(VC(y),C.current=!1):(i4(y),C.current=!0))}return Ga(jt(y,"focusin",O,!0),jt(y,"focusout",O,!0))},[y,A]),De(()=>{!y||D!==!0||!C.current||(VC(y),C.current=!1)},[D,y]);const M=x.useMemo(()=>({beforeOutsideRef:w,afterOutsideRef:S,beforeInsideRef:N,afterInsideRef:k,portalNode:y,setFocusManagerState:R}),[y]);return s.jsxs(x.Fragment,{children:[j,s.jsxs(y1.Provider,{value:M,children:[I&&y&&s.jsx(Yc,{"data-type":"outside",ref:w,onFocus:O=>{if(Fc(O,y))N.current?.focus();else{const _=E?E.domReference:null;HC(_)?.focus()}}}),I&&y&&s.jsx("span",{role:g,"aria-owns":b,style:iB}),y&&Ns.createPortal(f,y),I&&y&&s.jsx(Yc,{"data-type":"outside",ref:S,onFocus:O=>{if(Fc(O,y))k.current?.focus();else{const _=E?E.domReference:null;Pv(_)?.focus(),E?.closeOnFocusOut&&E?.onOpenChange(!1,Fe(fo,O.nativeEvent))}}})]})]})});function S1(){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 uB{constructor(){sn(this,"nodesRef",{current:[]});sn(this,"events",S1())}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 N1=x.createContext(null),k1=x.createContext(null),Xc=()=>x.useContext(N1)?.id||null,Ti=e=>{const t=x.useContext(k1);return e??t};function dB(e){const t=Pd(),a=Ti(e),o=Xc();return De(()=>{if(!t)return;const c={id:t,parentId:o};return a?.addNode(c),()=>{a?.removeNode(c)}},[a,t,o]),t}function fB(e){const{children:t,id:a}=e,o=Xc();return s.jsx(N1.Provider,{value:x.useMemo(()=>({id:a,parentId:o}),[a,o]),children:t})}function pB(e){const{children:t,externalTree:a}=e,o=Os(()=>a??new uB).current;return s.jsx(k1.Provider,{value:o,children:t})}function mB(e,t){const a=vn(os(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 C1=20;let mo=[];function Xv(){mo=mo.filter(e=>e.deref()?.isConnected)}function T1(e){Xv(),e&&zs(e)!=="body"&&(mo.push(new WeakRef(e)),mo.length>C1&&(mo=mo.slice(-C1)))}function E1(){return Xv(),mo[mo.length-1]?.deref()}function hB(e){return e?Iv(e)?e:Bd(e)[0]||e:null}function R1(e){if(e.hasAttribute("tabindex")&&!e.hasAttribute("data-tabindex")||!e.getAttribute("role")?.includes("dialog"))return;const a=zC(e).filter(c=>{const d=c.getAttribute("data-tabindex")||"";return Iv(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 $m(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"),R=N.useState("floatingElement"),{events:C,dataRef:A}=N.context,D=Ie(()=>A.current.floatingContext?.nodeId),I=c===!1,M=kv(E)&&I,O=Yn(c),_=Yn(d),L=Yn(v),z=Yn(k),U=Ti(w),B=j1(),Q=x.useRef(!1),W=x.useRef(!1),Z=x.useRef(!1),Y=x.useRef(null),q=x.useRef(""),G=x.useRef(""),F=x.useRef(null),$=x.useRef(null),X=Xr(F,j,B?.beforeInsideRef),re=Xr($,B?.afterInsideRef),P=Qs(),V=Qs(),J=$c(),ie=B!=null,me=Em(R),he=Ie((ee=me)=>ee?Bd(ee):[]),ae=Ie(()=>S?.().filter(ee=>ee!=null)??[]);x.useEffect(()=>{if(o||!p)return;function ee(K){K.key==="Tab"&&Ke(me,ar(Ut(me)))&&he().length===0&&!M&&Ss(K)}const de=Ut(me);return jt(de,"keydown",ee)},[o,me,p,M,he]),x.useEffect(()=>{if(o||!k)return;const ee=Ut(me);function de(){Z.current=!1}function K(ne){const ce=os(ne),we=ae(),Ee=Ke(R,ce)||Ke(E,ce)||Ke(B?.portalNode,ce)||we.some(ve=>ve===ce||Ke(ve,ce));Z.current=!Ee,G.current=ne.pointerType||"keyboard",ce?.closest(`[${x1}]`)&&(W.current=!0,V.start(0,()=>{W.current=!1}))}function be(){G.current="keyboard"}return Ga(jt(ee,"pointerdown",K,!0),jt(ee,"pointerup",de,!0),jt(ee,"pointercancel",de,!0),jt(ee,"keydown",be,!0),de)},[o,R,E,me,k,B,V,ae]),x.useEffect(()=>{if(o||!g)return;const ee=Ut(me);function de(){W.current=!0,V.start(0,()=>{W.current=!1})}function K(we){const Ee=os(we);Iv(Ee)&&(Y.current=Ee)}function be(we){const Ee=we.relatedTarget,ve=we.currentTarget,ke=os(we);p&&Ee==null&&ke!=null&&Ke(R,ke)&&T1(ke),queueMicrotask(()=>{const Ce=D(),Se=N.context.triggerElements,ge=ae(),Te=Ee?.hasAttribute(Kd("focus-guard"))&&[F.current,$.current,B?.beforeInsideRef.current,B?.afterInsideRef.current,B?.beforeOutsideRef.current,B?.afterOutsideRef.current,yl(b),yl(y)].includes(Ee),Oe=!(Ke(E,Ee)||Ke(R,Ee)||Ke(Ee,R)||Ke(B?.portalNode,Ee)||ge.some(Ne=>Ne===Ee||Ke(Ne,Ee))||Se.hasMatchingElement(Ne=>Ke(Ne,Ee))||Te||U&&(ao(U.nodesRef.current,Ce).find(Ne=>Ke(Ne.context?.elements.floating,Ee)||Ke(Ne.context?.elements.domReference,Ee))||TC(U.nodesRef.current,Ce).find(Ne=>[Ne.context?.elements.floating,Em(Ne.context?.elements.floating)].includes(Ee)||Ne.context?.elements.domReference===Ee)));if(ve===E&&me&&R1(me),f&&ve!==E&&!Im(ke)&&ar(ee)===ee.body){if(on(me)&&(me.focus(),f==="popup")){J.request(()=>{me.focus()});return}const Ne=he(),Be=Y.current,Qe=(Be&&Ne.includes(Be)?Be:null)||Ne[Ne.length-1]||me;on(Qe)&&Qe.focus()}if(A.current.insideReactTree){A.current.insideReactTree=!1;return}(M||!p)&&Ee&&Oe&&!W.current&&(M||Ee!==E1())&&(Q.current=!0,N.setOpen(!1,Fe(fo,we)))})}function ne(){Z.current||(A.current.insideReactTree=!0,P.start(0,()=>{A.current.insideReactTree=!1}))}const ce=on(E)?E:null;if(!(!R&&!ce))return Ga(ce&&jt(ce,"focusout",be),ce&&jt(ce,"pointerdown",de),R&&jt(R,"focusin",K),R&&jt(R,"focusout",be),R&&B&&jt(R,"focusout",ne,!0))},[o,E,R,me,p,U,B,N,g,f,he,M,D,A,P,V,J,y,b,ae]),x.useEffect(()=>{if(o||!R||!k)return;const ee=Array.from(B?.portalNode?.querySelectorAll(`[${Kd("portal")}]`)||[]),K=(U?TC(U.nodesRef.current,D()):[]).find(ve=>kv(ve.context?.elements.domReference||null))?.context?.elements.domReference,ne=[...[R,...ee,F.current,$.current,B?.beforeOutsideRef.current,B?.afterOutsideRef.current,...ae()],K,yl(b),yl(y),M?E:null].filter(ve=>ve!=null),ce=g1(ne,{ariaHidden:p||M,mark:!1}),we=[R,...ee].filter(ve=>ve!=null),Ee=g1(we);return()=>{Ee(),ce()}},[k,o,E,R,p,B,M,U,D,y,b,ae]),De(()=>{if(!k||o||!on(me))return;q.current="",G.current="";const ee=Ut(me),de=ar(ee);queueMicrotask(()=>{const K=O.current,be=typeof K=="function"?K(L.current||""):K;if(be===void 0||be===!1||Ke(me,de))return;let ce=null;const we=()=>(ce==null&&(ce=he(me)),ce[0]||me);let Ee;be===!0||be===null?Ee=we():Ee=yl(be),Ee=Ee||we();const ve=Ke(me,ar(ee));Vm(Ee,{preventScroll:Ee===me,shouldFocus(){if(!z.current)return!1;if(ve)return!0;const ke=ar(ee);return!(ke!==Ee&&Ke(me,ke))}})})},[o,k,me,he,O,L,z]),De(()=>{if(o||!me)return;const ee=Ut(me),de=ar(ee),K=L.current==null;T1(de);function be(ce){if(ce.open||(q.current=mB(ce.nativeEvent,G.current)),ce.reason===Hs&&ce.nativeEvent.type==="mouseleave"&&(Q.current=!0),ce.reason===Bm)if(ce.nested)Q.current=!1;else if(Rm(ce.nativeEvent)||Cv(ce.nativeEvent))Q.current=!1;else{let we=!1;Ut(me).createElement("div").focus({get preventScroll(){return we=!0,!1}}),we?Q.current=!1:Q.current=!0}}C.on("openchange",be);function ne(ce){const we=_.current;let Ee=typeof we=="function"?we(ce):we;if(Ee===void 0||Ee===!1)return null;Ee===null&&(Ee=!0);const ve=E?.isConnected?E:null,ke=de?.isConnected&&zs(de)!=="body"?de:null;let Ce=K?ke||ve:ve||ke;return Ce||(Ce=E1()||null),typeof Ee=="boolean"?Ce:yl(Ee)||Ce||null}return()=>{C.off("openchange",be);const ce=ar(ee),we=ae(),Ee=Ke(R,ce)||we.some(Se=>Se===ce||Ke(Se,ce))||U&&ao(U.nodesRef.current,D(),!1).some(Se=>Ke(Se.context?.elements.floating,ce)),ve=_.current,ke=q.current,Ce=ne(ke);queueMicrotask(()=>{const Se=hB(Ce),ge=typeof ve!="boolean";if(ve&&!Q.current&&on(Se)&&(!(!ge&&Se!==ce&&ce!==ee.body)||Ee)){const Te={preventScroll:!0};ke==="keyboard"&&(Te.focusVisible=!0),Se.focus(Te)}Q.current=!1})}},[o,R,me,_,L,C,U,E,D,ae]),De(()=>{if(!gl||k||!R)return;const ee=ar(Ut(R));!on(ee)||!Tm(ee)||Ke(R,ee)&&ee.blur()},[k,R]),De(()=>{if(!(o||!B))return B.setFocusManagerState({modal:p,closeOnFocusOut:g,open:k,onOpenChange:N.setOpen,domReference:E}),()=>{B.setFocusManagerState(null)}},[o,B,p,k,N,g,E]),De(()=>{if(!(o||!me))return R1(me),()=>{queueMicrotask(Xv)}},[o,me]);const oe=!o&&(p?!M:!0)&&(ie||p);return s.jsxs(x.Fragment,{children:[oe&&s.jsx(Yc,{"data-type":"inside",ref:X,onFocus:ee=>{if(p){const de=he();Vm(de[de.length-1])}else B?.portalNode&&(Q.current=!1,Fc(ee,B.portalNode)?Pv(E)?.focus():yl(b??B.beforeOutsideRef)?.focus())}}),a,oe&&s.jsx(Yc,{"data-type":"inside",ref:re,onFocus:ee=>{p?Vm(he()[0]):B?.portalNode&&(g&&(Q.current=!0),Fc(ee,B.portalNode)?HC(E)?.focus():yl(y??B.afterOutsideRef)?.focus())}})]})}function qm(e,t={}){const{enabled:a=!0,event:o="click",toggle:c=!0,ignoreMouse:d=!1,stickIfOpen:f=!0,touchOpenDelay:p=0,reason:g=uo}=t,v="rootStore"in e?e.rootStore:e,y=v.context.dataRef,b=x.useRef(void 0),j=$c(),w=Qs(),S=x.useMemo(()=>{function N(E,R,C,A){const D=Fe(g,R,C);E&&A==="touch"&&p>0?w.start(p,()=>{v.setOpen(!0,D)}):v.setOpen(E,D)}function k(E,R,C){const A=y.current.openEvent,D=v.select("domReferenceElement")!==R;return E&&D||!E||!c?!0:A&&f?!C(A.type):!1}return{onPointerDown(E){b.current=lo(E.pointerType,!0)&&Cv(E.nativeEvent)?"virtual":E.pointerType},onMouseDown(E){const R=b.current,C=E.nativeEvent,A=v.select("open");if(E.button!==0||o==="click"||lo(R,!0)&&d)return;const D=k(A,E.currentTarget,O=>O==="click"||O==="mousedown"),I=os(C);if(Tm(I)){N(D,C,I,R);return}const M=E.currentTarget;j.request(()=>{N(D,C,M,R)})},onClick(E){if(o==="mousedown-only")return;const R=b.current;if(o==="mousedown"&&R){b.current=void 0;return}if(lo(R,!0)&&d)return;const C=v.select("open"),A=k(C,E.currentTarget,D=>D==="click"||D==="mousedown"||D==="keydown"||D==="keyup");N(A,E.nativeEvent,E.currentTarget,R)},onKeyDown(){b.current=void 0}}},[y,o,d,g,v,f,c,j,w,p]);return x.useMemo(()=>a?{reference:S}:cn,[a,S])}function gB(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 A1(e){return e!=null&&e.clientX!=null}function xB(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,D,I)=>{v.current||g.current.openEvent&&!A1(g.current.openEvent)||c.set("positionReference",gB(I??p,{x:A,y:D,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)}),R=lo(b)?f:d;x.useEffect(()=>{if(!a){N(p);return}if(!R)return;function A(){y.current?.(),y.current=null}const D=vn(f);function I(M){const O=os(M);Ke(f,O)?A():k(M.clientX,M.clientY)}return!g.current.openEvent||A1(g.current.openEvent)?y.current=jt(D,"mousemove",I):N(p),A},[R,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(D){j(D.pointerType)}return{onPointerDown:A,onPointerEnter:A,onMouseMove:E,onMouseEnter:E}},[E]);return x.useMemo(()=>a?{reference:C,trigger:C}:{},[a,C])}function bB(){return!1}function vB(e){return{escapeKey:typeof e=="boolean"?e:e?.escapeKey??!1,outsidePress:typeof e=="boolean"?e:e?.outsidePress??!0}}function Xd(e,t={}){const{enabled:a=!0,escapeKey:o=!0,outsidePress:c=!0,outsidePressEvent:d="sloppy",referencePress:f=bB,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=Ti(g),N=Ie(typeof c=="function"?c:()=>!1),k=typeof c=="function"?N:c,E=k!==!1,R=Ie(()=>d),{escapeKey:C,outsidePress:A}=vB(p),D=x.useRef(!1),I=x.useRef(!1),M=x.useRef(!1),O=x.useRef(!1),_=x.useRef(!1),L=x.useRef(""),z=x.useRef(null),U=Qs(),B=Qs(),Q=Ie(()=>{B.clear(),j.current.insideReactTree=!1}),W=Ie(P=>{const V=j.current.floatingContext?.nodeId;return(S?ao(S.nodesRef.current,V):[]).some(ie=>ie.context?.open&&!ie.context.dataRef.current[P])}),Z=Ie(P=>Nv(P,v.select("floatingElement"))||Nv(P,v.select("domReferenceElement"))),Y=Ie(P=>{f()&&v.setOpen(!1,Fe(uo,P.nativeEvent))}),q=Ie(P=>{if(!y||!a||!o||P.key!=="Escape"||_.current||!C&&W("__escapeKeyBubbles"))return;const V=Fz(P)?P.nativeEvent:P,J=Fe(Gc,V);v.setOpen(!1,J),J.isCanceled||P.preventDefault(),!C&&!J.isPropagationAllowed&&P.stopPropagation()}),G=Ie(()=>{j.current.insideReactTree=!0,B.start(0,Q)}),F=Ie(P=>{if(!y||!a||P.button!==0)return;const V=os(P.nativeEvent);Ke(v.select("floatingElement"),V)&&(D.current||(D.current=!0,I.current=!1))}),$=Ie(P=>{!y||!a||(P.defaultPrevented||P.nativeEvent.defaultPrevented)&&D.current&&(I.current=!0)});x.useEffect(()=>{function P(V){V.open||(O.current=!1)}return w.on("openchange",P),()=>{w.off("openchange",P)}},[w]),x.useEffect(()=>{if(!y||!a)return y||(O.current=!1),Q;j.current.__escapeKeyBubbles=C,j.current.__outsidePressBubbles=A;const P=new Wr,V=new Wr,J=Ut(b);function ie(){P.clear(),_.current=!0}function me(){P.start(gl?5:0,()=>{_.current=!1})}function he(){M.current=!0,V.start(0,()=>{M.current=!1})}function ae(){D.current=!1,I.current=!1}function oe(){const Oe=L.current,Ne=Oe==="pen"||!Oe?"mouse":Oe,Be=R(),Qe=typeof Be=="function"?Be():Be;return typeof Qe=="string"?Qe:Qe[Ne]}function ee(Oe){const Ne=oe();return Ne==="intentional"&&Oe.type!=="click"||Ne==="sloppy"&&Oe.type==="click"}function de(Oe){const Ne=j.current.floatingContext?.nodeId,Be=S&&ao(S.nodesRef.current,Ne).some(Qe=>Nv(Oe,Qe.context?.elements.floating));return Z(Oe)||Be}function K(Oe){if(ee(Oe)){Oe.type!=="click"&&!Z(Oe)&&(V.clear(),M.current=!1),Q();return}if(j.current.insideReactTree){Q();return}const Ne=os(Oe),Be=`[${Kd("inert")}]`,Qe=kt(Ne)?Ne.getRootNode():null,Rt=Array.from((_c(Qe)?Qe:Ut(v.select("floatingElement"))).querySelectorAll(Be)),Wt=v.context.triggerElements;if(Ne&&(Wt.hasElement(Ne)||Wt.hasMatchingElement(ct=>Ke(ct,Ne))))return;let Dt=kt(Ne)?Ne:null;for(;Dt&&!Jl(Dt);){const ct=eo(Dt);if(Jl(ct)||!kt(ct))break;Dt=ct}if(!(Rt.length&&kt(Ne)&&!Hz(Ne)&&!Ke(Ne,v.select("floatingElement"))&&Rt.every(ct=>!Ke(Dt,ct)))){if(on(Ne)&&!("touches"in Oe)){const ct=Jl(Ne),$n=gr(Ne),us=/auto|scroll/,qn=ct||us.test($n.overflowX),gs=ct||us.test($n.overflowY),lt=qn&&Ne.clientWidth>0&&Ne.scrollWidth>Ne.clientWidth,Bt=gs&&Ne.clientHeight>0&&Ne.scrollHeight>Ne.clientHeight,Ln=$n.direction==="rtl",Jt=Bt&&(Ln?Oe.offsetX<=Ne.offsetWidth-Ne.clientWidth:Oe.offsetX>Ne.clientWidth),tt=lt&&Oe.offsetY>Ne.clientHeight;if(Jt||tt)return}if(!de(Oe)){if(oe()==="intentional"){if(Oe.detail!==0&&!Rm(Oe)&&!O.current)return;if(M.current){V.clear(),M.current=!1;return}}typeof k=="function"&&!k(Oe)||W("__outsidePressBubbles")||(v.setOpen(!1,Fe(Bm,Oe)),Q())}}}function be(Oe){oe()!=="sloppy"||Oe.pointerType==="touch"||!v.select("open")||!a||Z(Oe)||K(Oe)}function ne(Oe){if(oe()!=="sloppy"||!v.select("open")||!a||Z(Oe))return;const Ne=Oe.touches[0];Ne&&(z.current={startTime:Date.now(),startX:Ne.clientX,startY:Ne.clientY,dismissOnTouchEnd:!1,dismissOnMouseDown:!0},U.start(1e3,()=>{z.current&&(z.current.dismissOnTouchEnd=!1,z.current.dismissOnMouseDown=!1)}))}function ce(Oe,Ne){const Be=os(Oe);if(!Be)return;const Qe=jt(Be,Oe.type,()=>{Ne(Oe),Qe()})}function we(Oe){L.current="touch",ce(Oe,ne)}function Ee(Oe){U.clear(),Oe.type==="pointerdown"&&(Oe.button===0&&(O.current=!0),L.current=Oe.pointerType),!(Oe.type==="mousedown"&&z.current&&!z.current.dismissOnMouseDown)&&ce(Oe,Ne=>{Ne.type==="pointerdown"?be(Ne):K(Ne)})}function ve(Oe){if(Oe.type==="pointercancel"&&(O.current=!1),!D.current)return;const Ne=I.current;if(ae(),oe()==="intentional"){if(Oe.type==="pointercancel"){Ne&&he();return}if(!de(Oe)){if(Ne){he();return}typeof k=="function"&&!k(Oe)||(V.clear(),M.current=!0,Q())}}}function ke(Oe){if(oe()!=="sloppy"||!z.current||Z(Oe))return;const Ne=Oe.touches[0];if(!Ne)return;const Be=Math.abs(Ne.clientX-z.current.startX),Qe=Math.abs(Ne.clientY-z.current.startY),Rt=Math.sqrt(Be*Be+Qe*Qe);Rt>5&&(z.current.dismissOnTouchEnd=!0),Rt>10&&(K(Oe),U.clear(),z.current=null)}function Ce(Oe){ce(Oe,ke)}function Se(Oe){oe()!=="sloppy"||!z.current||Z(Oe)||(z.current.dismissOnTouchEnd&&K(Oe),U.clear(),z.current=null)}function ge(Oe){ce(Oe,Se)}const Te=Ga(o&&Ga(jt(J,"keydown",q),jt(J,"compositionstart",ie),jt(J,"compositionend",me)),E&&Ga(jt(J,"click",Ee,!0),jt(J,"pointerdown",Ee,!0),jt(J,"pointerup",ve,!0),jt(J,"pointercancel",ve,!0),jt(J,"mousedown",Ee,!0),jt(J,"mouseup",ve,!0),jt(J,"touchstart",we,{capture:!0,passive:!0}),jt(J,"touchmove",Ce,{capture:!0,passive:!0}),jt(J,"touchend",ge,{capture:!0,passive:!0})));return()=>{Te(),P.clear(),V.clear(),ae(),M.current=!1,Q()}},[j,b,o,E,k,y,a,C,A,q,Q,R,W,Z,S,v,U]);const X=x.useMemo(()=>({onKeyDown:q,onPointerDown:Y,onClick:Y}),[q,Y]),re=x.useMemo(()=>({onKeyDown:q,onPointerDown:$,onMouseDown:$,onClickCapture:G,onMouseDownCapture(P){G(),F(P)},onPointerDownCapture(P){G(),F(P)},onMouseUpCapture:G,onTouchEndCapture:G,onTouchMoveCapture:G}),[q,G,F,$]);return x.useMemo(()=>a?{reference:X,floating:re,trigger:X}:{},[a,X,re])}function O1(e,t,a){let{reference:o,floating:c}=e;const d=Zr(t),f=Rv(t),p=Ev(f),g=Qr(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=vl(t);return S&&(w[f]+=j*(S==="end"?1:-1)*(a&&v?-1:1)),w}async function yB(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}=oo(t,e),S=OC(w),k=p[j?b==="floating"?"reference":"floating":b],E=zd(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})),R=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},D=zd(d.convertOffsetParentRelativeRectToViewportRelativeRect?await d.convertOffsetParentRelativeRectToViewportRelativeRect({elements:p,rect:R,offsetParent:C,strategy:g}):R);return{top:(E.top-D.top+S.top)/A.y,bottom:(D.bottom-E.bottom+S.bottom)/A.y,left:(E.left-D.left+S.left)/A.x,right:(D.right-E.right+S.right)/A.x}}const jB=50,wB=async(e,t,a)=>{const{placement:o="bottom",strategy:c="absolute",middleware:d=[],platform:f}=a,p=f.detectOverflow?f:{...f,detectOverflow:yB},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}=O1(v,o,g),j=o,w=0;const S={};for(let N=0;NQ<=0)){var z,U;const Q=(((z=d.flip)==null?void 0:z.index)||0)+1,W=M[Q];if(W&&(!(b==="alignment"?R!==Zr(W):!1)||L.every(q=>Zr(q.placement)===R?q.overflows[0]>0:!0)))return{data:{index:Q,overflows:L},reset:{placement:W}};let Z=(U=L.filter(Y=>Y.overflows[0]<=0).sort((Y,q)=>Y.overflows[1]-q.overflows[1])[0])==null?void 0:U.placement;if(!Z)switch(w){case"bestFit":{var B;const Y=(B=L.filter(q=>{if(I){const G=Zr(q.placement);return G===R||G==="y"}return!0}).map(q=>[q.placement,q.overflows.filter(G=>G>0).reduce((G,F)=>G+F,0)]).sort((q,G)=>q[1]-G[1])[0])==null?void 0:B[0];Y&&(Z=Y);break}case"initialPlacement":Z=p;break}if(c!==Z)return{reset:{placement:Z}}}return{}}}},M1=new Set(["left","top"]);async function NB(e,t){const{placement:a,platform:o,elements:c}=e,d=await(o.isRTL==null?void 0:o.isRTL(c.floating)),f=Qr(a),p=vl(a),g=Zr(a)==="y",v=M1.has(f)?-1:1,y=d&&g?-1:1,b=oo(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 kB=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 NB(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}}}}},CB=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:R=>{let{x:C,y:A}=R;return{x:C,y:A}}},...v}=oo(e,t),y={x:a,y:o},b=await d.detectOverflow(t,v),j=Zr(c),w=Tv(j);let S=y[w],N=y[j];const k=(R,C)=>EC(C+b[R==="y"?"top":"left"],C,C-b[R==="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}}}}}},TB=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}=oo(e,t),j={x:c,y:d},w=Zr(f),S=Tv(w);let N=j[S],k=j[w];const E=oo(v,t),R=typeof E=="number"?{mainAxis:E,crossAxis:0}:{mainAxis:(a=E.mainAxis)!=null?a:0,crossAxis:(o=E.crossAxis)!=null?o:0};if(y){const D=S==="y"?"height":"width",I=p.reference[S]-p.floating[D]+R.mainAxis,M=p.reference[S]+p.reference[D]-R.mainAxis;NM&&(N=M)}if(b){var C,A;const D=S==="y"?"width":"height",I=M1.has(Qr(f)),M=p.reference[w]-p.floating[D]+(I&&((C=g.offset)==null?void 0:C[w])||0)+(I?0:R.crossAxis),O=p.reference[w]+p.reference[D]+(I?0:((A=g.offset)==null?void 0:A[w])||0)-(I?R.crossAxis:0);kO&&(k=O)}return{[S]:N,[w]:k}}}},EB=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}=oo(e,t),g=await c.detectOverflow(t,p),v=Qr(a),y=vl(a),b=Zr(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,R=Vc(w-g[S],k),C=Vc(j-g[N],E),A=t.middlewareData.shift,D=!A;let I=R,M=C;A!=null&&A.enabled.x&&(M=E),A!=null&&A.enabled.y&&(I=k),D&&!y&&(b?M=j-2*xl(g.left,g.right):I=w-2*xl(g.top,g.bottom)),await f({...t,availableWidth:M,availableHeight:I});const O=await c.getDimensions(d.floating);return j!==O.width||w!==O.height?{reset:{rects:!0}}:{}}}};function D1(e){const t=gr(e);let a=parseFloat(t.width)||0,o=parseFloat(t.height)||0;const c=on(e),d=c?e.offsetWidth:a,f=c?e.offsetHeight:o,p=Am(a)!==d||Am(o)!==f;return p&&(a=d,o=f),{width:a,height:o,$:p}}function Qv(e){return kt(e)?e:e.contextElement}function Qc(e){const t=Qv(e);if(!on(t))return bl(1);const a=t.getBoundingClientRect(),{width:o,height:c,$:d}=D1(t);let f=(d?Am(a.width):a.width)/o,p=(d?Am(a.height):a.height)/c;return(!f||!Number.isFinite(f))&&(f=1),(!p||!Number.isFinite(p))&&(p=1),{x:f,y:p}}const RB=bl(0);function I1(e){const t=vn(e);return!sv()||!t.visualViewport?RB:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function AB(e,t,a){return t===void 0&&(t=!1),!!a&&t&&a===vn(e)}function Ei(e,t,a,o){t===void 0&&(t=!1),a===void 0&&(a=!1);const c=e.getBoundingClientRect(),d=Qv(e);let f=bl(1);t&&(o?kt(o)&&(f=Qc(o)):f=Qc(e));const p=AB(d,a,o)?I1(d):bl(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=vn(d),w=kt(o)?vn(o):o;let S=j,N=rv(S);for(;N&&w!==S;){const k=Qc(N),E=N.getBoundingClientRect(),R=gr(N),C=E.left+(N.clientLeft+parseFloat(R.paddingLeft))*k.x,A=E.top+(N.clientTop+parseFloat(R.paddingTop))*k.y;g*=k.x,v*=k.y,y*=k.x,b*=k.y,g+=C,v+=A,S=vn(N),N=rv(S)}}return zd({width:y,height:b,x:g,y:v})}function Gm(e,t){const a=xm(e).scrollLeft;return t?t.left+a:Ei(pl(e)).left+a}function P1(e,t){const a=e.getBoundingClientRect(),o=a.left+t.scrollLeft-Gm(e,a),c=a.top+t.scrollTop;return{x:o,y:c}}function OB(e){let{elements:t,rect:a,offsetParent:o,strategy:c}=e;const d=c==="fixed",f=pl(o),p=t?gm(t.floating):!1;if(o===f||p&&d)return a;let g={scrollLeft:0,scrollTop:0},v=bl(1);const y=bl(0),b=on(o);if((b||!d)&&((zs(o)!=="body"||Md(f))&&(g=xm(o)),b)){const w=Ei(o);v=Qc(o),y.x=w.x+o.clientLeft,y.y=w.y+o.clientTop}const j=f&&!b&&!d?P1(f,g):bl(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 MB(e){return e.getClientRects?Array.from(e.getClientRects()):[]}function DB(e){const t=xm(e),a=e.ownerDocument.body,o=xl(e.scrollWidth,e.clientWidth,a.scrollWidth,a.clientWidth),c=xl(e.scrollHeight,e.clientHeight,a.scrollHeight,a.clientHeight);let d=-t.scrollLeft+Gm(e);const f=-t.scrollTop;return gr(a).direction==="rtl"&&(d+=xl(e.clientWidth,a.clientWidth)-o),{width:o,height:c,x:d,y:f}}const IB=25;function PB(e,t,a){a===void 0&&(a="viewport");const o=a==="layoutViewport",c=vn(e),d=pl(e),f=c.visualViewport;let p=d.clientWidth,g=d.clientHeight,v=0,y=0;if(f){const j=!sv()||t==="fixed";o?j||(v=-f.offsetLeft,y=-f.offsetTop):(p=f.width,g=f.height,j&&(v=f.offsetLeft,y=f.offsetTop))}if(Gm(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<=IB&&(p-=E)}return{width:p,height:g,x:v,y}}function _B(e,t){const a=Ei(e,!0,t==="fixed"),o=a.top+e.clientTop,c=a.left+e.clientLeft,d=Qc(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 _1(e,t,a){let o;if(t==="viewport"||t==="layoutViewport")o=PB(e,a,t);else if(t==="document")o=DB(pl(e));else if(kt(t))o=_B(t,a);else{const c=I1(e);o={x:t.x-c.x,y:t.y-c.y,width:t.width,height:t.height}}return zd(o)}function LB(e,t){const a=t.get(e);if(a)return a;let o=Lc(e,[],!1).filter(p=>kt(p)&&zs(p)!=="body"),c=null;const d=gr(e).position==="fixed";let f=d?eo(e):e;for(;kt(f)&&!Jl(f);){const p=gr(f),g=nv(f),v=c?c.position:d?"fixed":"";!g&&(v==="fixed"||v==="absolute"&&p.position==="static")?o=o.filter(b=>b!==f):c=p,f=eo(f)}return t.set(e,o),o}function zB(e){let{element:t,boundary:a,rootBoundary:o,strategy:c}=e;const f=[...a==="clippingAncestors"?gm(t)?[]:LB(t,this._c):[].concat(a),o],p=_1(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)}M=!1}try{o=new IntersectionObserver(O,{...I,root:d.ownerDocument})}catch{o=new IntersectionObserver(O,I)}o.observe(e)}const g=vn(e),v=()=>p(a);return g.addEventListener("resize",v),p(!0),()=>{g.removeEventListener("resize",v),f()}}function U1(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=Qv(e),y=c||d?[...v?Lc(v):[],...t?Lc(t):[]]:[];y.forEach(E=>{c&&E.addEventListener("scroll",a),d&&E.addEventListener("resize",a)});const b=v&&p?FB(v,a,d):null;let j=-1,w=null;f&&(w=new ResizeObserver(E=>{let[R]=E;R&&R.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?Ei(e):null;g&&k();function k(){const E=Ei(e);N&&!H1(N,E)&&a(),N=E,S=requestAnimationFrame(k)}return a(),()=>{var E;y.forEach(R=>{c&&R.removeEventListener("scroll",a),d&&R.removeEventListener("resize",a)}),b?.(),(E=w)==null||E.disconnect(),w=null,g&&cancelAnimationFrame(S)}}const $B=kB,qB=CB,GB=SB,KB=EB,YB=TB,XB=(e,t,a)=>{const o=new Map,c=a??{},d={...B1,...c.platform,_c:o};return wB(e,t,{...c,platform:d})};var QB=typeof document<"u",ZB=function(){},Km=QB?x.useLayoutEffect:ZB;function Ym(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(!Ym(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)&&!Ym(e[d],t[d]))return!1}return!0}return e!==e&&t!==t}function V1(e){return typeof window>"u"?1:(e.ownerDocument.defaultView||window).devicePixelRatio||1}function F1(e,t){const a=V1(e);return Math.round(t*a)/a}function Wv(e){const t=x.useRef(e);return Km(()=>{t.current=e}),t}function WB(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);Ym(j,o)||w(o);const[S,N]=x.useState(null),[k,E]=x.useState(null),R=x.useCallback(q=>{q!==I.current&&(I.current=q,N(q))},[]),C=x.useCallback(q=>{q!==M.current&&(M.current=q,E(q))},[]),A=d||S,D=f||k,I=x.useRef(null),M=x.useRef(null),O=x.useRef(y),_=g!=null,L=Wv(g),z=Wv(c),U=Wv(v),B=x.useCallback(()=>{if(!I.current||!M.current)return;const q={placement:t,strategy:a,middleware:j};z.current&&(q.platform=z.current),XB(I.current,M.current,q).then(G=>{const F={...G,isPositioned:U.current!==!1};Q.current&&!Ym(O.current,F)&&(O.current=F,Ns.flushSync(()=>{b(F)}))})},[j,t,a,z,U]);Km(()=>{v===!1&&O.current.isPositioned&&(O.current.isPositioned=!1,b(q=>({...q,isPositioned:!1})))},[v]);const Q=x.useRef(!1);Km(()=>(Q.current=!0,()=>{Q.current=!1}),[]),Km(()=>{if(A&&(I.current=A),D&&(M.current=D),A&&D){if(L.current)return L.current(A,D,B);B()}},[A,D,B,L,_]);const W=x.useMemo(()=>({reference:I,floating:M,setReference:R,setFloating:C}),[R,C]),Z=x.useMemo(()=>({reference:A,floating:D}),[A,D]),Y=x.useMemo(()=>{const q={position:a,left:0,top:0};if(!Z.floating)return q;const G=F1(Z.floating,y.x),F=F1(Z.floating,y.y);return p?{...q,transform:"translate("+G+"px, "+F+"px)",...V1(Z.floating)>=1.5&&{willChange:"transform"}}:{position:a,left:G,top:F}},[a,p,Z.floating,y.x,y.y]);return x.useMemo(()=>({...y,update:B,refs:W,elements:Z,floatingStyles:Y}),[y,B,W,Z,Y])}const JB=(e,t)=>{const a=$B(e);return{name:a.name,fn:a.fn,options:[e,t]}},eH=(e,t)=>{const a=qB(e);return{name:a.name,fn:a.fn,options:[e,t]}},tH=(e,t)=>({fn:YB(e).fn,options:[e,t]}),nH=(e,t)=>{const a=GB(e);return{name:a.name,fn:a.fn,options:[e,t]}},sH=(e,t)=>{const a=KB(e);return{name:a.name,fn:a.fn,options:[e,t]}};var Jv={exports:{}},ey={};var $1;function rH(){if($1)return ey;$1=1;var e=Od();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 ey.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:y,ey}var q1;function G1(){return q1||(q1=1,Jv.exports=rH()),Jv.exports}var ty=G1(),ny={exports:{}},sy={};var K1;function aH(){if(K1)return sy;K1=1;var e=Od(),t=G1();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 sy.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(!R){if(R=!0,C=I,I=j(I),w!==void 0&&N.hasValue){var M=N.value;if(w(M,I))return A=M}return A=I}if(M=A,o(C,I))return M;var O=j(I);return w!==void 0&&w(M,O)?(C=I,M):(C=I,A=O)}var R=!1,C,A,D=b===void 0?null:b;return[function(){return E(y())},D===null?void 0:function(){return E(D())}]},[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},sy}var Y1;function lH(){return Y1||(Y1=1,ny.exports=aH()),ny.exports}var oH=lH();const iH=dv(19)?uH:dH;function X1(e,t,a,o,c){return iH(e,t,a,o,c)}function cH(e,t,a,o,c){const d=x.useCallback(()=>t(e.getSnapshot(),a,o,c),[e,t,a,o,c]);return ty.useSyncExternalStore(e.subscribe,d,d)}Q4({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()}}),ty.useSyncExternalStore(e.subscribe,e.getSnapshot,e.getSnapshot))}});function uH(e,t,a,o,c){const d=X4();if(!d)return cH(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 dH(e,t,a,o,c){return oH.useSyncExternalStoreWithSelector(e.subscribe,e.getSnapshot,e.getSnapshot,d=>t(d,a,o,c))}class fH{constructor(t){sn(this,"subscribe",t=>(this.listeners.add(t),()=>{this.listeners.delete(t)}));sn(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 X1(this,t,a,o,c)}}class Zc extends fH{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),X1(this,this.selectors[t],a,o,c)}useContextCallback(t,a){x.useDebugValue(t);const o=Ie(a??Vt);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 pH={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 ry extends Zc{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:S1(),nested:c,triggerElements:f},pH);sn(this,"syncOpenEvent",(a,o)=>{(!a||!this.state.open||o!=null&&$z(o))&&(this.context.dataRef.current.openEvent=a?o:void 0)});sn(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)});sn(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 mH(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 ry({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};kt(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 Qd={tabIndex:-1,[bv]:""};function Q1(e){return t=>t==="touch"?e.current:!0}function ay(e,t=!1){const a=Pd(),o=Xc()!=null,c=Os(()=>e(a,o)).current;return mH({popupStore:c,treatPopupAsFloatingElement:t,floatingRootContext:c.state.floatingRootContext,floatingId:a,nested:o,onOpenChange:c.setOpen}),c}function ly({handle:e,store:t}){return De(()=>e.attachStore(t),[e,t]),null}function Z1(e){const t=e.context.triggerElements.size;e.select("open")&&e.state.triggerCount!==t&&e.set("triggerCount",t)}function hH(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),Z1(d))}o!==null&&e!==void 0&&(a.current={store:t,id:e,element:o},t.context.triggerElements.add(e,o),Z1(t))})}function oy(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 W1(e){let t=!1;return e.preventUnmountOnClose=()=>{t=!0},()=>t}function gH(e,t,a,o={}){const c=a.reason,d=c===Hs,f=t&&c===zm,p=!t&&(c===uo||c===Gc),g=W1(a);if(e.context.onOpenChange?.(t,a),a.isCanceled)return;o.onBeforeDispatch?.(),e.state.floatingRootContext.dispatchOpenChange(t,a);const v=()=>{const y=oy(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?Ns.flushSync(v):v()}function J1(e,t,a,o){const c=a.useState("isMountedByTrigger",e),d=hH(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 iy(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(Kn);e.setOpen(!1,j),j.isCanceled||e.update({activeTriggerId:null,activeTriggerElement:null})}})},[c,e,d,f,p,a])}function cy(e,t,a,o){const{mounted:c,setMounted:d,transitionStatus:f}=yi(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 Jr({enabled:c&&!e&&!g,open:e,ref:t.context.popupRef,onComplete(){e||v()}}),{forceUnmount:v,transitionStatus:f}}function uy(e,t){e.useSyncedValues(t),De(()=>()=>{e.update({activeTriggerProps:cn,inactiveTriggerProps:cn,popupProps:cn})},[e])}function eT(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 Xm{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 dy(e,t,a=!1){return{open:!1,openProp:void 0,mounted:!1,transitionStatus:void 0,floatingRootContext:new ry({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:cn,inactiveTriggerProps:cn,popupProps:cn}}const Zd=e=>e.triggerIdProp??e.activeTriggerId,fy=e=>e.openProp??e.open,tT=e=>(e.popupElement?.id??e.floatingId)||void 0;function nT(e,t){return t!==void 0&&fy(e)&&Zd(e)===t}function xH(e,t){return nT(e,t)?!0:t!==void 0&&fy(e)&&Zd(e)==null&&e.triggerCount===1}const py={open:fy,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:Zd,activeTriggerElement:e=>e.mounted?e.activeTriggerElement:null,popupId:tT,isTriggerActive:(e,t)=>t!==void 0&&Zd(e)===t,isOpenedByTrigger:(e,t)=>nT(e,t),isMountedByTrigger:(e,t)=>t!==void 0&&Zd(e)===t&&e.mounted,triggerProps:(e,t)=>t?e.activeTriggerProps:e.inactiveTriggerProps,triggerPopupId:(e,t)=>xH(e,t)?tT(e):void 0,popupProps:e=>e.popupProps,popupElement:e=>e.popupElement,positionerElement:e=>e.positionerElement};function sT(e){const t=x.useCallback(o=>e===void 0?Vt:e.subscribeStore(o),[e]),a=x.useCallback(()=>e===void 0?void 0:e.store,[e]);return ty.useSyncExternalStore(t,a,()=>e?.serverStore)}function rT(e){const{open:t=!1,onOpenChange:a,elements:o={}}=e,c=Pd(),d=Xc()!=null,f=Os(()=>new ry({open:t,transitionStatus:void 0,onOpenChange:a,referenceElement:o.reference??null,floatingElement:o.floating??null,triggerElements:new Xm,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=kt(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 bH(e){return vH(e,e.rootContext)}function vH(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=Ti(o),E=x.useMemo(()=>({reference:c,floating:d,domReference:f}),[c,d,f]),R=WB({...e,elements:{...E,...v&&{reference:v}}}),C=kt(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 D=x.useCallback(z=>{const U=kt(z)?{getBoundingClientRect:()=>z.getBoundingClientRect(),getClientRects:()=>z.getClientRects(),contextElement:z}:z;y(U),R.refs.setReference(U)},[R.refs]),I=x.useCallback(z=>{(kt(z)||z===null)&&(N.current=z,j(z)),(kt(R.refs.reference.current)||R.refs.reference.current===null||z!==null&&!kt(z))&&R.refs.setReference(z)},[R.refs,j]),M=x.useCallback(z=>{S(z),R.refs.setFloating(z)},[R.refs]),O=x.useMemo(()=>({...R.refs,setReference:I,setFloating:M,setPositionReference:D,domReference:N}),[R.refs,I,M,D]),_=x.useMemo(()=>({...R.elements,domReference:f}),[R.elements,f]),L=x.useMemo(()=>({...R,dataRef:t.context.dataRef,open:p,onOpenChange:t.setOpen,events:t.context.events,floatingId:g,refs:O,elements:_,nodeId:a,rootStore:t}),[R,O,_,a,t,p,g]);return De(()=>{f&&(N.current=f)},[f]),De(()=>{t.context.dataRef.current.floatingContext=L;const z=k?.nodesRef.current.find(U=>U.id===a);z&&(z.context=L)}),x.useMemo(()=>({...R,context:L,refs:O,elements:_,rootStore:t}),[R,O,_,L,t])}const my=wC&≷function yH(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=vn(j);function S(){const E=c.select("domReferenceElement");!c.select("open")&&on(E)&&E===ar(Ut(E))&&(p.current=!0,g.current=E)}function N(){v.current=!0}function k(){v.current=!1}return Ga(jt(w,"blur",S),my&&jt(w,"keydown",N,!0),my&&jt(w,"pointerdown",k,!0))},[c,a]),x.useEffect(()=>{if(!a)return;function j(w){if(w.reason===uo||w.reason===Gc){const S=c.select("domReferenceElement");kt(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=os(w.nativeEvent);if(kt(N)){if(my&&!w.relatedTarget){if(!v.current&&!Tm(N))return}else if(!Vz(N))return}const k=Cm(w.relatedTarget,c.context.triggerElements),{nativeEvent:E,currentTarget:R}=w,C=typeof o=="function"?o():o;if(c.select("open")&&k||C===0||C===void 0){c.setOpen(!0,Fe(zm,E,R));return}y.start(C,()=>{p.current||c.setOpen(!0,Fe(zm,E,R))})},onBlur(w){j();const S=w.relatedTarget,N=w.nativeEvent,k=kt(S)&&S.hasAttribute(Kd("focus-guard"))&&S.getAttribute("data-type")==="outside";y.start(0,()=>{const E=c.select("domReferenceElement"),R=ar(Ut(E));!S&&R===E||Ke(f.current.floatingContext?.refs.floating.current,R)||Ke(E,R)||k||Cm(S??R,c.context.triggerElements)||c.setOpen(!1,Fe(zm,N))})}}},[f,o,c,y]);return x.useMemo(()=>a?{reference:b,trigger:b}:{},[a,b])}class hy{constructor(){sn(this,"dispose",()=>{this.openChangeTimeout.clear(),this.restTimeout.clear()});sn(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 Wr,this.restTimeout=new Wr,this.handleCloseOptions=void 0}static create(){return new hy}}const Qm=new WeakMap;function Zm(e){if(!e.performedPointerEventsMutation)return;const t=e.pointerEventsScopeElement;t&&Qm.get(t)===e&&(e.pointerEventsScopeElement?.style.removeProperty("pointer-events"),e.pointerEventsReferenceElement?.style.removeProperty("pointer-events"),e.pointerEventsFloatingElement?.style.removeProperty("pointer-events"),Qm.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=Qm.get(a);d&&d!==e&&Zm(d),Zm(e),e.performedPointerEventsMutation=!0,e.pointerEventsScopeElement=a,e.pointerEventsReferenceElement=o,e.pointerEventsFloatingElement=c,Qm.set(a,e),a.style.pointerEvents="none",o.style.pointerEvents="auto",c.style.pointerEvents="auto"}function gy(e){const t=e.context.dataRef.current,a=Os(()=>t.hoverInteractionState??hy.create()).current;return t.hoverInteractionState||(t.hoverInteractionState=a),_v(t.hoverInteractionState.disposeEffect),t.hoverInteractionState}function lT(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=Ti(),b=Xc(),j=gy(d),w=Qs(),S=Ie(()=>c1(v.current.openEvent?.type,j.interactedInside)),N=Ie(()=>J4(v.current.openEvent?.type)),k=Ie(()=>{Zm(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()&&kt(g)&&p){const E=g,R=p,C=Ut(p),A=y?.nodesRef.current.find(O=>O.id===b)?.context?.elements.floating;A&&(A.style.pointerEvents="");const D=j.pointerEventsScopeElement!==R?j.pointerEventsScopeElement:null,I=A!==R?A:null,M=j.handleCloseOptions?.getScope?.()??D??I??E.closest("[data-rootownerid]")??C.body;return aT(j,{scopeElement:M,referenceElement:E,floatingElement:R}),()=>{k()}}},[a,f,g,p,j,N,y,b,k]),x.useEffect(()=>{if(!a)return;function E(){return!!(y&&b&&ao(y.nodesRef.current,b).length>0)}function R(O){const _=Ci(o,"close",j.pointerType),L=()=>{d.setOpen(!1,Fe(Hs,O)),y?.events.emit("floating.closed",O)};_?j.openChangeTimeout.start(_,L):(j.openChangeTimeout.clear(),L())}function C(O){const _=os(O);if(!Uz(_)){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 D(O){if(E()&&y){y.events.on("floating.closed",I);return}if(Cm(O.relatedTarget,d.context.triggerElements))return;const _=v.current.floatingContext?.nodeId??c,L=O.relatedTarget;if(!(y&&_&&kt(L)&&ao(y.nodesRef.current,_,!1).some(U=>Ke(U.context?.elements.floating,L)))){if(j.handler){j.handler(O);return}k(),N()&&!S()&&R(O)}}function I(O){!y||!b||E()||w.start(0,()=>{y.events.off("floating.closed",I),d.setOpen(!1,Fe(Hs,O)),y.events.emit("floating.closed",O)})}const M=p;return Ga(M&&jt(M,"mouseenter",A),M&&jt(M,"mouseleave",D),M&&jt(M,"pointerdown",C,!0),()=>{y?.events.off("floating.closed",I)})},[a,p,d,v,o,c,N,S,k,j,y,b,w])}const jH={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=jH,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,R=Ti(v),C=gy(N),A=x.useRef(!1),D=Yn(c),I=Yn(o),M=Yn(f),O=Yn(a),_=Yn(w),L=Yn(j),z=Ie(()=>c1(k.current.openEvent?.type,C.interactedInside)),U=Ie(()=>_.current?.()!==!1),B=Ie((Z,Y,q)=>{const G=N.context.triggerElements;if(G.hasElement(Y))return!Z||!Ke(Z,Y);if(!kt(q))return!1;const F=q;return G.hasMatchingElement($=>Ke($,F))&&(!Z||!Ke(Z,F))}),Q=Ie(()=>{if(!C.handler)return;Ut(N.select("domReferenceElement")).removeEventListener("mousemove",C.handler),C.handler=void 0}),W=Ie(()=>{Zm(C)});return y&&(C.handleCloseOptions=c?.__options),x.useEffect(()=>Q,[Q]),x.useEffect(()=>{if(!a)return;function Z(Y){Y.open?A.current=!1:(A.current=Y.reason===Hs,Q(),C.openChangeTimeout.clear(),C.restTimeout.clear(),C.blockMouseMove=!0,C.restTimeoutPending=!1)}return E.on("openchange",Z),()=>{E.off("openchange",Z)}},[a,E,C,Q]),x.useEffect(()=>{if(!a)return;function Z(X,re=!0){const P=Ci(I.current,"close",C.pointerType);P?C.openChangeTimeout.start(P,()=>{N.setOpen(!1,Fe(Hs,X)),R?.events.emit("floating.closed",X)}):re&&(C.openChangeTimeout.clear(),N.setOpen(!1,Fe(Hs,X)),R?.events.emit("floating.closed",X))}const Y=g.current??(y?N.select("domReferenceElement"):null);if(!kt(Y))return;function q(X){if(C.openChangeTimeout.clear(),C.blockMouseMove=!1,d&&!lo(C.pointerType))return;const re=i1(M.current),P=Ci(I.current,"open",C.pointerType),V=os(X),J=X.currentTarget??null,ie=N.select("domReferenceElement");let me=J;if(kt(V)&&!N.context.triggerElements.hasElement(V)){for(const ce of N.context.triggerElements.elements())if(Ke(ce,V)){me=ce;break}}kt(J)&&kt(ie)&&!N.context.triggerElements.hasElement(J)&&Ke(J,ie)&&(me=ie);const he=me==null?!1:B(ie,me,V),ae=N.select("open"),oe=L.current?.()??N.select("transitionStatus")==="ending",ee=!ae&&oe&&A.current,de=!he&&kt(me)&&kt(ie)&&Ke(ie,me)&&ee,K=re>0&&!P,be=he&&(ae||ee)||de,ne=!ae||he;if(be){U()&&N.setOpen(!0,Fe(Hs,X,me));return}K||(P?C.openChangeTimeout.start(P,()=>{ne&&U()&&N.setOpen(!0,Fe(Hs,X,me))}):ne&&U()&&N.setOpen(!0,Fe(Hs,X,me)))}function G(X){if(z()){W();return}Q();const re=N.select("domReferenceElement"),P=Ut(re);C.restTimeout.clear(),C.restTimeoutPending=!1;const V=k.current.floatingContext??b?.();if(Cm(X.relatedTarget,N.context.triggerElements))return;if(D.current&&V){N.select("open")||C.openChangeTimeout.clear();const ie=g.current;C.handler=D.current({...V,tree:R,x:X.clientX,y:X.clientY,onClose(){W(),Q(),O.current&&!z()&&ie===N.select("domReferenceElement")&&Z(X,!0)}}),P.addEventListener("mousemove",C.handler),C.handler(X);return}(C.pointerType!=="touch"||!Ke(N.select("floatingElement"),X.relatedTarget))&&Z(X)}function F(X){Ke(Y,X.relatedTarget)||(C.openChangeTimeout.clear(),C.restTimeout.clear(),C.restTimeoutPending=!1)}const $=S?jt(Y,"mouseout",F):void 0;return p?Ga(jt(Y,"mousemove",q,{once:!0}),jt(Y,"mouseenter",q),jt(Y,"mouseleave",G),$):Ga(jt(Y,"mouseenter",q),jt(Y,"mouseleave",G),$)},[Q,W,k,I,N,a,D,C,y,B,z,d,p,M,g,R,O,b,L,U,S]),x.useMemo(()=>{if(!a)return;function Z(Y){C.pointerType=Y.pointerType}return{onPointerDown:Z,onPointerEnter:Z,onMouseMove(Y){const{nativeEvent:q}=Y,G=Y.currentTarget,F=N.select("domReferenceElement"),$=N.select("open"),X=B(F,G,Y.target);if(d&&!lo(C.pointerType))return;if($&&X&&C.handleCloseOptions?.blockPointerEvents){const V=N.select("floatingElement");if(V){const J=C.handleCloseOptions?.getScope?.()??G.ownerDocument.body;aT(C,{scopeElement:J,referenceElement:G,floatingElement:V})}}const re=i1(M.current);if($&&!X||re===0||!X&&C.restTimeoutPending&&Y.movementX**2+Y.movementY**2<2)return;C.restTimeout.clear();function P(){if(C.restTimeoutPending=!1,z())return;const V=N.select("open");!C.blockMouseMove&&(!V||X)&&U()&&N.setOpen(!0,Fe(Hs,q,G))}C.pointerType==="touch"?Ns.flushSync(()=>{P()}):X&&$?P():(C.restTimeoutPending=!0,C.restTimeout.start(re,P))}}},[a,C,z,B,d,N,M,U])}const wH="Escape";function iT(e){return gl&&e.movementX===0&&e.movementY===0}function Wm(e,t,a){switch(e){case"vertical":return t;case"horizontal":return a;default:return t||a}}function Jm(e,t){return Wm(t,e===vv||e===km,e===xi||e===bi)}function xy(e,t,a){return Wm(t,e===km,a?e===xi:e===bi)||e==="Enter"||e===" "||e===""}function SH(e,t,a){return Wm(t,a?e===xi:e===bi,e===km)}function NH(e,t,a,o){const c=a?e===bi:e===xi,d=e===vv;return t==="both"||t==="horizontal"&&o?e===wH:Wm(t,c,d)}function cT(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:R,resetOnPointerLeave:C=!0,externalTree:A,grid:D}=t,I=D!=null,M="rootStore"in e?e.rootStore:e,O=M.useState("open"),_=M.useState("floatingElement"),L=M.useState("domReferenceElement"),z=M.context.dataRef,U=Em(_),B=kv(L),Q=Yn(U),W=Xc(),Z=Ti(A),Y=x.useRef(j),q=x.useRef(f??-1),G=x.useRef(null),F=x.useRef(!0),$=Ie(ge=>{c(q.current===-1?null:q.current,ge)}),X=x.useRef(!!_),re=x.useRef(O),P=x.useRef(!1),V=x.useRef(!1),J=x.useRef(null),ie=Yn(N),me=Yn(O),he=Yn(f),ae=Yn(C),oe=$c(),ee=$c(),de=Ie(()=>{function ge(Be){b?Z?.events.emit("virtualfocus",Be):J.current=Vm(Be,{sync:P.current,preventScroll:!0})}const Te=a.current[q.current],Oe=V.current;Te&&ge(Te),(P.current?Be=>Be():Be=>oe.request(Be))(()=>{const Be=a.current[q.current]||Te;if(!Be)return;Te||ge(Be),Ee&&(Oe||!F.current)&&Be.scrollIntoView?.({block:"nearest",inline:"nearest"})})});De(()=>{z.current.orientation=k},[z,k]),De(()=>{d&&(O&&_?(q.current=f??-1,Y.current&&f!=null&&(V.current=!0,$())):X.current&&(q.current=-1,$()))},[d,O,_,f,$]),De(()=>{if(d){if(!O){P.current=!1;return}if(_)if(o==null){if(P.current=!1,he.current!=null)return;if(X.current&&(q.current=-1,de()),(!re.current||!X.current)&&Y.current&&(G.current!=null||Y.current===!0&&G.current==null)){let ge=0;const Te=()=>{a.current[0]==null?(ge<2&&(ge?Ne=>ee.request(Ne):queueMicrotask)(Te),ge+=1):(q.current=G.current==null||xy(G.current,k,y)||v?Dm(a):Ov(a),G.current=null,$())};Te()}}else io(a.current,o)||(q.current=o,de(),V.current=!1)}},[d,O,_,o,he,v,a,k,y,$,de,ee]),De(()=>{if(!d||_||!Z||b||!X.current)return;const ge=Z.nodesRef.current,Te=ge.find(Be=>Be.id===W)?.context?.elements.floating,Oe=ar(Ut(L??Te??null)),Ne=ge.some(Be=>Be.context&&Ke(Be.context.elements.floating,Oe));Te&&!Ne&&F.current&&Te.focus({preventScroll:!0})},[d,_,L,Z,W,b]),De(()=>{re.current=O,X.current=!!_}),De(()=>{O||(G.current=null,Y.current=j)},[O,j]);const K=o!=null,be=Ie(ge=>{if(!me.current)return;const Te=a.current.indexOf(ge.currentTarget);Te!==-1&&(q.current!==Te||o!==Te)&&(q.current=Te,$(ge))}),ne=Ie(()=>E??Z?.nodesRef.current.find(ge=>ge.id===W)?.context?.dataRef?.current.orientation),ce=Ie(()=>Dm(a,ie.current)),we=Ie(ge=>{if(F.current=!1,P.current=!0,ge.which===229||!me.current&&ge.currentTarget===Q.current)return;if(v&&NH(ge.key,k,y,I)){Jm(ge.key,ne())||Ss(ge),M.setOpen(!1,Fe(Bv,ge.nativeEvent)),on(L)&&(b?Z?.events.emit("virtualfocus",L):L.focus());return}const Te=q.current,Oe=Dm(a,N),Ne=Ov(a,N);if(B||(ge.key==="Home"&&(Ss(ge),q.current=Oe,$(ge)),ge.key==="End"&&(Ss(ge),q.current=Ne,$(ge))),D!=null){const Be=D(ge,q.current,a,k,g,y,N,Oe,Ne);if(Be!=null&&(q.current=Be,$(ge)),k==="both")return}if(Jm(ge.key,k)){if(Ss(ge),O&&!b&&ar(ge.currentTarget.ownerDocument)===ge.currentTarget){q.current=xy(ge.key,k,y)?Oe:Ne,$(ge);return}xy(ge.key,k,y)?g?Te>=Ne?p&&Te!==a.current.length?q.current=-1:(P.current=!1,q.current=Oe):q.current=Ms(a.current,{startingIndex:Te,disabledIndices:N}):q.current=Math.min(Ne,Ms(a.current,{startingIndex:Te,disabledIndices:N})):g?Te<=Oe?p&&Te!==-1?q.current=a.current.length:(P.current=!1,q.current=Ne):q.current=Ms(a.current,{startingIndex:Te,decrement:!0,disabledIndices:N}):q.current=Math.max(Oe,Ms(a.current,{startingIndex:Te,decrement:!0,disabledIndices:N})),io(a.current,q.current)&&(q.current=-1),$(ge)}}),Ee=x.useMemo(()=>({onFocus(Te){P.current=!0,be(Te)},onClick:({currentTarget:Te})=>Te.focus({preventScroll:!0}),onMouseMove(Te){iT(Te)||(P.current=!0,V.current=!1,w&&be(Te))},onPointerLeave(Te){if(!me.current||!F.current||Te.pointerType==="touch")return;P.current=!0;const Oe=Te.relatedTarget;if(!(!w||a.current.includes(Oe))&&ae.current&&(J.current?.(),J.current=null,q.current=-1,$(Te),!b)){const Ne=Q.current,Be=ar(Ut(Ne));Ne&&Ke(Ne,Be)&&Ne.focus({preventScroll:!0})}}}),[be,me,Q,w,a,$,ae,b]),ve=x.useMemo(()=>b&&O&&K&&{"aria-activedescendant":`${R}-${o}`},[b,O,K,R,o]),ke=x.useMemo(()=>({...B?{}:ve,onKeyDown(ge){if(ge.key==="Tab"&&ge.shiftKey&&O&&!b){const Te=os(ge.nativeEvent);if(Te&&!Ke(Q.current,Te))return;Ss(ge),M.setOpen(!1,Fe(fo,ge.nativeEvent)),on(L)&&L.focus();return}we(ge)},onPointerMove(ge){iT(ge)||(F.current=!0)}}),[ve,we,Q,B,M,O,b,L]),Ce=x.useMemo(()=>{function ge(Ne){M.setOpen(!0,Fe(Bv,Ne.nativeEvent,Ne.currentTarget))}function Te(Ne){j==="auto"&&Rm(Ne.nativeEvent)&&(Y.current=!b)}function Oe(Ne){Y.current=j,j==="auto"&&Cv(Ne.nativeEvent)&&(Y.current=!0)}return{onKeyDown(Ne){const Be=M.select("open");F.current=!1;const Qe=Ne.key.startsWith("Arrow"),Rt=SH(Ne.key,ne(),y),Wt=Jm(Ne.key,k),Dt=(v?Rt:Wt)||Ne.key==="Enter"||Ne.key.trim()==="";if(b&&Be)return we(Ne);if(!(!Be&&!S&&Qe)){if(Dt){const ct=Jm(Ne.key,ne());G.current=v&&ct?null:Ne.key}if(v){Rt&&(Ss(Ne),Be?(q.current=ce(),$(Ne)):ge(Ne));return}Wt&&(he.current!=null&&(q.current=he.current),Ss(Ne),!Be&&S?ge(Ne):we(Ne),Be&&$(Ne))}},onFocus(Ne){M.select("open")&&!b&&(q.current=-1,$(Ne))},onPointerDown:Oe,onPointerEnter:Oe,onMouseDown:Te,onClick:Te}},[we,j,ce,v,$,M,S,k,ne,y,he,b]),Se=x.useMemo(()=>({...ve,...Ce}),[ve,Ce]);return x.useMemo(()=>d?{reference:Se,floating:ke,item:Ee,trigger:Ce}:{},[d,Se,ke,Ce,Ee])}function uT(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 D(Q){return o?.current[Q]}function I(Q){const W=D(Q);return W&&!Im(W)||W?.matches(":disabled")?!1:f==null||!co(Er,Q,f)}function M(Q,W,Z=0){if(Q.length===0)return-1;const Y=(Z%Q.length+Q.length)%Q.length,q=W.toLowerCase();for(let G=0;G0&&A.key===" "&&(Ss(A),p?.(!0)),S.current.length>0&&S.current[0]!==" "&&M(O,S.current)===-1&&A.key!==" "&&p?.(!1),O==null||A.key.length!==1||A.ctrlKey||A.metaKey||A.altKey)return;j&&A.key!==" "&&(Ss(A),p?.(!0));const _=S.current==="";_&&(N.current=y??c??-1),O.every((Q,W)=>Q&&I(W)?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 U=((_?y??c??-1:N.current)??0)+1,B=M(O,S.current,U);B!==-1?(d?.(B),k.current=B):A.key!==" "&&(S.current="",p?.(!1))}),R=Ie(A=>{const D=A.relatedTarget,I=b.select("domReferenceElement"),M=b.select("floatingElement");Ke(I,D)||Ke(M,D)||(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:R}),[E,R]);return x.useMemo(()=>g?{reference:C,floating:C}:{},[g,C])}const dT=.1,kH=dT*dT,gn=.5;function eh(e,t,a,o,c,d){return o>=t!=d>=t&&e<=(c-a)*(t-o)/(d-o)+a}function th(e,t,a,o,c,d,f,p,g,v){let y=!1;return eh(e,t,a,o,c,d)&&(y=!y),eh(e,t,c,d,f,p)&&(y=!y),eh(e,t,f,p,g,v)&&(y=!y),eh(e,t,g,v,a,o)&&(y=!y),y}function CH(e,t,a){return e>=a.x&&e<=a.x+a.width&&t>=a.y&&t<=a.y+a.height}function nh(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 fT(e={}){const{blockPointerEvents:t=!1}=e,a=new Wr,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(R,C){const A=performance.now(),D=A-N;if(w===null||S===null||D===0)return w=R,S=C,N=A,!1;const I=R-w,M=C-S,O=I*I+M*M,_=D*D*kH;return w=R,S=C,N=A,O<_}function E(){a.clear(),g()}return function(C){a.clear();const A=p.domReference,D=p.floating;if(!A||!D||b==null||c==null||d==null)return;const{clientX:I,clientY:M}=C,O=os(C),_=C.type==="mouseleave",L=Ke(D,O),z=Ke(A,O);if(L&&(j=!0,!_))return;if(z&&(j=!1,!_)){j=!0;return}if(_&&kt(C.relatedTarget)&&Ke(D,C.relatedTarget))return;function U(){return!!(y&&ao(y.nodesRef.current,v).length>0)}function B(){U()||E()}if(U())return;const Q=A.getBoundingClientRect(),W=D.getBoundingClientRect(),Z=c>W.right-W.width/2,Y=d>W.bottom-W.height/2,q=W.width>Q.width,G=W.height>Q.height,F=(q?Q:W).left,$=(q?Q:W).right,X=(G?Q:W).top,re=(G?Q:W).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){B();return}let P=!1;switch(b){case"top":P=nh(I,M,F,Q.top+1,$,W.bottom-1);break;case"bottom":P=nh(I,M,F,W.top+1,$,Q.bottom-1);break;case"left":P=nh(I,M,W.right-1,re,Q.left+1,X);break;case"right":P=nh(I,M,Q.right-1,re,W.left+1,X);break}if(P)return;if(j&&!CH(I,M,Q)){B();return}if(!_&&k(I,M)){B();return}let V=!1;switch(b){case"top":{const J=q?gn/2:gn*4,ie=q||Z?c+J:c-J,me=q?c-J:Z?c+J:c-J,he=d+gn+1,ae=Z||q?W.bottom-gn:W.top,oe=Z?q?W.bottom-gn:W.top:W.bottom-gn;V=th(I,M,ie,he,me,he,W.left,ae,W.right,oe);break}case"bottom":{const J=q?gn/2:gn*4,ie=q||Z?c+J:c-J,me=q?c-J:Z?c+J:c-J,he=d-gn,ae=Z||q?W.top+gn:W.bottom,oe=Z?q?W.top+gn:W.bottom:W.top+gn;V=th(I,M,ie,he,me,he,W.left,ae,W.right,oe);break}case"left":{const J=G?gn/2:gn*4,ie=G||Y?d+J:d-J,me=G?d-J:Y?d+J:d-J,he=c+gn+1,ae=Y||G?W.right-gn:W.left,oe=Y?G?W.right-gn:W.left:W.right-gn;V=th(I,M,ae,W.top,oe,W.bottom,he,ie,he,me);break}case"right":{const J=G?gn/2:gn*4,ie=G||Y?d+J:d-J,me=G?d-J:Y?d+J:d-J,he=c-gn,ae=Y||G?W.left+gn:W.right,oe=Y?G?W.left+gn:W.right:W.left+gn;V=th(I,M,he,ie,he,me,ae,W.top,oe,W.bottom);break}}V?j||a.start(40,B):B()}};return o.__options={...e,blockPointerEvents:t},o}const TH={...py,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 EH extends Zc{constructor(a,o,c){const d=new Xm;super(RH(a,d,o,c),AH(d),TH);sn(this,"setOpen",(a,o)=>{gH(this,a,o,{extraState:{openChangeReason:o.reason}})})}cancelPendingOpen(a){this.state.floatingRootContext.dispatchOpenChange(!1,Fe(uo,a))}}function RH(e,t,a,o=!1){return{...dy(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 AH(e){return{popupRef:x.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerElements:e}}const OH=Hm(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=ay((z,U)=>new EH({open:o,openProp:c,activeTriggerId:j,triggerIdProp:b},z,U));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"),R=S.useState("mounted"),C=S.useState("payload");S.useSyncedValues({trackCursorAxis:f,disableHoverablePopup:d,disabled:a}),iy(S,{closeOnActiveTriggerUnmount:!0});const{forceUnmount:A,transitionStatus:D}=cy(k,S),I=S.useState("isInstantPhase"),M=S.useState("instantType"),O=S.useState("lastOpenChangeReason"),_=x.useRef(null);De(()=>{N&&a&&S.setOpen(!1,Fe(h4))},[N,a,S]),De(()=>{D==="ending"&&O===Kn||D!=="ending"&&I?(M!=="delay"&&(_.current=M),S.set("instantType","delay")):_.current!==null&&(S.set("instantType",_.current),_.current=null)},[D,I,O,M,S]),De(()=>{k&&E==null&&S.set("payload",void 0)},[S,E,k]),x.useImperativeHandle(p,()=>({unmount:A,close:()=>S.setOpen(!1,Fe(Hv))}),[A,S]);const L=k||R||!a&&f!=="none";return s.jsxs(o1.Provider,{value:S,children:[y&&s.jsx(ly,{handle:y,store:S}),L&&s.jsx(MH,{store:S,disabled:a,trackCursorAxis:f}),typeof w=="function"?w({payload:C}):w]})});function MH({store:e,disabled:t,trackCursorAxis:a}){const o=e.useState("floatingRootContext"),c=Xd(o,{enabled:!t,referencePress:()=>e.select("closeOnClick")}),d=xB(o,{enabled:!t&&a!=="none",axis:a==="none"?void 0:a}),f=x.useMemo(()=>Kr(d.reference,c.reference),[d.reference,c.reference]);return uy(e,{activeTriggerProps:f,inactiveTriggerProps:f,popupProps:c.floating??cn}),null}const pT=x.createContext(void 0);function DH(){return x.useContext(pT)}const IH=600,mT="data-base-ui-tooltip-trigger";function hT(e){if("composedPath"in e){const a=e.composedPath();for(let o=0;ok.select("transitionStatus")==="ending",shouldOpen(){return!F.current}}),ie=yH(A,{enabled:!Z}).reference,me=de=>{const K=F.current,be=hT(de),ne=V(be),ce=D.current,we=ce&&be&&Ke(ce,be);if(ne&&k.select("open")&&k.select("lastOpenChangeReason")===Hs){k.setOpen(!1,Fe(Hs,de));return}if(K&&!ne&&we&&!Y.current&&!k.select("open")&&ce&&lo(X.current)){const Ee=()=>{!F.current&&!Y.current&&!k.select("open")&&k.setOpen(!0,Fe(Hs,de,ce))},ve=re();ve===0?($.clear(),Ee()):$.start(ve,Ee)}},he=k.useState("triggerProps",O);return bt("button",t,{state:{open:C},ref:[a,M,D],props:[J,ie,O||q!=="none"?he:void 0,{onMouseOver(de){me(de.nativeEvent)},onFocus(de){P(hT(de.nativeEvent))&&de.preventBaseUIHandler()},onMouseLeave(){F.current=!1,$.clear(),X.current=void 0},onPointerEnter(de){X.current=de.pointerType},onPointerDown(de){X.current=de.pointerType,k.set("closeOnClick",y),y&&!k.select("open")&&k.cancelPendingOpen(de.nativeEvent)},onClick(de){y&&!k.select("open")&&k.cancelPendingOpen(de.nativeEvent)},id:E,[Sv]:Z?"":void 0,[mT]:Z?void 0:""},w],stateAttributesMapping:yv})}),gT=x.createContext(void 0);function LH(){const e=x.useContext(gT);if(e===void 0)throw new Error(rn(70));return e}const zH=x.forwardRef(function(t,a){const{children:o,container:c,className:d,render:f,style:p,...g}=t,{node:v,subtree:y}=w1({container:c,ref:a,componentProps:t,elementProps:g});return!y&&!v?null:s.jsxs(x.Fragment,{children:[y,v&&Ns.createPortal(o,v)]})}),BH=x.forwardRef(function(t,a){const{keepMounted:o=!1,...c}=t;return Gd().useState("mounted")||o?s.jsx(gT.Provider,{value:o,children:s.jsx(zH,{ref:a,...c})}):null}),xT=x.createContext(void 0);function bT(){const e=x.useContext(xT);if(e===void 0)throw new Error(rn(71));return e}const HH=x.createContext(void 0);function Wd(){return x.useContext(HH)?.direction??"ltr"}const UH=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"}=oo(e,t)||{};if(v==null)return{};const j=OC(y),w={x:a,y:o},S=Rv(c),N=Ev(S),k=await f.getDimensions(v),E=S==="y",R=E?"top":"left",C=E?"bottom":"right",A=E?"clientHeight":"clientWidth",D=d.reference[N]+d.reference[S]-w[S]-d.floating[N],I=w[S]-d.reference[S],M=b==="real"?await f.getOffsetParent?.(v):p.floating;let O=p.floating[A]||d.floating[N];(!O||!await f.isElement?.(M))&&(O=p.floating[A]||d.floating[N]);const _=D/2-I/2,L=O/2-k[N]/2-1,z=Math.min(j[R],L),U=Math.min(j[C],L),B=z,Q=O-k[N]-U,W=O/2-k[N]/2+_,Z=EC(B,W,Q),Y=!g.arrow&&vl(c)!=null&&W!==Z&&d.reference[N]/2-(W{const{name:a,fn:o}=UH(e);return{name:a,fn:o,options:[e,t]}},FH={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}}}},$H={sideX:"left",sideY:"top"},qH="--available-width",GH="--available-height",KH="--anchor-width",YH="--anchor-height",XH="--transform-origin",vT=qH,yT=GH;function jT(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 wT(e,t,a){const{rects:o,placement:c}=e;return{side:jT(t,Qr(c),a),align:vl(c)||"center",anchor:{width:o.reference.width,height:o.reference.height},positioner:{width:o.floating.width,height:o.floating.height}}}function sh(e){return QH(e,bH)}function QH(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:R,nodeId:C,adaptiveOrigin:A,lazyFlip:D=!1,externalTree:I}=e,[M,O]=x.useState(null);!k&&M!==null&&O(null);const _=E.side||"flip",L=E.align||"flip",z=E.fallbackAxisSide||"end",U=R?.crossAxis??!1,B=R?.rootBoundary,Q=typeof a=="function"?a:void 0,W=Ie(Q),Z=Q?W:a,Y=Yn(a),q=Yn(k),F=Wd()==="rtl",$=M||{top:"top",right:"right",bottom:"bottom",left:"left","inline-end":F?"left":"right","inline-start":F?"right":"left"}[c],X=f==="center"?$:`${$}-${f}`;let re=v;typeof re=="number"?re={top:re,right:re,bottom:re,left:re}:re&&(re={top:re.top||0,right:re.right||0,bottom:re.bottom||0,left:re.left||0});const P=1,V=c==="bottom"?P:0,J=c==="top"?P:0,ie=c==="right"?P:0,me=c==="left"?P:0,he={boundary:g==="clipping-ancestors"?"clippingAncestors":g,padding:re},ae=x.useRef(null),oe=Yn(d),ee=Yn(p),de=typeof d!="function"?d:0,K=typeof p!="function"?p:0,be=[];w&&be.push(w),be.push(JB(tt=>{const Tt=wT(tt,c,F),Ht=typeof oe.current=="function"?oe.current(Tt):oe.current,Zn=typeof ee.current=="function"?ee.current(Tt):ee.current;return{mainAxis:Ht,crossAxis:Zn,alignmentAxis:Zn}},[de,K,F,c]));const ne=L==="none"&&_!=="shift",ce=!ne&&(y||U||_==="shift"),we=_==="none"?null:nH({...he,padding:{top:re.top+P+V,right:re.right+P+me,bottom:re.bottom+P+J,left:re.left+P+ie},mainAxis:!U&&_==="flip",crossAxis:L==="flip"?"alignment":!1,fallbackAxisSideDirection:z}),Ee=ne?null:eH({...he,rootBoundary:B,mainAxis:L!=="none",crossAxis:ce,limiter:y||U?void 0:tH(tt=>{if(!ae.current)return{};const{width:Tt,height:Ht}=ae.current.getBoundingClientRect(),Zn=Zr(Qr(tt.placement)),zn=Zn==="y"?Tt:Ht,Bn=Zn==="y"?re.left+re.right:re.top+re.bottom;return{offset:zn/2+Bn/2}})},[he,y,U,B,re,L]);_==="shift"||L==="shift"||f==="center"?be.push(Ee,we):be.push(we,Ee),be.push(sH({...he,apply({elements:{floating:tt},availableWidth:Tt,availableHeight:Ht,rects:Zn}){if(!q.current)return;const zn=tt.style;zn.setProperty(vT,`${Tt}px`),zn.setProperty(yT,`${Ht}px`);const Bn=vn(tt).devicePixelRatio||1,{x:Tn,y:Qt,width:rs,height:St}=Zn.reference,ht=(Math.round((Tn+rs)*Bn)-Math.round(Tn*Bn))/Bn,vt=(Math.round((Qt+St)*Bn)-Math.round(Qt*Bn))/Bn;zn.setProperty(KH,`${ht}px`),zn.setProperty(YH,`${vt}px`)}}),VH(tt=>({element:ae.current||Ut(tt.elements.floating).createElement("div"),padding:ae.current?b:0,offsetParent:"floating"}),[b]),{name:"transformOrigin",fn(tt){const{elements:{floating:Tt},middlewareData:Ht,placement:Zn,platform:zn,rects:Bn,y:Tn}=tt,Qt=Qr(Zn),rs=vl(Zn),St=Zr(Qt)==="y",ht=ae.current,vt=typeof d=="function"?d(wT(tt,c,F)):d;let yt;if(!ht&&rs&&Math.abs(St?Ht.shift?.x||0:Ht.shift?.y||0)<=1)yt=rs==="start"===(St&&zn.isRTL?.(Tt)===!0)?"100%":"0%";else{const nr=St?Ht.arrow?.x||0:Ht.arrow?.y||0,Pr=St?ht?.clientWidth||0:ht?.clientHeight||0;yt=`${nr+Pr/2}px`}let jr=Qt==="top"||Qt==="left"?`calc(100% + ${vt}px)`:`${-vt}px`;return ce&&St&&Math.abs(Ht.shift?.y||0)>vt&&(jr=`${Bn.reference.y+Bn.reference.height/2-Tn}px`),Tt.style.setProperty(XH,St?`${yt} ${jr}`:`${jr} ${yt}`),{}}},FH,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:ke,elements:Ce,x:Se,y:ge,middlewareData:Te,update:Oe,placement:Ne,context:Be,isPositioned:Qe,floatingStyles:Rt}=t({rootContext:N,open:S?k:void 0,placement:X,middleware:be,strategy:o,whileElementsMounted:S?void 0:(...tt)=>U1(...tt,ve),nodeId:C,externalTree:I}),{sideX:Wt,sideY:Dt}=Te.adaptiveOrigin||$H,ct=Qe?o:"fixed",$n=x.useMemo(()=>{let tt;return Qe?A?tt={position:ct,[Wt]:Se,[Dt]:ge}:tt={...Rt,position:ct}:tt={position:ct,top:0,left:0},tt[vT]="100vw",tt[yT]="100vh",Qe||(tt.opacity=0),tt},[A,ct,Wt,Se,Dt,ge,Rt,Qe]),us=x.useRef(null);De(()=>{if(!k)return;const tt=Y.current,Tt=typeof tt=="function"?tt():tt,Zn=(ST(Tt)?Tt.current:Tt)||null||null;Zn!==us.current&&(ke.setPositionReference(Zn),us.current=Zn)},[k,ke,Z,Y]),x.useEffect(()=>{if(!k)return;const tt=Y.current;typeof tt!="function"&&ST(tt)&&tt.current!==us.current&&(ke.setPositionReference(tt.current),us.current=tt.current)},[k,ke,Z,Y]),x.useEffect(()=>{if(S&&k&&Ce.reference&&Ce.floating)return U1(Ce.reference,Ce.floating,Oe,ve)},[S,k,Ce,Oe,ve]);const qn=Qr(Ne),gs=jT(c,qn,F),lt=vl(Ne)||"center",Bt=!!Te.hide?.referenceHidden;De(()=>{D&&k&&Qe&&qn!==$&&O(qn)},[D,k,Qe,qn,$]);const Ln=x.useMemo(()=>({position:"absolute",top:Te.arrow?.y,left:Te.arrow?.x}),[Te.arrow]),Jt=Te.arrow?.centerOffset!==0;return x.useMemo(()=>({positionerStyles:$n,arrowStyles:Ln,arrowRef:ae,arrowUncentered:Jt,side:gs,align:lt,physicalSide:qn,anchorHidden:Bt,refs:ke,context:Be,isPositioned:Qe,update:Oe}),[$n,Ln,ae,Jt,gs,lt,qn,Bt,ke,Be,Qe,Oe])}function ST(e){return e!=null&&"current"in e}function Jd(e){return e==="starting"?oB:cn}function rh(e,t,{styles:a,transitionStatus:o,props:c,refs:d,hidden:f,inert:p=!1}){const g={...a};return p&&(g.pointerEvents="none"),bt("div",e,{state:t,ref:d,props:[{role:"presentation",hidden:f,style:g},Jd(o),c],stateAttributesMapping:Uc})}const ZH=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=v1,style:E,...R}=t,C=Gd(),A=LH(),D=C.useState("open"),I=C.useState("mounted"),M=C.useState("trackCursorAxis"),O=C.useState("disableHoverablePopup"),_=C.useState("floatingRootContext"),L=C.useState("instantType"),z=C.useState("transitionStatus"),U=C.useState("adaptiveOrigin"),B=sh({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:U}),Q=x.useMemo(()=>({open:D,side:B.side,align:B.align,anchorHidden:B.anchorHidden,instant:M!=="none"?"tracking-cursor":L}),[D,B.side,B.align,B.anchorHidden,M,L]),W=rh(t,Q,{styles:B.positionerStyles,transitionStatus:z,props:R,refs:[a,C.useStateSetter("positionerElement")],hidden:!I,inert:!D||M==="both"||O});return s.jsx(xT.Provider,{value:B,children:W})}),WH=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t,p=Gd(),{side:g,align:v}=bT(),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");Jr({open:y,ref:p.context.popupRef,onComplete(){y&&p.context.onOpenChangeComplete?.(!0)}}),lT(S,{enabled:!N,closeDelay:k});const E=p.useStateSetter("popupElement");return bt("div",t,{state:{open:y,side:g,align:v,instant:b,transitionStatus:j},ref:[a,p.context.popupRef,E],props:[Qd,w,Jd(j),f],stateAttributesMapping:wv})}),JH=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t,p=Gd(),{arrowRef:g,side:v,align:y,arrowUncentered:b,arrowStyles:j}=bT(),w=p.useState("open"),S=p.useState("instantType");return bt("div",t,{state:{open:w,side:v,align:y,uncentered:b,instant:S},ref:[a,g],props:[{style:j,"aria-hidden":!0},f],stateAttributesMapping:Uc})}),eU=function(t){const{delay:a,closeDelay:o,timeout:c=400}=t,d=x.useMemo(()=>({open:a,close:o}),[a,o]);return s.jsx(pT.Provider,{value:a,children:s.jsx(tB,{delay:d,timeoutMs:c,children:t.children})})};function ah(e){return dv(19)?e:e?"true":void 0}function tU(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 nU(e){return s.jsx(eU,{"data-slot":"tooltip-provider",...e})}function Ri(e){return s.jsx(OH,{"data-slot":"tooltip",...e})}function Ai(e){return s.jsx(_H,{"data-slot":"tooltip-trigger",...e})}function Oi({className:e,sideOffset:t=8,side:a="top",children:o,...c}){return s.jsx(BH,{children:s.jsx(ZH,{sideOffset:t,side:a,className:"z-[35]",children:s.jsx(WH,{"data-slot":"tooltip-content",className:Ve("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 sU({className:e,...t}){return s.jsx(JH,{className:Ve("size-2 rotate-45 rounded-[1px] bg-primary","data-[side=top]:-bottom-1 data-[side=bottom]:-top-1",e),...t})}const NT=x.createContext(void 0);function Wc(e){const t=x.useContext(NT);if(!e&&t===void 0)throw new Error(rn(27));return t}const kT=x.forwardRef(function(t,a){const{render:o,className:c,style:d,forceRender:f=!1,...p}=t,g=Wc(),v=g.useState("open"),y=g.useState("nested"),b=g.useState("mounted"),j=g.useState("transitionStatus");return bt("div",t,{state:{open:v,transitionStatus:j},ref:[g.context.backdropRef,a],stateAttributesMapping:wv,props:[{role:"presentation",hidden:!b,style:{userSelect:"none",WebkitUserSelect:"none"}},p],enabled:f||!y})}),CT=x.forwardRef(function(t,a){const{render:o,className:c,style:d,disabled:f=!1,nativeButton:p=!0,...g}=t,v=Wc(),y=v.useState("open"),{getButtonProps:b,buttonRef:j}=Yr({disabled:f,native:p}),w={disabled:f};function S(N){y&&v.setOpen(!1,Fe(zv,N.nativeEvent))}return bt("button",t,{state:w,ref:[a,j],props:[{onClick:S},g,b]})}),TT=x.createContext(void 0);function rU(){const e=x.useContext(TT);if(e===void 0)throw new Error(rn(26));return e}const by="ArrowUp",vy="ArrowDown",yy="ArrowLeft",jy="ArrowRight",wy="Home",Sy="End",lh=new Set([by,vy,yy,jy,wy,Sy]),ET="Shift",aU=[ET,"Control","Alt","Meta"];function lU(e){return on(e)&&e.tagName==="INPUT"}function RT(e){return!!(lU(e)&&e.selectionStart!=null||on(e)&&e.tagName==="TEXTAREA")}function AT(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=OT(e,t,"top"),v=oh(e),y=oh(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 OT(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 oh(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 oU="--nested-dialogs",iU="data-nested-dialog-open",cU={...Uc,...ro,nestedDialogOpen(e){return e?{[iU]:""}:null}},MT=x.forwardRef(function(t,a){const{render:o,className:c,style:d,finalFocus:f,initialFocus:p,...g}=t,v=Wc(),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"),R=v.useState("open"),C=v.useState("openMethod"),A=v.useState("titleElementId"),D=v.useState("transitionStatus"),I=v.useState("role"),M=j.useState("floatingId");rU(),Jr({open:R,ref:v.context.popupRef,onComplete(){R&&v.context.onOpenChangeComplete?.(!0)}});const O=p===void 0?Q1(v.context.popupRef):p,_=E>0,L=v.useStateSetter("popupElement"),U=bt("div",t,{state:{open:R,nested:k,transitionStatus:D,nestedDialogOpen:_},props:[w,{id:M,"aria-labelledby":A,"aria-describedby":y,role:I,...Qd,hidden:!N,onKeyDown(B){lh.has(B.key)&&B.stopPropagation()},style:{[oU]:E}},g],ref:[a,v.context.popupRef,L],stateAttributesMapping:cU});return s.jsx($m,{context:j,openInteractionType:C,disabled:!N,closeOnFocusOut:!b,initialFocus:O,returnFocus:f,modal:S!==!1,restoreFocus:"popup",children:U})}),ih=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}})}),DT=x.forwardRef(function(t,a){const{keepMounted:o=!1,...c}=t,d=Wc(),f=d.useState("mounted"),p=d.useState("modal"),g=d.useState("open");return f||o?s.jsx(TT.Provider,{value:o,children:s.jsxs(Fm,{ref:a,...c,children:[f&&p===!0&&s.jsx(ih,{ref:d.context.internalBackdropRef,inert:ah(!g)}),t.children]})}):null});let IT={},PT={},_T="";function ch(e,t){return Md(e)?e:t}function LT(e,t,a){return/hidden|clip/.test(e.getComputedStyle(ch(t,a)).overflowY)}function uU(e){if(typeof document>"u")return!1;const t=Ut(e);return vn(t).innerWidth-t.documentElement.clientWidth>0}function dU(e){if(!(typeof CSS<"u"&&CSS.supports&&CSS.supports("scrollbar-gutter","stable"))||typeof document>"u")return!1;const a=Ut(e),o=a.documentElement,c=a.body,d=ch(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 fU(e){const t=Ut(e),a=t.documentElement,o=t.body,c=ch(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 pU(e){const t=Ut(e),a=t.documentElement,o=t.body,c=vn(a);let d=0,f=0,p=!1;const g=Fa.create();if(gl&&(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,IT={scrollbarGutter:a.style.scrollbarGutter,overflowY:a.style.overflowY,overflowX:a.style.overflowX},_T=a.style.scrollBehavior,PT={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 R=a.scrollHeight>a.clientHeight,C=a.scrollWidth>a.clientWidth,A=w.overflowY==="scroll"||S.overflowY==="scroll",D=w.overflowX==="scroll"||S.overflowX==="scroll",I=Math.max(0,c.innerWidth-o.clientWidth),M=Math.max(0,c.innerHeight-o.clientHeight),O=parseFloat(S.marginTop)+parseFloat(S.marginBottom),_=parseFloat(S.marginLeft)+parseFloat(S.marginRight),L=ch(a,o);if(p=dU(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"}),(R||A)&&(a.style.overflowY="scroll"),(C||D)&&(a.style.overflowX="scroll"),Object.assign(o.style,{position:"relative",height:O||M?`calc(100dvh - ${O+M}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,IT),Object.assign(o.style,PT),p||(a.scrollTop=d,a.scrollLeft=f,a.removeAttribute("data-base-ui-scroll-locked"),a.style.scrollBehavior=_T)}function b(){y(),g.request(v)}v();const j=jt(c,"resize",b);return()=>{g.cancel(),y(),typeof c.removeEventListener=="function"&&j()}}class mU{constructor(){sn(this,"lockCount",0);sn(this,"restore",null);sn(this,"timeoutLock",Wr.create());sn(this,"timeoutUnlock",Wr.create());sn(this,"release",()=>{this.lockCount-=1,this.lockCount===0&&this.restore&&this.timeoutUnlock.start(0,this.unlock)});sn(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=Ut(t),o=a.documentElement,c=a.body,d=vn(o);if(LT(d,o,c)){const p=new d.MutationObserver(()=>{LT(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=Ld||!uU(t);this.restore=f?fU(t):pU(t)}}const hU=new mU;function zT(e=!0,t=null){De(()=>{if(e)return hU.acquire(t)},[e,t])}function gU({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=Xd(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=os(S);if(j&&!c){if(d){const k=e.context.internalBackdropRef.current,E=e.context.backdropRef.current;return k||E?k===N||E===N||Ke(N,f)&&!N?.hasAttribute("data-base-ui-portal"):!0}return!0}return!1},escapeKey:j});return zT(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]),uy(e,{activeTriggerProps:w.reference,inactiveTriggerProps:w.trigger,popupProps:w.floating,nestedOpenDialogCount:g,nestedOpenDrawerCount:y}),null}const xU={...py,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 bU extends Zc{constructor(a,o,c){const d=new Xm,f=vU(a,d,o,c);super(f,yU(d),xU);sn(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(oy(this.state,a,o.trigger)))})}}function vU(e,t,a,o=!1){return{...dy(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 yU(e){return{popupRef:x.createRef(),backdropRef:x.createRef(),internalBackdropRef:x.createRef(),outsidePressEnabledRef:{current:!0},triggerElements:e,onOpenChange:void 0,onOpenChangeComplete:void 0}}function BT(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",R=Wc(!0),C=R!=null,A={modal:N,disablePointerDismissal:k,nested:C,role:E},D=ay((z,U)=>new bU({open:c,openProp:o,activeTriggerId:j,triggerIdProp:b,...A},z,U),!0);D.useControlledProp("openProp",o),D.useControlledProp("triggerIdProp",b),D.useSyncedValues(A),D.useContextCallback("onOpenChange",d),D.useContextCallback("onOpenChangeComplete",f);const I=D.useState("open"),M=D.useState("mounted"),O=D.useState("payload");eT(D,I),iy(D);const{forceUnmount:_}=cy(I,D);x.useImperativeHandle(v,()=>({unmount:_,close:()=>D.setOpen(!1,Fe(Hv))}),[_,D]);const L=I||M;return s.jsxs(NT.Provider,{value:D,children:[y&&s.jsx(ly,{handle:y,store:D}),L&&s.jsx(gU,{store:D,parentContext:R?.context,isDrawer:w}),typeof a=="function"?a({payload:O}):a]})}const jU=Hm(function(t){return BT("dialog",t)}),HT=x.forwardRef(function(t,a){const{render:o,className:c,style:d,id:f,...p}=t,g=Wc(),v=Sa(f);return g.useSyncedValueWithCleanup("titleElementId",v),bt("h2",t,{ref:a,props:[{id:v},p]})});function wU(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 UT(e,t){const a=Ie((d,f)=>{(typeof e=="function"?e():e)||t(f||(Ld?"touch":""))}),{onClick:o,onPointerDown:c}=wU(a);return x.useMemo(()=>({onClick:o,onPointerDown:c}),[o,c])}function VT(e){const[t,a]=x.useState(null),o=UT(e,a);return ea(e,c=>{c&&!e&&a(null)}),x.useMemo(()=>({openMethod:t,triggerProps:o}),[t,o])}function Kt(e){return s.jsx(jU,{"data-slot":"dialog",...e})}function SU(e){return s.jsx(DT,{"data-slot":"dialog-portal",...e})}const Ft=e=>s.jsx(HT,{"data-slot":"dialog-title",...e});function NU({className:e,...t}){return s.jsx(kT,{"data-slot":"dialog-overlay",className:Ve("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 Yt({className:e,children:t,showCloseButton:a=!0,keepMounted:o=!1,overlayForceRender:c=!1,...d}){return s.jsxs(SU,{keepMounted:o,children:[s.jsx(NU,{forceRender:c}),s.jsxs(MT,{"data-slot":"dialog-content",className:Ve("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(CT,{"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:po("关闭")})]})]})]})}function $t({className:e,...t}){return s.jsx("div",{"data-slot":"dialog-header",className:Ve("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 _t({className:e,...t}){return s.jsx("div",{"data-slot":"dialog-body",className:Ve("flex flex-col gap-4 overflow-y-auto px-5 py-[18px]",e),...t})}function en({className:e,...t}){return s.jsx("div",{"data-slot":"dialog-footer",className:Ve("flex items-center gap-2 border-t border-hairline bg-surface-2 px-5 py-[13px]",e),...t})}function Hn({className:e,...t}){return s.jsx("div",{"data-slot":"dialog-section",className:Ve("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 kU(e){return BT("alert-dialog",e)}const CU=kU,TU=DT,EU=e=>s.jsx(HT,{"data-slot":"alert-dialog-title",...e});function RU({className:e,...t}){return s.jsx(kT,{"data-slot":"alert-dialog-overlay",className:Ve("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 AU({className:e,children:t,showCloseButton:a=!1,...o}){return s.jsxs(TU,{children:[s.jsx(RU,{}),s.jsxs(MT,{"data-slot":"alert-dialog-content",className:Ve("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(CT,{"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:po("关闭")})]})]})]})}function OU({className:e,...t}){return s.jsx("div",{"data-slot":"alert-dialog-header",className:Ve("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 MU({className:e,...t}){return s.jsx("div",{"data-slot":"alert-dialog-body",className:Ve("flex flex-col gap-4 overflow-y-auto px-5 py-[18px]",e),...t})}function DU({className:e,...t}){return s.jsx("div",{"data-slot":"alert-dialog-footer",className:Ve("flex items-center gap-2 border-t border-hairline bg-surface-2 px-5 py-[13px]",e),...t})}function IU({className:e,tone:t="danger",...a}){return s.jsx("div",{"data-slot":"alert-dialog-banner","data-tone":t,className:Ve("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 Ny({className:e,containerClassName:t,...a}){return s.jsx("div",{"data-slot":"table-container",className:Ve("relative w-full overflow-auto",t),children:s.jsx("table",{"data-slot":"table",className:Ve("w-full caption-bottom border-collapse text-[12.5px]",e),...a})})}function FT({className:e,...t}){return s.jsx("thead",{"data-slot":"table-header",className:Ve(e),...t})}function ky({className:e,...t}){return s.jsx("tbody",{"data-slot":"table-body",className:Ve(e),...t})}function jl({className:e,...t}){return s.jsx("tr",{"data-slot":"table-row",className:Ve("transition-colors duration-100 hover:[&>td]:bg-control-hover",e),...t})}function $T({className:e,...t}){return s.jsx("th",{"data-slot":"table-head",className:Ve("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 yn({className:e,...t}){return s.jsx("td",{"data-slot":"table-cell",className:Ve("border-b border-hairline px-3.5 py-2 align-middle",e),...t})}const PU="data-checked",_U="data-unchecked",Cy={checked(e){return e?{[PU]:""}:{[_U]:""}},...ro,...gi},Ty="data-composite-item-active",qT=x.createContext({register:()=>{},unregister:()=>{},subscribeMapChange:()=>()=>{},nextIndexRef:{current:0}});function LU(){return x.useContext(qT)}function Ey(e={}){const{guess:t,label:a,metadata:o,textRef:c,index:d}=e,{register:f,unregister:p,subscribeMapChange:g,nextIndexRef:v}=LU(),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 zU(e={}){const{highlightItemOnHover:t,highlightedIndex:a,onHighlightedIndexChange:o}=Vk(),{ref:c,index:d}=Ey(e),f=a===d,p=x.useRef(null),g=Xr(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 GT(e){const{render:t,className:a,style:o,state:c=cn,props:d=Er,refs:f=Er,metadata:p,stateAttributesMapping:g,tag:v="div",...y}=e,{compositeProps:b,compositeRef:j}=zU({metadata:p});return bt(v,e,{state:c,ref:[j,...f],props:[b,...d,y],stateAttributesMapping:g})}const KT=x.createContext(void 0);function BU(){return x.useContext(KT)}function uh(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}const YT=x.createContext(void 0);function HU(){const e=x.useContext(YT);if(e===void 0)throw new Error(rn(52));return e}const XT=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=BU(),{disabled:k,readOnly:E,required:R,form:C,checkedValue:A,touched:D=!1,validation:I,name:M,setCheckedValue:O=Vt,setTouched:_=Vt,registerInputRef:L=Vt}=N??{},{setTouched:z,setFilled:U,state:B,disabled:Q}=wa(),W=FC(),{labelId:Z,getDescriptionProps:Y}=hl(),q=Q||W.disabled||k||d,G=E||f,F=R||p,$=C,X=N?A===v:v==="",re=x.useRef(null),P=x.useRef(null),V=I?.registerInput,J=x.useCallback(Ce=>V?.(Ce,{controlRef:re,value:void 0}),[V]),ie=Xr(y,P,L,J);De(()=>{P.current?.checked&&U(!0)},[U]),De(()=>{if(P.current){if(q&&X){L(null);return}L(P.current)}},[X,q,L]);const me=Sa(),he=so({id:j}),ae=b?void 0:he,oe=gv(g,Z,P,!b,ae),ee={role:"radio","aria-checked":X,"aria-labelledby":oe,[Ty]:X?"":void 0,id:b?he:me,onKeyDown(Ce){Ce.key==="Enter"&&Ce.preventDefault()},onClick(Ce){if(Ce.defaultPrevented||q||G)return;Ce.preventDefault();const Se=P.current;Se&&zc(Se,Ce)},onFocus(Ce){Ce.defaultPrevented||q||G||!D||(P.current?.click(),_(!1))}},{getButtonProps:de,buttonRef:K}=Yr({disabled:q,native:b,composite:!1}),be={type:"radio",ref:ie,form:$,id:ae,name:M,tabIndex:-1,style:M?Kc:Ni,"aria-hidden":!0,...v!==void 0?{value:uh(v)}:cn,disabled:q,checked:X,required:F,readOnly:G,onChange(Ce){if(Ce.nativeEvent.defaultPrevented||q||G||v===void 0)return;const Se=Fe(Kn,Ce.nativeEvent);O(v,Se),!Se.isCanceled&&z(!0)},onClick(Ce){Ce.stopPropagation()},onFocus(){re.current?.focus()}},ne=x.useMemo(()=>({...B,required:F,disabled:q,readOnly:G,checked:X}),[B,q,G,X,F]),ce=ne,we=N!==void 0,Ee=[a,re,K],ve=[ee,S,de,Y,I?Ce=>I.getValidationProps(q,Ce):cn],ke=bt("span",t,{enabled:!we,state:ne,ref:Ee,props:ve,stateAttributesMapping:Cy});return s.jsxs(YT.Provider,{value:ce,children:[we?s.jsx(GT,{tag:"span",render:o,className:c,style:w,state:ne,refs:Ee,props:ve,stateAttributesMapping:Cy}):ke,s.jsx("input",{...be,suppressHydrationWarning:!0})]})}),UU=x.forwardRef(function(t,a){const{render:o,className:c,style:d,keepMounted:f=!1,...p}=t,g=HU(),v=g.checked,{mounted:y,transitionStatus:b,setMounted:j}=yi(v),w={...g,transitionStatus:b},S=x.useRef(null),N=f||y,k=bt("span",t,{ref:[a,S],state:w,props:p,stateAttributesMapping:Cy});return Jr({batch:!0,enabled:!v,open:v,ref:S,onComplete(){v||j(!1)}}),N?k:null});function Ry(e){const{children:t,elementsRef:a,labelsRef:o,onMapChange:c}=e,d=Ie(c),[,f]=x.useState(!1),p=Os(FU).current,g=Os(VU).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(D=>!D))}),S=Ie((D,I)=>{g.set(D,I),w()}),N=Ie(D=>{g.delete(D),w()}),k=Ie(D=>{const I=new Map;return a.current.length=0,o&&(o.current.length=0),D.forEach(M=>{I.set(M.element,{...M.registration.metadata??{},index:M.index}),a.current[M.index]=M.element,o&&(o.current[M.index]=M.registration.label!==void 0?M.registration.label:M.registration.textRef?.current?.textContent??M.element.textContent)}),v.current=a.current.length,I});function E(D){if(j.current?.disconnect(),j.current=null,typeof MutationObserver!="function"||D.length<2)return;const I=new MutationObserver(O=>{if(!GU(O))return;let _=null;for(const L of D)if(L.isConnected){if(_&&QT(_,L)>0){I.disconnect(),w();return}_=L}});j.current=I;const M=new Set;for(let O=1;OI.observe(O,{childList:!0}))}const R=Ie(()=>{const[D,I]=$U(g),M=k(D),O=b.current,_=!O||O.length!==D.length||D.some((L,z)=>{const U=O[z];return L.index!==U.index||L.element!==U.element||L.registration.index!==U.registration.index||L.registration.metadata!==U.registration.metadata});E(I),b.current=D,y.current=!1,_&&(p.forEach(L=>L(M)),d(M))});De(()=>(!y.current&&b.current&&k(b.current),()=>{a.current=[],o&&(o.current=[])}),[a,o,k]),De(()=>{y.current&&R()}),De(()=>()=>{j.current?.disconnect(),y.current=!0},[]);const C=Ie(D=>(p.add(D),()=>{p.delete(D)})),A=x.useMemo(()=>({register:S,unregister:N,subscribeMapChange:C,nextIndexRef:v}),[S,N,C,v]);return s.jsx(qT.Provider,{value:A,children:t})}function VU(){return new Map}function FU(){return new Set}function $U(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)=>QT(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 qU(e,t){let a=e.parentElement;for(;a&&!a.contains(t);)a=a.parentElement;return a}function GU(e){for(const t of e)for(let a=0;a{if(A.current=R.current[z]??null,(p??S)(z),U){const B=R.current[z];AT(k.current,B,d,a)}}),M=Ie(z=>{if(z.size===0)return;if(C.current){const W=R.current,Z=W.indexOf(A.current);if(Z===-1){const Y=W[D];!Y||co(W,D,b)?I(YU(W,b)):A.current=Y}else Z!==D&&I(Z);return}C.current=!0;const U=Array.from(z.keys()),B=U.find(W=>W?.hasAttribute(Ty))??null,Q=B?z.get(B)?.index??-1:-1;if(Q!==-1)I(Q);else if(co(U,D,b)){const W=Ms(U,{disabledIndices:b});io(U,W)||I(W)}AT(k.current,B,d,a)});De(()=>{if(b==null||f!=null||!C.current)return;const z=R.current;if(co(z,D,b)){const U=Ms(z,{disabledIndices:b});io(z,U)||I(U)}},[b,f,D,R,I]);const O=Ie((z,U,B)=>c?c(z,U,B,R):B),_=Ie(z=>{const U=z.key===wy||z.key===Sy;if(!lh.has(z.key)||!v&&U||XU(z,j)||!k.current)return;const Q=d==="rtl",W=Q?yy:jy,Z=Q?jy:yy,Y=a==="vertical"?vy:W,q=a==="vertical"?by:Z,G=os(z.nativeEvent);if(G!=null&&RT(G)&&!ZT(G)){const V=G.selectionStart,J=G.selectionEnd,ie=G.value;if(V==null||z.shiftKey||V!==J||z.key!==q&&V0)return}let F=D;const $=Dm(R,b),X=Ov(R,b);o!=null&&(F=o({disabledIndices:b,elementsRef:R,event:z,highlightedIndex:D,loopFocus:t,maxIndex:X,minIndex:$,onLoop:O,orientation:a,rtl:Q}));const re=a!=="vertical"&&z.key===W||a!=="horizontal"&&z.key===vy,P=a!=="vertical"&&z.key===Z||a!=="horizontal"&&z.key===by;v&&(z.key===wy?F=$:z.key===Sy&&(F=X)),F===D&&(re||P)&&(t&&F===X&&re?(F=$,c&&(F=c(z,D,F,R))):t&&F===$&&P?(F=X,c&&(F=c(z,D,F,R))):F=Ms(R.current,{startingIndex:F,decrement:P,disabledIndices:b})),F!==D&&!io(R.current,F)&&(y&&z.stopPropagation(),(N||U||re||P)&&z.preventDefault(),I(F,!0),queueMicrotask(()=>{R.current[F]?.focus()}))});return{props:{ref:E,onFocus(z){const U=k.current,B=os(z.nativeEvent);!U||B==null||!RT(B)||B.setSelectionRange(0,B.value.length)},onKeyDown:_},highlightedIndex:D,onHighlightedIndexChange:I,elementsRef:R,onMapChange:M,relayKeyboardEvent:_}}function YU(e,t){let a=-1;for(let o=0;o({highlightedIndex:_,onHighlightedIndexChange:L,highlightItemOnHover:A,relayKeyboardEvent:B}),[_,L,A,B]);return s.jsx(Uk.Provider,{value:W,children:s.jsx(Ry,{elementsRef:z,onMapChange:Z=>{N?.(Z),U(Z)},children:Q})})}const ZU=[ET],WT=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:R,validationMode:C,name:A,disabled:D,state:I,validation:M,setDirty:O,setFilled:_,validityData:L}=wa(),{labelId:z}=hl(),{clearErrors:U,elementRef:B}=Hc(),Q=gz(!0),W=D||d,Z=A??j,Y=Sa(S),[q,G]=$a({controlled:v,default:y,name:"RadioGroup",state:"value"}),[F,$]=x.useState(!1),X=Ie((K,be)=>{g?.(K,be),!be.isCanceled&&G(K)}),re=M.getInputControl,P=x.useMemo(()=>({get current(){return re()}}),[re]),V=x.useRef(null),J=x.useRef(null);function ie(K){let be;return w&&(typeof w=="function"?be=w(K):w.current=K),V.current=K,be}const me=Ie(K=>{if(!K||K.disabled)return;J.current||(J.current=K);const be=V.current,ne=K.checked||be==null||be.disabled?ie(K):void 0;return()=>{J.current===K&&(J.current=null),V.current===K?ne?(ne(),V.current=null):ie(null):ne?.()}}),he=Ie(()=>{const K=B.current;if(!K)return q??null;for(const be of M.registeredInputs.keys())if(be.checked&&c4(be,K))return q??null;return null});qc(P,Y,q??null,he,!W,j),ea(q,()=>{U(Z),O(q!==L.initialValue),_(q!=null),M.change(q);const K=J.current;q==null&&K&&!K.disabled&&ie(K)});const ae=z??Q?.legendId,oe={...I,disabled:W??!1,required:p??!1,readOnly:f??!1},ee=x.useMemo(()=>({checkedValue:q,disabled:W,form:b,validation:M,name:Z,readOnly:f,registerInputRef:me,required:p,setCheckedValue:X,setTouched:$,touched:F}),[q,W,b,M,Z,f,me,p,X,$,F]),de={id:S,role:"radiogroup","aria-required":p||void 0,"aria-disabled":W||void 0,"aria-readonly":f||void 0,"aria-labelledby":ae,onFocus(){R(!0)},onBlur(K){Ke(K.currentTarget,K.relatedTarget)||(E(!0),R(!1),C==="onBlur"&&M.commit(q))},onKeyDownCapture(K){K.key.startsWith("Arrow")&&($(!0),R(!0))}};return s.jsx(KT.Provider,{value:ee,children:s.jsx(QU,{render:o,className:c,style:N,state:oe,props:[de,k,K=>M.getValidationProps(W??!1,K)],refs:[a],stateAttributesMapping:gi,enableHomeAndEndKeys:!1,modifierKeys:ZU})})});function dh({className:e,...t}){return s.jsx(WT,{"data-slot":"radio-group",className:Ve("flex flex-col gap-2",e),...t})}function Mi({className:e,...t}){return s.jsx(XT,{"data-slot":"radio-group-item",className:Ve("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(UU,{"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 JT(e){const t=x.useRef(!0);t.current&&(t.current=!1,e())}const eE=x.createContext(void 0),tE=x.createContext(void 0),nE=x.createContext(void 0);function ho(){const e=x.useContext(eE);if(e===void 0)throw new Error(rn(60));return e}function Ay(){const e=x.useContext(tE);if(e===void 0)throw new Error(rn(101));return e}function sE(){const e=x.useContext(nE);if(e===void 0)throw new Error(rn(61));return e}function WU(e,t,a=Object.is){const{length:o}=e;if(o!==t.length)return!1;for(let c=0;cObject.is(e,t);function na(e,t,a){return e==null||t==null?Object.is(e,t):a(e,t)}function rE(e,t,a){return Array.isArray(e)&&Array.isArray(t)?!WU(e,t,(o,c)=>na(o,c,a)):e!==t}function ph(e,t,a){return e?e.some(o=>o===void 0?!1:na(t,o,a)):!1}function Jc(e,t,a){return e?e.findIndex(o=>o===void 0?!1:na(o,t,a)):-1}function JU(e,t){if(t!==fh)return o=>ph(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 ef(e,t,a,o){const c=o&&Array.isArray(t)?e.findIndex(JU(t,a)):Jc(e,t,a);return c===-1?null:c}function aE(e,t,a,o,c,d){return ph(o,t,c)?d!=null&&e>d&&ph(o,a[d],c)?d:e:e===d?ef(a,o,c,!0):d}function lE(e,t,a){return e.filter(o=>!na(t,o,a))}function eV(e){return typeof e=="object"&&e!=null&&Array.isArray(e.items)}function Oy(e){return eV(e?.[0])}function mh(e){return Oy(e)?e.flatMap(t=>t.items):e}function oE(e){if(!Array.isArray(e))return e!=null&&"null"in e;const t=e;if(Oy(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 go(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 uh(e)}function Na(e,t){return t&&e!=null?t(e)??"":e&&typeof e=="object"&&"value"in e&&"label"in e?uh(e.value):uh(e)}function iE(e,t,a){function o(){return go(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=mh(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 tV(e,t,a){return e.reduce((o,c,d)=>(d>0&&o.push(", "),o.push(s.jsx(x.Fragment,{children:iE(c,t,a)},d)),o),[])}const nV={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:Na(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=>na(t,c,a)):na(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},wl=1;function cE(e,t){return Math.max(0,e-t)}function sV(e,t){if(t<=0)return 0;const a=ki(e,0,t),o=a,c=t-a,d=o<=wl,f=c<=wl;return d&&f?o<=c?0:t:d?0:f?t:a}function rV(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:R,multiple:C=!1,itemToStringLabel:A,itemToStringValue:D,isItemEqualToValue:I=fh,highlightItemOnHover:M=!0,children:O}=e,{clearErrors:_}=Hc(),{setDirty:L,setTouched:z,setFocused:U,validityData:B,setFilled:Q,name:W,disabled:Z,validation:Y,validationMode:q}=wa(),G=so({id:t}),F=Z||b,$=W??g,[X,re]=$a({controlled:a,default:C?o??Er:o,name:"Select",state:"value"}),[P,V]=$a({controlled:d,default:f,name:"Select",state:"open"}),J=x.useRef([]),ie=x.useRef([]),me=x.useRef(null),he=x.useRef(null),ae=x.useRef(0),oe=x.useRef(null),ee=x.useRef([]),de=x.useRef(!1),K=x.useRef(null),be=x.useRef(null),ne=x.useRef({allowSelectedMouseUp:!1,allowUnselectedMouseUp:!1,dragY:0}),ce=x.useRef(!1),we=x.useRef(X),{mounted:Ee,setMounted:ve,transitionStatus:ke}=yi(P),{openMethod:Ce,triggerProps:Se}=VT(P),ge=Os(()=>new Zc({id:G,labelId:void 0,modal:S,multiple:C,itemToStringLabel:A,itemToStringValue:D,isItemEqualToValue:I,value:X,open:P,mounted:Ee,transitionStatus:ke,items:R,forceMount:!1,openMethod:null,activeIndex:null,selectedIndex:null,popupProps:cn,triggerProps:cn,triggerElement:null,positionerElement:null,listElement:null,popupSide:null,scrollUpArrowVisible:!1,scrollDownArrowVisible:!1,hasScrollArrows:!1},{setValue:Vt,setOpen:Vt,handleScrollArrowVisibility:Vt,onOpenChangeComplete:Vt,listRef:J,popupRef:me,scrollHandlerRef:he,scrollArrowsMountedCountRef:ae,valueRef:oe,valuesRef:ee,labelsRef:ie,typingRef:de,selectionRef:ne,firstItemTextRef:K,selectedItemTextRef:be,alignItemWithTriggerActiveRef:ce,initialValueRef:we},nV)).current,Te=ge.useState("activeIndex"),Oe=ge.useState("selectedIndex"),Ne=ge.useState("triggerElement"),Be=ge.useState("positionerElement"),Qe=tU(Ce),Rt=Ce??Qe,Wt=x.useMemo(()=>C?"":Na(X,D),[C,X,D]),Dt=x.useMemo(()=>C&&Array.isArray(X)?X.map(ht=>Na(ht,D)):Na(X,D),[C,X,D]),ct=Yn(Ne),$n=Ie(()=>Dt);qc(ct,G,X,$n,!F,g);const us=C?Array.isArray(X)&&X.length>0:X!=null&&Wt!=="";De(()=>{Q(us)},[us,Q]),De(function(){const vt=ef(ee.current,X,I,C);vt===null&&(be.current=null),!P&&ge.set("selectedIndex",vt)},[C,P,X,I,ge]),ea(X,()=>{_($),L(rE(X,B.initialValue,I)),Y.change(X)});const qn=Ie((ht,vt)=>{p?.(ht,vt),!vt.isCanceled&&(V(ht),!ht&&(vt.reason===fo||vt.reason===Bm)&&(z(!0),U(!1),q==="onBlur"&&Y.commit(X)))}),gs=Ie(()=>{ve(!1),ge.update({activeIndex:null,openMethod:null,scrollUpArrowVisible:!1,scrollDownArrowVisible:!1}),E?.(!1)});Jr({enabled:!N,open:P,ref:me,onComplete(){P||gs()}}),x.useImperativeHandle(N,()=>({unmount:gs}),[gs]);const lt=Ie((ht,vt)=>{c?.(ht,vt),!vt.isCanceled&&re(ht)}),Bt=Ie(ht=>{const vt=cE(ht.scrollHeight,ht.clientHeight),yt=sV(ht.scrollTop,vt),jr=yt>0,nr=ytZT(J.current[ht]),onMatch(ht){P?ge.set("activeIndex",ht):lt(ee.current[ht],Fe(Kn))},onTyping(ht){de.current=ht}}),Zn=x.useMemo(()=>Kr(Ht.reference,Tt.reference,tt.reference,Jt.reference,Se),[Jt.reference,Ht.reference,Tt.reference,tt.reference,Se]),zn=x.useMemo(()=>Kr(Qd,Ht.floating,Tt.floating,tt.floating),[Ht.floating,Tt.floating,tt.floating]),Bn=Tt.item??cn;ge.useContextCallback("setValue",lt),ge.useContextCallback("setOpen",qn),ge.useContextCallback("handleScrollArrowVisibility",Bt),ge.useContextCallback("onOpenChangeComplete",E),JT(()=>{ge.update({popupProps:zn,triggerProps:Zn})}),ge.useSyncedValues({id:G,modal:S,multiple:C,value:X,open:P,mounted:Ee,transitionStatus:ke,popupProps:zn,triggerProps:Zn,items:R,itemToStringLabel:A,itemToStringValue:D,isItemEqualToValue:I,openMethod:Rt});const Tn=x.useMemo(()=>({disabled:F,readOnly:j,required:w,multiple:C,highlightItemOnHover:M,itemProps:Bn}),[F,j,w,C,M,Bn]),Qt=Xr(k,Y.inputRef),rs=C?void 0:$,St=x.useMemo(()=>!C||!Array.isArray(X)||!$?null:X.map(ht=>{const vt=Na(ht,D);return s.jsx("input",{type:"hidden",form:v,name:$,value:vt,disabled:F},vt)}),[C,X,v,$,D,F]);return s.jsxs(eE.Provider,{value:ge,children:[s.jsx(tE.Provider,{value:Tn,children:s.jsx(nE.Provider,{value:Ln,children:O})}),s.jsx("input",{...Y.getValidationProps(F,{onFocus(){ge.state.triggerElement?.focus({focusVisible:!0})},onChange(ht){if(ht.nativeEvent.defaultPrevented||F||j)return;const vt=ht.currentTarget.value,yt=Fe(Kn,ht.nativeEvent);function jr(){if(C)return;const nr=vt.toLowerCase();let Pr=ee.current.findIndex(el=>Na(el,D).toLowerCase()===nr||go(el,A).toLowerCase()===nr);Pr===-1&&(Pr=ee.current.findIndex((el,tn)=>{const ac=ie.current[tn];return ac!=null&&ac.toLowerCase()===nr}));const xn=ee.current[Pr];xn!=null&<(xn,yt)}ge.set("forceMount",!0),queueMicrotask(jr)}}),id:G&&rs==null?`${G}-hidden-input`:void 0,form:v,name:rs,autoComplete:y,value:Wt,disabled:F,required:w&&!(C&&us),readOnly:j,ref:Qt,style:$?Kc:Ni,tabIndex:-1,"aria-hidden":!0,suppressHydrationWarning:!0}),St]})}function uE(e,t){return e??t}const hh=5;function dE(e,t){const a=aV(t);return e.clientX>=a.left-hh&&e.clientX<=a.right+hh&&e.clientY>=a.top-hh&&e.clientY<=a.bottom+hh}function aV(e){const t=e.getBoundingClientRect(),a=vn(e);if(xv)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 lV="data-popup-side",oV=400,iV={...jv,...gi,popupSide:e=>e?{[lV]:e}:null,value:()=>null},cV=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}=wa(),{labelId:k}=hl(),E=ho(),{readOnly:R,required:C,disabled:A}=Ay(),D=N||A||f,I=E.useState("open"),M=E.useState("mounted"),O=E.useState("value"),_=E.useState("triggerProps"),L=E.useState("positionerElement"),z=E.useState("listElement"),U=E.useState("popupSide"),B=E.useState("id"),Q=E.useState("labelId"),W=E.useState("hasSelectedValue"),Z=M&&L?U:null,Y=d??B,q=uE(k,Q);so({id:d});const G=Yn(L),F=x.useRef(null),{getButtonProps:$,buttonRef:X}=Yr({disabled:D,native:p}),re=E.useStateSetter("triggerElement"),P=Qs(),V=Qs(),J=Qs();x.useEffect(()=>{if(I)return J.start(oV,()=>{E.context.selectionRef.current.allowUnselectedMouseUp=!0,E.context.selectionRef.current.allowSelectedMouseUp=!0}),()=>{J.clear()};E.context.selectionRef.current={allowSelectedMouseUp:!1,allowUnselectedMouseUp:!1,dragY:0},V.clear()},[I,E,V,J]);const ie=Kr(_,{id:Y,role:"combobox","aria-expanded":I,"aria-haspopup":"listbox","aria-controls":I?z?.id??Em(L)?.id:void 0,"aria-labelledby":q,"aria-readonly":R||void 0,"aria-required":C||void 0,tabIndex:D?-1:0,onFocus(ae){b(!0),I&&E.context.alignItemWithTriggerActiveRef.current&&E.context.setOpen(!1,Fe(Kn,ae.nativeEvent)),P.start(0,()=>{E.set("forceMount",!0)})},onBlur(ae){Ke(L,ae.relatedTarget)||(y(!0),b(!1),j==="onBlur"&&w.commit(O))},onMouseDown(ae){if(I)return;const oe=Ut(ae.currentTarget);function ee(de){if(!F.current)return;const K=de.target;Ke(F.current,K)||Ke(G.current,K)||dE(de,F.current)||E.context.setOpen(!1,Fe(QC,de))}V.start(0,()=>{oe.addEventListener("mouseup",ee,{once:!0})})}},v,$),me=w.getValidationProps(D,ie);me.role="combobox";const he={...S,open:I,disabled:D,value:O,readOnly:R,popupSide:Z,placeholder:!W};return bt("button",t,{ref:[a,F,X,re],state:he,stateAttributesMapping:iV,props:me})}),uV={value:()=>null},dV=x.forwardRef(function(t,a){const{className:o,render:c,children:d,placeholder:f,style:p,...g}=t,v=ho(),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=tV(y,b,j):E=iE(y,b,j),bt("span",t,{state:k,ref:[a,v.context.valueRef],props:[{children:E},g],stateAttributesMapping:uV})}),fV=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t,v={open:ho().useState("open")};return bt("span",t,{state:v,ref:a,props:[{"aria-hidden":!0,children:"▼"},f],stateAttributesMapping:yv})}),pV=x.forwardRef(function(t,a){const o=ho(),c=o.useState("mounted"),d=o.useState("forceMount");return c||d?s.jsx(Fm,{ref:a,...t}):null}),fE=x.createContext(void 0);function mV(){const e=x.useContext(fE);if(!e)throw new Error(rn(59));return e}function gh(e,t){e&&Object.assign(e.style,t)}const hV={position:"relative",maxHeight:"100%",overflowX:"hidden",overflowY:"auto"},gV=20;function My(e,t,a,o){const[c,d]=x.useState(!1);De(()=>{if(!e||!t||a==null){d(!1);return}const f=Ut(a).documentElement.clientWidth,p=a.offsetWidth;d(f>0&&p>0&&p>=f-gV)},[e,t,a]),zT(e&&(!t||c),o)}const xV={position:"fixed"},bV=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=b1,style:R,...C}=t,A=ho(),D=sE(),I=A.useState("open"),M=A.useState("mounted"),O=A.useState("modal"),_=A.useState("value"),L=A.useState("openMethod"),z=A.useState("positionerElement"),U=A.useState("triggerElement"),B=A.useState("isItemEqualToValue"),Q=A.useState("transitionStatus"),W=x.useRef(null),Z=x.useRef(null),[Y,q]=x.useState(k),G=M&&Y&&L!=="touch";!M&&Y!==k&&q(k),x.useImperativeHandle(A.context.alignItemWithTriggerActiveRef,()=>G),My((G||O)&&I,L==="touch",z,U);const F=sh({anchor:o,floatingRootContext:D,positionMethod:f,mounted:M,side:p,sideOffset:v,align:g,alignOffset:y,arrowPadding:w,collisionBoundary:b,collisionPadding:j,sticky:S,disableAnchorTracking:N??G,collisionAvoidance:E,keepMounted:!0}),$=G?"none":F.side,X=G?xV:F.positionerStyles,re={open:I,side:$,align:F.align,anchorHidden:F.anchorHidden};De(()=>{A.set("popupSide",F.side)},[A,F.side]);const P=A.useStateSetter("positionerElement"),V=rh(t,re,{styles:X,transitionStatus:Q,props:C,refs:[a,P],hidden:!M,inert:!I}),J=x.useRef(0),ie=Ie(he=>{if(A.context.valuesRef.current.length===0)return;const ae=J.current;J.current=he.size;const oe=Fe(Kn);if(ae!==0&&!A.state.multiple&&_!==null&&Jc(A.context.valuesRef.current,_,B)===-1){const de=A.context.initialValueRef.current,be=de!=null&&Jc(A.context.valuesRef.current,de,B)!==-1?de:null;A.context.setValue(be,oe),be===null&&(A.set("selectedIndex",null),A.context.selectedItemTextRef.current=null)}if(ae!==0&&A.state.multiple&&Array.isArray(_)){const ee=_.filter(de=>Jc(A.context.valuesRef.current,de,B)!==-1);ee.length!==_.length&&(A.context.setValue(ee,oe),ee.length===0&&(A.set("selectedIndex",null),A.context.selectedItemTextRef.current=null))}if(I&&G){A.update({scrollUpArrowVisible:!1,scrollDownArrowVisible:!1});const ee={height:""};gh(z,ee),gh(A.context.popupRef.current,ee)}}),me=x.useMemo(()=>({...F,side:$,alignItemWithTriggerActive:G,setControlledAlignItemWithTrigger:q,scrollUpArrowRef:W,scrollDownArrowRef:Z}),[F,$,G,q]);return s.jsx(Ry,{elementsRef:A.context.listRef,labelsRef:A.context.labelsRef,onMapChange:ie,children:s.jsxs(fE.Provider,{value:me,children:[M&&O&&s.jsx(ih,{inert:ah(!I),cutout:U}),V]})})}),xh="base-ui-disable-scrollbar",pE={className:xh,getElement(e){return s.jsx("style",{nonce:e,href:xh,precedence:"base-ui:low",children:`.${xh}{scrollbar-width:none}.${xh}::-webkit-scrollbar{display:none}`})}},vV=x.createContext(void 0);function mE(e){return x.useContext(vV)}const yV=x.createContext(void 0),jV={disableStyleElements:!1};function wV(){return x.useContext(yV)??jV}const hE="--transform-origin",SV={...Uc,...ro},NV=x.forwardRef(function(t,a){const{render:o,className:c,style:d,finalFocus:f,...p}=t,g=ho(),{multiple:v,readOnly:y,highlightItemOnHover:b}=Ay(),j=sE(),{side:w,align:S,alignItemWithTriggerActive:N,isPositioned:k,setControlledAlignItemWithTrigger:E}=mV(),R=mE()!=null,C=Wd(),{nonce:A,disableStyleElements:D}=wV(),I=g.useState("id"),M=g.useState("open"),O=g.useState("openMethod"),_=g.useState("mounted"),L=g.useState("popupProps"),z=g.useState("transitionStatus"),U=g.useState("triggerElement"),B=g.useState("positionerElement"),Q=g.useState("listElement"),W=x.useRef(!1),Z=x.useRef(!1),Y=x.useRef({}),q=$c(),G=Ie(re=>{if(!B||!g.context.popupRef.current||!Z.current)return;const P=B.style.top==="0px",V=B.style.bottom==="0px";if(W.current||!N||!P&&!V){g.context.handleScrollArrowVisibility(re);return}const J=xE(B),ie=tf(B.getBoundingClientRect().height,"y",J),me=Ut(B),he=vn(B),ae=he.getComputedStyle(B),oe=parseFloat(ae.marginTop),ee=parseFloat(ae.marginBottom),de=gE(he.getComputedStyle(g.context.popupRef.current)),K=Math.min(me.documentElement.clientHeight-oe-ee,de),be=re.scrollTop,ne=bh(re);let ce=null;const we=Ce=>{B.style.height=`${Ce}px`},Ee=P?ne-be:be,ve=Math.min(ie+Ee,K);if(Ee<=wl){const Ce=ki(Ee,0,K-ie);Ce>0&&we(ie+Ce),re.scrollTop=P?ne:0,K-(ie+Ce)<=wl&&(W.current=!0),g.context.handleScrollArrowVisibility(re);return}if(K-ve>wl)ce=P?1/0:0;else if(V&&bewl&&(re.scrollTop=Ce)}ke>=K-wl&&(W.current=!0),g.context.handleScrollArrowVisibility(re)});x.useImperativeHandle(g.context.scrollHandlerRef,()=>G,[G]),Jr({open:M,ref:g.context.popupRef,onComplete(){M&&g.context.onOpenChangeComplete(!0)}});const F={open:M,transitionStatus:z,side:w,align:S};De(()=>{!B||!g.context.popupRef.current||Object.keys(Y.current).length||(Y.current={top:B.style.top||"0",left:B.style.left||"0",right:B.style.right,height:B.style.height,bottom:B.style.bottom,minHeight:B.style.minHeight,maxHeight:B.style.maxHeight,marginTop:B.style.marginTop,marginBottom:B.style.marginBottom})},[g,B]),De(()=>{M||N||(Z.current=!1,W.current=!1,gh(B,Y.current))},[M,N,B]),De(()=>{const re=g.context.popupRef.current;if(!M||!U||!B||!re||N&&!k||g.state.transitionStatus==="ending")return;if(Z.current=!0,re.style.removeProperty(hE),!N){q.request(()=>g.context.handleScrollArrowVisibility(Q||re));return}const P=kV(re);try{let V=g.context.selectedItemTextRef.current;V?.isConnected||(V=!g.select("hasSelectedValue")&&g.context.firstItemTextRef.current?.isConnected?g.context.firstItemTextRef.current:null);const J=g.context.valueRef.current,ie=vn(B),me=ie.getComputedStyle(B),he=ie.getComputedStyle(re),ae=Ut(U),oe=xE(U),ee=vh(U.getBoundingClientRect(),oe),de=vh(B.getBoundingClientRect(),oe),K=ee.height,be=Q||re,ne=be.scrollHeight,ce=parseFloat(he.borderBottomWidth),we=parseFloat(me.marginTop)||10,Ee=parseFloat(me.marginBottom)||10,ve=parseFloat(me.minHeight)||100,ke=gE(he),Ce=5,Se=5,ge=20,Te=ae.documentElement.clientHeight-we-Ee,Oe=ae.documentElement.clientWidth,Ne=Te-ee.bottom+K;let Be,Qe=C==="rtl"?ee.right-de.width:ee.left,Rt=0;if(V&&J){const Jt=vh(J.getBoundingClientRect(),oe);Be=vh(V.getBoundingClientRect(),oe),Qe=de.left+(C==="rtl"?Jt.right-Be.right:Jt.left-Be.left);const tt=Jt.top-ee.top+Jt.height/2;Rt=Be.top-de.top+Be.height/2-tt}const Wt=Ne+Rt+Ee+ce;let Dt=Math.min(Te,Wt);const ct=Te-we-Ee,$n=Wt-Dt,us=Oe-Se;B.style.left=`${ki(Qe,Ce,us-de.width)}px`,B.style.height=`${Dt}px`,B.style.maxHeight="none",B.style.marginTop=`${we}px`,B.style.marginBottom=`${Ee}px`,re.style.height="100%";const qn=bh(be),gs=$n>=qn-wl;gs&&(Dt=Math.min(Te,de.height)-($n-qn));const lt=ee.topTe-ge||Math.ceil(Dt)+wl=ct?"0":`${Jt}px`,B.style.height=`${Dt}px`,be.scrollTop=bh(be)}else B.style.bottom="0",be.scrollTop=$n;if(Be){const Jt=de.top,tt=de.height,Tt=Be.top+Be.height/2,Ht=ki(tt>0?(Tt-Jt)/tt*100:50,0,100);re.style.setProperty(hE,`50% ${Ht}%`)}(Ln===Te||Dt>=ke)&&(W.current=!0),g.context.handleScrollArrowVisibility(be),b&&g.state.selectedIndex===null&&g.state.activeIndex===null&&g.context.listRef.current[0]!=null&&g.set("activeIndex",0)}finally{P()}},[g,M,B,U,N,E,q,Q,b,C,k]),x.useEffect(()=>{if(!N||!B||!M)return;const re=vn(B);function P(V){g.context.setOpen(!1,Fe(g4,V))}return jt(re,"resize",P)},[g,N,B,M]);const $={...Q?{role:"presentation"}:{role:"listbox","aria-multiselectable":v||void 0,"aria-readonly":y||void 0,id:`${I}-list`},onKeyDown(re){R&&lh.has(re.key)&&re.stopPropagation()},onScroll(re){Q||G(re.currentTarget)},...N&&{style:Q?{height:"100%"}:hV},className:!Q&&N?pE.className:void 0},X=bt("div",t,{ref:[a,g.context.popupRef],state:F,stateAttributesMapping:SV,props:[L,$,Jd(z),p]});return s.jsxs(x.Fragment,{children:[!D&&pE.getElement(A),s.jsx($m,{context:j,modal:!1,disabled:!_,openInteractionType:O,returnFocus:f,restoreFocus:!0,children:X})]})});function gE(e){const t=e.maxHeight;return t.endsWith("px")&&parseFloat(t)||1/0}function bh(e){return cE(e.scrollHeight,e.clientHeight)}function xE(e){return B1.getScale(e)}function tf(e,t,a){return e/a[t]}function vh(e,t){return zd({x:tf(e.x,"x",t),y:tf(e.y,"y",t),width:tf(e.width,"x",t),height:tf(e.height,"y",t)})}const bE=[["transform","none"],["scale","1"],["translate","0 0"]];function kV(e){const{style:t}=e,a={};for(const[o,c]of bE)a[o]=t.getPropertyValue(o),t.setProperty(o,c,"important");return()=>{for(const[o]of bE){const c=a[o];c?t.setProperty(o,c):t.removeProperty(o)}}}const vE=x.createContext(void 0);function Dy(){const e=x.useContext(vE);if(!e)throw new Error(rn(57));return e}const CV=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=Ey({guess:!0,label:p,textRef:b}),w=ho(),{itemProps:S,multiple:N,disabled:k,readOnly:E}=Ay(),R=k||g,C=w.useState("isActive",j.index),A=w.useState("open"),D=w.useState("isSelected",f),I=w.useState("isSelectedByFocus",j.index),M=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,$=w.state.selectedIndex;let X=$,re;N&&Array.isArray(F)?(X=aE(O,f,w.context.valuesRef.current,F,M,$),re=X===O,O===$&&!re&&(w.context.selectedItemTextRef.current=null)):(re=F!==void 0&&na(f,F,M),re&&(X=O)),w.set("selectedIndex",X),re&&b.current&&(w.context.selectedItemTextRef.current=b.current)},[O,N,M,w,f]);const L=x.useRef("mouse"),z=x.useRef(!1),{getButtonProps:U,buttonRef:B}=Yr({disabled:R,focusableWhenDisabled:!0,native:v,composite:!0}),Q={disabled:R,selected:D,highlighted:C};function W(F){if(k||E)return;const $=w.state.value;if(N){const X=Array.isArray($)?$:[],re=D?lE(X,f,M):[...X,f];w.context.setValue(re,Fe(Ud,F))}else w.context.setValue(f,Fe(Ud,F)),w.context.setOpen(!1,Fe(Ud,F))}function Z(){w.context.selectionRef.current.dragY=0}const Y={role:"option","aria-selected":D,tabIndex:A&&C?0:-1,onKeyDown(F){w.set("activeIndex",O),F.key===" "&&w.context.typingRef.current&&F.preventDefault()},onClick(F){const $=L.current!=="touch",X=F.nativeEvent.pointerType,re=$&&Rm(F.nativeEvent)&&(X!==void 0||C),P=$&&!re&&!z.current;z.current=!1,!(R||P)&&W(F.nativeEvent)},onPointerEnter(F){L.current=F.pointerType},onPointerMove(F){if(F.pointerType==="mouse"&&F.buttons===1){const $=w.context.selectionRef.current;$.dragY+=F.movementY,$.dragY**2>=64&&($.allowUnselectedMouseUp=!0)}},onPointerDown(F){L.current=F.pointerType,z.current=!0,Z()},onMouseUp(){if(Z(),R||L.current==="touch"||z.current)return;const F=!w.context.selectionRef.current.allowSelectedMouseUp&&D,$=!w.context.selectionRef.current.allowUnselectedMouseUp&&!D;F||$||(z.current=!0,_.current?.click(),z.current=!1)}},q=bt("div",t,{ref:[B,a,j.ref,_],state:Q,props:[S,Y,y,U]}),G=x.useMemo(()=>({selected:D,index:O,textRef:b,selectedByFocus:I}),[D,O,b,I]);return s.jsx(vE.Provider,{value:G,children:q})})),TV=x.forwardRef(function(t,a){const{selected:o}=Dy();return t.keepMounted||o?s.jsx(EV,{...t,ref:a}):null}),EV=x.memo(x.forwardRef((e,t)=>{const{render:a,className:o,style:c,keepMounted:d,...f}=e,{selected:p}=Dy(),g=x.useRef(null),{transitionStatus:v,setMounted:y}=yi(p),j=bt("span",e,{ref:[t,g],state:{selected:p,transitionStatus:v},props:[{"aria-hidden":!0,children:"✔️"},f],stateAttributesMapping:ro});return Jr({batch:!0,enabled:!p,open:p,ref:g,onComplete(){p||y(!1)}}),j})),RV=x.memo(x.forwardRef(function(t,a){const{index:o,textRef:c,selectedByFocus:d}=Dy(),f=ho(),{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 bt("div",t,{ref:[b,a,c],props:y})})),ut=rV,dt=dV;function ft({className:e,children:t,...a}){return s.jsxs(cV,{"data-slot":"select-trigger",className:Ve("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(fV,{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 pt({className:e,sideOffset:t=4,children:a,...o}){return s.jsx(pV,{children:s.jsx(bV,{sideOffset:t,className:"z-[35]",children:s.jsx(NV,{"data-slot":"select-content",className:Ve("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 Xe({className:e,children:t,...a}){return s.jsxs(CV,{"data-slot":"select-item",className:Ve("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(RV,{className:"min-w-0 flex-1 truncate",children:t}),s.jsx(TV,{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 Pn({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,R=k.width;v(C=>C.ready&&C.left===E&&C.width===R?C:{left:E,width:R,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(WT,{ref:f,"data-slot":"segmented-control",className:Ve("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:Ve("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(XT,{value:w.value,"data-slot":"segmented-item",disabled:w.disabled,"data-zero":w.count===0?"true":void 0,className:Ve("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:Ve("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 AV=x.createContext(void 0);function OV(){return x.useContext(AV)}const MV=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=Sa(b||void 0),k=OV(),E=k?.value??[],R=(d||k?.disabled)??!1,[C,A]=$a({controlled:k?N!==void 0&&E.indexOf(N)>-1:g,default:c,name:"Toggle",state:"pressed"}),{getButtonProps:D,buttonRef:I}=Yr({disabled:R,native:j}),M={disabled:R,pressed:C},O=[I,a],_=[{"aria-pressed":C,onClick(U){const B=!C,Q=Fe(Kn,U.nativeEvent);p?.(B,Q),!Q.isCanceled&&(N&&k?.setGroupValue?.(N,B,Q),!Q.isCanceled&&A(B))}},S,D],L=bt("button",t,{enabled:!k,state:M,ref:O,props:_}),z=x.useMemo(()=>({disabled:R,focusableWhenDisabled:!1}),[R]);return k?s.jsx(GT,{tag:"button",render:v,className:o,style:w,metadata:z,state:M,refs:O,props:_}):L}),DV=Bc(["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 IV({className:e,variant:t,size:a,...o}){return s.jsx(MV,{"data-slot":"toggle",className:Ve(DV({variant:t,size:a}),e),...o})}function PV(e,t,a,o,c,d,f,p,g,v=2){const y=Jz(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 io(a.current,y)?void 0:y}const yE=x.createContext(void 0),jE=x.createContext(void 0),wE=x.createContext(void 0),SE=x.createContext(!1),NE=x.createContext("");function ka(){const e=x.useContext(yE);if(!e)throw new Error(rn(22));return e}function yh(){const e=x.useContext(jE);if(!e)throw new Error(rn(23));return e}function nf(){const e=x.useContext(wE);if(!e)throw new Error(rn(24));return e}function kE(){return x.useContext(NE)}function _V(){return x.useContext(SE)}const LV={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=>na(t,c,a)):na(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 CE(e){return e==null?void 0:`${e}-popup`}function zV(e,t){return(a,o)=>a==null?!1:e.contains(a,o,t)}const TE=new Map;function BV(e={}){const t={usage:"search",sensitivity:"base",ignorePunctuation:!0,...e},a=`${Vv(e.locale)}|${JSON.stringify(t)}`,o=TE.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=go(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=go(f,g);return c.compare(v.slice(0,p.length),p)===0},endsWith(f,p,g){if(!p)return!0;const v=go(f,g),y=p.length;return v.length>=y&&c.compare(v.slice(v.length-y),p)===0}};return TE.set(a,d),d}const HV=BV;function UV(e,t=!1){const{overflowY:a}=gr(e);return a!=="auto"&&a!=="scroll"?!1:t?e.clientHeight>0:e.scrollHeight>e.clientHeight}const EE=Symbol("none"),Iy={value:EE,index:-1};function VV(e,t,a){const o=e.get(t);if(o!==void 0||a===fh)return o;for(const[c,d]of e)if(na(c,t,a))return d}function FV(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:R=!1,items:C,filteredItems:A,filter:D,filterQuery:I,openOnInputClick:M=!0,autoHighlight:O=!1,keepHighlight:_=!1,highlightItemOnHover:L=!0,loopFocus:z=!0,itemToStringLabel:U,itemToStringValue:B,isItemEqualToValue:Q=fh,virtualized:W=!1,inline:Z=!1,fillInputOnItemPress:Y=!0,modal:q=!1,limit:G=-1,autoComplete:F="list",formAutoComplete:$,locale:X,submitOnItemClick:re=!1}=e,{clearErrors:P}=Hc(),{setDirty:V,validityData:J,setFilled:ie,name:me,disabled:he,setTouched:ae,setFocused:oe,validationMode:ee,validation:de}=wa(),K=Wd(),be=so({id:t}),ne=HV({locale:X}),ce=Array.isArray(C)?null:C;if(ce&&typeof ce.label!="function")throw new Error(rn(100));const we=ce?ce.data:C,Ee=ce?.value,ve=Ee?void 0:we,ke=x.useMemo(()=>{if(!A||!Ee)return;const Me=mh(A),_e=Me.map(Ee);let at;return{values:_e,findItem(qt,En){if(!at){at=new Map;for(let fn=0;fn<_e.length;fn+=1)at.has(_e[fn])||at.set(_e[fn],Me[fn])}return VV(at,qt,En)}}},[A,Ee]),Ce=x.useMemo(()=>ce?Me=>ce.label(Me,Q,_e=>{const at=ke?.findItem(_e,Q);return at!=null?ce.itemLabel(at):go(_e,U)}):U,[ce,U,ke,Q]),Se=x.useMemo(()=>ce?Object.assign(Me=>ce.itemLabel(Me),{selected:Me=>go(Me,Ce)}):U,[ce,Ce,U]);function ge(Me){return go(Me,Ce)}const[Te,Oe]=x.useState(!1),[Ne,Be]=x.useState(null),Qe=x.useRef(Ne),Rt=x.useRef([]),Wt=x.useRef([]),Dt=x.useRef(null),ct=x.useRef(null),$n=x.useRef(null),us=x.useRef(null),qn=x.useRef(null),gs=x.useRef(!0),lt=x.useRef(!1),Bt=x.useRef(null),Ln=x.useRef(null),Jt=x.useRef(null),tt=x.useRef(Iy),Tt=x.useRef(null),Ht=x.useRef([]),Zn=x.useRef(null),zn=he||S,Bn=me??j,Tn=y==="multiple",Qt=y==="single",rs=p!==void 0||f!==void 0,St=we!==void 0,ht=A!==void 0;let vt;O==="always"?vt="always":vt=O?"input-change":!1;const[yt,jr]=$a({controlled:c,default:Tn?o??Er:o,name:"Combobox",state:"selectedValue"}),nr=x.useMemo(()=>D===null?()=>!0:D!==void 0?D:zV(ne,Se),[D,ne,Se]),Pr=Os(()=>rs?f??"":Qt?ge(yt):"").current,[xn,el]=$a({controlled:p,default:Pr,name:"Combobox",state:"inputValue"}),[tn,ac]=$a({controlled:g,default:v,name:"Combobox",state:"open"}),Ax=Oy(we),ur=!tn&&Ne!==null?Ne:String(xn).trim(),Ma=Qt?ge(yt):"",Po=Qt&&!Te&&ur!==""&&Ma.length===ur.length&&ne.contains(Ma,ur),_o=Po?"":I??ur,vp=St&&ht&&Po&&(!ce||ce.hasValue(yt,Q)),lc=x.useMemo(()=>we?mh(we):Er,[we]),Lo=x.useMemo(()=>{if(A&&!vp)return A;if(!we)return Er;if(Ax){const _e=we,at=[];let qt=0;for(const En of _e){if(G>-1&&qt>=G)break;const fn=G>-1?G-qt:1/0,Rn=_o===""?En.items.slice(0,fn):[];if(_o!=="")for(const ds of En.items){if(Rn.length>=fn)break;nr(ds,_o,Se)&&Rn.push(ds)}if(Rn.length>0){const ds={...En,items:Rn};at.push(ds),qt+=Rn.length}}return at}if(_o==="")return G>-1?lc.slice(0,G):lc;const Me=[];for(const _e of lc){if(G>-1&&Me.length>=G)break;nr(_e,_o,Se)&&Me.push(_e)}return Me},[A,vp,we,Ax,_o,G,nr,Se,lc]),Ts=x.useMemo(()=>{if(ke&&Lo===A)return ke.values;const Me=mh(Lo);return Ee?Me.map(_e=>Ee(_e)):Me},[Lo,A,ke,Ee]),Je=Os(()=>{let Me=null;return Z&&tn&&St&&y!=="none"&&(Me=ef(Ts,yt,Q,Tn)),new Zc({id:be,labelId:void 0,selectedValue:yt,open:tn,items:ve,selectionMode:y,name:Bn,form:w,disabled:zn,readOnly:N,required:k,grid:R,virtualized:W,openOnInputClick:M,itemToStringLabel:Ce,isItemEqualToValue:Q,modal:q,autoHighlight:vt,submitOnItemClick:re,hasInputValue:rs,mounted:!1,forceMounted:!1,transitionStatus:"idle",inline:Z,activeIndex:null,selectedIndex:Me,popupProps:{},listProps:{},inputProps:{},triggerProps:{},itemProps:cn,positionerElement:null,listElement:null,popupId:void 0,triggerElement:null,inputElement:null,inputGroupElement:null,popupSide:null,openMethod:null,inputInsidePopup:!0,inputOwnsFormValue:y==="none"},{onOpenChangeComplete:Vt,setOpen:Vt,setInputValue:Vt,setSelectedValue:Vt,setIndices:Vt,handleSelection:Vt,forceMount:Vt,requestSubmit:Vt,listRef:Rt,labelsRef:Wt,popupRef:Dt,emptyRef:qn,inputRef:ct,startDismissRef:$n,endDismissRef:us,keyboardActiveRef:gs,chipsContainerRef:Bt,clearRef:Ln,valuesRef:Ht,pointerDownItemRef:Zn,selectionEventRef:Jt},LV)}).current,Dl=y==="none"?xn:yt,Ox=x.useMemo(()=>y==="none"?Dl:Array.isArray(yt)?yt.map(Me=>Na(Me,B)):Na(yt,B),[Dl,B,y,yt]),Da=Ie(b),Es=Ie(a),$s=Je.useState("activeIndex"),zo=Je.useState("selectedIndex"),oc=Je.useState("positionerElement"),Mx=Je.useState("listElement"),ic=Je.useState("triggerElement"),cc=Je.useState("inputElement"),uc=Je.useState("inputGroupElement"),Rs=Je.useState("inline"),sr=Je.useState("inputInsidePopup"),Il=Je.useState("inputOwnsFormValue"),Pl=Qt&&!sr&&xn===Ma,dc=Yn(ic),{mounted:Bo,setMounted:xs,transitionStatus:yp}=yi(tn),{openMethod:Dx,triggerProps:jp}=VT(tn),_l=Ie(()=>Ox);qc(sr?dc:ct,be,Dl,_l,!zn,j);const Ll=Ie(()=>{we?Wt.current=Ts.map(ge):Je.set("forceMounted",!0)}),Ho=Ie((Me,_e,at)=>{if(_e===-1){if(tt.current===Iy)return;tt.current=Iy}else tt.current={value:Me,index:_e};Da(Me,x4(at,void 0,{index:_e}))}),_r=Ie(Me=>{const _e={};Me.activeIndex!==void 0&&(_e.activeIndex=Me.activeIndex),Me.selectedIndex!==void 0&&(_e.selectedIndex=Me.selectedIndex),Je.update(_e);const at=Me.activeIndex;if(at===void 0)return;const qt=Me.type||Kn;at===null?Ho(void 0,-1,qt):Ho(Ht.current[at],at,qt)}),Lr=Ie((Me,_e)=>{if(e.onInputValueChange?.(Me,_e),!_e.isCanceled){if(lt.current=_e.reason===qa,_e.reason===Vd){tn&&Ne!==null&&Be(null);const at=_e.event,qt=at.inputType;if(at.type==="compositionend"||qt!=null&&qt!==""&&qt!=="insertReplacementText"){const fn=Me.trim()!=="";fn&&Oe(!0),Tt.current={hasQuery:fn};const Rn=Je.state.listElement;if(!Je.state.virtualized&&Rn){const ds=Dt.current;for(const wr of Lc(Rn.firstElementChild??Rn)){if(!on(wr)||(ds?!Ke(ds,wr):wr.getAttribute("role")==="dialog"))break;if(UV(wr)){wr.scrollTop=0;break}}}fn&&vt&&Je.state.activeIndex==null&&(tn||Rs)&&Je.set("activeIndex",0)}}else _e.reason===qa&&Me===""&&Je.state.inputInsidePopup&&(Tt.current={hasQuery:!1,selection:!0});el(Me)}}),Ix=Ie(Me=>{const _e=!Me&&sr&&!Rs&&xn!==""&&(String(xn).trim()===Ne||xn===Ma);!Me&&(_e||xn===""||Pl)&&Oe(!1),Be(null),_e&&Lr("",Fe(qa))}),Et=Ie((Me,_e)=>{if(tn!==Me&&(_e.reason===Gc&&St&&Ts.length===0&&!qn.current&&_e.allowPropagation(),e.onOpenChange?.(Me,_e),!_e.isCanceled&&(Me&&Ne!==null&&Ix(_e.reason===Vd),!Me&&Te&&(Qt?(Rs||Be(ur),ur===""&&Oe(!1)):Tn&&(Rs||Be(ur),sr&&_r({activeIndex:null}),(!sr||Rs)&&Lr("",Fe(qa,_e.event,void 0,{isItemPress:_e.reason===Ud})))),ac(Me),!Me&&sr&&(_e.reason===fo||_e.reason===Bm)&&(ae(!0),oe(!1),ee==="onBlur")))){const at=y==="none"?xn:yt;de.commit(at)}}),fc=Ie((Me,_e)=>{if(d?.(Me,_e),_e.isCanceled)return;jr(Me),(y==="none"&&Dt.current&&Y||Qt&&!Je.state.inputInsidePopup)&&Lr(ge(Me),Fe(_e.reason,_e.event))}),Fu=Ie((Me,_e)=>{const at=os(Me),qt=Jt.current??Me;Jt.current=null;const En=Fe(Ud,qt),fn=at?.closest("a")?.getAttribute("href");if(fn){fn.startsWith("#")&&Et(!1,En);return}if(Tn){const Rn=Array.isArray(yt)?yt:[],ds=ph(Rn,_e,Q),wr=ds?lE(Rn,_e,Q):[...Rn,_e];if(fc(wr,En),En.isCanceled||!(ct.current?ct.current.value.trim()!=="":!1))return;if(Je.state.inputInsidePopup){Lr("",Fe(qa,En.event,void 0,{isItemPress:!0}));const Br=Tt.current;Br&&!ds&&(Br.toggledValue=_e)}else Et(!1,En)}else{if(fc(_e,En),En.isCanceled)return;Et(!1,En)}}),$u=Ie(()=>{const Me=de.inputRef.current?.form??Je.state.inputElement?.form;Me&&typeof Me.requestSubmit=="function"&&Me.requestSubmit()}),zr=Ie(()=>{if(xs(!1),Es?.(!1),Oe(!1),Be(null),_r(y==="none"?{activeIndex:null,selectedIndex:null}:{activeIndex:null}),Tn&&ct.current&&ct.current.value!==""&&!lt.current&&Lr("",Fe(qa)),Qt)if(Je.state.inputInsidePopup)ct.current&&ct.current.value!==""&&Lr("",Fe(qa));else{const Me=ge(yt);ct.current&&ct.current.value!==Me&&Lr(Me,Fe(Me===""?qa:Kn))}}),dr=x.useMemo(()=>Rs&&oc?{current:oc.closest('[role="dialog"]')}:Dt,[Rs,oc]);Jr({enabled:!e.actionsRef,open:tn,ref:dr,onComplete(){tn||zr()}}),x.useImperativeHandle(e.actionsRef,()=>({unmount:zr}),[zr]),De(function(){const _e=Qe.current!==null&&Ne===null;if(Qe.current=Ne,tn&&(!_e||!St)||(tn||(Zn.current=null),y==="none"))return;const at=St?Ts:Ht.current;_r({selectedIndex:ef(at,yt,Q,Tn)})},[tn,Ne,yt,y,Tn,St,Ts,Q,_r]),De(()=>{we&&(Ht.current=Ts,Rt.current.length=Ts.length)},[we,Ts]),De(()=>{const Me=Tt.current;if(Me){const ds=tn||Rs||Je.state.positionerElement?.hidden===!1;if(Me.hasQuery)vt&&ds&&Je.set("activeIndex",0),Tt.current=null;else if(String(xn).trim()===""&&(Tt.current=null,ds)){const wr=Me.selection;vt==="always"&&!wr&&Je.state.selectionMode==="none"&&Je.set("activeIndex",0),queueMicrotask(()=>{if(!Je.state.open&&!Je.state.inline||ct.current&&ct.current.value.trim()!=="")return;const pa=Je.state.selectedValue,Br=Je.state.selectionMode==="multiple";if(Br&&Array.isArray(pa)?pa.length>0:Je.state.selectionMode!=="none"&&pa!=null){const Is=St||ht?Ts:Ht.current,Pa=Jc(Is,Me.toggledValue,Je.state.isItemEqualToValue);Je.set("activeIndex",Pa!==-1?Pa:ef(Is,pa,Je.state.isItemEqualToValue,Br))}else wr?Je.set("activeIndex",null):vt==="always"&&Je.set("activeIndex",0)})}}if(!tn&&!Rs)return;const at=St||ht?Ts:Ht.current,qt=Je.state.activeIndex;if(qt==null){if(vt==="always"&&at.length>0){Je.set("activeIndex",0);return}Ho(void 0,-1,Kn);return}if(qt>=at.length){Ho(void 0,-1,Kn),Je.set("activeIndex",null);return}const En=at[qt],fn=tt.current.value,Rn=fn!==EE&&na(En,fn,Je.state.isItemEqualToValue);(tt.current.index!==qt||!Rn)&&Ho(En,qt,Kn)},[$s,vt,Ho,ht,St,Ts,Rs,tn,Je,xn]),De(()=>{if(y==="none"){ie(String(xn)!=="");return}ie(Tn?Array.isArray(yt)&&yt.length>0:yt!=null)},[ie,y,xn,yt,Tn]),x.useEffect(()=>{St&&vt&&Ts.length===0&&_r({activeIndex:null})},[St,vt,Ts.length,_r]);function Px(){tn&&ur!==""&&ur!==String(Pr)&&!Pl&&Oe(!0)}function fS(){tn&&Ne!==null&&Ix(!1)}let qu=!1;function wp(){!qu&&xn!==Ma&&(qu=!0,Lr(Ma,Fe(Kn)))}function pS(){y!=="none"&&(P(Bn),V(rE(yt,J.initialValue,Q)),de.change(yt),Qt&&!rs&&!sr&&wp())}function fr(){Qt&&!rs&&!sr&&!Te&&wp()}function Sp(){y==="none"&&(P(Bn),V(xn!==J.initialValue),de.change(xn))}ea(ur,Px),ea(tn,fS),ea(yt,pS),ea(Ma,fr),ea(we,fr),ea(xn,Sp);const pc=rT({open:Rs?!0:tn,onOpenChange:Et,elements:{reference:sr?ic:cc,floating:oc}}),Gu=R?"grid":"listbox",Ia=tn||Rs,Np=Ia?"true":"false",mc=x.useMemo(()=>{const Me=cc?.tagName==="INPUT",_e=cc==null||Me,at=_e||Ia,qt=_e?{autoComplete:"off",spellCheck:"false",autoCorrect:"off",autoCapitalize:"none"}:{};return at&&(qt.role="combobox",qt["aria-expanded"]=Np,qt["aria-haspopup"]=Gu,qt["aria-controls"]=Ia?Mx?.id:void 0,qt["aria-autocomplete"]=N?"none":F),{reference:qt,floating:{role:"presentation"}}},[cc,Ia,Np,Gu,Mx?.id,F,N]),zl=qm(pc,{enabled:!zn&&M,event:"mousedown-only",toggle:!1,touchOpenDelay:sr?0:100,reason:m4}),Ku=Xd(pc,{enabled:!zn&&!Rs,outsidePressEvent:{mouse:"sloppy",touch:"intentional"},bubbles:Rs?!0:void 0,outsidePress(Me){const _e=os(Me);return!Ke(ic,_e)&&!Ke(Ln.current,_e)&&!Ke(Bt.current,_e)&&!Ke(uc,_e)}}),Bl=cT(pc,{enabled:!zn,id:be,listRef:Rt,activeIndex:$s,selectedIndex:zo,virtual:!0,loopFocus:z,allowEscape:z&&!vt,focusItemOnOpen:Te||y==="none"&&!vt?!1:"auto",focusItemOnHover:L,resetOnPointerLeave:!_,orientation:R?"horizontal":void 0,rtl:K==="rtl",disabledIndices:Er,grid:R?PV:void 0,onNavigate(Me,_e){!_e&&!tn||yp==="ending"||_r(_e?{activeIndex:Me,type:gs.current?YC:XC}:{activeIndex:Me})}}),kp=x.useMemo(()=>Kr(Bl.reference,{onKeyDown(Me){R&&Je.state.activeIndex==null&&(Me.key==="ArrowLeft"||Me.key==="ArrowRight")&&Me.preventBaseUIHandler()}},Ku.reference,zl.reference,mc.reference),[Bl.reference,Ku.reference,zl.reference,mc.reference,R,Je]),Yu=x.useMemo(()=>Kr(Qd,Ku.floating),[Ku.floating]),_x=x.useMemo(()=>Kr(Bl.floating,mc.floating),[Bl.floating,mc.floating]),Lx=x.useMemo(()=>{const Me=Bl.item;return Me?{...Me,onFocus:void 0}:cn},[Bl.item]);Je.useContextCallback("setOpen",Et),Je.useContextCallback("setInputValue",Lr),Je.useContextCallback("setSelectedValue",fc),Je.useContextCallback("setIndices",_r),Je.useContextCallback("handleSelection",Fu),Je.useContextCallback("forceMount",Ll),Je.useContextCallback("requestSubmit",$u),Je.useContextCallback("onOpenChangeComplete",a),JT(()=>{Je.update({inline:Z,popupProps:Yu,listProps:_x,inputProps:kp,triggerProps:jp,itemProps:Lx})});const hc={id:be,selectedValue:yt,open:tn,mounted:Bo,transitionStatus:yp,items:ve,inline:Z,popupProps:Yu,listProps:_x,inputProps:kp,triggerProps:jp,itemProps:Lx,openMethod:Dx,selectionMode:y,name:Bn,form:w,disabled:zn,readOnly:N,required:k,grid:R,virtualized:W,openOnInputClick:M,itemToStringLabel:Ce,modal:q,autoHighlight:vt,isItemEqualToValue:Q,submitOnItemClick:re,hasInputValue:rs};De(()=>{Je.update({...hc,inputOwnsFormValue:y==="none"&&(Z||!Je.state.inputInsidePopup)})},[Je,...Object.values(hc)]);const fa=Xr(E,de.inputRef),Cp=x.useMemo(()=>({query:ur,hasItems:St,filteredItems:Lo,flatFilteredValues:Ts}),[ur,St,Lo,Ts]),Tp=x.useMemo(()=>Array.isArray(Dl)?"":Na(Dl,B),[Dl,B]),Uo=Tn&&Array.isArray(yt)&&yt.length>0,tl=Tn||y==="none"&&Il?void 0:Bn,zx=x.useMemo(()=>!Tn||!Array.isArray(yt)||!Bn?null:yt.map(Me=>{const _e=Na(Me,B);return s.jsx("input",{type:"hidden",form:w,name:Bn,value:_e,disabled:zn},_e)}),[Tn,yt,w,Bn,B,zn]),Ep=s.jsxs(x.Fragment,{children:[e.children,s.jsx("input",{...de.getValidationProps(zn,{onFocus(){if(sr){ic?.focus();return}(ct.current||ic)?.focus()},onChange(Me){if(Me.nativeEvent.defaultPrevented||zn||N)return;const _e=Me.currentTarget.value,at=_e.toLowerCase(),qt=Fe(Kn,Me.nativeEvent),En=()=>Ht.current.findIndex(Rn=>Na(Rn,B).toLowerCase()===at||ge(Rn).toLowerCase()===at);function fn(){if(Tn)return;if(y==="none"){Lr(_e,qt);return}let Rn=En();Rn===-1&&(Rn=Ht.current.findIndex((wr,pa)=>{const Br=Wt.current[pa];return Br!=null&&Br.toLowerCase()===at}));const ds=Rn===-1?void 0:Ht.current[Rn];ds!=null&&fc?.(ds,qt)}Qt&&(Ll(),we&&En()===-1&&Je.set("forceMounted",!0)),queueMicrotask(fn)}}),id:be&&tl==null?`${be}-hidden-input`:void 0,form:w,name:tl,autoComplete:$,disabled:zn,required:k&&!Uo,readOnly:N,value:Tp,ref:fa,style:tl?Kc:Ni,tabIndex:-1,"aria-hidden":!0,suppressHydrationWarning:!0}),zx]});return s.jsx(yE.Provider,{value:Je,children:s.jsx(jE.Provider,{value:pc,children:s.jsx(SE.Provider,{value:St,children:s.jsx(wE.Provider,{value:Cp,children:s.jsx(NE.Provider,{value:xn,children:Ep})})})})})}function $V(e){const{multiple:t=!1,defaultValue:a,value:o,onValueChange:c,autoComplete:d,...f}=e;return s.jsx(FV,{...f,selectionMode:t?"multiple":"single",selectedValue:o,defaultSelectedValue:a,onSelectedValueChange:c,formAutoComplete:d})}const qV="data-popup-side",GV="data-list-empty",RE={...jv,...gi,popupSide:e=>e?{[qV]:e}:null,listEmpty:e=>e?{[GV]:""}:null},KV=x.createContext(void 0);function YV(){return x.useContext(KV)}const AE=x.createContext(void 0);function Py(e){const t=x.useContext(AE);if(t===void 0&&!e)throw new Error(rn(21));return t}const OE=x.forwardRef(function(t,a){const o=ka(),{buttonRef:c,getButtonProps:d}=Yr({native:!1}),f=Xr(a,c);function p(v){o.context.setOpen(!1,Fe(zv,v.nativeEvent,v.currentTarget))}const g=d({onClick:p});return s.jsx("span",{ref:f,...g,"aria-label":"Dismiss",tabIndex:void 0,style:Kc})});function ME(e){const t=e.useState("mounted"),a=e.useState("popupSide"),o=e.useState("positionerElement");return t&&o?a:null}function jh(){return nf().filteredItems.length===0}function XV(e){return e==="rtl"?["ArrowRight","ArrowLeft"]:["ArrowLeft","ArrowRight"]}function QV(e,t){const a=e>=t-1?t-2:e;return a>=0?a:void 0}function DE(e,t,a){const o=e.context.listRef.current[t];o&&(e.context.selectionEventRef.current=a,o.click(),e.context.selectionEventRef.current=null)}const ZV=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}=wa(),{labelId:N}=hl(),k=YV(),R=!!Py(!0),C=ka(),A=kE(),D=Wd(),I=C.useState("required"),M=C.useState("disabled"),O=C.useState("readOnly"),_=C.useState("name"),L=C.useState("form"),z=C.useState("selectionMode"),U=C.useState("autoHighlight"),B=C.useState("inputProps"),Q=C.useState("triggerProps"),W=C.useState("open"),Z=C.useState("mounted"),Y=C.useState("selectedValue"),q=C.useState("id"),G=C.useState("inline"),F=C.useState("modal"),$=!!U,X=ME(C),re=y||M||d,P=jh(),V=R||G,J=!V||F,ie=Sa(f??(V?void 0:q)),me=R?gC:v,[he,ae]=x.useState(null),oe=x.useRef(!1),ee=x.useRef(null),de=x.useRef(!1),K=z==="none"&&!R,be=Ie(Se=>{const ge=R||C.state.inline;ge&&!C.state.hasInputValue&&C.context.setInputValue("",Fe(Kn)),C.update({inputElement:Se,inputInsidePopup:ge,inputOwnsFormValue:K})}),ne=R?g:S.getValidationProps(re,g);function ce(){C.context.setIndices({activeIndex:null,selectedIndex:null,type:C.context.keyboardActiveRef.current?YC:XC})}function we(){C.context.keyboardActiveRef.current=!1}const Ee={...me,open:W,disabled:re,readOnly:O,popupSide:X,listEmpty:P};function ve(Se){if(!k)return;let ge;const{highlightedChipIndex:Te}=k,Oe=k.chipsRef.current.length,[Ne,Be]=XV(D);return Te!==void 0?(Se.key===Ne?(Se.preventDefault(),Te>0?ge=Te-1:ge=void 0):Se.key===Be?(Se.preventDefault(),Te0&&(Se.preventDefault(),ge=Oe>0?Oe-1:void 0),ge)}const ke=bt("input",t,{state:Ee,ref:[a,C.context.inputRef,be],props:[B,Q,{value:he??A,"aria-readonly":O||void 0,"aria-required":I||void 0,"aria-labelledby":N,disabled:re,readOnly:O,required:z==="none"?I:void 0,form:L,...K&&_&&{name:_},id:ie,onFocus(){if(j(!0),!G||!de.current)return;de.current=!1;const Se=ee.current;Se==null||!Object.hasOwn(C.context.valuesRef.current,Se)||C.context.setIndices({activeIndex:Se})},onBlur(){b(!0),j(!1);const Se=C.state.activeIndex;if(G&&Se!==null&&U!=="always"&&(ee.current=Se,de.current=!0,C.context.setIndices({activeIndex:null})),w==="onBlur"){const ge=z==="none"?A:Y;S.commit(ge)}},onCompositionStart(Se){Nm||(oe.current=!0,ae(Se.currentTarget.value))},onCompositionEnd(Se){oe.current=!1;const ge=Se.currentTarget.value;ae(null),C.context.setInputValue(ge,Fe(Vd,Se.nativeEvent))},onChange(Se){const ge=Se.nativeEvent,Te=ge.inputType,Oe=!Te||Te==="insertReplacementText",Ne=oe.current||!Oe;function Be(Dt){O||re||!Dt||!Ne||(C.context.setOpen(!0,Fe(Vd,ge)),$||ce())}if(oe.current){const Dt=Se.currentTarget.value;ae(Dt),Dt===""&&!C.state.openOnInputClick&&!C.state.inputInsidePopup&&C.context.setOpen(!1,Fe(qa,ge));const ct=Dt.trim(),$n=$&&ct!=="";Be(ct),W&&C.state.activeIndex!==null&&!$n&&ce();return}const Qe=Fe(Vd,ge);if(C.context.setInputValue(Se.currentTarget.value,Qe),Qe.isCanceled)return;const Rt=Se.currentTarget.value==="",Wt=Fe(qa,ge);Rt&&!C.state.inputInsidePopup&&(z==="single"&&C.context.setSelectedValue(null,Wt),C.state.openOnInputClick||C.context.setOpen(!1,Wt)),Be(Se.currentTarget.value.trim()),W&&C.state.activeIndex!==null&&!$&&ce()},onKeyDown(Se){if(Se.ctrlKey||Se.shiftKey||Se.altKey||Se.metaKey)return;if(C.context.keyboardActiveRef.current=!0,re||O){O&&Se.key==="Enter"&&W&&C.state.activeIndex!==null&&Ss(Se);return}const ge=Se.currentTarget,Te=ge.scrollWidth-ge.clientWidth,Oe=D==="rtl";if(Se.key==="Home"){Ss(Se);const Qe=SC&&Oe?ge.value.length:0;ge.setSelectionRange(Qe,Qe),ge.scrollLeft=0;return}if(Se.key==="End"){Ss(Se);const Qe=SC&&Oe?0:ge.value.length;ge.setSelectionRange(Qe,Qe),ge.scrollLeft=Oe?-Te:Te;return}if(!Z&&Se.key==="Escape"){const Qe=z==="multiple"&&Array.isArray(Y)?Y.length===0:Y===null,Rt=Fe(Gc,Se.nativeEvent),Wt=z==="multiple"?[]:null;C.context.setInputValue("",Rt),C.context.setSelectedValue(Wt,Rt),!Qe&&!C.state.inline&&!Rt.isPropagationAllowed&&Se.stopPropagation();return}if(k&&Se.key==="Backspace"&&ge.value===""&&k.highlightedChipIndex===void 0&&Array.isArray(Y)&&Y.length>0){const Qe=k.chipsRef.current.length,Rt=Qe>0?Qe-1:Y.length-1,Wt=Y.filter((Dt,ct)=>ct!==Rt);ce(),C.context.setSelectedValue(Wt,Fe(Kn,Se.nativeEvent));return}const Ne=k?.highlightedChipIndex!==void 0,Be=ve(Se);if(k?.setHighlightedChipIndex(Be),Be!==void 0?k?.chipsRef.current[Be]?.focus():Ne&&C.context.inputRef.current?.focus(),Se.which!==229&&Se.key==="Enter"&&W){const Qe=C.state.activeIndex,Rt=Se.nativeEvent;if(Qe===null){if(G)return;C.context.setOpen(!1,Fe(Kn,Rt));return}Ss(Se),DE(C,Qe,Rt)}},onPointerMove:we,onPointerDown:we},ne],stateAttributesMapping:RE}),Ce=R?s.jsx(bC.Provider,{value:xC,children:ke}):ke;return s.jsxs(x.Fragment,{children:[W&&J&&s.jsx(OE,{ref:C.context.startDismissRef}),Ce]})}),WV=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}=wa(),{labelId:k}=hl(),E=ka(),R=E.useState("selectionMode"),C=E.useState("disabled"),A=E.useState("readOnly"),D=E.useState("required"),I=E.useState("positionerElement"),M=E.useState("listElement"),O=E.useState("popupId"),_=E.useState("triggerProps"),L=E.useState("inputInsidePopup"),z=E.useState("id"),U=E.useState("labelId"),B=E.useState("open"),Q=E.useState("selectedValue"),W=E.useState("activeIndex"),Z=E.useState("selectedIndex"),Y=E.useState("hasSelectedValue"),q=yh(),G=kE(),F=Qs(),$=b||C||f,X=jh(),re=ME(E);so({id:L?p:void 0});const P=L?p??z:p,V=uE(k,U);let J;B&&L?J=O??CE(z):B&&(J=M?.id);const ie=x.useRef("");function me(ne){ie.current=ne.pointerType}const{reference:he}=uT(q,{enabled:!B&&!A&&!C&&R==="single",listRef:E.context.labelsRef,activeIndex:W,selectedIndex:Z,onMatch(ne){const ce=E.context.valuesRef.current[ne];ce!==void 0&&E.context.setSelectedValue(ce,Fe(Kn))}}),{reference:ae}=qm(q,{enabled:!C,event:"mousedown"}),{buttonRef:oe,getButtonProps:ee}=Yr({native:d,disabled:$}),de={...y,readOnly:A,open:B,disabled:$,popupSide:re,listEmpty:X,placeholder:R==="none"?!1:!Y},K=Ie(ne=>{E.set("triggerElement",ne)});return bt("button",t,{ref:[a,oe,K],state:de,props:[_,ae,he,{id:P,tabIndex:L?0:-1,role:L?"combobox":void 0,"aria-expanded":B,"aria-haspopup":L?"dialog":"listbox","aria-controls":J,"aria-required":L&&D||void 0,"aria-readonly":L&&A||void 0,"aria-labelledby":V,onPointerDown:me,onPointerEnter:me,onFocus(){w(!0),!$&&F.start(0,E.context.forceMount)},onBlur(ne){if(!Ke(I,ne.relatedTarget)&&(j(!0),w(!1),S==="onBlur")){const ce=R==="none"?G:Q;N.commit(ce)}},onMouseDown(ne){if($||(L||q.set("domReferenceElement",ne.currentTarget),E.context.forceMount(),ie.current!=="touch"&&(E.context.inputRef.current?.focus(),L||ne.preventDefault()),B))return;const ce=Ut(ne.currentTarget);function we(Ee){const ve=E.state.triggerElement;if(!ve)return;const ke=os(Ee),Ce=E.state.positionerElement,Se=E.state.listElement;Ke(ve,ke)||Ke(Ce,ke)||Ke(Se,ke)||dE(Ee,ve)||E.context.setOpen(!1,Fe(QC,Ee))}L&&ce.addEventListener("mouseup",we,{once:!0})},onKeyDown(ne){(ne.key==="ArrowDown"||ne.key==="ArrowUp")&&(Ss(ne),E.context.setOpen(!0,Fe(Bv,ne.nativeEvent)),E.context.inputRef.current?.focus())}},N.getValidationProps($,v),ee],stateAttributesMapping:RE})}),JV=x.createContext(null);function e6(){return x.useContext(JV)}function t6(e){const{children:t}=e,{filteredItems:a}=nf(),o=e6(),c=o?o.items:a;return s.jsx(x.Fragment,{children:c.map(t)})}const n6=x.forwardRef(function(t,a){var o;const{render:c,className:d,style:f,children:p,...g}=t,v=ka(),y=yh(),b=!!Py(!0),{filteredItems:j,hasItems:w}=nf(),S=v.useState("selectionMode"),N=v.useState("grid"),k=v.useState("readOnly"),E=v.useState("listProps"),R=v.useState("virtualized"),C=v.useState("forceMounted"),A=S==="multiple",D=j.length===0,I=Ie(B=>{v.set("positionerElement",B)}),M=Ie(B=>{v.set("listElement",B)}),O=x.useMemo(()=>typeof p=="function"?o||(o=s.jsx(t6,{children:p})):p,[p]),_={empty:D},L=y.useState("floatingId"),z=bt("div",t,{state:_,ref:[a,M,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(B){if(!(v.state.disabled||v.state.readOnly)&&B.key==="Enter"){const Q=v.state.activeIndex;if(Q==null)return;Ss(B),DE(v,Q,B.nativeEvent)}},onKeyDownCapture(){v.context.keyboardActiveRef.current=!0},onPointerMoveCapture(){v.context.keyboardActiveRef.current=!1}},g]});if(R)return z;const U=w&&!C?void 0:v.context.labelsRef;return s.jsx(Ry,{elementsRef:v.context.listRef,labelsRef:U,children:z})}),s6="⁠",r6=200;function a6(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 l6(){const e=Qs(),t=x.useRef(null);return x.useEffect(()=>{if(Ld)return;const a=t.current;if(a==null)return;const o=a6(a);if(o==null)return;const c=o.data,d=`${c}${s6}`;return o.nodeValue=d,e.start(r6,()=>{o.nodeValue===d&&(o.nodeValue=c)}),()=>{e.clear(),o.nodeValue===d&&(o.nodeValue=c)}},[t,e]),t}const IE=x.createContext(void 0);function o6(){const e=x.useContext(IE);if(e===void 0)throw new Error(rn(20));return e}const i6=x.forwardRef(function(t,a){const{keepMounted:o=!1,...c}=t,d=ka(),f=d.useState("mounted"),p=d.useState("forceMounted");return f||o||p?s.jsx(IE.Provider,{value:o,children:s.jsx(Fm,{ref:a,...c})}):null}),c6=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=b1,style:E,...R}=t,C=ka(),A=yh(),D=o6(),I=C.useState("modal"),M=C.useState("open"),O=C.useState("mounted"),_=C.useState("openMethod"),L=C.useState("positionerElement"),z=C.useState("triggerElement"),U=C.useState("inputElement"),B=C.useState("inputGroupElement"),Q=C.useState("inputInsidePopup"),W=C.useState("transitionStatus"),Z=jh(),q=sh({anchor:d??(Q?z:B??U),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:D,collisionAvoidance:k,lazyFlip:!0});My(M&&I,_==="touch",L,z);const G={open:M,side:q.side,align:q.align,anchorHidden:q.anchorHidden,empty:Z};De(()=>{C.set("popupSide",q.side)},[C,q.side]);const F=Ie(X=>{C.set("positionerElement",X)}),$=rh(t,G,{styles:q.positionerStyles,transitionStatus:W,props:R,refs:[a,F],hidden:!O,inert:!M});return s.jsxs(AE.Provider,{value:q,children:[O&&I&&s.jsx(ih,{inert:ah(!M),cutout:B??U??z}),$]})}),u6={...Uc,...ro},d6=x.forwardRef(function(t,a){const{render:o,className:c,style:d,initialFocus:f,finalFocus:p,...g}=t,v=ka(),y=Py(),b=yh(),j=v.useState("mounted"),w=v.useState("open"),S=v.useState("openMethod"),N=v.useState("popupProps"),k=v.useState("transitionStatus"),E=v.useState("inputInsidePopup"),R=v.useState("inputElement"),C=v.useState("modal"),A=v.useState("id"),D=jh(),I=g.id??(E?CE(A):void 0);De(()=>(v.set("popupId",v.context.popupRef.current?.id||I),()=>{v.set("popupId",void 0)}),[v,I]),Jr({open:w,ref:v.context.popupRef,onComplete(){w&&v.context.onOpenChangeComplete(!0)}});const M={open:w,side:y.side,align:y.align,anchorHidden:y.anchorHidden,transitionStatus:k,empty:D},O=bt("div",t,{state:M,ref:[a,v.context.popupRef],props:[N,{id:I,role:E?"dialog":"presentation",onFocus(B){const Q=os(B.nativeEvent);S!=="touch"&&(Ke(v.state.listElement,Q)||Q===B.currentTarget)&&v.context.inputRef.current?.focus()}},Jd(k),g],stateAttributesMapping:u6}),L=f===void 0?E?B=>B==="touch"?v.context.popupRef.current:R:!1:f;let z;p!=null?z=p:z=E?void 0:!1;const U=!E||C;return s.jsx($m,{context:b,disabled:!j,modal:U,openInteractionType:S,initialFocus:L,returnFocus:z,getInsideElements:()=>[v.context.startDismissRef.current,v.context.endDismissRef.current],children:s.jsxs(x.Fragment,{children:[O,U&&s.jsx(OE,{ref:v.context.endDismissRef})]})})}),f6=x.forwardRef(function(t,a){const{render:o,className:c,style:d,...f}=t;return bt("span",t,{ref:a,props:[{"aria-hidden":!0,children:"▼"},f]})}),PE=x.createContext(void 0);function _E(){const e=x.useContext(PE);if(!e)throw new Error(rn(19));return e}const p6=x.createContext(!1);function m6(){return x.useContext(p6)}function LE(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=Ey({guess:!0,index:v,textRef:w}),N=ka(),k=m6(),E=_V(),R=N.useState("selectionMode"),C=N.useState("disabled"),A=N.useState("readOnly"),D=N.useState("isItemEqualToValue"),I=C||y,M=R!=="none",O=v??c??S.index,_=O!==-1,L=N.useState("id"),z=N.useState("isActive",O),U=N.useState("isSelected",g),B=N.useState("itemProps"),Q=x.useRef(null),W=L!=null&&_?`${L}-${O}`:void 0,Z=U&&M;De(()=>{if(!(_&&(o||v!=null)))return;const V=N.context.listRef.current;return V[O]=Q.current,()=>{delete V[O]}},[_,o,O,v,N]),De(()=>{if(!_||E)return;const P=N.context.valuesRef.current;return P[O]=g,()=>{delete P[O]}},[_,E,O,g,N]),De(()=>{if(!_||E)return;const P=N.state.selectedValue;let V=N.state.selectedIndex;N.state.selectionMode==="multiple"&&Array.isArray(P)?V=aE(O,g,N.context.valuesRef.current,P,D,V):na(g,P,D)&&(V=O),N.set("selectedIndex",V)},[_,E,N,O,g,D]);const{getButtonProps:Y,buttonRef:q}=Yr({disabled:I,focusableWhenDisabled:!0,native:b,composite:!0}),G={disabled:I,selected:Z,highlighted:z};function F(P){function V(){N.context.handleSelection(P,g)}N.state.submitOnItemClick?(Ns.flushSync(V),N.context.requestSubmit()):V()}const $={id:W,role:k?"gridcell":"option","aria-selected":M?Z:void 0,tabIndex:void 0,onPointerDownCapture(P){P.isPrimary&&(N.context.pointerDownItemRef.current=P.currentTarget),P.preventDefault()},onMouseDown(P){P.preventDefault()},onClick(P){I||A||F(P.nativeEvent)},onMouseUp(P){const V=N.context.pointerDownItemRef.current===P.currentTarget;N.context.pointerDownItemRef.current=null,!(I||A||P.button!==0||V||!z)&&F(P.nativeEvent)}},X=bt("div",t,{ref:[q,a,S.ref,Q],state:G,props:[B,$,j,Y]}),re=x.useMemo(()=>({selected:Z,textRef:w}),[Z,w]);return s.jsx(PE.Provider,{value:re,children:X})}function h6(e){const{componentProps:t,forwardedRef:a}=e,c=ka().useState("isItemEqualToValue"),{flatFilteredValues:d}=nf(),f=t.value??null,p=Jc(d,f,c);return s.jsx(LE,{componentProps:t,forwardedRef:a,virtualized:!0,indexFromFilter:p})}const g6=x.memo(x.forwardRef(function(t,a){const c=ka().useState("virtualized");return c&&t.index==null?s.jsx(h6,{componentProps:t,forwardedRef:a}):s.jsx(LE,{componentProps:t,forwardedRef:a,virtualized:c,indexFromFilter:void 0})})),x6=x.forwardRef(function(t,a){const{selected:o}=_E();return t.keepMounted||o?s.jsx(b6,{...t,ref:a}):null}),b6=x.memo(x.forwardRef((e,t)=>{const{render:a,className:o,style:c,keepMounted:d,...f}=e,{selected:p}=_E(),g=x.useRef(null),{transitionStatus:v,setMounted:y}=yi(p),j=bt("span",e,{ref:[t,g],state:{selected:p,transitionStatus:v},props:[{"aria-hidden":!0,children:"✔️"},f],stateAttributesMapping:ro});return Jr({batch:!0,enabled:!p,open:p,ref:g,onComplete(){p||y(!1)}}),j})),v6=x.forwardRef(function(t,a){const{render:o,className:c,style:d,children:f,...p}=t,{filteredItems:g}=nf(),v=ka(),y=l6(),b=g.length===0?f:null;return bt("div",t,{ref:[a,v.context.emptyRef,y],props:[{children:b,role:"status","aria-live":"polite","aria-atomic":!0},p]})}),y6="、";function _y({value:e,onValueChange:t,options:a,placeholder:o="",emptyHint:c=po("没有匹配的选项"),searchPlaceholder:d=po("搜索…"),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(y6):o;return s.jsxs($V,{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(WV,{"data-slot":"multi-select-trigger",id:g,title:v,"aria-label":y["aria-label"],className:Ve("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(f6,{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(i6,{children:s.jsx(c6,{sideOffset:4,className:"z-[35]",children:s.jsxs(d6,{"data-slot":"multi-select-content",className:Ve("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(ZV,{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(v6,{children:s.jsx("div",{className:"px-2.5 py-3 text-[11.5px] leading-[1.5] text-muted-foreground",children:c})}),s.jsx(n6,{className:"min-h-0 flex-1 overflow-y-auto overscroll-contain p-[5px]",children:w=>s.jsxs(g6,{value:w,className:Ve("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(x6,{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 zE=x.createContext(void 0);function sf(e){const t=x.useContext(zE);if(t===void 0&&!e)throw new Error(rn(47));return t}const j6={...py,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 w6 extends Zc{constructor(a,o,c){const d=new Xm;super(S6(a,d,o,c),N6(d),j6);sn(this,"setOpen",(a,o)=>{const c=o.reason===Hs,d=o.reason===uo&&o.event.detail===0,f=!a&&(o.reason===Gc||o.reason==null),p=W1(o),g=this.select("activeTriggerId");if(!a&&o.reason===zv&&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=oy(this.state,a,o.trigger,p());b.openChangeReason=o.reason,this.update(b)};c?(this.set("stickIfOpen",!0),this.context.stickIfOpenTimeout.start(lB,()=>{this.set("stickIfOpen",!1)}),Ns.flushSync(v)):v();let y;d?y="click":f?y="dismiss":o.reason===fo&&(y="focus"),this.set("instantType",y)})}}function S6(e,t,a,o=!1){const c={...dy(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 N6(e){return{popupRef:x.createRef(),onOpenChange:void 0,onOpenChangeComplete:void 0,triggerFocusTargetRef:x.createRef(),beforeContentFocusGuardRef:x.createRef(),stickIfOpenTimeout:new Wr,triggerElements:e}}const BE=Hm(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=C6(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),eT(b,j),iy(b);const{forceUnmount:N}=cy(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(Hv))}),[N,b]);const k=j||w;return s.jsxs(zE.Provider,{value:b,children:[g&&s.jsx(ly,{handle:g,store:b}),k&&s.jsx(T6,{store:b,modal:p}),typeof a=="function"?a({payload:S}):a]})});function k6(e){return sf(!0)?s.jsx(BE,{props:e}):s.jsx(pB,{children:s.jsx(BE,{props:e})})}function C6(e,t){const a=ay((o,c)=>new w6(t,o,c));return x.useEffect(()=>a.context.stickIfOpenTimeout.disposeEffect(),[a]),a}function T6({store:e,modal:t}){const a=e.useState("floatingRootContext"),o=Xd(a,{outsidePressEvent:{mouse:t==="trap-focus"?"sloppy":"intentional",touch:"sloppy"}}),c=o.reference,d=o.floating;return uy(e,{activeTriggerProps:c,inactiveTriggerProps:c,popupProps:d}),null}const E6=300;function R6(e,t){const a=x.useRef(null);function o(d){Ns.flushSync(()=>{e.setOpen(!1,Fe(fo,d.nativeEvent,d.currentTarget))}),o4(a.current)?.focus()}function c(d){const f=e.select("positionerElement");if(f&&Fc(d,f))e.context.beforeContentFocusGuardRef.current?.focus();else{Ns.flushSync(()=>{e.setOpen(!1,Fe(fo,d.nativeEvent,d.currentTarget))});let p=l4(e.context.triggerFocusTargetRef.current||t.current);for(;p!==null&&Ke(f,p);){const g=p;if(p=Pv(p),p===g)break}p?.focus()}}return{preFocusGuardRef:a,handlePreFocusGuardFocus:o,handleFocusTargetFocus:c}}const A6=l1(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=E6,closeDelay:j=0,id:w,...S}=t,N=sf(!0),E=sT(g)??N;if(!E)throw new Error(rn(74));const R=Sa(w),C=E.useState("isTriggerActive",R),A=E.useState("floatingRootContext"),D=E.useState("isOpenedByTrigger",R),I=E.useState("triggerPopupId",R),M=x.useRef(null),{registerTrigger:O,isMountedByThisTrigger:_}=J1(R,M,E,{payload:v,disabled:f,openOnHover:y,closeDelay:j}),L=E.useState("openChangeReason"),z=E.useState("stickIfOpen"),U=E.useState("openMethod"),B=E.useState("focusManagerModal"),Q=oT(A,{enabled:!f&&y&&(U!=="touch"||L!==uo),mouseOnly:!0,move:!1,handleClose:fT(),restMs:b,delay:{close:j},triggerElementRef:M,isActiveTrigger:C,isClosing:()=>E.select("transitionStatus")==="ending"}),W=qm(A,{stickIfOpen:z}),Z=UT(()=>E.select("open"),ie=>{E.set("openMethod",ie)}),Y=E.useState("triggerProps",_),{getButtonProps:q,buttonRef:G}=Yr({disabled:f,native:p}),F={open(ie){return ie&&L===uo?jv.open(ie):yv.open(ie)}},{preFocusGuardRef:$,handlePreFocusGuardFocus:X,handleFocusTargetFocus:re}=R6(E,M),V=bt("button",t,{state:{disabled:f,open:D},ref:[G,a,O,M],props:[W.reference,Q,Y,Z,{[x1]:"",id:R,"aria-haspopup":"dialog","aria-expanded":D,"aria-controls":I},S,q],stateAttributesMapping:F}),J=s.jsx(x.Fragment,{children:V},R);return _&&!B?s.jsxs(x.Fragment,{children:[s.jsx(Yc,{ref:$,onFocus:X}),J,s.jsx(Yc,{ref:E.context.triggerFocusTargetRef,onFocus:re})]}):J}),HE=x.createContext(void 0);function O6(){const e=x.useContext(HE);if(e===void 0)throw new Error(rn(45));return e}const M6=x.forwardRef(function(t,a){const{keepMounted:o=!1,...c}=t;return sf().useState("mounted")||o?s.jsx(HE.Provider,{value:o,children:s.jsx(Fm,{ref:a,...c})}):null}),UE=x.createContext(void 0);function D6(){const e=x.useContext(UE);if(!e)throw new Error(rn(46));return e}const I6=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=v1,...R}=t,C=sf(),A=O6(),D=dB(),I=C.useState("floatingRootContext"),M=C.useState("mounted"),O=C.useState("open"),_=C.useState("openChangeReason"),L=C.useState("activeTriggerElement"),z=C.useState("modal"),U=C.useState("openMethod"),B=C.useState("positionerElement"),Q=C.useState("instantType"),W=C.useState("transitionStatus"),Z=C.useState("adaptiveOrigin"),Y=x.useRef(null),q=KC(B),G=sh({anchor:f,floatingRootContext:I,positionMethod:p,mounted:M,side:g,sideOffset:y,align:v,alignOffset:b,arrowPadding:S,collisionBoundary:j,collisionPadding:w,sticky:N,disableAnchorTracking:k,keepMounted:A,nodeId:D,collisionAvoidance:E,adaptiveOrigin:Z}),F=I.useState("domReferenceElement");De(()=>{const V=F,J=Y.current;if(V&&(Y.current=V),J&&V&&V!==J){C.set("instantType",void 0);const ie=new AbortController;return q(()=>{C.set("instantType","trigger-change")},ie.signal),()=>{ie.abort()}}},[F,q,C]);const $=z===!0&&_!==Hs;My(O&&$,U==="touch",B,L);const X=C.useStateSetter("positionerElement"),re={open:O,side:G.side,align:G.align,anchorHidden:G.anchorHidden,instant:Q},P=rh(t,re,{styles:G.positionerStyles,transitionStatus:W,props:R,refs:[a,X],hidden:!M,inert:!O});return s.jsxs(UE.Provider,{value:G,children:[M&&$&&s.jsx(ih,{inert:ah(!O),cutout:L}),s.jsx(fB,{id:D,children:P})]})}),P6=x.createContext(void 0);function _6(){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 L6=x.forwardRef(function(t,a){const{render:o,className:c,style:d,initialFocus:f,finalFocus:p,...g}=t,v=sf(),y=D6(),b=mE()!=null,{context:j,hasClosePart:w}=_6(),S=v.useState("open"),N=v.useState("openMethod"),k=v.useState("instantType"),E=v.useState("transitionStatus"),R=v.useState("popupProps"),C=v.useState("titleElementId"),A=v.useState("descriptionElementId"),D=v.useState("modal"),I=v.useState("mounted"),M=v.useState("openChangeReason"),O=v.useState("activeTriggerElement"),_=v.useState("floatingRootContext"),L=_.useState("floatingId"),z=v.useState("disabled"),U=v.useState("openOnHover"),B=v.useState("closeDelay");Jr({open:S,ref:v.context.popupRef,onComplete(){S&&v.context.onOpenChangeComplete?.(!0)}}),lT(_,{enabled:U&&!z,closeDelay:B});const Q=f===void 0?Q1(v.context.popupRef):f,W=D!==!1&&w;v.useSyncedValue("focusManagerModal",W);const Z=v.useStateSetter("popupElement"),Y={open:S,side:y.side,align:y.align,instant:k,transitionStatus:E},q=bt("div",t,{state:Y,ref:[a,v.context.popupRef,Z],props:[R,{id:L,role:"dialog",...Qd,"aria-labelledby":C,"aria-describedby":A,onKeyDown(G){b&&lh.has(G.key)&&G.stopPropagation()}},Jd(E),g],stateAttributesMapping:wv});return s.jsx($m,{context:_,openInteractionType:N,modal:W,disabled:!I||M===Hs,initialFocus:Q,returnFocus:p,restoreFocus:"popup",previousFocusableElement:on(O)?O:void 0,nextFocusableElement:v.context.triggerFocusTargetRef,beforeContentFocusGuardRef:v.context.beforeContentFocusGuardRef,children:s.jsx(P6.Provider,{value:j,children:q})})});function rf(e){return s.jsx(k6,{"data-slot":"popover",...e})}function wh(e){return s.jsx(A6,{"data-slot":"popover-trigger",...e})}function af({className:e,sideOffset:t=6,align:a="start",side:o,alignOffset:c,collisionPadding:d=8,anchor:f,children:p,...g}){return s.jsx(M6,{children:s.jsx(I6,{className:"z-[35] outline-none",sideOffset:t,align:a,side:o,alignOffset:c,collisionPadding:d,anchor:f,children:s.jsx(L6,{"data-slot":"popover-content",className:Ve("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 z6({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:po("第 {current} / {total} 页",{current:p,total:f})});return s.jsxs("div",{"data-slot":"pager",className:Ve("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:po("上一页")}),s.jsx(se,{type:"button",variant:"outline",size:"sm",disabled:o||p>=f,onClick:()=>a(p+1),children:po("下一页")}),!d&&g]})}const B6=Bc(["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 eu({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:Ve(B6({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:Ve("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 Sh(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 lf(e){const t=e.name||e.id,o=[e.resolveError?r("解析失败"):Sh(e),e.enabled===!1?r("已禁用"):""].filter(Boolean);return o.length?r("{name}({parts})",{name:t,parts:o.join(" · ")}):t}const Ka="pool:";function Pe(){return window}function He(e,t){Pe().wbApp?.toast?.(e,t)}function Sl(e){const t=Pe().wbApp?.esc;return t?t(e):String(e??"").replace(/[&<>"']/g,a=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[a]||a)}function Us(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 mt(e){return e instanceof Error?e.message:String(e)}function tu(e){if(e==null||e==="")return null;const t=Number(e);return Number.isFinite(t)?t:null}function Ly(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 H6(e){return e==="积分"?r("积分"):e==="额度"?r("额度"):e}function U6(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=tu(c?.total),g=tu(c?.used),v=tu(c?.remain),y=c?.unlimited===!0,b=tu(c?.grantAt),j=tu(c?.startAt),w=tu(c?.expireAt),S=c?.daily===!0,N=String(c?.grantReason||"").trim(),k=w!==null&&w>0&&w<=o,E=p!==null&&p>0,R=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&&R!=="—"?`${R} ${H6(f)}`:R,A=E&&v!==null?Math.max(0,Math.min(100,v/p*100)):null,D=v!==null&&v<=0||v===null&&g!==null&&E&&g>=p,I=!y&&!S&&(D||k),M=[];b!==null&&b>0?M.push(r("{time} 领取",{time:Ly(b)})):j!==null&&j>0&&M.push(r("{time} 生效",{time:Ly(j)})),S?M.push(r("每日重置")):w!==null&&w>0&&M.push(k?r("已过期"):r("{time} 到期",{time:Ly(w)})),N&&M.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:Us(b)}):j!==null&&j>0?r("生效 {time}",{time:Us(j)}):"",w!==null&&w>0?k?r("已过期({time})",{time:Us(w)}):r("到期 {time}",{time:Us(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:M.length?M.join(" · "):null,title:_,spent:I}})}function VE({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 FE({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(rf,{open:f,onOpenChange:p,children:[s.jsxs(wh,{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(af,{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(VE,{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(VE,{row:k},`spent-${k.name}-${E}`)):null]}):null]})})]})}const nu="workbuddy",V6="raccoon",F6={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"}},$6={usage:!1,edition:!1,identifier:"userId",expiry:"tokenExpiresAt",emailAsName:!1};function On(e){const t=e?.provider;return typeof t=="string"&&t?t:nu}function lr(e){return e&&F6[e]||$6}function $E(e){const t=Array.isArray(e?.providers)?e.providers:[],a=Array.isArray(e?.accounts)?e.accounts:[],o=new Map;a.forEach(d=>{const f=On(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(nu,{id:nu,label:Pe().wbProviders?.labelOf?.(nu)||"WorkBuddy 国内版",count:0}),[...c.values()]}function Nh(e){const t=lr(On(e)).identifier;return String(e?.[t]||"")}function qE(e){const t=Number(e)||0;return t<=0?0:t<1e11?t*1e3:t}function q6(e){const t=lr(On(e)).expiry;return qE(e?.[t])}function Ca(e){return lr(On(e)).usage}const zy=30,GE=86400,KE=60,YE=1800,XE=86400,QE=1,G6=95e5;function K6(e){return e==="codearts"?[{type:"token",action:"skip",threshold:G6,reset:"daily",enabled:!0}]:e==="cline-free"?[]:[{type:"balance",action:"skip",threshold:QE,enabled:!0}]}function ZE(e){const t=e?.usageQuery;if(!t||typeof t!="object")return{enabled:!0,interval:KE};const a=t.enabled===void 0?!0:t.enabled===!0,o=Number(t.interval)||0,c=o>=zy&&o<=GE;return{enabled:a,interval:a&&!c?KE:o}}function Y6(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)||oXE)return!1}return!0}function X6(e){const t=e?.lowBalance;if(!t||typeof t!="object"||!t.mode)return K6(On(e));const a=Number(t.threshold),o=Number.isFinite(a)&&a>0?a:QE;return t.mode!=="skip"&&t.mode!=="disable"?[]:[{type:"balance",action:t.mode,threshold:o,enabled:!0}]}function su(e){const t=e?.limiters;return Array.isArray(t)?t.filter(Y6):X6(e)}function Q6(e){return su(e).filter(t=>t.type==="token")}function Z6(e,t){const a=t*1e3;return e-e%a}function WE(e){return e.reset==="daily"?0:e.period??0}function By(e,t=Date.now()){if(e===0){const a=new Date(t);return a.setHours(0,0,0,0),a.getTime()}return Z6(t,e)}function of(e,t,a=Date.now()){if(e.type!=="token")return null;const o=WE(e),c=(t||[]).find(d=>Number(d.kind)===o);return c&&Number(c.windowStart)===By(o,a)?c:null}function kh(e,t){const a=su(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=of(c,t,o);return d!==null&&Number(d.used)>=c.threshold})}function W6(e,t){return su(e).some(a=>{if(a.type!=="token"||a.action!=="disable"||a.enabled===!1)return!1;const o=of(a,t);return o!==null&&Number(o.used)>=a.threshold})}function Uy(e,t=Date.now()){const a=WE(e),o=By(a,t),c=a===0?Math.max(0,By(0,o+864e5+36e5)-t):Math.max(0,o+a*1e3-t);return{kind:a,startMs:o,remainingMs:c,daily:a===0}}function Ch(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 Nl(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 JE(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 cf(e){return e?.desktop===!0}function eR(e){return e?.chatSupported!==!1}function J6(e){return typeof e=="string"&&e.startsWith("custom-")}function eF(e){return r(e==="enterprise"?"企业":e==="ultimate"?"旗舰":"个人")}function Th(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 or(e){return e?.enabled!==!1}function uf(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 tR(e){return e?.edition==="intl"?"intl":"cn"}function nR(e){return lr(On(e)).claim?e?.canClaim!==!1:!1}const sR="coding-plan",xo="start-plan";function Eh(e){return!!lr(On(e)).planChannel}function Vy(e){return Eh(e)?String(e?.zcodePlan||"").trim()===xo?xo:sR:""}function tF(e){return r(e===xo?"活动套餐(Start Plan)":"编码套餐(Coding Plan)")}function rR(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 Rh(e){const t=e?.claimPlans;if(!t||typeof t!="object"||Array.isArray(t))return[];const a=Fy();return Object.entries(t).filter(([,o])=>Number(o)>0&&Fy(Number(o))===a).map(([o])=>o)}function nF(e){return Rh(e).length>0}function sF(e){const t=Rh(e),a=t.length?r("({plans})",{plans:t.join(r("、"))}):"";return r("今天(北京时间 {day})已领取 {n} 份{names};还有其他可领套餐时,点这里可以继续领;活动按自然日发新套餐,明天可再领",{day:Fy(),n:t.length,names:a})}function rF(e){return!!lr(On(e)).usageDetail}function aR(e){return!!lr(On(e)).creditDetail}function lR(e){return/^free$/i.test(String(e??"").trim())}function aF(e){const t=String(e??"").trim();return/^trial$/i.test(t)?r("试用版"):lR(t)?r("免费版"):t}function Fy(e=Date.now()){return new Date(e+8*3600*1e3).toISOString().slice(0,10)}function df(e,t,a){return uf(e)||kh(e,t)||Hy(e,a)}function oR(e,t){const a=String(t.q||"").trim().toLowerCase();return a?[ru(e),e?.name,e?.nickname,e?.email,Nh(e),e?.id].some(c=>String(c||"").toLowerCase().includes(a)):!0}function iR(e,t){return t.provider==="all"||On(e)===t.provider}function $y(e,t){return t.enabled==="all"?!0:t.enabled==="enabled"?or(e):!or(e)}function cR(e,t,a,o){if(t.limit==="all")return!0;if(!or(e))return!1;const c=df(e,a?.(e),o?.(e));return t.limit==="limited"?c:!c}function uR(e,t,a,o){return iR(e,t)&&$y(e,t)&&cR(e,t,a,o)&&oR(e,t)}function lF(e,t,a,o){return(e||[]).filter(c=>uR(c,t,a,o))}function dR(e,t,a,o){const c=e||[],d=g=>c.filter(v=>iR(v,t)&&(g==="enabled"||$y(v,t))&&oR(v,t)),f=d("enabled"),p=d("limit");return{enabledAll:f.length,enabled:f.filter(or).length,disabled:f.filter(g=>!or(g)).length,limitAll:p.length,normal:p.filter(g=>or(g)&&!df(g,a?.(g),o?.(g))).length,limited:p.filter(g=>or(g)&&df(g,a?.(g),o?.(g))).length}}function qy(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 Gy(e){const t=(e||[]).slice().sort(Th),a=new Map;return t.forEach((o,c)=>a.set(o.id,{position:c+1,total:t.length})),a}function oF(e,t,a,o){const c=(e||[]).slice().sort(Th),d=[],f=new Map;for(const p of c){const g=On(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(or).length,disabled:v.filter(y=>!or(y)).length,limited:v.filter(y=>or(y)&&df(y,a?.(y),o?.(y))).length}})}function ru(e){if(!e)return"";const t=String(e.name||"").trim();if(e.nameCustom===!0&&t)return t;const a=String(e.email||"").trim();return lr(On(e)).emailAsName&&a?a:e?.nickname||t||Nh(e)||e?.id||""}const Ky="已限流",fR=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime();function Yy(e){const t=Number(e);if(!Number.isFinite(t)||t<=0||t<=Date.now())return Ky;const a=new Date(t),o=a.toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit",hour12:!1}),c=Math.round((fR(a)-fR(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 iF(e){const t=On(e);if(!lr(t).edition)return"";const a=tR(e),o=e?.editionLabel,c=o||(a==="intl"?"国际版":"国内版");return(Pe().wbProviders?.labelOf?.(t)||"").includes(c)?"":o||r(a==="intl"?"国际版":"国内版")}function cF(e){return[eR(e)?null:{text:r("仅账号管理"),kind:"plain",title:r("该提供商的推理转发尚未接入,账号不参与转发")},J6(On(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,Vy(e)===xo?{text:r("活动套餐"),kind:"plain",title:r("转发走活动套餐通道(zcode.z.ai 的 Anthropic 端点,用账号里领到的额度);在账号设置里可切回编码套餐")}:null].filter(t=>t!==null)}const pR="workbuddy-desktop-accounts-filters",mR="workbuddy-desktop-accounts-collapsed",hR="workbuddy-desktop-accounts-names-hidden";function uF(){const e={provider:"all",enabled:"all",limit:"all",q:""},t=Pe().wbFilterMemory?.load(pR,e)||e;return{provider:String(t.provider||"all"),enabled:String(t.enabled||"all"),limit:String(t.limit||"all"),q:""}}function dF(){try{const e=JSON.parse(localStorage.getItem(mR)||"[]");return new Set(Array.isArray(e)?e.map(t=>String(t)).filter(Boolean):[])}catch{return new Set}}function fF(){try{return localStorage.getItem(hR)==="1"}catch{return!1}}let un={version:0,filter:uF(),collapsed:dF(),selected:new Set,panels:new Map,connections:new Map,clash:null,dialog:null,namesHidden:fF(),usageBusy:!1,usageInflight:new Set};const Xy=new Set;function gR(e){return Xy.add(e),()=>{Xy.delete(e)}}function Zs(){return un}function jn(e){un={...un,...e,version:un.version+1},Xy.forEach(t=>t())}function xr(){jn({})}function Qy(){return Pe().wbApp?.getState?.()?.accounts}function kl(){const e=Qy()?.accounts;return Array.isArray(e)?e:[]}function Ta(e){return kl().find(t=>t.id===e)||null}function pF(e,t){const a=oF(kl(),c=>uR(c,un.filter,e,t),e,t);return{groups:a.filter(c=>c.accounts.length>0),allGroups:a}}function xR(){return $E(Qy())}function mF(e,t){return dR(kl(),un.filter,e,t)}function hF(){return Gy(kl())}function Ah(){Pe().wbFilterMemory?.save(pR,{provider:un.filter.provider,enabled:un.filter.enabled,limit:un.filter.limit})}function gF(e){un.filter.q!==e&&jn({filter:{...un.filter,q:e}})}function xF(e){const t=e||"all";un.filter.provider!==t&&(jn({filter:{...un.filter,provider:t}}),Ah())}function bR(e,t){const a={...un.filter,[e]:t};a.enabled==="disabled"&&a.limit!=="all"&&(a.limit="all"),jn({filter:a}),Ah()}function Oh(){return un.filter.provider!=="all"||un.filter.enabled!=="all"||un.filter.limit!=="all"||un.filter.q.trim()!==""}function vR(){jn({filter:{provider:"all",enabled:"all",limit:"all",q:""}}),Ah()}function bF(){const e=un.filter.provider;e!=="all"&&(xR().some(t=>t.id===e)||(jn({filter:{...un.filter,provider:"all"}}),Ah()))}function yR(e){try{localStorage.setItem(mR,JSON.stringify([...e]))}catch{}}function jR(e){const t=new Set(un.collapsed);t.has(e)?t.delete(e):t.add(e),yR(t),jn({collapsed:t})}function vF(e,t){const a=new Set(un.collapsed);for(const o of e)t?a.add(o):a.delete(o);yR(a),jn({collapsed:a})}function yF(e){return un.selected.has(e)}function jF(e,t){const a=new Set(un.selected);t?a.add(e):a.delete(e),jn({selected:a})}function wR(e,t){const a=new Set(un.selected);for(const o of e)t?a.add(o):a.delete(o);jn({selected:a})}function wF(){jn({selected:new Set})}function SR(e,t){return un.panels.get(e)?.has(t)===!0}function NR(e,t,a){if(!e)return;const o=new Map(un.panels),c=new Set(o.get(e)||[]);a?c.add(t):c.delete(t),c.size?o.set(e,c):o.delete(e),jn({panels:o})}function SF(e,t){const a=new Map(un.panels);for(const o of e){const c=new Set(a.get(o)||[]);c.add(t),a.set(o,c)}jn({panels:a})}function NF(){const e=!un.namesHidden;try{localStorage.setItem(hR,e?"1":"0")}catch{}jn({namesHidden:e})}function kF(e){return"*".repeat(Math.min(Math.max(e.length,4),12))}const kR="usage_not_configured",bo=new Map,ff=new Map;function sa(e,t,a){bo.set(e,t),t!=null&&au(t)?ff.set(e,a):ff.delete(e)}function Ya(e){const t=bo.get(e.id);if(t===void 0)return;if(!au(t))return t;const a=Math.max(Number(e.addedAt)||0,Number(e.updatedAt)||0);return(ff.get(e.id)||0)>=a?t:void 0}const pf=new Map;let CR=0;function Cl(e){return e?pf.get(e.id)||[]:[]}function CF(e){const t=Number(e?.tokenAt)||0;if(!t||t===CR)return!1;const a=e?.tokenUsage;if(!a||typeof a!="object")return!1;CR=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!==pf.size||[...o].some(([d,f])=>{const p=pf.get(d);return!p||p.length!==f.length||f.some((g,v)=>g.used!==p[v]?.used||g.windowStart!==p[v]?.windowStart)});pf.clear();for(const[d,f]of o)pf.set(d,f);return c}let Mh=null;async function TR(e={}){const t=Zs().clash;if(!e.force&&t)return t;Mh||(Mh=(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{Mh=null}})());const a=await Mh;return jn({clash:a}),a}function TF(){jn({clash:null})}let mf=null,Dh=null;function EF(){return mf}async function ER(e={}){if(!e.force&&mf)return mf;Dh||(Dh=(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{Dh=null}})());const t=await Dh;return mf=t,t}let Zy=null;function RF(){return Zy}let Ih=0,RR=!1;function AF(){if(!(mf||Date.now(){Ih=0,Zy=null,xr()}).catch(e=>{Zy=mt(e),xr()})}}function Ph(e){if(!Ta(e)){He(r("账号不存在,请刷新后重试"),"err");return}jn({dialog:{kind:"settings",id:e}})}function _h(){jn({dialog:null})}function Wy(e,t="enable"){const a=(Array.isArray(e)?e:[]).filter(o=>Ta(o));if(!a.length){He(r("请先勾选要操作的账号"),"err");return}jn({dialog:{kind:"batch",ids:a,action:t}})}function OF(e){let t=!1;for(const f of[...bo.keys()])e.has(f)||(bo.delete(f),t=!0);for(const f of[...ff.keys()])e.has(f)||ff.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&&jn({panels:a,connections:o,usageInflight:c,selected:d})}const MF=2e3;function AR(e){return Zs().connections.get(e)||0}async function OR(){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 jn({connections:a}),!0}catch{return!1}}let MR=null;function DF(){MR||(MR=setInterval(()=>{document.hidden||Pe().wbApp?.currentPage!=="accounts"||OR()},MF))}function Jy(){return kl().filter(e=>Ca(e)&&e.available!==!1)}function au(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===kR}:null}function DR(e){return e.usage?e.usage:{error:e.error?String(e.error):r("余额响应为空"),code:e.code}}function IR(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&&(sa(String(c.id),DR(c),Number(c.at)||a),o++);return o&&(xr(),Pe().wbApp?.renderTopbarStatus?.()),o}let PR=!1;function IF(e){if(!aR(e))return!1;const t=Ya(e);return!t||typeof t!="object"||Array.isArray(t)||au(t)?!1:!Array.isArray(t.credits)}async function PF(){if(!PR){PR=!0;for(const e of kl().filter(IF)){const t=bo.get(e.id);try{await hf(e.id)}catch{}const a=bo.get(e.id);t!==void 0&&(!a||au(a))&&sa(e.id,t,Date.now()),xr()}}}let _R=0;async function _F(){try{const e=await Pe().workbuddyDesktop?.getBalancesSnapshot?.(),t=CF(e);t&&(xr(),Pe().wbApp?.renderTopbarStatus?.());const a=Number(e?.at)||0;return!a||a===_R||(_R=a,!IR(e))?t:(PF(),!0)}catch{return!1}}async function hf(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),sa(f,DR(d),o))}if(e)return c.has(e)||sa(e,r("未返回余额数据"),o),xr(),t;for(const d of Jy())c.has(d.id)||sa(d.id,r("未返回余额数据"),o);return xr(),t}async function LR(){if(Zs().usageBusy)return;const e=Jy();if(!e.length){He(r("暂无可查询余额的账号"),"err");return}jn({usageBusy:!0}),e.forEach(t=>sa(t.id,null,Date.now())),xr();try{const t=(await hf(null))?.results||[],a=t.filter(f=>f.usage).length,o=t.filter(f=>f.code===kR).length,c=o?r("({n} 个未配置查询凭证)",{n:o}):"",d=t.length-a-o;He(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=mt(t);e.forEach(o=>sa(o.id,r("查询失败:{message}",{message:a}),Date.now())),xr(),He(r("余额查询失败:{message}",{message:a}),"err")}finally{jn({usageBusy:!1})}}async function zR(e){if(Zs().usageInflight.has(e))return;const t=new Set(Zs().usageInflight);t.add(e),sa(e,null,Date.now()),jn({usageInflight:t});try{await hf(e)}finally{const a=new Set(Zs().usageInflight);a.delete(e),jn({usageInflight:a})}}async function LF(e){if(!Zs().usageInflight.has(e))try{await zR(e);const t=au(bo.get(e));t?.notConfigured?He(t.message,"ok"):t?He(r("余额查询失败:{message}",{message:t.message}),"err"):He(r("✅ 已更新余额"))}catch(t){sa(e,r("查询失败:{message}",{message:mt(t)}),Date.now()),xr(),He(r("余额查询失败:{message}",{message:mt(t)}),"err")}}async function Lh(e){if(e){const a=Ta(e);if(!a||!Ca(a))return;try{await zR(e)}catch(o){sa(e,r("查询失败:{message}",{message:mt(o)}),Date.now()),xr()}return}if(Zs().usageBusy)return;const t=Jy();if(t.length){jn({usageBusy:!0}),t.forEach(a=>sa(a.id,null,Date.now())),xr();try{await hf(null)}catch(a){const o=mt(a);t.forEach(c=>sa(c.id,r("查询失败:{message}",{message:o}),Date.now())),xr()}finally{jn({usageBusy:!1})}}}async function BR(e,t){try{await Pe().workbuddyDesktop?.updateAccount?.(e,{enabled:t}),await Pe().wbApp?.refresh?.(),He(r(t?"✅ 已启用":"✅ 已禁用"))}catch(a){He(r("操作失败:{message}",{message:mt(a)}),"err"),Pe().wbApp?.refresh?.()}}async function HR(e,t){if(!e.length)return!1;try{return await Pe().workbuddyDesktop?.reorderAccounts?.(e),He(t?r("✅ 已保存:{note}",{note:t}):r("✅ 顺序已保存")),await Pe().wbApp?.refresh?.(),!0}catch(a){return He(r("顺序未保存:{message}",{message:mt(a)}),"err"),Pe().wbApp?.refresh?.(),!1}}async function UR(e,t){if(e.length)try{await Pe().workbuddyDesktop?.batchAccounts?.({action:t?"enable":"disable",ids:e}),He(t?r("✅ 已启用 {n} 个账号",{n:e.length}):r("✅ 已禁用 {n} 个账号",{n:e.length})),await Pe().wbApp?.refresh?.()}catch(a){He(r("操作失败:{message}",{message:mt(a)}),"err"),Pe().wbApp?.refresh?.()}}async function zF(e,t){try{await Pe().workbuddyDesktop?.clearRateLimits?.(e,t||null),He(t?r("✅ 已清除 {model} 的限流标记",{model:t}):r("✅ 已清除该账号全部限流标记")),await Pe().wbApp?.refresh?.()}catch(a){He(r("清除失败:{message}",{message:mt(a)}),"err")}}async function BF(e,t,a){if(t===VR){Ph(e);return}if(t!==zh&&t!==a)try{const o=t===""?null:{source:"pool",proxyId:t.slice(Ka.length)},d=(await Pe().workbuddyDesktop?.updateAccount?.(e,{proxy:o}))?.changes,f=Array.isArray(d)&&d.length?d[0]:r("代理已更新");He(`✅ ${f}`)}catch(o){He(r("保存失败:{message}",{message:mt(o)}),"err")}finally{await Pe().wbApp?.refresh?.()}}const zh="__proxy_custom__",VR="__proxy_custom_edit__";function FR(e,t){const a=Ta(e);if(!a){He(r("账号不存在,请刷新后重试"),"err");return}const o=Pe().wbZcodePlans;if(!o?.open){He(r("套餐明细弹窗未加载,请重启应用后重试"),"err");return}o.open({id:e,name:t||a.name})}function HF(e,t,a=1){return{seat:t.get(e.id)||{position:1,total:1},rank:a,picked:yF(e.id),usageEntry:bo.get(e.id),limitsOpen:SR(e.id,"limits"),connections:AR(e.id)}}const UF={DEFAULT_PROVIDER_ID:nu,RACCOON_PROVIDER_ID:V6,providerOf:On,providerFeatures:lr,providerSummaries:$E,identifierOf:Nh,tokenExpiryOf:q6,supportsUsage:Ca,isDesktopAccount:cf,supportsChat:eR,byPriorityOrder:Th,typeLabel:eF,isEnabled:or,isRateLimited:uf,isLimited:e=>df(e,e?Ya(e):void 0,Cl(e)),accountEdition:tR,supportsClaim:nR,matchEnabled:$y,matchLimit:cR,visibleAccounts:lF,filterCounts:dR,positionMap:Gy,activeLimits:qy,editionSuffix:iF,formatResetText:Yy};function VF(){window.wbAccountsView={render:()=>xr(),refreshCaches:OF,openPanels:SF,syncConnections:OR,applyBalances:IR,syncBalancesSnapshot:_F,queryUsageFor:hf,queryAllUsage:LR,refreshUsageAfterCheckin:Lh,supportsUsage:Ca,isDesktopAccount:cf,isEnabled:or,isRateLimited:uf},window.wbAccountsModel=UF,window.wbAccountPanel={open:Ph,close:_h,openBatch:Wy,closeBatch:_h,syncAddProvider:()=>Pe().wbAccountAddForms?.syncAddProvider?.(),invalidate:TF}}function FF(e){return e.type==="balance"?r("余额 < {threshold}",{threshold:e.threshold}):e.reset==="daily"?r("每日消耗 ≥ {count} Token(每天 0 点重置)",{count:Nl(e.threshold)}):r("每 {period}消耗 ≥ {count} Token",{period:JE(e.period??0),count:Nl(e.threshold)})}function $F(e){return e.action==="disable"?r("禁用该账号(需手动重新启用)"):r("跳过该账号(自动恢复)")}function qF(e){return`${Math.round(e.threshold).toLocaleString("en-US")} Token`}function GF(e,t){if(t.enabled===!1)return{text:r("已停用"),kind:"off"};if(t.type==="balance"){const v=Ya(e),y=kh(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=Cl(e),o=of(t,a),c=o?o.used:0,d=Nl(t.threshold),f=t.reset==="daily"?r(" · 今日 {used} / {quota}",{used:Nl(c),quota:d}):r(" · 本周期 {used} / {quota}",{used:Nl(c),quota:d}),p=o?` · ${Ch(Uy(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:qF(t)}}function KF(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 $R(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=KF(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 qR(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 cXE?{error:r("重置周期必须是 30 分钟 ~ 24 小时")}:{rule:{type:"token",action:e.action,threshold:a,period:c,reset:"fixed",enabled:!0}}}function YF({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=qR(f);if("error"in b){d(b.error);return}o(b.rule,t.index)},y=()=>{if(f.type==="balance"){const R=Ya(e);if(R&&typeof R=="object"){const C=R;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=qR(f);if(!("rule"in b))return"";const j=b.rule,w=of(j,Cl(e));if(!w)return j.reset==="daily"?r("窗口 = 今天 0 点起(本地时区),0 点重置即清零恢复;按账号在 requests 表聚合"):r("窗口对齐自然时间(整点 / 整 N 分钟一轮回),重置即清零恢复;按账号在 requests 表聚合");const S=Uy(j),N=Nl(w.used),k=Nl(j.threshold),E=j.reset==="daily"?r("今日已用"):r("本周期已用");return r("{scope} {used} / {quota} Token,{countdown}重置",{scope:E,used:N,quota:k,countdown:Ch(S.remainingMs,S.daily)})};return s.jsx(Kt,{open:!0,onOpenChange:b=>{b||a()},children:s.jsxs(Yt,{className:"w-[min(580px,calc(100vw-48px))]",showCloseButton:!0,children:[s.jsx($t,{children:s.jsx(Ft,{children:t.index>=0?r("编辑限制"):r("添加限制")})}),s.jsxs(_t,{children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("限制类型")}),s.jsxs(ut,{value:f.type,onValueChange:b=>g({type:b,thresholdInput:""}),children:[s.jsx(ft,{className:"w-[150px]","aria-label":r("限制类型"),children:s.jsx(dt,{children:f.type==="balance"?r("余额"):r("Token 消耗")})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"balance",children:r("余额")}),s.jsx(Xe,{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(Ye,{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(ut,{value:f.action,onValueChange:b=>g({action:b}),children:[s.jsx(ft,{className:"min-w-[280px]","aria-label":r("触发动作"),children:s.jsx(dt,{children:f.action==="disable"?r("禁用该账号(需手动重新启用)"):r("跳过该账号(余额回升自动恢复)")})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"skip",children:r("跳过该账号(余额回升自动恢复)")}),s.jsx(Xe,{value:"disable",children:r("禁用该账号(需手动重新启用)")})]})]})]})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"field-row",children:[s.jsx("label",{children:r("重置方式")}),s.jsxs(ut,{value:f.reset,onValueChange:b=>g({reset:b}),children:[s.jsx(ft,{className:"w-[190px]","aria-label":r("重置方式"),children:s.jsx(dt,{children:f.reset==="daily"?r("自然日(每天 0 点)"):r("固定周期")})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"fixed",children:r("固定周期")}),s.jsx(Xe,{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(Ye,{type:"number",min:0,step:1,className:"max-w-[110px]",placeholder:r("阈值"),value:f.thresholdInput,onChange:b=>g({thresholdInput:b.currentTarget.value})}),s.jsxs(ut,{value:f.tokenUnit,onValueChange:b=>g({tokenUnit:b}),children:[s.jsx(ft,{className:"w-[92px]","aria-label":r("Token 单位"),children:s.jsx(dt,{children:f.tokenUnit==="wan"?r("万"):r("个")})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"wan",children:r("万")}),s.jsx(Xe,{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(Ye,{type:"number",min:1,step:1,className:"max-w-[90px]",placeholder:r("周期"),value:f.periodInput,onChange:b=>g({periodInput:b.currentTarget.value})}),s.jsxs(ut,{value:f.periodUnit,onValueChange:b=>g({periodUnit:b}),children:[s.jsx(ft,{className:"w-[92px]","aria-label":r("周期单位"),children:s.jsx(dt,{children:f.periodUnit==="hours"?r("小时"):r("分钟")})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"minutes",children:r("分钟")}),s.jsx(Xe,{value:"hours",children:r("小时")})]})]}),s.jsx("span",{className:"detail",style:{fontSize:13},children:r("内消耗 ≥")}),s.jsx(Ye,{type:"number",min:0,step:1,className:"max-w-[110px]",placeholder:r("阈值"),value:f.thresholdInput,onChange:b=>g({thresholdInput:b.currentTarget.value})}),s.jsxs(ut,{value:f.tokenUnit,onValueChange:b=>g({tokenUnit:b}),children:[s.jsx(ft,{className:"w-[92px]","aria-label":r("Token 单位"),children:s.jsx(dt,{children:f.tokenUnit==="wan"?r("万"):r("个")})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"wan",children:r("万")}),s.jsx(Xe,{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(ut,{value:f.action,onValueChange:b=>g({action:b}),children:[s.jsx(ft,{className:"min-w-[280px]","aria-label":r("触发动作"),children:s.jsx(dt,{children:f.action==="disable"?r("禁用该账号(需手动重新启用)"):r("跳过该账号(重置后自动恢复)")})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"skip",children:r("跳过该账号(重置后自动恢复)")}),s.jsx(Xe,{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(en,{children:[s.jsx(se,{variant:"outline",onClick:a,children:r("取消")}),s.jsx(se,{variant:"default",onClick:v,children:t.index>=0?r("保存规则"):r("添加规则")})]})]})})}function XF({account:e,draft:t,onChange:a}){const[o,c]=x.useState(null),d=()=>c({index:-1,draft:$R(null)}),f=y=>c({index:y,draft:$R(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=GF(e,y);return s.jsxs("div",{className:"limiter-rule","data-off":y.enabled===!1||void 0,children:[s.jsx(ps,{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:FF(y),action:$F(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(YF,{account:e,target:o,onClose:()=>c(null),onSave:p})]})}function QF(e,t){const a=su(e);return JSON.stringify(t)===JSON.stringify(a)?null:{patch:{limiters:t}}}function ZF(e){return su(e).map(t=>({...t}))}const WF={seconds:1,minutes:60,hours:3600};function JF(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 e$(e){const{enabled:t,interval:a}=ZE(e),o=JF(t?a:0);return{enabled:t,intervalInput:o.value,unit:o.unit}}function t$(e,t){const a=Math.round(Number(t.intervalInput)*WF[t.unit]);if(t.enabled){if(!Number.isFinite(Number(t.intervalInput))||Number(t.intervalInput)<=0)return{error:r("请填写查询间隔")};if(aGE)return{error:r("查询间隔必须是 {min} 秒 ~ 24 小时",{min:zy})}}const o={},c=ZE(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 n$({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(st,{className:"inline-flex cursor-pointer items-center gap-2.5 font-normal",children:[s.jsx(ps,{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(Ye,{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(ut,{value:t.unit,onValueChange:c=>o({unit:c}),children:[s.jsx(ft,{className:"w-[92px]","aria-label":r("间隔单位"),children:s.jsx(dt,{children:t.unit==="hours"?r("小时"):t.unit==="minutes"?r("分钟"):r("秒")})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"seconds",children:r("秒")}),s.jsx(Xe,{value:"minutes",children:r("分钟")}),s.jsx(Xe,{value:"hours",children:r("小时")})]})]}),s.jsx("span",{className:"detail",children:r("30 秒 ~ 24 小时;手动查询会顺延下一轮")})]}):null]})}const GR=64;function s$(e,t){const a=On(e);return t.filter(o=>o.id!==e.id&&On(o)===a)}const Tl=999;function Bh(e){return ru(e)||e?.id||""}function KR(e){const t=e?.config?.source||e?.source,a=e?.config||null;return{mode:t==="pool"?"pool":t==="clash"?"clash":t==="custom"?"custom":"none",proxyId:t==="pool"?String(a?.proxyId||""):"",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 ej(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==="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 XR({draft:e,onChange:t,idPrefix:a}){const c=Zs().clash,d=Array.isArray(c?.options)?c.options:[],f=e.mode==="clash",[p,g]=x.useState(!1),[v,y]=x.useState(null),[b,j]=x.useState(null),[w,S]=x.useState(""),N=R=>t({...e,...R});x.useEffect(()=>{f&&TR().catch(()=>{})},[f]);const k=x.useCallback((R=!1)=>{S(""),ER({force:R}).then(C=>j(C)).catch(C=>{j([]),S(mt(C))})},[]);x.useEffect(()=>{e.mode==="pool"&&b===null&&k()},[e.mode,b,k]);async function E(){if(p)return;if(e.mode==="pool"){if(!e.proxyId){He(r("请先选择已保存的代理"),"err");return}g(!0),y(r("正在连接上游…"));try{const C=await Pe().workbuddyDesktop?.testProxyPoolItem?.(e.proxyId);y(C?.success?s.jsxs("span",{className:"text-success",children:[r("✅ 出口可用"),C.ip?r(" 出口 IP {ip}",{ip:Sl(C.ip)}):"",C.durationMs!==void 0&&C.durationMs!==""?` ${Sl(String(C.durationMs))}ms`:""]}):s.jsxs("span",{className:"text-destructive",children:["❌ ",Sl(C?.error||r("连接失败"))]}))}catch(C){y(s.jsxs("span",{className:"text-destructive",children:["❌ ",Sl(mt(C))]}))}finally{g(!1)}return}let R;try{R=ej(e)}catch(C){He(mt(C),"err");return}g(!0),y(r("正在连接上游…"));try{const C=await Pe().workbuddyDesktop?.testProxy?.({proxy:R});C?.success?y(s.jsxs("span",{className:"text-success",children:[r("✅ 出口可用"),C.status!==void 0&&C.status!==""?` HTTP ${Sl(String(C.status))}`:"",C.ip?r(" 出口 IP {ip}",{ip:Sl(C.ip)}):"",C.durationMs!==void 0&&C.durationMs!==""?` ${Sl(String(C.durationMs))}ms`:""]})):y(s.jsxs("span",{className:"text-destructive",children:["❌ ",Sl(C?.error||r("连接失败"))]}))}catch(C){y(s.jsxs("span",{className:"text-destructive",children:["❌ ",Sl(mt(C))]}))}finally{g(!1)}}return s.jsxs("div",{className:"flex flex-col",children:[s.jsxs(dh,{value:e.mode,onValueChange:R=>N({mode:R}),className:"flex-row flex-wrap items-center gap-5","aria-label":r("代理方式"),children:[s.jsxs(st,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(Mi,{value:"none"}),r("无代理(直连)")]}),s.jsxs(st,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(Mi,{value:"pool"}),r("已保存的代理")]}),f?s.jsxs(st,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(Mi,{value:"clash"}),"Clash Verge"]}):null,s.jsxs(st,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(Mi,{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(ut,{value:e.proxyId,disabled:!b?.length,onValueChange:R=>N({proxyId:String(R)}),children:[s.jsx(ft,{id:`${a}-pool-exit`,className:"min-w-[220px]",children:s.jsx(dt,{children:b?.find(R=>R.id===e.proxyId)?lf(b.find(R=>R.id===e.proxyId)):b===null?r("正在读取…"):b.length?r("请选择代理"):r("还没有保存的代理")})}),s.jsx(pt,{children:(b??[]).map(R=>s.jsx(Xe,{value:R.id,children:lf(R)},R.id))})]}),s.jsx(se,{variant:"outline",size:"sm",onClick:()=>k(!0),children:r("重新读取")})]}),s.jsx("div",{className:"detail mt-1.5",children:w?r("读取失败:{error}",{error:w}):b===null?r("正在读取代理列表…"):b.length?r("地址与端口由「网络代理」页管理:那边改一次、测一次,所有引用它的账号一起生效"):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(ut,{value:e.listenerUid,disabled:!d.length,onValueChange:R=>N({listenerUid:String(R)}),children:[s.jsx(ft,{id:`${a}-clash-exit`,className:"min-w-[220px]",children:s.jsx(dt,{children:d.find(R=>String(R.uid)===e.listenerUid)?YR(d.find(R=>String(R.uid)===e.listenerUid)):c?.available===!1?r("未检测到 Clash Verge"):d.length?r("请选择出口"):r("没有可用出口")})}),s.jsx(pt,{children:d.map(R=>s.jsx(Xe,{value:String(R.uid),children:YR(R)},String(R.uid)))})]}),s.jsx(se,{variant:"outline",size:"sm",onClick:()=>{TR({force:!0}).then(()=>He(r("✅ 已重新读取 Clash Verge 配置"))).catch(R=>He(r("读取失败:{error}",{error:mt(R)}),"err"))},children:r("重新读取")})]}),s.jsx("div",{className:"detail mt-1.5",children:c===null?r("正在读取 Clash Verge 配置…"):c.available===!1?c.error?r("不可用:{error}",{error:c.error}):r("未检测到 Clash Verge 配置"):d.length?r("读取自 {dir};端口由 Clash Verge 管理,这里实时同步",{dir:c.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(ut,{value:e.protocol,onValueChange:R=>N({protocol:R}),children:[s.jsx(ft,{id:`${a}-protocol`,className:"min-w-[110px]",children:s.jsx(dt,{children:e.protocol==="socks5"?"SOCKS5":"HTTP"})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"http",children:"HTTP"}),s.jsx(Xe,{value:"socks5",children:"SOCKS5"})]})]}),s.jsx("label",{htmlFor:`${a}-host`,className:"ml-2",children:r("主机")}),s.jsx(Ye,{id:`${a}-host`,className:"min-w-[140px]",placeholder:"127.0.0.1",value:e.host,onChange:R=>N({host:R.currentTarget.value})}),s.jsx("label",{htmlFor:`${a}-port`,children:r("端口")}),s.jsx(Ye,{id:`${a}-port`,type:"number",min:1,max:65535,className:"max-w-[110px]",placeholder:"7890",value:e.port,onChange:R=>N({port:R.currentTarget.value})})]}),s.jsxs("div",{className:"field-row mt-2.5",children:[s.jsx("label",{htmlFor:`${a}-user`,children:r("用户名")}),s.jsx(Ye,{id:`${a}-user`,placeholder:r("可选"),autoComplete:"off",value:e.username,onChange:R=>N({username:R.currentTarget.value})}),s.jsx("label",{htmlFor:`${a}-pass`,children:r("密码")}),s.jsx(Ye,{id:`${a}-pass`,type:"password",placeholder:r("可选"),autoComplete:"new-password",value:e.password,onChange:R=>N({password:R.currentTarget.value})})]})]}):null,s.jsxs("div",{className:"field-row mt-3",children:[s.jsx(se,{variant:"outline",size:"sm",disabled:p,onClick:()=>{E()},children:r(p?"测试中…":"测试出口")}),s.jsx("span",{className:"detail",children:v})]})]})}function r$({plan:e,hasJwt:t,onChange:a}){const o=tF(e),[c,d]=x.useState(null);return x.useEffect(()=>{if(e!==xo)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(ut,{value:e,onValueChange:f=>a(String(f)),children:[s.jsx(ft,{id:"account-plan-channel",className:"min-w-[220px]",children:s.jsx(dt,{children:o})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:sR,children:r("编码套餐(Coding Plan)— 走开放平台端点,用自己订阅的额度")}),s.jsx(Xe,{value:xo,children:r("活动套餐(Start Plan)— 走官方活动端点,用活动里领到的额度")})]})]}),e===xo&&!t?s.jsx("span",{className:"detail text-destructive",children:r("该账号没有套餐登录态(jwt),活动套餐会失败:请重新登录该账号")}):null,e===xo?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 a$({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(Ye,{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 l$({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(Ye,{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(st,{className:"inline-flex cursor-pointer items-center gap-2.5 font-normal",children:[s.jsx(ta,{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 o$({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(Hn,{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(Ye,{id:"account-provider-name",maxLength:GR,className:"min-w-[220px]",placeholder:r("提供商显示名,1~{max} 个字符",{max:GR}),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(ut,{value:a,onValueChange:w=>p(String(w)),children:[s.jsx(ft,{id:"account-provider-protocol",className:"min-w-[180px]",children:s.jsx(dt,{children:j})}),s.jsx(pt,{children:b.map(w=>s.jsx(Xe,{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(Ye,{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(st,{className:"inline-flex cursor-pointer items-center gap-2.5 font-normal",children:[s.jsx(ta,{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 i$({id:e,onClose:t}){const a=Ta(e),[o,c]=x.useState(a?.enabled!==!1),[d,f]=x.useState(a?.name||""),[p,g]=x.useState(()=>KR(a?.proxy)),[v,y]=x.useState(""),[b,j]=x.useState(()=>Vy(a)),[w,S]=x.useState(!1),[N,k]=x.useState(""),[E,R]=x.useState(null),[C,A]=x.useState(""),[D,I]=x.useState("chat_completions"),[M,O]=x.useState(""),[_,L]=x.useState(""),[z,U]=x.useState(""),[B,Q]=x.useState(a?.noAuth===!0),[W,Z]=x.useState(()=>e$(a)),[Y,q]=x.useState(()=>ZF(a)),[G,F]=x.useState("basic"),[$,X]=x.useState(()=>String(Number(a?.maxConcurrent)||0));if(x.useEffect(()=>{let K=!0;R(null);const be=Ta(e);return be?(Promise.resolve(Pe().wbCustomProvidersUi?.find?.(On(be))).then(ne=>{!K||!ne||(R(ne),A(ne.name||""),I(ne.protocol||"chat_completions"),O(ne.baseUrl||""),L(typeof ne.clientEmulation=="string"?ne.clientEmulation:""))}).catch(()=>{}),()=>{K=!1}):()=>{K=!1}},[e]),!a)return s.jsx(Kt,{open:!0,onOpenChange:K=>{K||t()},children:s.jsxs(Yt,{children:[s.jsx($t,{children:s.jsx(Ft,{children:r("账号设置")})}),s.jsx(_t,{children:s.jsx("p",{className:"detail",children:r("账号不存在,请刷新后重试。")})}),s.jsxs(en,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("关闭")})]})]})});const re=a,P=s$(re,kl()),V=On(re)==="catpaw",J=On(re).startsWith("custom-");async function ie(){if(!w){S(!0);try{await Pe().workbuddyDesktop?.updateAccount?.(e,{balanceToken:null}),y(""),He(r("✅ 已清除余额查询凭证")),await Pe().wbApp?.refresh?.()}catch(K){He(r("清除失败:{error}",{error:mt(K)}),"err")}finally{S(!1)}}}async function me(){if(!w){S(!0);try{await Pe().workbuddyDesktop?.updateAccount?.(e,{apiKey:null}),U(""),He(r("✅ 已清除 API Key(该账号现在没有凭证,转发会被跳过)")),await Pe().wbApp?.refresh?.()}catch(K){He(r("清除失败:{error}",{error:mt(K)}),"err")}finally{S(!1)}}}function he(){if(!J)return null;const K=z.trim(),be={};return K?be.apiKey=K:B!==(re.noAuth===!0)&&(be.noAuth=B),Object.keys(be).length?be:null}function ae(){if(!E)return null;const K=C.trim(),be=M.trim();if(!K)return{error:r("请填写提供商名称")};if(!be)return{error:r("请填写提供商的 Base URL")};const ne=typeof E.clientEmulation=="string"?E.clientEmulation:"";return E.name===K&&E.protocol===D&&E.baseUrl===be&&ne===_?null:{id:E.id,name:K,protocol:D,baseUrl:be,clientEmulation:_}}async function oe(){if(w)return;let K;try{K=ej(p)}catch(Se){He(mt(Se),"err");return}const be=ae();if(be&&"error"in be){k(s.jsx("span",{className:"text-destructive",children:be.error}));return}const ne=Ca(re)?t$(re,W):null;if(ne&&"error"in ne){k(s.jsx("span",{className:"text-destructive",children:ne.error}));return}const ce=QF(re,Y),we=he()||{},Ee=Number($);if(!Number.isFinite(Ee)||Ee<0){He(r("并发上限必须是 0~{max} 的整数",{max:Tl}),"err");return}const ve=Math.min(Tl,Math.round(Ee)),ke=Number(re.maxConcurrent)||0,Ce=ve!==ke?{maxConcurrent:ve}:{};S(!0);try{const Se=V&&v.trim()?{balanceToken:v.trim()}:{},ge=Eh(re)&&b!==Vy(re)?{zcodePlan:b}:{};if(await Pe().workbuddyDesktop?.updateAccount?.(e,{name:d.trim()||re.name,enabled:o,proxy:K,...Se,...ge,...we,...Ce,...ne&&"patch"in ne?ne.patch:{},...ce&&"patch"in ce?ce.patch:{}}),be)try{await Pe().wbCustomProvidersUi?.update?.(be)}catch(Te){k(s.jsx("span",{className:"text-destructive",children:r("账号已保存,但提供商未更新:{error}",{error:mt(Te)})})),await Pe().wbApp?.refresh?.(),S(!1);return}t(),He(r("✅ 账号设置已保存"));try{await Pe().wbApp?.refresh?.()}catch{}}catch(Se){k(s.jsx("span",{className:"text-destructive",children:mt(Se)})),He(r("保存失败:{error}",{error:mt(Se)}),"err")}finally{S(!1)}}const ee=Number(lr(On(re)).concurrencyDefault)||0,de=V||J||Eh(re);return s.jsx(Kt,{open:!0,onOpenChange:K=>{K||w||t()},children:s.jsxs(Yt,{className:"w-[min(900px,calc(100vw-48px))]",children:[s.jsx($t,{children:s.jsx(Ft,{children:r("账号设置 · {name}",{name:Bh(a)})})}),s.jsx(_t,{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("基本")],...de?[["credential",r("凭证与套餐")]]:[],...Ca(re)?[["query",r("查询设置")],["limiter",r("限制器")]]:[],["network",r("网络")]].map(([K,be])=>s.jsx(eu,{active:G===K,title:be,className:"shadow-none",onClick:()=>F(K),children:be},K))]})}),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(ps,{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(Ye,{id:"account-name-input",maxLength:100,placeholder:r("账号显示名称"),className:"max-w-[280px]",value:d,onChange:K=>f(K.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(Ye,{id:"account-conc-input",type:"number",min:0,max:Tl,step:1,className:"max-w-[110px]",value:$,onChange:K=>X(K.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:Tl})})]}):null,G==="credential"&&de?s.jsxs("div",{children:[s.jsxs("div",{className:"acct-dlg-pane-head",children:[s.jsx("h3",{children:r("凭证与套餐")}),s.jsx("p",{children:r("这一段按提供商出现:有什么配什么。")})]}),V?s.jsx(a$,{configured:a.hasBalanceToken===!0,value:v,onChange:y,clearBusy:w,onClear:()=>{ie()}}):null,J?s.jsx(l$,{hasApiKey:re.hasApiKey===!0,noAuth:B,value:z,onValue:U,onToggleNoAuth:Q,onClear:()=>{me()},clearBusy:w}):null,Eh(re)?s.jsx(r$,{plan:b,hasJwt:a.canClaim===!0,onChange:j}):null,E?s.jsx(o$,{provider:E,count:P.length+1,name:C,protocol:D,baseUrl:M,emulation:_,onName:A,onProtocol:I,onBaseUrl:O,onEmulation:L,onRemove:()=>{w||Promise.resolve(Pe().wbCustomProvidersUi?.remove?.(E.id)).then(K=>{K&&t()})}}):null]}):null,G==="query"&&Ca(re)?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(n$,{account:re,draft:W,onChange:Z})]}):null,G==="limiter"&&Ca(re)?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(XF,{account:re,draft:Y,onChange:q})]}):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(XR,{draft:p,onChange:g,idPrefix:"account-proxy"}),a.proxy?.error?s.jsx("p",{className:"detail text-destructive",children:r("当前代理不可用:{error}(转发时会回退直连)",{error:a.proxy.error})}):null]}):null]})]})}),s.jsxs(en,{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:()=>{oe()},children:r(w?"保存中…":"保存")})]})]})})}const c$=[{value:"enable",label:r("启用")},{value:"disable",label:r("禁用")},{value:"proxy",label:r("修改代理")},{value:"concurrency",label:r("设置并发上限")},{value:"remove",label:r("删除")}];function u$({ids:e,action:t,onClose:a}){const[o,c]=x.useState(t),[d,f]=x.useState(()=>KR(null)),[p,g]=x.useState(""),[v,y]=x.useState(!1),[b,j]=x.useState(""),w=e.map(R=>Ta(R)).filter(R=>R!==null),S=w.reduce((R,C)=>Math.max(R,Number(lr(On(C)).concurrencyDefault)||0),0);function N(R){return Promise.resolve(Pe().wbConfirm?.ask?.({title:r("删除选中的账号"),html:r("确定删除选中的 {count} 个账号?此操作不可恢复,账号的登录态会一并移除。",{count:R}),okText:r("删除"),okClass:"danger"})??!1)}async function k(){if(v)return;if(!e.length){He(r("没有选中的账号"),"err");return}let R;if(o==="proxy")try{R=ej(d)}catch(A){He(mt(A),"err");return}let C;if(o==="concurrency"){const A=Number(p.trim());if(!p.trim()||!Number.isFinite(A)||A<0){He(r("并发上限必须是 0~{max} 的整数",{max:Tl}),"err");return}C=Math.min(Tl,Math.round(A))}if(!(o==="remove"&&!await N(e.length))){if(o==="disable"||o==="remove"){const A=new Set(e);if(!kl().filter(I=>I.enabled!==!1&&!A.has(I.id)).length){const I=r(o==="remove"?"删除":"禁用");if(!await Promise.resolve(Pe().wbConfirm?.ask?.({title:r("全部启用中的账号将被{what}",{what:I}),html:r("这会{what}所有启用中的账号,转发将不可用。确定继续?",{what:I}),okText:I,okClass:o==="remove"?"danger":"primary"})??!1))return}}y(!0),j("");try{const A={action:o,ids:e};o==="proxy"&&(A.proxy=R),o==="concurrency"&&(A.maxConcurrent=C);const D=await Pe().workbuddyDesktop?.batchAccounts?.(A),I=(D?.ok||[]).filter(z=>z.changes?.length).length,M=(D?.removed||[]).length,O=D?.failed||[],_=o==="remove"?M:I,L={enable:r("启用"),disable:r("禁用"),proxy:r("修改代理"),concurrency:r("设置并发上限"),remove:r("删除")}[o]||o;if(O.length){const z=O.slice(0,3).map(U=>Bh(Ta(String(U.id)))||U.id).join(r("、"));He(r("{verb}完成:成功 {ok} 个,失败 {fail} 个({detail}{more})",{verb:L,ok:_,fail:O.length,detail:z,more:O.length>3?r(" 等"):""}),"err"),j(s.jsxs("span",{className:"text-destructive",children:[r("失败 {count} 个:",{count:O.length}),O.map(U=>`${Bh(Ta(String(U.id)))||U.id}(${U.error})`).join(r(";"))]}))}else He(r("✅ {verb}完成:共 {count} 个账号",{verb:L,count:_})),a();await Pe().wbApp?.refresh?.()}catch(A){j(s.jsx("span",{className:"text-destructive",children:mt(A)})),He(r("批量操作失败:{error}",{error:mt(A)}),"err")}finally{y(!1)}}}const E={enable:r("启用"),disable:r("禁用"),proxy:r("修改代理"),concurrency:r("设置并发上限"),remove:r("删除")}[o]||o;return s.jsx(Kt,{open:!0,onOpenChange:R=>{R||v||a()},children:s.jsxs(Yt,{children:[s.jsx($t,{children:s.jsx(Ft,{children:r("批量操作 · 已选 {count} 个账号",{count:e.length})})}),s.jsxs(_t,{children:[s.jsxs(Hn,{children:[s.jsx("h3",{children:r("将作用于以下账号")}),s.jsx("p",{style:{maxHeight:84,overflowY:"auto"},children:w.map(R=>Bh(R)).join(r("、"))})]}),s.jsxs(Hn,{children:[s.jsx("h3",{children:r("操作")}),s.jsx(dh,{value:o,onValueChange:c,className:"flex-row flex-wrap items-center gap-5","aria-label":r("批量动作"),children:c$.map(R=>s.jsxs(st,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(Mi,{value:R.value}),R.label]},R.value))}),o==="proxy"?s.jsx("div",{className:"mt-2.5",children:s.jsx(XR,{draft:d,onChange:f,idPrefix:"batch-proxy"})}):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(Ye,{id:"batch-conc-input",type:"number",min:0,max:Tl,step:1,className:"max-w-[110px]",placeholder:r("不限"),value:p,onChange:R=>g(R.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:Tl}):r("并发上限 0~{max};达到上限的账号会被跳过、请求转给其他账号",{max:Tl})})]}):null]}),s.jsx("div",{className:"detail",style:{minHeight:18},children:b})]}),s.jsxs(en,{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:()=>{k()},children:v?r("执行中…"):r("执行({action})",{action:E})})]})]})})}function d$(){const e=Zs();return e.dialog?e.dialog.kind==="settings"?s.jsx(i$,{id:e.dialog.id,onClose:_h},e.dialog.id):s.jsx(u$,{ids:e.dialog.ids,action:e.dialog.action,onClose:_h},e.dialog.ids.join(",")):null}var tj={exports:{}},gf={},nj={exports:{}},sj={};var QR;function f$(){return QR||(QR=1,(function(e){function t(Z,Y){var q=Z.length;Z.push(Y);e:for(;0>>1,F=Z[G];if(0>>1;G<$;){var X=2*(G+1)-1,re=Z[X],P=X+1,V=Z[P];if(0>c(re,q))Pc(V,re)?(Z[G]=V,Z[P]=q,G=P):(Z[G]=re,Z[X]=q,G=X);else if(Pc(V,q))Z[G]=V,Z[P]=q,G=P;else break e}}return Y}function c(Z,Y){var q=Z.sortIndex-Y.sortIndex;return q!==0?q:Z.id-Y.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,R=typeof clearTimeout=="function"?clearTimeout:null,C=typeof setImmediate<"u"?setImmediate:null;function A(Z){for(var Y=a(v);Y!==null;){if(Y.callback===null)o(v);else if(Y.startTime<=Z)o(v),Y.sortIndex=Y.expirationTime,t(g,Y);else break;Y=a(v)}}function D(Z){if(N=!1,A(Z),!S)if(a(g)!==null)S=!0,I||(I=!0,U());else{var Y=a(v);Y!==null&&W(D,Y.startTime-Z)}}var I=!1,M=-1,O=5,_=-1;function L(){return k?!0:!(e.unstable_now()-_Z&&L());){var G=b.callback;if(typeof G=="function"){b.callback=null,j=b.priorityLevel;var F=G(b.expirationTime<=Z);if(Z=e.unstable_now(),typeof F=="function"){b.callback=F,A(Z),Y=!0;break t}b===a(g)&&o(g),A(Z)}else o(g);b=a(g)}if(b!==null)Y=!0;else{var $=a(v);$!==null&&W(D,$.startTime-Z),Y=!1}}break e}finally{b=null,j=q,w=!1}Y=void 0}}finally{Y?U():I=!1}}}var U;if(typeof C=="function")U=function(){C(z)};else if(typeof MessageChannel<"u"){var B=new MessageChannel,Q=B.port2;B.port1.onmessage=z,U=function(){Q.postMessage(null)}}else U=function(){E(z,0)};function W(Z,Y){M=E(function(){Z(e.unstable_now())},Y)}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(Z){Z.callback=null},e.unstable_forceFrameRate=function(Z){0>Z||125G?(Z.sortIndex=q,t(v,Z),a(g)===null&&Z===a(v)&&(N?(R(M),M=-1):N=!0,W(D,q-G))):(Z.sortIndex=F,t(g,Z),S||w||(S=!0,I||(I=!0,U()))),Z},e.unstable_shouldYield=L,e.unstable_wrapCallback=function(Z){var Y=j;return function(){var q=j;j=Y;try{return Z.apply(this,arguments)}finally{j=q}}}})(sj)),sj}var ZR;function p$(){return ZR||(ZR=1,nj.exports=f$()),nj.exports}var WR;function m$(){if(WR)return gf;WR=1;var e=p$(),t=Od(),a=GC();function o(n){var l="https://react.dev/errors/"+n;if(1be||(n.current=K[be],K[be]=null,be--)}function we(n,l){be++,K[be]=n.current,n.current=l}var Ee=ne(null),ve=ne(null),ke=ne(null),Ce=ne(null);function Se(n,l){switch(we(ke,l),we(ve,n),we(Ee,null),l.nodeType){case 9:case 11:n=(n=l.documentElement)&&(n=n.namespaceURI)?ZL(n):0;break;default:if(n=l.tagName,l=l.namespaceURI)l=ZL(l),n=WL(l,n);else switch(n){case"svg":n=1;break;case"math":n=2;break;default:n=0}}ce(Ee),we(Ee,n)}function ge(){ce(Ee),ce(ve),ce(ke)}function Te(n){var l=n.memoizedState;l!==null&&(Td._currentValue=l.memoizedState,we(Ce,n)),l=Ee.current;var i=WL(l,n.type);l!==i&&(we(ve,n),we(Ee,i))}function Oe(n){ve.current===n&&(ce(Ee),ce(ve)),Ce.current===n&&(ce(Ce),Td._currentValue=de)}var Ne,Be;function Qe(n){if(Ne===void 0)try{throw Error()}catch(i){var l=i.stack.trim().match(/\n( *(at )?)/);Ne=l&&l[1]||"",Be=-1)":-1m||te[u]!==pe[m]){var je=` -`+te[u].replace(" at new "," at ");return n.displayName&&je.includes("")&&(je=je.replace("",n.displayName)),je}while(1<=u&&0<=m);break}}}finally{Rt=!1,Error.prepareStackTrace=i}return(i=n?n.displayName||n.name:"")?Xe(i):""}function Mt(n,a){switch(n.tag){case 26:case 27:case 5:return Xe(n.type);case 16:return Xe("Lazy");case 13:return n.child!==a&&a!==null?Xe("Suspense Fallback"):Xe("Suspense");case 19:return Xe("SuspenseList");case 0:case 15:return Qt(n.type,!1);case 11:return Qt(n.type.render,!1);case 1:return Qt(n.type,!0);case 31:return Xe("Activity");case 30:return Xe("ViewTransition");default:return""}}function it(n){try{var a="",i=null;do a+=Mt(n,i),i=n,n=n.return;while(n);return a}catch(u){return` +`+te[u].replace(" at new "," at ");return n.displayName&&je.includes("")&&(je=je.replace("",n.displayName)),je}while(1<=u&&0<=m);break}}}finally{Rt=!1,Error.prepareStackTrace=i}return(i=n?n.displayName||n.name:"")?Qe(i):""}function Dt(n,l){switch(n.tag){case 26:case 27:case 5:return Qe(n.type);case 16:return Qe("Lazy");case 13:return n.child!==l&&l!==null?Qe("Suspense Fallback"):Qe("Suspense");case 19:return Qe("SuspenseList");case 0:case 15:return Wt(n.type,!1);case 11:return Wt(n.type.render,!1);case 1:return Wt(n.type,!0);case 31:return Qe("Activity");case 30:return Qe("ViewTransition");default:return""}}function ct(n){try{var l="",i=null;do l+=Dt(n,i),i=n,n=n.return;while(n);return l}catch(u){return` Error generating stack: `+u.message+` -`+u.stack}}var Un=Object.prototype.hasOwnProperty,as=e.unstable_scheduleCallback,Vn=e.unstable_cancelCallback,fs=e.unstable_shouldYield,lt=e.unstable_requestPaint,_t=e.unstable_now,Pn=e.unstable_getCurrentPriorityLevel,Zt=e.unstable_ImmediatePriority,Je=e.unstable_UserBlockingPriority,Tt=e.unstable_NormalPriority,Lt=e.unstable_LowPriority,Yn=e.unstable_IdlePriority,_n=e.log,Ln=e.unstable_setDisableYieldValue,Cn=null,Gt=null;function Jn(n){if(typeof _n=="function"&&Ln(n),Gt&&typeof Gt.setStrictMode=="function")try{Gt.setStrictMode(Cn,n)}catch{}}var St=Math.clz32?Math.clz32:yt,ht=Math.log,vt=Math.LN2;function yt(n){return n>>>=0,n===0?32:31-(ht(n)/vt|0)|0}var jr=256,nr=262144,Ir=4194304;function gn(n){var a=n&42;if(a!==0)return a;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 Ja(n,a,i){var u=n.pendingLanes;if(u===0)return 0;var m=0,h=n.suspendedLanes,T=n.pingedLanes;n=n.warmLanes;var H=u&134217727;return H!==0?(u=H&~h,u!==0?m=gn(u):(T&=H,T!==0?m=gn(T):i||(i=H&~n,i!==0&&(m=gn(i))))):(H=u&~h,H!==0?m=gn(H):T!==0?m=gn(T):i||(i=u&~n,i!==0&&(m=gn(i)))),m===0?0:a!==0&&a!==m&&(a&h)===0&&(h=m&-m,i=a&-a,h>=i||h===32&&(i&4194048)!==0)?a:m}function Jt(n,a){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&a)===0}function ac(n,a){(a&8)!==0&&(a|=a&32);var i=n.entangledLanes;if(i!==0)for(n=n.entanglements,i&=a;0i;i++)a.push(n);return a}function Po(n,a){n.pendingLanes|=a,a!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function _o(n,a,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 H=n.entanglements,te=n.expirationTimes,pe=n.hiddenUpdates;for(i=T&~i;0"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Ut=!1;if(at)try{var kn={};Object.defineProperty(kn,"passive",{get:function(){Ut=!0}}),window.addEventListener("test",kn,kn),window.removeEventListener("test",kn,kn)}catch{Ut=!1}var dn=null,Tn=null,ls=null;function wr(){if(ls)return ls;var n,a=Tn,i=a.length,u,m="value"in dn?dn.value:dn.textContent,h=m.length;for(n=0;n=Rp),VI=" ",$I=!1;function FI(n,a){switch(n){case"keyup":return OJ.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function qI(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Xu=!1;function DJ(n,a){switch(n){case"compositionend":return qI(a);case"keypress":return a.which!==32?null:($I=!0,VI);case"textInput":return n=a.data,n===VI&&$I?null:n;default:return null}}function IJ(n,a){if(Xu)return n==="compositionend"||!pS&&FI(n,a)?(n=wr(),ls=Tn=dn=null,Xu=!1,n):null;switch(n){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1"u")return null;try{return n.activeElement||n.body}catch{return n.body}}function JI(n){for(;n&&n.firstChild;)n=n.firstChild;return n}function eP(n,a){var i=JI(n);n=0;for(var u;i;){if(i.nodeType===3){if(u=n+i.textContent.length,n<=a&&u>=a)return{node:i,offset:a-n};n=u}e:{for(;i;){if(i.nextSibling){i=i.nextSibling;break e}i=i.parentNode}i=void 0}i=JI(i)}}function tP(n,a){return n&&a?n===a?!0:n&&n.nodeType===3?!1:a&&a.nodeType===3?tP(n,a.parentNode):"contains"in n?n.contains(a):n.compareDocumentPosition?!!(n.compareDocumentPosition(a)&16):!1:!1}function nP(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var a=gS(n.document);a instanceof n.HTMLIFrameElement;){try{var i=typeof a.contentWindow.location.href=="string"}catch{i=!1}if(i)n=a.contentWindow;else break;a=gS(n.document)}return a}function xS(n){var a=n&&n.nodeName&&n.nodeName.toLowerCase();return a&&(a==="input"&&(n.type==="text"||n.type==="search"||n.type==="tel"||n.type==="url"||n.type==="password")||a==="textarea"||n.contentEditable==="true")}var VJ=at&&"documentMode"in document&&11>=document.documentMode,Qu=null,bS=null,Dp=null,vS=!1;function sP(n,a,i){var u=i.window===i?i.document:i.nodeType===9?i:i.ownerDocument;vS||Qu==null||Qu!==gS(u)||(u=Qu,"selectionStart"in u&&xS(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}),Dp&&Mp(Dp,u)||(Dp=u,u=Lb(bS,"onSelect"),0>=T,m-=T,tl=1<<32-St(a)+m|i<st?(xs=et,et=null):xs=et.sibling;var Vt=ue(fe,et,xe[st],Re);if(Vt===null){et===null&&(et=xs);break}n&&et&&Vt.alternate===null&&a(fe,et),le=h(Vt,le,st),It===null?$e=Vt:It.sibling=Vt,It=Vt,et=xs}if(st===xe.length)return i(fe,et),Nt&&Vl(fe,st),$e;if(et===null){for(;stst?(xs=et,et=null):xs=et.sibling;var di=ue(fe,et,Vt.value,Re);if(di===null){et===null&&(et=xs);break}n&&et&&di.alternate===null&&a(fe,et),le=h(di,le,st),It===null?$e=di:It.sibling=di,It=di,et=xs}if(Vt.done)return i(fe,et),Nt&&Vl(fe,st),$e;if(et===null){for(;!Vt.done;st++,Vt=xe.next())Vt=Ae(fe,Vt.value,Re),Vt!==null&&(le=h(Vt,le,st),It===null?$e=Vt:It.sibling=Vt,It=Vt);return Nt&&Vl(fe,st),$e}for(et=u(et);!Vt.done;st++,Vt=xe.next())Vt=ye(et,fe,st,Vt.value,Re),Vt!==null&&(n&&(xs=Vt.alternate,xs!==null&&et.delete(xs.key===null?st:xs.key)),le=h(Vt,le,st),It===null?$e=Vt:It.sibling=Vt,It=Vt);return n&&et.forEach(function(Dte){return a(fe,Dte)}),Nt&&Vl(fe,st),$e}function xt(fe,le,xe,Re){if(typeof xe=="object"&&xe!==null&&xe.type===z&&xe.key===null&&xe.props.ref===void 0&&(xe=xe.props.children),typeof xe=="object"&&xe!==null){switch(xe.$$typeof){case _:e:{for(var $e=xe.key;le!==null;){if(le.key===$e){if($e=xe.type,$e===z){if(le.tag===7){i(fe,le.sibling),Re=m(le,xe.props.children),Go(Re,xe),Re.return=fe,fe=Re;break e}}else if(le.elementType===$e||typeof $e=="object"&&$e!==null&&$e.$$typeof===$&&kc($e)===le.type){i(fe,le.sibling),Re=m(le,xe.props),Go(Re,xe),Re.return=fe,fe=Re;break e}i(fe,le);break}else a(fe,le);le=le.sibling}xe.type===z?(Re=vc(xe.props.children,fe.mode,Re,xe.key),Go(Re,xe),Re.return=fe,fe=Re):(Re=Vx(xe.type,xe.key,xe.props,null,fe.mode,Re),Go(Re,xe),Re.return=fe,fe=Re)}return T(fe);case L:e:{for($e=xe.key;le!==null;){if(le.key===$e)if(le.tag===4&&le.stateNode.containerInfo===xe.containerInfo&&le.stateNode.implementation===xe.implementation){i(fe,le.sibling),Re=m(le,xe.children||[]),Re.return=fe,fe=Re;break e}else{i(fe,le);break}else a(fe,le);le=le.sibling}Re=kS(xe,fe.mode,Re),Re.return=fe,fe=Re}return T(fe);case $:return xe=kc(xe),xt(fe,le,xe,Re)}if(ae(xe))return Le(fe,le,xe,Re);if(ie(xe)){if($e=ie(xe),typeof $e!="function")throw Error(o(150));return xe=$e.call(xe),Qe(fe,le,xe,Re)}if(typeof xe.then=="function")return xt(fe,le,Wx(xe),Re);if(xe.$$typeof===W)return xt(fe,le,Yx(fe,xe),Re);Jx(fe,xe)}return typeof xe=="string"&&xe!==""||typeof xe=="number"||typeof xe=="bigint"?(xe=""+xe,le!==null&&le.tag===6?(i(fe,le.sibling),Re=m(le,xe),Re.return=fe,fe=Re):(i(fe,le),Re=CS(xe,fe.mode,Re),Re.return=fe,fe=Re),T(fe)):i(fe,le)}return function(fe,le,xe,Re){try{Bp=0;var $e=xt(fe,le,xe,Re);return ad=null,$e}catch(et){if(et===rd||et===Qx)throw et;var It=Sr(29,et,null,fe.mode);return It.lanes=Re,It.return=fe,It}}}var Ec=TP(!0),EP=TP(!1),Ko=!1;function _S(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function LS(n,a){n=n.updateQueue,a.updateQueue===n&&(a.updateQueue={baseState:n.baseState,firstBaseUpdate:n.firstBaseUpdate,lastBaseUpdate:n.lastBaseUpdate,shared:n.shared,callbacks:null})}function Yo(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function Xo(n,a,i){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(en&2)!==0){var m=u.pending;return m===null?a.next=a:(a.next=m.next,m.next=a),u.pending=a,a=Ux(n),dP(n,null,i),a}return Hx(n,u,a,i),Ux(n)}function Hp(n,a,i){if(a=a.updateQueue,a!==null&&(a=a.shared,(i&4194048)!==0)){var u=a.lanes;u&=n.pendingLanes,i|=u,a.lanes=i,lc(n,i)}}function zS(n,a){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=a:h=h.next=a}else m=h=a;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=a:n.next=a,i.lastBaseUpdate=a}var BS=!1;function Up(){if(BS){var n=sd;if(n!==null)throw n}}function Vp(n,a,i,u){BS=!1;var m=n.updateQueue;Ko=!1;var h=m.firstBaseUpdate,T=m.lastBaseUpdate,H=m.shared.pending;if(H!==null){m.shared.pending=null;var te=H,pe=te.next;te.next=null,T===null?h=pe:T.next=pe,T=te;var je=n.alternate;je!==null&&(je=je.updateQueue,H=je.lastBaseUpdate,H!==T&&(H===null?je.firstBaseUpdate=pe:H.next=pe,je.lastBaseUpdate=te))}if(h!==null){var Ae=m.baseState;T=0,je=pe=te=null,H=h;do{var ue=H.lane&-536870913,ye=ue!==H.lane;if(ye?(Dt&ue)===ue:(u&ue)===ue){ue!==0&&ue===Nc&&(BS=!0),je!==null&&(je=je.next={lane:0,tag:H.tag,payload:H.payload,callback:null,next:null});e:{var Le=n,Qe=H;ue=a;var xt=i;switch(Qe.tag){case 1:if(Le=Qe.payload,typeof Le=="function"){Ae=Le.call(xt,Ae,ue);break e}Ae=Le;break e;case 3:Le.flags=Le.flags&-65537|128;case 0:if(Le=Qe.payload,ue=typeof Le=="function"?Le.call(xt,Ae,ue):Le,ue==null)break e;Ae=M({},Ae,ue);break e;case 2:Ko=!0}}ue=H.callback,ue!==null&&(n.flags|=64,ye&&(n.flags|=8192),ye=m.callbacks,ye===null?m.callbacks=[ue]:ye.push(ue))}else ye={lane:ue,tag:H.tag,payload:H.payload,callback:H.callback,next:null},je===null?(pe=je=ye,te=Ae):je=je.next=ye,T|=ue;if(H=H.next,H===null){if(H=m.shared.pending,H===null)break;ye=H,H=ye.next,ye.next=null,m.lastBaseUpdate=ye,m.shared.pending=null}}while(!0);je===null&&(te=Ae),m.baseState=te,m.firstBaseUpdate=pe,m.lastBaseUpdate=je,h===null&&(m.shared.lanes=0),ni|=T,n.lanes=T,n.memoizedState=Ae}}function RP(n,a){if(typeof n!="function")throw Error(o(191,n));n.call(a)}function AP(n,a){var i=n.callbacks;if(i!==null)for(n.callbacks=null,n=0;nh?h:8;var T=oe.T,H={};H.types=T!==null?T.types:null,oe.T=H,aN(n,!1,a,i);try{var te=m(),pe=oe.S;if(pe!==null&&pe(H,te),te!==null&&typeof te=="object"&&typeof te.then=="function"){var je=JJ(te,u);Gp(n,a,je,Fr(n))}else Gp(n,a,u,Fr(n))}catch(Ae){Gp(n,a,{then:function(){},status:"rejected",reason:Ae},Fr())}finally{ee.p=h,T!==null&&H.types!==null&&(T.types=H.types),oe.T=T}}function aee(){}function sN(n,a,i,u){if(n.tag!==5)throw Error(o(476));var m=i_(n).queue;o_(n,m,a,de,i===null?aee:function(){return c_(n),i(u)})}function i_(n){var a=n.memoizedState;if(a!==null)return a;a={memoizedState:de,baseState:de,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Gl,lastRenderedState:de},next:null};var i={};return a.next={memoizedState:i,baseState:i,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Gl,lastRenderedState:i},next:null},n.memoizedState=a,n=n.alternate,n!==null&&(n.memoizedState=a),a}function c_(n){var a=i_(n);a.next===null&&(a=n.alternate.memoizedState),Gp(n,a.next.queue,{},Fr())}function rN(){return Fs(Td)}function u_(){return os().memoizedState}function d_(){return os().memoizedState}function lee(n){for(var a=n.return;a!==null;){switch(a.tag){case 24:case 3:var i=Fr();n=Yo(i);var u=Xo(a,n,i);u!==null&&(Tr(u,a,i),Hp(u,a,i)),a={cache:MS()},n.payload=a;return}a=a.return}}function oee(n,a,i){var u=Fr();i={lane:u,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},cb(n)?p_(a,i):(i=SS(n,a,i,u),i!==null&&(Tr(i,n,u),m_(i,a,u)))}function f_(n,a,i){var u=Fr();Gp(n,a,i,u)}function Gp(n,a,i,u){var m={lane:u,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null};if(cb(n))p_(a,m);else{var h=n.alternate;if(n.lanes===0&&(h===null||h.lanes===0)&&(h=a.lastRenderedReducer,h!==null))try{var T=a.lastRenderedState,H=h(T,i);if(m.hasEagerState=!0,m.eagerState=H,Br(H,T))return Hx(n,a,m,0),En===null&&Bx(),!1}catch{}if(i=SS(n,a,m,u),i!==null)return Tr(i,n,u),m_(i,a,u),!0}return!1}function aN(n,a,i,u){if(u={lane:2,revertLane:XN(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},cb(n)){if(a)throw Error(o(479))}else a=SS(n,i,u,2),a!==null&&Tr(a,n,2)}function cb(n){var a=n.alternate;return n===gt||a!==null&&a===gt}function p_(n,a){ld=nb=!0;var i=n.pending;i===null?a.next=a:(a.next=i.next,i.next=a),n.pending=a}function m_(n,a,i){if((i&4194048)!==0){var u=a.lanes;u&=n.pendingLanes,i|=u,a.lanes=i,lc(n,i)}}var ub={readContext:Fs,use:ab,useCallback:es,useContext:es,useEffect:es,useImperativeHandle:es,useLayoutEffect:es,useInsertionEffect:es,useMemo:es,useReducer:es,useRef:es,useState:es,useDebugValue:es,useDeferredValue:es,useTransition:es,useSyncExternalStore:es,useId:es,useHostTransitionStatus:es,useFormState:es,useActionState:es,useOptimistic:es,useMemoCache:es,useCacheRefresh:es,useEffectEvent:es},h_={readContext:Fs,use:ab,useCallback:function(n,a){return pr().memoizedState=[n,a===void 0?null:a],n},useContext:Fs,useEffect:WP,useImperativeHandle:function(n,a,i){i=i!=null?i.concat([n]):null,ob(4194308,4,n_.bind(null,a,n),i)},useLayoutEffect:function(n,a){return ob(4194308,4,n,a)},useInsertionEffect:function(n,a){ob(4,2,n,a)},useMemo:function(n,a){var i=pr();a=a===void 0?null:a;var u=n();if(Rc){Jn(!0);try{n()}finally{Jn(!1)}}return i.memoizedState=[u,a],u},useReducer:function(n,a,i){var u=pr();if(i!==void 0){var m=i(a);if(Rc){Jn(!0);try{i(a)}finally{Jn(!1)}}}else m=a;return u.memoizedState=u.baseState=m,n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:n,lastRenderedState:m},u.queue=n,n=n.dispatch=oee.bind(null,gt,n),[u.memoizedState,n]},useRef:function(n){var a=pr();return n={current:n},a.memoizedState=n},useState:function(n){n=WS(n);var a=n.queue,i=f_.bind(null,gt,a);return a.dispatch=i,[n.memoizedState,i]},useDebugValue:tN,useDeferredValue:function(n,a){var i=pr();return nN(i,n,a)},useTransition:function(){var n=WS(!1);return n=o_.bind(null,gt,n.queue,!0,!1),pr().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,a,i){var u=gt,m=pr();if(Nt){if(i===void 0)throw Error(o(407));i=i()}else{if(i=a(),En===null)throw Error(o(349));(Dt&127)!==0||_P(u,a,i)}m.memoizedState=i;var h={value:i,getSnapshot:a};return m.queue=h,WP(zP.bind(null,u,h,n),[n]),u.flags|=2048,id(9,{destroy:void 0},LP.bind(null,u,h,i,a),null),i},useId:function(){var n=pr(),a=En.identifierPrefix;if(Nt){var i=nl,u=tl;i=(u&~(1<<32-St(u)-1)).toString(32)+i,a="_"+a+"R_"+i,i=sb++,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[Ns]=a,h[$s]=u;e:for(T=a.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===a)break e;for(;T.sibling===null;){if(T.return===null||T.return===a)break e;T=T.return}T.sibling.return=T.return,T=T.sibling}a.stateNode=h;e:switch(Ys(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&&Yl(a)}}return Mn(a),a.subtreeFlags&=-33554433,bN(a,a.type,n===null?null:n.memoizedProps,a.pendingProps,i),null;case 6:if(n&&a.stateNode!=null)n.memoizedProps!==u&&Yl(a);else{if(typeof u!="string"&&a.stateNode===null)throw Error(o(166));if(n=Ce.current,nd(a)){if(n=a.stateNode,i=a.memoizedProps,u=null,m=Ds,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[Ns]=a,n=!!(n.nodeValue===i||u!==null&&u.suppressHydrationWarning===!0||zL(n.nodeValue,i)),n||Fo(a,!0)}else n=am(n).createTextNode(u),n[Ns]=a,a.stateNode=n}return Mn(a),null;case 31:if(i=a.memoizedState,n===null||n.memoizedState!==null){if(u=nd(a),i!==null){if(n===null){if(!u)throw Error(o(318));if(n=a.memoizedState,n=n!==null?n.dehydrated:null,!n)throw Error(o(557));n[Ns]=a}else yc(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Mn(a),n=!1}else i=RS(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=i),n=!0;if(!n)return a.flags&256?(Hr(a),a):(Hr(a),null);if((a.flags&128)!==0)throw Error(o(558))}return Mn(a),null;case 13:if(u=a.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=nd(a),u!==null&&u.dehydrated!==null){if(n===null){if(!m)throw Error(o(318));if(m=a.memoizedState,m=m!==null?m.dehydrated:null,!m)throw Error(o(317));m[Ns]=a}else yc(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Mn(a),m=!1}else m=RS(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return a.flags&256?(Hr(a),a):(Hr(a),null)}return Hr(a),(a.flags&128)!==0?(a.lanes=i,a):(i=u!==null,n=n!==null&&n.memoizedState!==null,i&&(u=a.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&&(a.child.flags|=8192),gb(a,a.updateQueue),Mn(a),null);case 4:return ge(),n===null&&JN(a.stateNode.containerInfo),a.flags|=67108864,Mn(a),null;case 10:return Fl(a.type),Mn(a),null;case 19:if($S(a),u=a.memoizedState,u===null)return Mn(a),null;if(m=(a.flags&128)!==0,h=u.rendering,h===null)if(m)Yp(u,!1);else{if(ts!==0||n!==null&&(n.flags&128)!==0)for(n=a.child;n!==null;){if(h=tb(n),h!==null){for(a.flags|=128,Yp(u,!1),n=h.updateQueue,a.updateQueue=n,gb(a,n),a.subtreeFlags=0,n=i,i=a.child;i!==null;)fP(i,n),i=i.sibling;return $p(a,Gs.current&1|2),Nt&&Vl(a,u.treeForkCount),a.child}n=n.sibling}u.tail!==null&&_t()>Eb&&(a.flags|=128,m=!0,Yp(u,!1),a.lanes=4194304)}else{if(!m)if(n=tb(h),n!==null){if(a.flags|=128,m=!0,n=n.updateQueue,a.updateQueue=n,gb(a,n),Yp(u,!0),u.tail===null&&u.tailMode!=="collapsed"&&u.tailMode!=="visible"&&!h.alternate&&!Nt)return Mn(a),null}else 2*_t()-u.renderingStartTime>Eb&&i!==536870912&&(a.flags|=128,m=!0,Yp(u,!1),a.lanes=4194304);u.isBackwards?(h.sibling=a.child,a.child=h):(n=u.last,n!==null?n.sibling=h:a.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=_t(),n.sibling=null,h=Gs.current,h=m?h&1|2:h&1,u.tailMode==="visible"||u.tailMode==="collapsed"||!i||Nt?$p(a,h):(i=h,we(qs,a),we(Gs,i),rr===null&&(rr=a)),Nt&&Vl(a,u.treeForkCount),n}return Mn(a),null;case 22:case 23:return Hr(a),US(),u=a.memoizedState!==null,n!==null?n.memoizedState!==null!==u&&(a.flags|=8192):u&&(a.flags|=8192),u?(i&536870912)!==0&&(a.flags&128)===0&&(Mn(a),a.subtreeFlags&6&&(a.flags|=8192)):Mn(a),i=a.updateQueue,i!==null&&gb(a,i.retryQueue),i=null,n!==null&&n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(i=n.memoizedState.cachePool.pool),u=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(u=a.memoizedState.cachePool.pool),u!==i&&(a.flags|=2048),n!==null&&ce(Cc),null;case 24:return i=null,n!==null&&(i=n.memoizedState.cache),a.memoizedState.cache!==i&&(a.flags|=2048),Fl(ms),Mn(a),null;case 25:return null;case 30:return a.flags|=33554432,Mn(a),null}throw Error(o(156,a.tag))}function mee(n,a){switch(TS(a),a.tag){case 1:return n=a.flags,n&65536?(a.flags=n&-65537|128,a):null;case 3:return Fl(ms),ge(),n=a.flags,(n&65536)!==0&&(n&128)===0?(a.flags=n&-65537|128,a):null;case 26:case 27:case 5:return Oe(a),null;case 31:if(a.memoizedState!==null){if(Hr(a),a.alternate===null)throw Error(o(340));yc()}return n=a.flags,n&65536?(a.flags=n&-65537|128,a):null;case 13:if(Hr(a),n=a.memoizedState,n!==null&&n.dehydrated!==null){if(a.alternate===null)throw Error(o(340));yc()}return n=a.flags,n&65536?(a.flags=n&-65537|128,a):null;case 19:return $S(a),n=a.flags,n&65536?(a.flags=n&-65537|128,n=a.memoizedState,n!==null&&(n.rendering=null,n.tail=null),a.flags|=4,a):null;case 4:return ge(),null;case 10:return Fl(a.type),null;case 22:case 23:return Hr(a),US(),n!==null&&ce(Cc),n=a.flags,n&65536?(a.flags=n&-65537|128,a):null;case 24:return Fl(ms),null;case 25:return null;default:return null}}function H_(n,a){switch(TS(a),a.tag){case 3:Fl(ms),ge();break;case 26:case 27:case 5:Oe(a);break;case 4:ge();break;case 31:a.memoizedState!==null&&Hr(a);break;case 13:Hr(a);break;case 19:$S(a);break;case 10:Fl(a.type);break;case 22:case 23:Hr(a),US(),n!==null&&ce(Cc);break;case 24:Fl(ms)}}function Xp(n,a){try{var i=a.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(H){pn(a,a.return,H)}}function Jo(n,a,i){try{var u=a.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,H=T.destroy;if(H!==void 0){T.destroy=void 0,m=a;var te=i,pe=H;try{pe()}catch(je){pn(m,te,je)}}}u=u.next}while(u!==h)}}catch(je){pn(a,a.return,je)}}function U_(n){var a=n.updateQueue;if(a!==null){var i=n.stateNode;try{AP(a,i)}catch(u){pn(n,n.return,u)}}}function V_(n,a,i){i.props=Ac(n.type,n.memoizedProps),i.state=n.memoizedState;try{i.componentWillUnmount()}catch(u){pn(n,a,u)}}function sl(n,a){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=Bl(n.memoizedProps,m);(m.ref===null||m.ref.name!==h)&&(m.ref=XL(h)),u=m.ref;break;case 7:if(n.stateNode===null){var T=new qr(n);b(n.child,!1,rte,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(H){pn(n,a,H)}}function Ks(n,a){var i=n.ref,u=n.refCleanup;if(i!==null)if(typeof u=="function")try{u()}catch(m){pn(n,a,m)}finally{n.refCleanup=null,n=n.alternate,n!=null&&(n.refCleanup=null)}else if(typeof i=="function")try{i(null)}catch(m){pn(n,a,m)}else i.current=null}function xb(n,a){if((n.tag===5||n.tag===27||n.tag===6)&&n.alternate===null&&a!==null)for(var i=0;i title"))),Ys(u,a,i),u[Ns]=n,ps(u),a=u;break e;case"link":if(h=f3("link","href",m).get(a+(i.href||""))){for(T=0;Txt&&(T=xt,xt=Qe,Qe=T);var fe=eP(H,Qe),le=eP(H,xt);if(fe&&le&&(ye.rangeCount!==1||ye.anchorNode!==fe.node||ye.anchorOffset!==fe.offset||ye.focusNode!==le.node||ye.focusOffset!==le.offset)){var xe=Ae.createRange();xe.setStart(fe.node,fe.offset),ye.removeAllRanges(),Qe>xt?(ye.addRange(xe),ye.extend(le.node,le.offset)):(xe.setEnd(le.node,le.offset),ye.addRange(xe))}}}}for(Ae=[],ye=H;ye=ye.parentNode;)ye.nodeType===1&&Ae.push({element:ye,left:ye.scrollLeft,top:ye.scrollTop});for(typeof H.focus=="function"&&H.focus(),H=0;Hi?32:i,oe.T=null,i=BN,BN=null;var h=Ba,T=cl;if(Xn=0,Ic=Ba=null,cl=0,(en&6)!==0)throw Error(o(331));var H=en;if(en|=4,dL(h.current),iL(h,h.current,T,i),en=H,nm(0,!1),Gt&&typeof Gt.onPostCommitFiberRoot=="function")try{Gt.onPostCommitFiberRoot(Cn,h)}catch{}return!0}finally{ee.p=m,oe.T=u,kL(n,a)}}function TL(n,a,i){a=pa(i,a),a=iN(n.stateNode,a,2),n=Xo(n,a,2),n!==null&&(Po(n,2),ul(n))}function pn(n,a,i){if(n.tag===3)TL(n,n,i);else for(;a!==null;){if(a.tag===3){TL(a,n,i);break}else if(a.tag===1){var u=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(si===null||!si.has(u))){n=pa(i,n),i=S_(2),u=Xo(a,i,2),u!==null&&(N_(i,u,a,n),Po(u,2),ul(u));break}}a=a.return}}function GN(n,a,i){var u=n.pingCache;if(u===null){u=n.pingCache=new bee;var m=new Set;u.set(a,m)}else m=u.get(a),m===void 0&&(m=new Set,u.set(a,m));m.has(i)||(_N=!0,m.add(i),n=kee.bind(null,n,a,i),a.then(n,n))}function kee(n,a,i){var u=n.pingCache;u!==null&&u.delete(a),n.pingedLanes|=n.suspendedLanes&i,n.warmLanes&=~i,En===n&&(Dt&i)===i&&((ts===4||ts===3&&(Dt&62914560)===Dt&&300>_t()-Tb)&&(en&2)===0?vd(n,0):kb|=i,md===Dt&&(md=0)),ul(n)}function EL(n,a){a===0&&(a=ur()),n=bc(n,a),n!==null&&(Po(n,a),ul(n))}function Tee(n){var a=n.memoizedState,i=0;a!==null&&(i=a.retryLane),EL(n,i)}function Eee(n,a){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(a),EL(n,i)}function Ree(n,a){return as(n,a)}var jd=null,wd=null,KN=!1,Pb=!1,YN=!1,ai=0;function ul(n){n!==wd&&n.next===null&&(wd===null?jd=wd=n:wd=wd.next=n),Pb=!0,KN||(KN=!0,Oee())}function nm(n,a){if(!YN&&Pb){YN=!0;do for(var i=!1,u=jd;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var h=0;else{var T=u.suspendedLanes,H=u.pingedLanes;h=(1<<31-St(42|n)+1)-1,h&=m&~(T&~H),h=h&201326741?h&201326741|1:h?h|2:0}h!==0&&(i=!0,ML(u,h))}else h=Dt,h=Ja(u,u===En?h:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(h&3)===0||Jt(u,h)||(i=!0,ML(u,h));u=u.next}while(i);YN=!1}}function Aee(){RL()}function RL(){Pb=KN=!1;var n=0;ai!==0&&Vee()&&(n=ai);for(var a=_t(),i=null,u=jd;u!==null;){var m=u.next,h=AL(u,a);h===0?(u.next=null,i===null?jd=m:i.next=m,m===null&&(wd=i)):(i=u,(n!==0||(h&3)!==0)&&(Pb=!0)),u=m}Xn!==0&&Xn!==5||nm(n),ai!==0&&(ai=0)}function AL(n,a){for(var i=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,h=n.pendingLanes&-62914561;0H)break;var je=te.transferSize,Ae=te.initiatorType;je&&BL(Ae)&&(te=te.responseEnd,T+=je*(teHb){Qe.length=Le;break}xe=new Promise(Yee.bind(xe)),Qe.push(xe)}}}if(0"u"?null:document;function i3(n,a,i){var u=Nd;if(u&&typeof a=="string"&&a){var m=fr(a);m='link[rel="'+n+'"][href="'+m+'"]',typeof i=="string"&&(m+='[crossorigin="'+i+'"]'),o3.has(m)||(o3.add(m),n={rel:n,crossOrigin:i,href:a},u.querySelector(m)===null&&(a=u.createElement("link"),Ys(a,"link",n),ps(a),u.head.appendChild(a)))}}function pte(n){Ql.D(n),i3("dns-prefetch",n,null)}function mte(n,a){Ql.C(n,a),i3("preconnect",n,a)}function hte(n,a,i){Ql.L(n,a,i);var u=Nd;if(u&&n&&a){var m='link[rel="preload"][as="'+fr(a)+'"]';a==="image"&&i&&i.imageSrcSet?(m+='[imagesrcset="'+fr(i.imageSrcSet)+'"]',typeof i.imageSizes=="string"&&(m+='[imagesizes="'+fr(i.imageSizes)+'"]')):m+='[href="'+fr(n)+'"]';var h=m;switch(a){case"style":h=Cd(n);break;case"script":h=kd(n)}if(!(va.has(h)||(n=M({rel:"preload",href:a==="image"&&i&&i.imageSrcSet?void 0:n,as:a},i),va.set(h,n),u.querySelector(m)!==null||a==="style"&&u.querySelector(om(h))||a==="script"&&u.querySelector(im(h))))){var T=u.createElement("link");Ys(T,"link",n),a==="style"&&(T[Cs]=!0,T.onload=T.onerror=function(){bp(T)}),ps(T),u.head.appendChild(T)}}}function gte(n,a){Ql.m(n,a);var i=Nd;if(i&&n){var u=a&&typeof a.as=="string"?a.as:"script",m='link[rel="modulepreload"][as="'+fr(u)+'"][href="'+fr(n)+'"]',h=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":h=kd(n)}if(!va.has(h)&&(n=M({rel:"modulepreload",href:n},a),va.set(h,n),i.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(i.querySelector(im(h)))return}u=i.createElement("link"),Ys(u,"link",n),ps(u),i.head.appendChild(u)}}}function xte(n,a,i){Ql.S(n,a,i);var u=Nd;if(u&&n){var m=Bo(u).hoistableStyles,h=Cd(n);a=a||"default";var T=m.get(h);if(!T){var H={loading:0,preload:null};if(T=u.querySelector(om(h)))H.loading=5;else{n=M({rel:"stylesheet",href:n,"data-precedence":a},i),(i=va.get(h))&&hC(n,i);var te=T=u.createElement("link");ps(te),Ys(te,"link",n),te._p=new Promise(function(pe,je){te.onload=pe,te.onerror=je}),te.addEventListener("load",function(){H.loading|=1}),te.addEventListener("error",function(){H.loading|=2}),H.loading|=4,zb(T,a,u)}T={type:"stylesheet",instance:T,count:1,state:H},m.set(h,T)}}}function bte(n,a){Ql.X(n,a);var i=Nd;if(i&&n){var u=Bo(i).hoistableScripts,m=kd(n),h=u.get(m);h||(h=i.querySelector(im(m)),h||(n=M({src:n,async:!0},a),(a=va.get(m))&&gC(n,a),h=i.createElement("script"),ps(h),Ys(h,"link",n),i.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},u.set(m,h))}}function vte(n,a){Ql.M(n,a);var i=Nd;if(i&&n){var u=Bo(i).hoistableScripts,m=kd(n),h=u.get(m);h||(h=i.querySelector(im(m)),h||(n=M({src:n,async:!0,type:"module"},a),(a=va.get(m))&&gC(n,a),h=i.createElement("script"),ps(h),Ys(h,"link",n),i.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},u.set(m,h))}}function c3(n,a,i,u){var m=(m=Ce.current)?lm(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=Cd(i.href),a=Bo(m).hoistableStyles,u=a.get(i),u||(u={type:"style",instance:null,count:0,state:null},a.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=Cd(i.href);var h=Bo(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(om(n)))?h._p||(T.instance=h,T.state.loading=5):(h=va.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},va.set(n,h)),yte(m,n,h,T.state))),a&&u===null)throw Error(o(528,""));return T}if(a&&u!==null)throw Error(o(529,""));return null;case"script":return a=i.async,i=i.src,typeof i=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(i=kd(i),a=Bo(m).hoistableScripts,u=a.get(i),u||(u={type:"script",instance:null,count:0,state:null},a.set(i,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(o(444,n))}}function Cd(n){return'href="'+fr(n)+'"'}function om(n){return'link[rel="stylesheet"]['+n+"]"}function u3(n){return M({},n,{"data-precedence":n.precedence,precedence:null})}function yte(n,a,i,u){if(a=n.querySelector('link[rel="preload"][as="style"]['+a+"]")){if(a[Cs]!==!0){u.loading=1;return}}else a=n.createElement("link"),a[Cs]=!0,a.onload=a.onerror=bp.bind(null,a),Ys(a,"link",i),ps(a),n.head.appendChild(a);u.preload=a,a.addEventListener("load",function(){return u.loading|=1}),a.addEventListener("error",function(){return u.loading|=2})}function kd(n){return'[src="'+fr(n)+'"]'}function im(n){return"script[async]"+n}function d3(n,a,i){if(a.count++,a.instance===null)switch(a.type){case"style":var u=n.querySelector('style[data-href~="'+fr(i.href)+'"]');if(u)return a.instance=u,ps(u),u;var m=M({},i,{"data-href":i.href,"data-precedence":i.precedence,href:null,precedence:null});return u=(n.ownerDocument||n).createElement("style"),ps(u),Ys(u,"style",m),zb(u,i.precedence,n),a.instance=u;case"stylesheet":m=Cd(i.href);var h=n.querySelector(om(m));if(h)return a.state.loading|=4,a.instance=h,ps(h),h;u=u3(i),(m=va.get(m))&&hC(u,m),h=(n.ownerDocument||n).createElement("link"),ps(h);var T=h;return T._p=new Promise(function(H,te){T.onload=H,T.onerror=te}),Ys(h,"link",u),a.state.loading|=4,zb(h,i.precedence,n),a.instance=h;case"script":return h=kd(i.src),(m=n.querySelector(im(h)))?(a.instance=m,ps(m),m):(u=i,(m=va.get(h))&&(u=M({},i),gC(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),ps(m),Ys(m,"link",u),n.head.appendChild(m),a.instance=m);case"void":return null;default:throw Error(o(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(u=a.instance,a.state.loading|=4,zb(u,i.precedence,n));return a.instance}function zb(n,a,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 jte(n,a,i){if(i===1||a.itemProp!=null)return!1;switch(n){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(n=a.disabled,typeof a.precedence=="string"&&n==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function p3(n,a){return n==="img"&&a.src!=null&&a.src!==""&&a.onLoad==null&&a.loading!=="lazy"}function m3(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function h3(n){return(n.width||100)*(n.height||100)*(typeof devicePixelRatio=="number"?devicePixelRatio:1)*.25}function g3(n,a){typeof a.decode=="function"&&(n.imgCount++,a.complete||(n.imgBytes+=h3(a),n.suspenseyImages.push(a)),n=Nte.bind(n),a.decode().then(n,n))}function wte(n,a,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=Cd(u.href),h=a.querySelector(om(m));if(h){a=h._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(n.count++,n=cm.bind(n),a.then(n,n)),i.state.loading|=4,i.instance=h,ps(h);return}h=a.ownerDocument||a,u=u3(u),(m=va.get(m))&&hC(u,m),h=h.createElement("link"),ps(h);var T=h;T._p=new Promise(function(H,te){T.onload=H,T.onerror=te}),Ys(h,"link",u),i.instance=h}n.stylesheets===null&&(n.stylesheets=new Map),n.stylesheets.set(i,a),(a=i.state.preload)&&(i.state.loading&3)===0&&(n.count++,i=cm.bind(n),a.addEventListener("load",i),a.addEventListener("error",i))}}var Hb=0;function Ste(n,a){return n.stylesheets&&n.count===0&&Vb(n,n.stylesheets),0Hb?50:800)+a);return n.unsuspend=i,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function x3(n){if(n.count===0&&(n.imgCount===0||!n.waitingForImages)){if(n.stylesheets)Vb(n,n.stylesheets);else if(n.unsuspend){var a=n.unsuspend;n.unsuspend=null,a()}}}function cm(){this.count--,x3(this)}function Nte(){this.imgCount--,x3(this)}var Ub=null;function Vb(n,a){n.stylesheets=null,n.unsuspend!==null&&(n.count++,Ub=new Map,a.forEach(Cte,n),Ub=null,cm.call(n))}function Cte(n,a){if(!(a.state.loading&4)){var i=Ub.get(n);if(i)var u=i.get(null);else{i=new Map,Ub.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(),Zy.exports=sF(),Zy.exports}var jn=rF();const zh=[20,50,100,200],Bh=[20,50,100,200,"all"],lu=50,YR="workbuddy-desktop-table-size:";function XR(e){return e==="all"?l("全部"):String(e)}function Hh(e,t=Bh,r=lu){t.includes(r)||(r=t.includes(lu)?lu:t[0]);let o=null;try{o=localStorage.getItem(YR+e)}catch{return r}if(o===null||o.trim()==="")return r;if(o==="all")return t.includes("all")?"all":r;const c=Number(o);return Number.isFinite(c)&&t.includes(c)?c:r}function Uh(e,t){try{localStorage.setItem(YR+e,String(t))}catch{}}function Vh(e,t,r={}){const o=r.sizes??Bh,c=r.defaultSize??lu,[d,f]=x.useState(()=>Hh(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(C=>{f(C),Uh(t,C),g(1)},[t]),j=x.useCallback(C=>{g(Math.min(Math.max(1,Math.round(C)||1),v))},[v]),w=d==="all"?0:(y-1)*d,S=d==="all"?e:Math.min(e,w+d),N=x.useCallback(C=>d==="all"?C.slice():C.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 Di({total:e,page:t,pageCount:r,size:o,sizes:c=Bh,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 C=b.trim();if(!C){j(String(t));return}const E=Number(C);if(!Number.isFinite(E)){j(String(t));return}const R=Math.min(Math.max(1,Math.round(E)),r);j(String(R)),R!==t&&f(R)},S=r<=1,N=e===0?l("共 0 条"):p?l("共 {total} 条 · 当前第 {start}–{end} 条",{total:e,start:p.start,end:p.end}):l("共 {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:[l("每页"),s.jsxs(ct,{value:String(o),onValueChange:C=>d(C==="all"?"all":Number(C)),children:[s.jsx(dt,{className:"h-[26px] w-[86px]",disabled:g,"aria-label":l("每页条数"),children:s.jsx(ut,{children:XR(o)})}),s.jsx(ft,{children:c.map(C=>s.jsx(Ye,{value:String(C),children:XR(C)},String(C)))})]}),l("条")]}),s.jsxs("span",{className:"table-foot-jump",children:[l("跳至"),s.jsx(Ke,{className:"h-[26px] w-[52px] px-1 text-center",value:b,disabled:g||S,"aria-label":l("跳转到指定页"),title:S?l("当前只有一页"):l("跳转到第 1–{pageCount} 页",{pageCount:r}),inputMode:"numeric",onChange:C=>j(C.target.value),onKeyDown:C=>{C.key==="Enter"?(C.preventDefault(),w()):C.key==="Escape"&&j(String(t))},onBlur:w}),l("页")]}),s.jsx(T6,{page:t,pageCount:r,onPageChange:f,disabled:g})]})]})}const ej=[{key:"pick",label:l("选择"),align:"center",legacyAlign:"left"},{key:"order",label:l("顺序"),title:l("组内先后:按住左边的把手上下拖动即可调整;整组的先后拖分组带的把手"),align:"center",legacyAlign:"left"},{key:"account",label:l("账号"),align:"center",legacyAlign:"left"},{key:"proxy",label:l("代理"),title:l("该账号出网走的代理(Clash 出口 / 自定义 / 直连);点击可修改"),align:"center"},{key:"connections",label:l("连接数"),title:l("此刻正在使用这个账号的请求数(含还在下发内容的流式请求);为 0 时不显示"),align:"center"},{key:"status",label:l("状态"),align:"center",legacyAlign:"left"},{key:"limits",label:l("限流"),title:l("该账号当前限流中的模型;点徽章看明细"),align:"center",legacyAlign:"left"},{key:"expiry",label:l("有效期"),align:"center",legacyAlign:"left"},{key:"usage",label:l("余额"),align:"center",legacyAlign:"left"},{key:"actions",label:l("操作"),align:"right"}],QR="agent2api-accounts-col-widths",xf={pick:47,order:84,proxy:186,connections:56,status:80,limits:148,expiry:80,usage:132,actions:200},tj=new Set(["account"]),aF=300,nj=56,lF=new Set([...Object.keys(xf),...tj]),ou=(()=>{try{const e=JSON.parse(localStorage.getItem(QR)||"{}"),t={};for(const[r,o]of Object.entries(e||{})){const c=Number(o);lF.has(r)&&Number.isFinite(c)&&c>=nj&&(t[r]=Math.round(c))}return t}catch{return{}}})();function ZR(){try{localStorage.setItem(QR,JSON.stringify(ou))}catch{}}function oF(){return{...xf,...ou}}function iF(e){let t=0;for(const r of e){const o=ou[r];o?t+=o:tj.has(r)?t+=aF:xf[r]?t+=xf[r]:t+=nj}return Math.round(t)}function WR(e,t){const r=e?.querySelector(`thead th:nth-child(${t+1})`),o=r?.getAttribute("data-col")||r?.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 cF(e,t,r){const o=Math.max(nj,Math.round(r));e.style.width=o+"px",tj.has(t)||o!==xf[t]?ou[t]=o:delete ou[t]}let sj=()=>{};function uF(e,t){if(sj=t,!e)return;let r=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=WR(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{}r={...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(r){if(w.buttons===0){j();return}cF(r.col,r.key,r.startWidth+w.clientX-r.startX)}}function j(){if(!r)return;const{grip:w,pointerId:S}=r;r=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),ZR(),sj()}}),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=WR(f,p);g&&(delete ou[g.key],ZR(),sj())})}function kt(){return window}function Zs(e,t){kt().wbApp?.toast?.(e,t)}function $h(e){return e instanceof Error&&e.message?e.message:String(e??"").trim()||l("未知错误")}function JR(e){return(kt().wbApp?.getState?.()?.accounts?.accounts||[]).filter(r=>(r?.provider||"workbuddy")===e).length}async function eA(e){const t=kt().__TAURI_INTERNALS__;if(!t||typeof t.invoke!="function")throw new Error(l("桌面运行时不可用(Tauri 未初始化)"));return t.invoke("api_request",{request:{method:"POST",path:"/api/accounts",body:e}})}function tA(e){return e?.name||e?.uid||e?.userId||""}function rj(){kt().wbAddAccountModal?.close?.()}async function Fh(e,t){rj(),await kt().wbApp?.refresh?.(),Zs(l("✅ {label}账号已添加{name}",{label:t,name:e?`:${e}`:""}))}const iu=new Map;function Tl(e){return{defaultValue:iu.get(e)??"",onChange:t=>{const r=t.currentTarget.value;r?iu.set(e,r):iu.delete(e)}}}function Ii(e,t){t?iu.set(e,t):iu.delete(e);const r=document.getElementById(e);(r instanceof HTMLInputElement||r instanceof HTMLTextAreaElement)&&(r.value=t)}function sa(e){const t=document.getElementById(e);return t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?t.value.trim():(iu.get(e)??"").trim()}function aj(e){for(const t of e)Ii(t,"")}const Pi={edition:"cn",loginMode:"embedded",socialRestore:!1},dF=100,fF=256,pF=e=>e.key==="name"?dF:fF,mF={provider:"raccoon",label:"小浣熊",addButton:l("添加小浣熊账号"),webLogin:{noteHtml:l("在内嵌窗口里完成官方登录,成功后自动加入账号列表。"),button:l("打开网页登录"),hint:l("内嵌窗口打开;完成后自动加入列表,关窗即取消等待"),busyText:l("等待小浣熊登录完成…")},manualTitle:l("粘贴 token / refreshToken"),manualNoteHtml:l('refreshToken 可选,填了到期可自动续期;两者都能从小浣熊客户端登录态文件里取到。'),fields:[{key:"name",label:l("备注名"),optional:!0,placeholder:l("可选,留空则用凭证里的账号名")},{key:"token",label:"token",rows:3,placeholder:l("粘贴 access_token(一长串 JWT)")},{key:"refreshToken",inputKey:"refresh",label:"refreshToken",rows:2,optional:!0,placeholder:l("可选")}],desktopNote:l("读本机客户端当前登录态,每次实时读取(删掉这条记录不影响客户端登录态)。客户端重新登录后点「刷新 Token」同步。")},hF={provider:"catpaw",label:"CatPaw",webLogin:{noteHtml:l("用 CatPaw 账号完成登录(美团 passport),成功后自动加入账号列表。"),button:l("打开 CatPaw 网页登录"),busyText:l("等待 CatPaw 登录完成…"),modes:[{value:"embedded",label:l("内嵌窗口(推荐)"),hint:l("内嵌窗口打开;完成后自动加入列表,关窗即取消等待")},{value:"external",label:l("系统浏览器"),hint:l("系统浏览器打开(复用已登录的美团账号);完成后自动加入列表")}]},manualNote:l("token 是登录态 Cookie;CatPaw 没有刷新机制,过期后需在客户端重新登录。"),fields:[{key:"token",label:"token",rows:3,placeholder:l("CatPaw 的 X-Passport-Token(登录态 Cookie)")},{key:"uid",label:"uid",placeholder:l("必填,CatPaw 账号标识")},{key:"name",label:l("备注名"),optional:!0,placeholder:l("可选,留空则用登录名或 uid")}],desktopNote:l("读本机客户端当前登录态,每次实时读取(删掉这条记录不影响客户端登录态)。客户端重新登录后重新导入即可。"),desktopHint:l("读取 ~/.meituan-catpaw/auth.json,需已在 CatPaw 客户端登录")},gF={provider:"autoclaw",label:l("AutoClaw 国内版"),manualNote:l("token 支持 enc: 前缀(Windows 上自动解密)。未填 refreshToken 无法自动续期。"),smsLogin:{noteHtml:l("用绑定的手机号登录:点「获取验证码」后填入即可。这是国内版官方唯一的登录方式。")},fields:[{key:"token",label:"token",rows:3,placeholder:l("明文 JWT 或 auth.json 里的 enc: 加密值(自动解密)")},{key:"refreshToken",label:"refreshToken",rows:2,optional:!0,placeholder:l("没有则无法自动续期")},{key:"deviceId",label:"deviceId",optional:!0,placeholder:l("可选,续期时带上")},{key:"name",label:l("备注名"),optional:!0,placeholder:l("可选,留空则用 userId")}],desktopNote:l("读本机客户端当前登录态,每次实时读取(删掉这条记录不影响客户端登录态)。"),desktopHint:l("读取 %APPDATA%/AutoClaw/auth.json 并解密,仅 Windows"),desktopWindowsOnly:!0},xF={provider:"autoclaw-intl",label:l("AutoClaw 国际版"),manualNote:l("国际版与国内版账号体系独立,请填国际版的凭证。未填 refreshToken 无法自动续期。"),oauthLogin:{title:l("网页登录(Zai / Google)"),noteHtml:l("点按钮后先过一次滑块验证(官方风控),随后打开登录页,登录完成即自动添加账号。
这是国际版官方唯一的登录方式;已在客户端登录过的,用「导入桌面端登录态」更快。"),modes:[{value:"embedded",label:l("内嵌窗口(推荐)"),hint:l("内嵌窗口打开;关窗即取消等待(Google 账号被拒时改用系统浏览器)")},{value:"external",label:l("系统浏览器"),hint:l("系统浏览器打开(复用已登录的 Zai / Google 账号);完成后自动加入列表")}]},fields:[{key:"token",label:"token",rows:3,placeholder:l("明文 JWT(国际版账号的 access token)")},{key:"refreshToken",label:"refreshToken",rows:2,optional:!0,placeholder:l("没有则无法自动续期")},{key:"deviceId",label:"deviceId",optional:!0,placeholder:l("可选,续期时带上")},{key:"name",label:l("备注名"),optional:!0,placeholder:l("可选,留空则用 userId")}],desktopNote:l("读本机客户端当前登录态,每次实时读取(删掉这条记录不影响客户端登录态)。用 Zai / Google 登录客户端的用户走这一条。"),desktopHint:l("读取 %APPDATA%/AutoClaw/auth.json 并解密,仅 Windows"),desktopWindowsOnly:!0};function nA(e){const{provider:t,label:r,siteNote:o}=e;return{provider:t,label:r,desktop:!1,webLogin:{noteHtml:l("打开官方授权页完成设备码授权,登录的是{label}({site})的账号。",{label:r,site:o}),button:l("打开 Qoder 网页登录"),busyText:l("等待 Qoder 授权完成…"),edition:t==="qoder"?"cn":"global",modes:[{value:"embedded",label:l("内嵌窗口(推荐)"),hint:l("内嵌窗口用全新环境,多账号互不影响;关窗即取消等待")},{value:"external",label:l("系统浏览器"),hint:l("系统浏览器打开(复用已登录账号);完成后自动加入列表")}]},manualTitle:l("使用个人访问令牌(PAT)"),manualNote:l("在{label}的 Qoder 账号设置 → Integrations 生成 PAT(别填 Google / GitHub 的令牌)。两个地区的账号与凭证不通用。",{label:r}),fields:[{key:"pat",label:"Qoder PAT",rows:3,placeholder:l("粘贴 Qoder 个人访问令牌(pt-…)")},{key:"name",label:l("备注名"),optional:!0,placeholder:l("可选,留空使用账号昵称或邮箱")}]}}const bF=nA({provider:"qoder",label:l("中国版"),siteNote:"qoder.com.cn"}),vF=nA({provider:"qoder-intl",label:l("国际版"),siteNote:"qoder.com"});function sA(e){const{provider:t,label:r,poolNote:o}=e;return{provider:t,label:r,desktop:!0,webLogin:{noteHtml:l("打开授权页完成确认,账号自动加入 {label}{note}",{label:r,note:o}),button:l("打开 Cline 授权页"),busyText:l("等待 Cline 授权确认…"),modes:[{value:"embedded",label:l("内嵌窗口(推荐)"),hint:l("内嵌窗口打开;完成后自动加入列表,关窗即取消等待")},{value:"external",label:l("系统浏览器"),hint:l("系统浏览器打开(复用已登录的 Cline 账号);完成后自动加入列表")}]},manualTitle:l("填写凭证"),manualNote:l("refreshToken 可选,填了可自动续期;两者都能从客户端登录态文件取到。同一个 Cline 账号两个池都能用,这里归入 {label}。",{label:r}),fields:[{key:"accessToken",label:"accessToken",rows:3,placeholder:l("粘贴 workos:… 开头的令牌(不带前缀也会自动补上)")},{key:"refreshToken",label:"refreshToken",rows:2,optional:!0,placeholder:l("可选,没有则无法自动续期")},{key:"name",label:l("备注名"),optional:!0,placeholder:l("可选,留空使用账号姓名、邮箱或令牌指纹")}],desktopNote:l("读本机客户端当前登录态,每次实时读取(删掉这条记录不影响客户端登录态)。这一条归入 {label}。",{label:r}),desktopHint:l("读取 ~/.cline/data/settings/providers.json,需已在 Cline 客户端登录")}}function rA(e){const{provider:t,label:r,site:o,siteNote:c}=e;return{provider:t,label:r,webLogin:{noteHtml:l("打开 Accio {label}的官方登录页({site})并用你的 Accio 账号登录:登录成功后官方页面会跳回本机;同机自动完成,Docker / 远程面板按提示粘贴回调地址即可(授权码只在本机传给网关,界面不显示明文 token)。",{label:r,site:o}),button:l("打开 Accio {label}登录页",{label:r}),busyText:l("等待 Accio {label}登录完成…",{label:r}),modes:[{value:"embedded",label:l("内嵌窗口(推荐)"),hint:l("将打开内嵌窗口;登录完成后自动加入账号列表。关掉窗口即取消等待")},{value:"external",label:l("系统浏览器"),hint:l("将用系统默认浏览器打开登录页(会复用浏览器里已登录的 Accio 账号);完成登录后自动加入账号列表,关掉弹窗即取消等待")}]},manualTitle:l("填写凭证"),manualNoteHtml:l("accessToken 是 Accio 的登录凭证(一长串不透明 token,不是 JWT);refreshToken 可选,填了之后到期能自动续期。请填写 {label}账号的凭证 —— {siteNote}(最容易拿到的办法:直接用上方的「网页登录」,不需要手工找 token。)",{label:r,siteNote:c}),fields:[{key:"accessToken",label:"accessToken",rows:3,placeholder:l("粘贴 Accio 的 accessToken")},{key:"refreshToken",label:"refreshToken",rows:2,optional:!0,placeholder:l("可选,没有则无法自动续期")},{key:"name",label:l("备注名"),optional:!0,placeholder:l("可选,留空使用账号昵称或邮箱")}]}}function aA(e){const{provider:t,label:r,site:o,planNote:c}=e;return{provider:t,label:r,desktop:!1,webLogin:{noteHtml:l("打开 ZCode {label}的官方授权页并用你的账号登录。授权结果由 ZCode 服务端记录,网关在后台自动取回凭证并加入账号列表。",{label:r}),button:l("打开 ZCode {label}授权页",{label:r}),busyText:l("等待 ZCode {label}授权完成…",{label:r}),modes:[{value:"embedded",label:l("内嵌窗口(推荐)"),hint:l("将打开内嵌窗口;授权完成后自动加入账号列表。关掉窗口即取消等待。授权页最后可能提示无法打开 zcode:// 链接,这是正常的 —— 结果已由服务端记下")},{value:"external",label:l("系统浏览器"),hint:l("将用系统默认浏览器打开授权页(会复用浏览器里已登录的 ZCode 账号);授权完成后自动加入账号列表。页面最后可能提示无法打开 zcode:// 链接,属正常现象")}]},manualTitle:l("填写凭证"),manualNoteHtml:l("本家有两个**互不替代**的凭证,按你要用的功能填,至少填一个:编码套餐 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:r,plan:c}),fields:[{key:"accessToken",label:l("编码套餐 API Key"),rows:3,optional:!0,placeholder:l("用于转发;形如 apiKey.secret 两段点分(不填则这个账号不能转发)")},{key:"jwt",label:"Coding Plan JWT",inputKey:"jwt",rows:3,optional:!0,placeholder:l("用于领取套餐与查询余额;不填则这个账号不能领取与查余额")},{key:"userId",label:l("用户 ID"),optional:!0,placeholder:l("可选;用于生成账号 id 与展示名")},{key:"name",label:l("备注名"),optional:!0,placeholder:l("可选,留空自动生成")}]}}const yF={provider:"codearts",label:"CodeArts",desktop:!1,webLogin:{noteHtml:l("打开华为云 CodeArts 的官方授权页登录:登录完成后官方页面会把浏览器带回网关自己的 /oauth/callback,网关用一次性授权码换取临时凭据并加入账号列表。
网关跑在另一台机器上时,网页端会提示把地址栏中的最终回调地址直接粘贴回面板。"),button:l("打开 CodeArts 授权页"),busyText:l("等待 CodeArts 登录完成…"),modes:[{value:"embedded",label:l("内嵌窗口(推荐)"),hint:l("将打开内嵌窗口;登录完成后自动加入账号列表。关掉窗口即取消等待")},{value:"external",label:l("系统浏览器"),hint:l("将用系统默认浏览器打开授权页(会复用浏览器里已登录的华为云账号);浏览器与网关不在同一台机器时,按上方说明把最终回调地址粘贴回面板")}]},manualTitle:l("粘贴登录凭据"),manualNoteHtml:l('整份粘贴官方插件 / CLIProxyAPI 落盘的凭据 JSON(形如 {"codearts_provider_credential":{…}},铺平的也行)。
必填:access_key_id、secret_access_key、security_token。要能自动续期,必须连 refresh_token 与 oauth_context 一起粘 —— 临时凭据约一小时到期,缺这半块就续不回来,只能重新登录。'),fields:[{key:"credentialJson",label:l("凭据 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:l("备注名"),optional:!0,placeholder:l("可选,留空使用凭据里的 user_name")}]},jF={provider:"trae",label:"Trae",desktop:!1,webLogin:{noteHtml:l("打开 Trae SOLO 的官方授权页(trae.cn)并用你的 Trae 账号登录:授权完成后官方页面会跳回本机的一个临时端口;同机部署自动接收,Docker / 远程面板请按提示复制地址栏回调地址。"),button:l("打开 Trae 授权页"),busyText:l("等待 Trae 授权完成…"),modes:[{value:"embedded",label:l("内嵌窗口(推荐)"),hint:l("将打开内嵌窗口;授权完成后自动加入账号列表。远程面板可粘贴回调地址。关掉窗口即取消等待。链接 5 分钟内有效,超时或未点就会作废(可重新发起)")},{value:"external",label:l("系统浏览器"),hint:l("将用系统默认浏览器打开授权页(会复用浏览器里已登录的 Trae 账号);同机完成后自动加入,Docker / 远程面板按提示粘贴地址栏回调地址。")}]},manualTitle:l("填写凭证"),manualNoteHtml:l("accessToken 是 Trae 的 Cloud-IDE-JWT(三段点分),refreshToken 用于到期自动续期(本家 refreshToken 一次一换:换发一次旧的即作废,所以两份程序别同时刷同一个账号)。
手工粘贴时请连 machineId / deviceId 一起填:上游把它们与登录时上传的设备公钥绑在一起判设备,凭空换一对会撞 2xxxx 那族设备绑定拒绝。
没有这三样时的正路是用上方的「网页登录」;容器 / 远程部署形态按提示粘贴地址栏回调地址即可。"),fields:[{key:"accessToken",label:"accessToken",rows:3,placeholder:l("Cloud-IDE-JWT(三段点分)")},{key:"refreshToken",label:"refreshToken",rows:2,optional:!0,placeholder:l("可选;填了才能到期自动续期")},{key:"uid",label:l("用户 ID"),optional:!0,placeholder:l("可选;用于去重与展示名(留空时网关会问一次上游)")},{key:"machineId",label:"machineId",optional:!0,placeholder:l("可选;UUID 形态,与凭据同生共死")},{key:"deviceId",label:"deviceId",optional:!0,placeholder:l("可选;纯数字串(上游只收 8–24 位数字)")},{key:"name",label:l("备注名"),optional:!0,placeholder:l("可选,留空自动用昵称")}]},wF={provider:"loomy",label:"Loomy",smsLogin:{noteHtml:l("用 Loomy 账号绑定的手机号登录:点「获取验证码」后填入即可。这是本家最省事的入口。")},manualNote:l("粘贴的是登录 session(同时是模型网关的 token)。Loomy 没有续期接口,session 有效期约 14 天,过期后重新登录即可。"),fields:[{key:"session",label:"session",rows:3,placeholder:l("登录 session(一长串)")},{key:"userId",label:"userId",optional:!0,placeholder:l("可选,讯飞侧 userid")},{key:"phone",label:l("手机号"),optional:!0,placeholder:l("可选,展示用")},{key:"name",label:l("备注名"),optional:!0,placeholder:l("可选,留空则用脱敏手机号或 userId")}],desktop:!1},SF={provider:"kuku",label:"KukuAI",webLogin:{noteHtml:l("在打开的窗口里用百度账号登录 KukuAI 主站(手机验证码 / 扫码均可),登录成功后自动加入账号列表。网关会向百度换发 KukuAI 业务会话令牌(依赖本机已安装库库AI 客户端)。"),button:l("打开网页登录"),busyText:l("等待 KukuAI 登录完成…")},manualTitle:l("粘贴 Cookie"),manualNote:l("BDUSS 必填;请粘贴**完整 Cookie**(Cookie 编辑器一键导出即可)—— 其中 **PTOKEN 必须保留**,网关要用它向百度换发 KukuAI 业务会话令牌,缺了它模型刷新会报「未登录」。支持整段 Cookie 头、Cookie 编辑器导出的 JSON 数组,或 {BDUSS, STOKEN} 对象。KukuAI 没有刷新机制,登录态过期后重新粘贴即可。"),fields:[{key:"cookie",label:"Cookie",rows:3,placeholder:l("BDUSS=…; STOKEN=…(或 Cookie 编辑器导出的 JSON)")},{key:"name",label:l("备注名"),optional:!0,placeholder:l("可选,留空则用账号 uk")}],desktop:!0,desktopHint:l("读取本机 KukuAI 客户端登录态(%APPDATA%\\baidugenflowpro\\Network\\Cookies),需已在 KukuAI 客户端登录"),desktopNote:l("读本机客户端当前登录态(明文 Cookie,无需解密)。客户端运行时 Cookies 文件被独占占用,导入前请先关闭 KukuAI 客户端。")};function lA(e){const{provider:t,label:r,siteNote:o}=e;return{provider:t,label:r,desktop:!1,manualTitle:l("粘贴 session cookie"),manualNoteHtml:l("粘贴网页登录态 cookie monkeycode_ai_session 的值(在浏览器里复制整段 Cookie 直接粘贴也行,网关会自己剥出值)。
{siteNote}
MonkeyCode 没有续期接口:session 有效期约 30 天(硬限制),过期后重新登录网页、再粘贴一次即可。",{siteNote:o}),fields:[{key:"session",label:"session",rows:3,placeholder:l("monkeycode_ai_session 的值(也可直接粘贴整段 Cookie)")},{key:"imageId",label:l("任务镜像 id"),optional:!0,placeholder:l("可选:发起对话必需,留空则由网关从该账号已有任务里自动发现,发现不到时之后手动补")},{key:"name",label:l("备注名"),optional:!0,placeholder:l("可选,留空则用上游返回的账号名或账号 id")}]}}const NF=lA({provider:"monkeycode",label:l("MonkeyCode"),siteNote:l("这里填国内站(monkeycode-ai.com)的账号:请粘贴国内站的 session。国际站(monkeycode-ai.net)是另一家 provider、另一套账号,两边的凭证不通用。")}),CF=lA({provider:"monkeycode-intl",label:l("MonkeyCode 国际版"),siteNote:l("这里填国际站(monkeycode-ai.net)的账号:请粘贴国际站的 session。国内站(monkeycode-ai.com)是另一家 provider、另一套账号,两边的凭证不通用。")}),kF={provider:"commandcode",label:l("Command Code"),desktop:!1,manualTitle:l("粘贴 API Key"),manualNote:l("粘贴 Command Code 的 API Key(user_ 开头;从官方 CLI 的 ~/.commandcode/auth.json 或网页 studio 获取)。整行 / 带引号 / 带 Bearer 前缀地粘都行,网关会自己剥成裸 key。key 不过期、也没有续期接口,失效后重新获取即可;添加时网关会做一次轻量探活,失败不影响添加。"),fields:[{key:"apiKey",label:"apiKey",rows:3,placeholder:l("user_ 开头的 API Key(也可直接粘贴 Authorization: Bearer … 整行)")},{key:"name",label:l("备注名"),optional:!0,placeholder:l("可选,留空则用 key 尾号")}]},TF={provider:"antigravity",label:l("Antigravity"),desktop:!1,webLogin:{noteHtml:l("在打开的窗口里登录 Google 账号(Antigravity 的授权页),授权完成后自动加入账号列表。"),button:l("打开 Antigravity 网页登录"),busyText:l("等待 Google 授权完成…"),modes:[{value:"embedded",label:l("内嵌窗口(推荐)"),hint:l("内嵌窗口打开;完成后自动加入列表,关窗即取消等待")},{value:"external",label:l("系统浏览器"),hint:l("系统浏览器打开(复用已登录的 Google 账号);完成后自动加入列表")}]},manualTitle:l("粘贴 Google refresh token"),manualNoteHtml:l("粘贴 Antigravity 的 Google refresh token(以 1// 开头;直接粘贴含 refresh_token= 的整行也行)。
这是网页登录之外的手工入口(例如从已登录的官方 IDE 里导出)。refresh token 不会过期,access token 到期由网关自动续期;令牌丢了只能重新走 Google 授权,请妥善保存。"),fields:[{key:"refreshToken",label:"refreshToken",rows:2,placeholder:l("1// 开头的 Google refresh token(也可直接粘贴 refresh_token=… 整行)")},{key:"projectId",label:"projectId",optional:!0,placeholder:l("可选(cloudaicompanionProject):留空由网关自动发现")},{key:"email",label:"email",optional:!0,placeholder:l("可选:账号邮箱,用于展示与身份识别(换新令牌也能认回同一账号)")},{key:"name",label:l("备注名"),optional:!0,placeholder:l("可选,留空则用邮箱或令牌尾号")}]},EF={provider:"officeace",label:l("OfficeAce 果办"),desktop:!1,webLogin:{noteHtml:l("打开华为云授权页登录:登录完成后网关会自动轮询云端取回授权码并加入账号列表(不需要装 OfficeAce 桌面端,也无需手工回填回调地址)。"),button:l("打开授权页"),busyText:l("等待 OfficeAce 登录完成…")},manualTitle:l("粘贴网关凭据"),manualNoteHtml:l("从别的机器(或 OfficeAce 桌面端 models.json)取三项贴进来:模型网关基址(baseUrl,形如 https://modelgw-…/v2)与 modelAppKey / modelAppSecret。这三项就能转发(网关凭据不过期);控制面临时凭据(accessKeyId 等)可选,留空则额度/自动续期不可用,但不影响转发。"),fields:[{key:"baseUrl",label:l("模型网关基址"),placeholder:"https://modelgw-…huaweicloud-agentarts.com/v2"},{key:"modelAppKey",label:l("网关 Key"),placeholder:"model_app_key"},{key:"modelAppSecret",label:l("网关 Secret"),placeholder:"model_app_secret"},{key:"name",label:l("备注名"),optional:!0,placeholder:l("可选,留空用「OfficeAce 果办」")}]},oA=[mF,hF,gF,xF,bF,vF,sA({provider:"cline-free",label:"Cline Free",poolNote:l("(免费额度池,模型名带 cline-free/ 前缀)。")}),sA({provider:"cline-pass",label:"Cline Pass",poolNote:l("(订阅池,模型名带 cline-pass/ 前缀,需要账号有对应订阅)。")}),rA({provider:"accio",label:l("国际版"),site:"www.accio.com",siteNote:l("国际版与国内版是**两套独立的账号**(同一账号体系的两个站点),凭证不通用。")}),rA({provider:"accio-cn",label:l("国内版"),site:"www.accio-ai.com",siteNote:l("国内版的登录站点是 www.accio-ai.com,与国际版不是同一站。")}),aA({provider:"zcode",label:l("国内版"),site:"open.bigmodel.cn",planNote:l("国内版与**国际版是两套独立的账号与套餐**,凭证与领取的套餐都不通用。")}),aA({provider:"zcode-intl",label:l("国际版"),site:"api.z.ai",planNote:l("国际版的推理站点是 api.z.ai,与国内版不是同一站;套餐也各自独立。")}),yF,jF,wF,SF,NF,CF,kF,TF,EF],_i="workbuddy",cu="custom",lj="WorkBuddy";function RF(e){return oA.find(t=>t.provider===e)}const iA=[{id:"oauth",label:l("网页登录(Zai / Google)")},{id:"sms",label:l("手机验证码登录")},{id:"web",label:l("网页登录")},{id:"manual",label:l("填写凭证")},{id:"desktop",label:l("导入桌面端登录态")}],cA=()=>kt().workbuddyDesktop?.platform||"";function uA(e){return!(e.desktop===!1||cA()==="web"||e.desktopWindowsOnly&&cA()==="macos")}function dA(e,t){return iA.filter(r=>r.id==="oauth"?!!e.oauthLogin:r.id==="sms"?!!e.smsLogin:r.id==="web"?!!e.webLogin&&(!e.webLogin?.region||t===e.webLogin.region):r.id==="desktop"?uA(e):!0).map(r=>r.id)}const AF=e=>e.manualTitle||l("填写凭证添加"),OF=e=>e.manualNoteHtml?{html:e.manualNoteHtml}:{text:e.manualNote||""},MF=e=>e.addButton||l("添加 {name} 账号",{name:e.label}),oj=(e,t)=>`${e.provider}-${t.inputKey||t.key}-input`,bf="max-w-full flex-wrap [&_[data-slot=segmented-item]]:h-7 [&_[data-slot=segmented-item]]:px-3 [&_[data-slot=segmented-item]]:text-[12.5px]",DF=l("登录态文件路径:~/.box-agent/config/auth.json(Windows:C:\\Users\\<你的用户名>\\.box-agent\\config\\auth.json)");let ij=!1;async function fA(e,t){if(!ij){ij=!0,e(!0);try{await t()}finally{ij=!1,e(!1)}}}function qh({html:e,text:t}){return e?s.jsx("p",{dangerouslySetInnerHTML:{__html:e}}):s.jsx("p",{children:t||""})}function IF(e,t,r){let o;try{o=JSON.parse(t)}catch(c){return Zs(l("{name} 不是合法 JSON:{reason}",{name:e.label,reason:$h(c)}),"err"),!1}return!o||typeof o!="object"||Array.isArray(o)?(Zs(l("{name}要粘一个 JSON 对象(形如 {sample})",{name:e.label,sample:'{"codearts_provider_credential":{…}}'}),"err"),!1):(Object.assign(r,o),!0)}function PF({config:e,region:t,visible:r}){const o=e.provider,[c,d]=x.useState(!1),[f,p]=x.useState(""),g=OF(e),v=e.fields.map(b=>oj(e,b));async function y(){const b={provider:e.provider};e.regionOptions?.length&&(b.mode=t);for(const j of e.fields){const w=sa(oj(e,j));if(!j.optional&&!w){Zs(l("请填写 {label}",{label:j.label}),"err");return}if(w){if(j.jsonExpand){if(!IF(j,w,b))return;continue}b[j.key]=w}}await fA(d,async()=>{try{const j=await eA(b);aj(v),p(""),await Fh(tA(j?.account),e.label)}catch(j){Zs(l("添加失败:{reason}",{reason:$h(j)}),"err")}})}return s.jsxs(zn,{hidden:!r,onClick:b=>{b.target.closest("[data-raccoon-hint]")&&(b.preventDefault(),p(DF))},children:[s.jsx("h3",{children:AF(e)}),s.jsx(qh,{...g}),e.fields.map(b=>{const j=oj(e,b),w=b.optional?"":l("(必填)");return s.jsxs("div",{className:`field-row${b.rows?" stack":""}`,children:[s.jsxs("label",{htmlFor:j,children:[b.label,w]}),b.rows?s.jsx($d,{id:j,rows:b.rows,placeholder:b.placeholder,...Tl(j)}):s.jsx(Ke,{id:j,type:"text",maxLength:pF(b),placeholder:b.placeholder,...Tl(j)})]},j)}),s.jsxs("div",{className:"field-row",children:[s.jsx(se,{id:`${o}-add-button`,onClick:()=>{y()},disabled:c,children:c?l("添加中…"):MF(e)}),s.jsx("span",{className:"detail",id:`${o}-add-hint`,children:f})]})]})}function _F({config:e,visible:t}){const r=e.provider,[o,c]=x.useState(!1);if(!uA(e)||!e.desktopNote)return null;async function d(){await fA(c,async()=>{try{const f=await eA({provider:e.provider,importDesktop:!0});await Fh(f?.account?.name||"",e.label)}catch(f){Zs(l("导入失败:{reason}",{reason:$h(f)}),"err")}})}return s.jsxs(zn,{hidden:!t,children:[s.jsx("h3",{children:l("从本机导入桌面端登录态")}),s.jsx("p",{children:e.desktopNote}),s.jsx("div",{className:"field-row",children:s.jsx(se,{id:`${r}-desktop-button`,title:e.desktopHint,onClick:()=>{d()},disabled:o,children:l(o?"导入中…":"从本机导入桌面端登录态")})})]})}function LF({config:e,mode:t,onModeChange:r,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=kt().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:()=>kt().workbuddyDesktop?.startLogin(d.edition||g.current||"cn",p.current||"embedded",f),onSuccess:async j=>{rj(),await kt().wbApp?.refresh?.();const w=j?.payload?.warning;w?Zs(l("账号已添加,但请留意:{warning}",{warning:w}),"err"):Zs(l("✅ {label}账号已添加",{label:e.label}))}})??null},[]),x.useEffect(()=>{v.current?.syncTexts()},[t]),d?s.jsxs(zn,{hidden:!c,children:[s.jsx("h3",{children:l("网页登录")}),s.jsx(qh,{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:l("打开方式")}),s.jsx(Gn,{"aria-label":l("{label} 网页登录的打开方式",{label:e.label}),options:d.modes,value:t,onValueChange:r})]}):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:l("取消等待")}),s.jsx("span",{className:"detail",id:`${f}-web-hint`,children:d.hint||d.modes?.[0]?.hint||""})]})]}):null}function zF({config:e,visible:t}){const r=e.smsLogin,o=e.provider;return x.useEffect(()=>{r&&kt().wbSmsLogin?.create({provider:o,onSuccess:c=>Fh(tA(c?.account),e.label)})},[]),r?s.jsxs(zn,{hidden:!t,children:[s.jsx("h3",{children:l("手机验证码登录")}),s.jsx(qh,{html:r.noteHtml,text:l("用 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:[l("手机号"),s.jsx("i",{className:"req",children:"*"})]}),s.jsxs(ji,{children:[s.jsx(Si,{id:`${o}-sms-phone`,type:"text",maxLength:11,placeholder:l("11 位大陆手机号"),...Tl(`${o}-sms-phone`)}),s.jsx(wi,{align:"inline-end",children:s.jsx(d4,{id:`${o}-sms-send`,className:"text-primary-fg",children:l("获取验证码")})})]})]}),s.jsxs("div",{className:"sms-field",children:[s.jsxs("label",{className:"lb",htmlFor:`${o}-sms-code`,children:[l("验证码"),s.jsx("i",{className:"req",children:"*"})]}),s.jsxs("div",{className:"sms-pair",children:[s.jsx(Ke,{id:`${o}-sms-code`,className:"sms-code",type:"text",maxLength:6,placeholder:l("6 位数字")}),s.jsx("label",{className:"lb-inline",htmlFor:`${o}-sms-name`,children:l("备注名")}),s.jsx(Ke,{id:`${o}-sms-name`,className:"sms-name",type:"text",placeholder:l("可选,留空则用脱敏手机号"),...Tl(`${o}-sms-name`)})]})]}),s.jsxs("div",{className:"sms-foot",children:[s.jsx(se,{id:`${o}-sms-submit`,children:l("登录并添加")}),s.jsx("span",{className:"detail sms-hint",id:`${o}-sms-hint`})]})]})]}):null}function BF({config:e,mode:t,onModeChange:r,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=kt().wbAutoclawOauth;!v||!c||(p.current=v.create({provider:d,mode:()=>f.current||"embedded",hint:g,cancelId:`${d}-oauth-cancel`,onSuccess:()=>Fh("",e.label)})??null)},[]),x.useEffect(()=>{p.current?.syncTexts()},[t]),c?s.jsxs(zn,{hidden:!o,children:[s.jsx("h3",{children:c.title||l("网页登录")}),s.jsx(qh,{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:l("打开方式")}),s.jsx(Gn,{"aria-label":l("{label} 网页登录的打开方式",{label:e.label}),options:c.modes,value:t,onValueChange:r})]}):null,s.jsxs("div",{className:"field-row",children:[s.jsx(se,{id:`${d}-oauth-zai`,children:l("使用 Zai 账号登录")}),s.jsx(se,{id:`${d}-oauth-google`,variant:"outline",children:l("使用 Google 账号登录")}),s.jsx(se,{id:`${d}-oauth-cancel`,variant:"outline",hidden:!0,children:l("取消")})]}),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 HF({config:e,active:t}){const r=e.regionOptions?.[0]?.value??"",[o,c]=x.useState(r),[d,f]=x.useState(()=>dA(e,r)[0]),[p,g]=x.useState(e.webLogin?.modes?.[0]?.value??""),[v,y]=x.useState(e.oauthLogin?.modes?.[0]?.value??""),b=dA(e,o),j=b.includes(d)?d:b[0],w=x.useMemo(()=>iA.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(zn,{children:[s.jsx("h3",{children:l("地区")}),s.jsx(Gn,{"aria-label":l("{label} 账号地区",{label:e.label}),className:bf,options:e.regionOptions,value:o,onValueChange:c})]}):null,s.jsxs(zn,{children:[s.jsx("h3",{children:l("添加方式")}),s.jsx(Gn,{"aria-label":l("{label} 账号的添加方式",{label:e.label}),className:bf,options:w,value:j,onValueChange:S=>f(S)})]}),s.jsx(BF,{config:e,mode:v,onModeChange:y,visible:j==="oauth"}),s.jsx(zF,{config:e,visible:j==="sms"}),s.jsx(LF,{config:e,mode:p,onModeChange:g,region:o,visible:j==="web"}),s.jsx(PF,{config:e,region:o,visible:j==="manual"}),s.jsx(_F,{config:e,visible:j==="desktop"})]})}function pA(e){return e==="intl"?"workbuddy-intl":"workbuddy"}function UF({active:e}){const[t,r]=x.useState(Pi.edition),[o,c]=x.useState(Pi.loginMode),[d,f]=x.useState(Pi.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=kt().wbWebLogin;E&&(y.current=E.create({get provider(){return pA(p.current)},buttonId:"web-login-button",cancelId:"web-login-cancel",hintId:"web-login-hint",busyText:l("等待网页登录…"),texts:()=>{const R=g.current==="external";return{button:l(R?"在浏览器中打开登录页":"打开网页登录"),hint:l(R?"系统浏览器打开(复用已登录账号);完成后自动加入列表":"内嵌窗口打开;完成后自动加入列表,关窗即取消等待")}},start:()=>kt().workbuddyDesktop?.startLogin(p.current,g.current,pA(p.current),v.current),onSuccess:async()=>{const R=p.current==="intl"?l("国际版"):l("国内版");rj(),await kt().wbApp?.refresh?.(),Zs(l("✅ 登录成功,{edition}账号已加入列表",{edition:R}))}})??null)},[]),x.useEffect(()=>{y.current?.syncTexts()},[t,o]);function b(E){const R=E==="intl"?"external":"embedded";r(E),Pi.edition=E,c(R),Pi.loginMode=R}function j(E){const R=E==="external"?"external":"embedded";c(R),Pi.loginMode=R}const w=t==="intl",N=w&&o==="embedded",C=l(N?"国际版登录页默认只显示邮箱登录,勾选后恢复 Google / GitHub / X 入口":w?"只有「内嵌窗口」能恢复第三方入口:系统浏览器里我们无法改动登录页":"国内版登录页没有 Google / GitHub 入口(它用微信 / 手机号 / 邮箱登录)");return s.jsxs("div",{className:"add-provider-block",hidden:!e,children:[s.jsxs(zn,{children:[s.jsx("h3",{children:l("账号版本")}),s.jsx("p",{children:l("两版账号可同时保存,各自一份模型清单(国内版与国际版是两家提供商,可分别启用与映射)。")}),s.jsx(Gn,{"aria-label":l("账号版本"),className:bf,options:[{value:"cn",label:l("国内版(WorkBuddy)")},{value:"intl",label:l("国际版(WorkBuddy AI)")}],value:t,onValueChange:E=>b(E)})]}),s.jsxs(zn,{children:[s.jsx("h3",{children:l("网页登录")}),s.jsx("p",{children:l("完成登录后自动加入账号列表,昵称取自上游。")}),s.jsxs("div",{className:"field-row",children:[s.jsx("span",{className:"text-[12.5px] whitespace-nowrap text-subtle",children:l("打开方式")}),s.jsx(Gn,{"aria-label":l("网页登录的打开方式"),className:bf,options:[{value:"embedded",label:l("内嵌窗口")},{value:"external",label:l("系统默认浏览器")}],value:o,onValueChange:j}),s.jsxs("label",{className:"flex items-center gap-2",title:C,children:[s.jsx(Rs,{checked:d,disabled:!N,onCheckedChange:E=>{f(E),Pi.socialRestore=E}}),s.jsx("span",{className:"text-[12.5px] text-subtle",children:l("恢复 Google / GitHub 入口")})]})]}),s.jsx("p",{children:l("系统浏览器可复用已有登录态(国际版推荐);内嵌窗口更干净。")}),s.jsxs("div",{className:"field-row",children:[s.jsx(se,{id:"web-login-button",onClick:()=>y.current?.start(),children:l("打开网页登录")}),s.jsx(se,{id:"web-login-cancel",variant:"outline",hidden:!0,onClick:()=>y.current?.cancel(),children:l("取消等待")}),s.jsx("span",{className:"detail",id:"web-login-hint",children:l("内嵌窗口打开;完成后自动加入列表,关窗即取消等待")})]})]})]})}const cj="proxy",uj="preset",Gh="custom",VF="import",vf="preset:",dj="__new__";function $F(e){return e===uj||e===Gh?e:cj}const Kh={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"},FF=new Set(["monkeycode","monkeycode-intl","commandcode","antigravity"]);function qF(e){const t=kt().wbProviders;if(e===uj){const g=new Set((t?.customList?.()||[]).map(v=>v.name||""));return(kt().wbPresetProviders?.list||[]).filter(v=>!g.has(v.name)).map(v=>({id:vf+v.key,label:v.name,count:0,preset:!0}))}if(e===Gh)return(t?.customList?.()||[]).map(g=>({id:g.id,label:g.name||g.id,count:JR(g.id),custom:!0}));const r=t?.all?.()||[],o=(g,v)=>g===_i?lj:kt().wbProviders?.labelOf?.(g)||v,d=(r.length?r.map(g=>{const v=String(g.id||"");return{id:v,label:o(v,String(g.label||g.id||"")),count:Number(g.count)||0,beta:FF.has(v)}}):[{id:_i,label:lj,count:JR(_i)}]).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 GF({item:e}){const t=e.id.startsWith(vf)?kt().wbPresetProviders?.iconOf?.(e.id.slice(vf.length))||"":Kh[e.id];if(t)return s.jsx("span",{className:"add-provider-logo has-icon",children:s.jsx("img",{src:t,alt:"",loading:"lazy"})});const r=String(e.label||"?").trim().slice(0,1).toUpperCase()||"?";return s.jsx("span",{className:"add-provider-logo",children:r})}function KF(e){return e.preset?l("点开即预填,填 Key 接入"):e.custom?e.count?l("{n} 个账号,点击添加",{n:e.count}):l("点击添加账号"):e.count?l("{n} 个账号",{n:e.count}):l("还没有账号")}function YF({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(GF,{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:KF(e)})]}),s.jsx("span",{className:"add-provider-go",children:"›"})]})}function XF({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:l("新建自定义提供商")}),s.jsx("span",{className:"add-provider-meta",children:l("接入一个兼容上游")})]}),s.jsx("span",{className:"add-provider-go",children:"›"})]})}function QF({accountType:e,onAccountTypeChange:t,search:r,onSearchChange:o,onPick:c,version:d,importing:f,importPanel:p}){const g=x.useMemo(()=>qF(e),[e,d]),v=r.trim().toLowerCase(),y=g.filter(j=>!v||j.label.toLowerCase().includes(v)),b=e===Gh&&!v;return s.jsxs(zn,{children:[s.jsx("h3",{children:l("选择提供商")}),s.jsxs("div",{className:"add-pick-row",style:f?{display:"none"}:void 0,children:[s.jsx(Gn,{"aria-label":l("账号类型"),className:bf,options:[{value:cj,label:"Agent"},{value:uj,label:l("预置 API")},{value:Gh,label:l("自定义")}],value:e,onValueChange:j=>t($F(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(ji,{children:[s.jsx(wi,{children:"⌕"}),s.jsx(Si,{id:"add-provider-search",type:"search",placeholder:l("搜索提供商…"),autoComplete:"off","aria-label":l("搜索提供商"),value:r,onChange:j=>o(j.currentTarget.value)})]})})]}),p,s.jsxs("div",{className:"add-provider-grid",id:"add-provider-grid",role:"listbox","aria-label":l("选择要添加账号的提供商"),style:f?{display:"none"}:void 0,children:[b?s.jsx(XF,{onPick:c}):null,y.map(j=>s.jsx(YF,{item:j,onPick:c},j.id)),!y.length&&v?s.jsx("div",{className:"add-provider-empty",children:l("没有匹配「{keyword}」的提供商",{keyword:r.trim()})}):null]})]})}function Yh(e,t){return Pe().wbIcons?.icon?.(e,t)||""}function ZF({account:e,rank:t}){const r=l("组内第 {rank} 位",{rank:t});return s.jsxs("div",{className:"order-cell",children:[s.jsx("span",{className:"order-grip",role:"button",tabIndex:-1,"aria-label":l("拖动调整组内顺序"),title:l("按住拖动,调整这个账号在本组内的顺序"),dangerouslySetInnerHTML:{__html:Yh("gripVertical",14)}}),s.jsx("span",{className:"order-rank",title:r,children:`#${t}`})]})}function WF({group:e,ids:t,collapsed:r}){const[o,c]=x.useState(!1),d="w-full justify-start px-2 font-normal";return s.jsxs(rf,{open:o,onOpenChange:c,children:[s.jsx(yh,{render:s.jsx("button",{type:"button",className:"grp-iconbtn",title:l("本组操作")}),children:"⋯"}),s.jsx(af,{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:l("启用这一组里的全部账号(含被筛选隐藏的)"),onClick:()=>{c(!1),PR(t,!0)},children:l("全部启用({n})",{n:t.length})}),s.jsx(se,{variant:"ghost",size:"sm",className:d,title:l("禁用这一组里的全部账号(含被筛选隐藏的)"),onClick:()=>{c(!1),PR(t,!1)},children:l("全部禁用({n})",{n:t.length})}),s.jsx(se,{variant:"ghost",size:"sm",className:d,title:l("打开批量操作弹窗,并预选这一组的账号(改代理等动作在弹窗里挑参数)"),onClick:()=>{c(!1),Yy(t,"proxy")},children:l("批量操作本组")}),s.jsx("div",{className:"my-1 h-px bg-hairline"}),s.jsx(se,{variant:"ghost",size:"sm",className:d,onClick:()=>{c(!1),hR(e.provider)},children:l(r?"展开这一组":"折叠这一组")})]})})]})}function JF({group:e,collapsed:t,colSpan:r}){const o=Kh[e.provider];return s.jsx("tr",{className:"grp-band","data-provider":e.provider,children:s.jsx("td",{colSpan:r,children:s.jsxs("div",{className:"grp-band-inner",children:[s.jsx("span",{className:"queue-grip",role:"button",tabIndex:-1,"aria-label":l("拖动调整整组顺序"),title:l("按住拖动,调整这一家的组顺位(整组一起动)"),dangerouslySetInnerHTML:{__html:Yh("gripVertical",14)}}),s.jsx("span",{className:"grp-rank",title:l("组顺位:越小越先用(拖动分组带调整)"),children:l("第 {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:l("{total} 个账号 · 启用 {enabled} · 禁用 {disabled}{limited}",{total:e.members.length,enabled:e.enabled,disabled:e.disabled,limited:e.limited>0?l(" · 限流 {n}",{n:e.limited}):""})}),s.jsx("span",{className:"grp-spacer"}),s.jsx("button",{type:"button",className:"grp-iconbtn grp-fold","aria-expanded":!t,title:l(t?"展开这一组":"折叠这一组"),onClick:()=>hR(e.provider),dangerouslySetInnerHTML:{__html:Yh("chevronDown",14)}}),s.jsx(WF,{group:e,ids:e.accounts.map(c=>c.id),collapsed:t})]})})})}function e8({account:e}){const t=or(e),r=W6(e);!t&&U6(e,Cl(e))&&r.push({text:l("Token 限额 · 已禁用"),kind:"bad",title:l("本周期 Token 消耗达到限制器的上限,账号已被自动禁用(窗口重置也不恢复,需手动启用)")});const o=ru(e)||e.id;return s.jsxs(s.Fragment,{children:[s.jsx(Rs,{checked:t,"aria-label":l("{action}{who}",{action:l(t?"禁用":"启用"),who:o}),title:l(t?"已启用,点击禁用(不参与转发)":"已禁用,点击启用"),onCheckedChange:c=>{DR(e.id,c)}}),r.length?s.jsx("div",{className:"status-tags",children:r.map(c=>s.jsx(ze,{shape:"tag",variant:c.kind==="bad"?"destructive":"secondary",title:c.title,children:c.text},c.text))}):null]})}function t8({account:e,open:t}){const r=Uy(e);if(!r.length)return Sh(e,Ka(e))?s.jsx(ze,{variant:"warning",shape:"tag",title:l("余额低于限制器的阈值,转发时会跳过该账号(余额回升自动恢复)"),children:l("余额不足")}):_y(e,Cl(e))?s.jsx(ze,{variant:"warning",shape:"tag",title:l("本周期 Token 消耗达到限制器的上限,转发时会跳过该账号(窗口重置自动恢复)"),children:l("Token 限额")}):s.jsxs(ze,{variant:"success",shape:"tag",title:l("当前没有任何模型处于限流中"),children:[s.jsx(Lv,{}),l("正常")]});const o=Fy(r[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:l("点击{action}各模型的限流明细",{action:l(t?"收起":"查看")}),onClick:()=>bR(e.id,"limits",!t),children:l("{n} 个模型 ▾",{n:r.length})}),s.jsx("span",{className:"lim-sub",title:l("最早恢复"),children:l("最早 {soonest} 恢复",{soonest:o===$y?l("待定"):o})})]})}function n8({account:e}){const t=lr(Rn(e)),r=BE(t.edition?e.expiresAt:e[t.expiry]);if(!r)return s.jsx("span",{className:"muted",title:l("记录里没有过期时间"),children:"—"});const o=r-Date.now();if(o<=0)return s.jsx(ze,{variant:"destructive",shape:"tag",title:l("凭证已过期,转发时会先刷新"),children:l("已过期")});const c=o<36e5?l("{n} 分钟后",{n:Math.max(1,Math.round(o/6e4))}):o<48*36e5?l("{n} 小时后",{n:(o/36e5).toFixed(1)}):l("{n} 天后",{n:Math.floor(o/24/36e5)}),d=Bs(r);return s.jsx("span",{title:d?l("{text}过期({full})",{text:c,full:d}):l("{text}过期",{text:c}),children:c})}function s8({account:e}){const t=NR(e.id);return t<=0?null:s.jsx("span",{className:"conn-count",title:l("{n} 个请求正在使用该账号(含还在下发内容的流式请求)",{n:t}),children:t})}function br(e){if(e==null||e==="")return"—";const t=Number(e);return Number.isFinite(t)?String(t):String(e)}function r8(e){return!e||typeof e!="object"||Array.isArray(e)?"":mA(e.subscription)}function mA(e){if(!e||typeof e!="object")return"";const t=e,r=[];t.planName&&r.push(l("套餐 {name}",{name:String(t.planName)})),t.status&&r.push(l("状态 {status}",{status:String(t.status)})),t.state&&String(t.state)!=="active"&&r.push(WE(t.state));const o=t.expireAt;if(o!=null&&o!==""){const c=Number(o),d=Number.isFinite(c)&&c>1e11?Bs(c):String(o);d&&r.push(l("到期 {time}",{time:d}))}return Number.isFinite(Number(t.remainQuota))&&r.push(l("余量 {value}",{value:br(t.remainQuota)})),Number.isFinite(Number(t.totalQuota))&&r.push(l("总量 {value}",{value:br(t.totalQuota)})),r.join(" ")}function a8(e){if(!e||typeof e!="object"||Array.isArray(e))return[];const t=e.plans;return Array.isArray(t)?t.filter(r=>r&&typeof r=="object"&&String(r.state||"")==="pending"):[]}function l8(e){const t=e.map(r=>{const o=String(r.name||r.planId||l("套餐")),c=Number(r.pendingUntil??r.startsAt);return Number.isFinite(c)&&c>0?l("{name}({time} 起生效)",{name:o,time:Bs(c*1e3)}):o});return l(`已领到、还没到生效时间的套餐(生效后余额列会按它显示): +`+u.stack}}var $n=Object.prototype.hasOwnProperty,us=e.unstable_scheduleCallback,qn=e.unstable_cancelCallback,gs=e.unstable_shouldYield,lt=e.unstable_requestPaint,Bt=e.unstable_now,Ln=e.unstable_getCurrentPriorityLevel,Jt=e.unstable_ImmediatePriority,tt=e.unstable_UserBlockingPriority,Tt=e.unstable_NormalPriority,Ht=e.unstable_LowPriority,Zn=e.unstable_IdlePriority,zn=e.log,Bn=e.unstable_setDisableYieldValue,Tn=null,Qt=null;function rs(n){if(typeof zn=="function"&&Bn(n),Qt&&typeof Qt.setStrictMode=="function")try{Qt.setStrictMode(Tn,n)}catch{}}var St=Math.clz32?Math.clz32:yt,ht=Math.log,vt=Math.LN2;function yt(n){return n>>>=0,n===0?32:31-(ht(n)/vt|0)|0}var jr=256,nr=262144,Pr=4194304;function xn(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 el(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 H=u&134217727;return H!==0?(u=H&~h,u!==0?m=xn(u):(T&=H,T!==0?m=xn(T):i||(i=H&~n,i!==0&&(m=xn(i))))):(H=u&~h,H!==0?m=xn(H):T!==0?m=xn(T):i||(i=u&~n,i!==0&&(m=xn(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 tn(n,l){return(n.pendingLanes&~(n.suspendedLanes&~n.pingedLanes)&l)===0}function ac(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 Po(n,l){n.pendingLanes|=l,l!==268435456&&(n.suspendedLanes=0,n.pingedLanes=0,n.warmLanes=0)}function _o(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 H=n.entanglements,te=n.expirationTimes,pe=n.hiddenUpdates;for(i=T&~i;0"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),qt=!1;if(at)try{var En={};Object.defineProperty(En,"passive",{get:function(){qt=!0}}),window.addEventListener("test",En,En),window.removeEventListener("test",En,En)}catch{qt=!1}var fn=null,Rn=null,ds=null;function wr(){if(ds)return ds;var n,l=Rn,i=l.length,u,m="value"in fn?fn.value:fn.textContent,h=m.length;for(n=0;n=Op),JI=" ",eP=!1;function tP(n,l){switch(n){case"keyup":return GJ.indexOf(l.keyCode)!==-1;case"keydown":return l.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function nP(n){return n=n.detail,typeof n=="object"&&"data"in n?n.data:null}var Xu=!1;function YJ(n,l){switch(n){case"compositionend":return nP(l);case"keypress":return l.which!==32?null:(eP=!0,JI);case"textInput":return n=l.data,n===JI&&eP?null:n;default:return null}}function XJ(n,l){if(Xu)return n==="compositionend"||!vS&&tP(n,l)?(n=wr(),ds=Rn=fn=null,Xu=!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 uP(n){for(;n&&n.firstChild;)n=n.firstChild;return n}function dP(n,l){var i=uP(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=uP(i)}}function fP(n,l){return n&&l?n===l?!0:n&&n.nodeType===3?!1:l&&l.nodeType===3?fP(n,l.parentNode):"contains"in n?n.contains(l):n.compareDocumentPosition?!!(n.compareDocumentPosition(l)&16):!1:!1}function pP(n){n=n!=null&&n.ownerDocument!=null&&n.ownerDocument.defaultView!=null?n.ownerDocument.defaultView:window;for(var l=wS(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=wS(n.document)}return l}function SS(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 see=at&&"documentMode"in document&&11>=document.documentMode,Qu=null,NS=null,Pp=null,kS=!1;function mP(n,l,i){var u=i.window===i?i.document:i.nodeType===9?i:i.ownerDocument;kS||Qu==null||Qu!==wS(u)||(u=Qu,"selectionStart"in u&&SS(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}),Pp&&Ip(Pp,u)||(Pp=u,u=Ub(NS,"onSelect"),0>=T,m-=T,nl=1<<32-St(l)+m|i<rt?(js=nt,nt=null):js=nt.sibling;var Gt=ue(fe,nt,xe[rt],Re);if(Gt===null){nt===null&&(nt=js);break}n&&nt&&Gt.alternate===null&&l(fe,nt),le=h(Gt,le,rt),Pt===null?$e=Gt:Pt.sibling=Gt,Pt=Gt,nt=js}if(rt===xe.length)return i(fe,nt),Nt&&Fl(fe,rt),$e;if(nt===null){for(;rtrt?(js=nt,nt=null):js=nt.sibling;var di=ue(fe,nt,Gt.value,Re);if(di===null){nt===null&&(nt=js);break}n&&nt&&di.alternate===null&&l(fe,nt),le=h(di,le,rt),Pt===null?$e=di:Pt.sibling=di,Pt=di,nt=js}if(Gt.done)return i(fe,nt),Nt&&Fl(fe,rt),$e;if(nt===null){for(;!Gt.done;rt++,Gt=xe.next())Gt=Ae(fe,Gt.value,Re),Gt!==null&&(le=h(Gt,le,rt),Pt===null?$e=Gt:Pt.sibling=Gt,Pt=Gt);return Nt&&Fl(fe,rt),$e}for(nt=u(nt);!Gt.done;rt++,Gt=xe.next())Gt=ye(nt,fe,rt,Gt.value,Re),Gt!==null&&(n&&(js=Gt.alternate,js!==null&&nt.delete(js.key===null?rt:js.key)),le=h(Gt,le,rt),Pt===null?$e=Gt:Pt.sibling=Gt,Pt=Gt);return n&&nt.forEach(function(Yte){return l(fe,Yte)}),Nt&&Fl(fe,rt),$e}function xt(fe,le,xe,Re){if(typeof xe=="object"&&xe!==null&&xe.type===z&&xe.key===null&&xe.props.ref===void 0&&(xe=xe.props.children),typeof xe=="object"&&xe!==null){switch(xe.$$typeof){case _:e:{for(var $e=xe.key;le!==null;){if(le.key===$e){if($e=xe.type,$e===z){if(le.tag===7){i(fe,le.sibling),Re=m(le,xe.props.children),Go(Re,xe),Re.return=fe,fe=Re;break e}}else if(le.elementType===$e||typeof $e=="object"&&$e!==null&&$e.$$typeof===F&&Cc($e)===le.type){i(fe,le.sibling),Re=m(le,xe.props),Go(Re,xe),Re.return=fe,fe=Re;break e}i(fe,le);break}else l(fe,le);le=le.sibling}xe.type===z?(Re=vc(xe.props.children,fe.mode,Re,xe.key),Go(Re,xe),Re.return=fe,fe=Re):(Re=Gx(xe.type,xe.key,xe.props,null,fe.mode,Re),Go(Re,xe),Re.return=fe,fe=Re)}return T(fe);case L:e:{for($e=xe.key;le!==null;){if(le.key===$e)if(le.tag===4&&le.stateNode.containerInfo===xe.containerInfo&&le.stateNode.implementation===xe.implementation){i(fe,le.sibling),Re=m(le,xe.children||[]),Re.return=fe,fe=Re;break e}else{i(fe,le);break}else l(fe,le);le=le.sibling}Re=MS(xe,fe.mode,Re),Re.return=fe,fe=Re}return T(fe);case F:return xe=Cc(xe),xt(fe,le,xe,Re)}if(ae(xe))return Le(fe,le,xe,Re);if(ie(xe)){if($e=ie(xe),typeof $e!="function")throw Error(o(150));return xe=$e.call(xe),We(fe,le,xe,Re)}if(typeof xe.then=="function")return xt(fe,le,nb(xe),Re);if(xe.$$typeof===W)return xt(fe,le,Wx(fe,xe),Re);sb(fe,xe)}return typeof xe=="string"&&xe!==""||typeof xe=="number"||typeof xe=="bigint"?(xe=""+xe,le!==null&&le.tag===6?(i(fe,le.sibling),Re=m(le,xe),Re.return=fe,fe=Re):(i(fe,le),Re=OS(xe,fe.mode,Re),Re.return=fe,fe=Re),T(fe)):i(fe,le)}return function(fe,le,xe,Re){try{Up=0;var $e=xt(fe,le,xe,Re);return ad=null,$e}catch(nt){if(nt===rd||nt===eb)throw nt;var Pt=Sr(29,nt,null,fe.mode);return Pt.lanes=Re,Pt.return=fe,Pt}}}var Ec=zP(!0),BP=zP(!1),Ko=!1;function VS(n){n.updateQueue={baseState:n.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function FS(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 Yo(n){return{lane:n,tag:0,payload:null,callback:null,next:null}}function Xo(n,l,i){var u=n.updateQueue;if(u===null)return null;if(u=u.shared,(nn&2)!==0){var m=u.pending;return m===null?l.next=l:(l.next=m.next,m.next=l),u.pending=l,l=qx(n),wP(n,null,i),l}return $x(n,u,l,i),qx(n)}function Vp(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,lc(n,i)}}function $S(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 qS=!1;function Fp(){if(qS){var n=sd;if(n!==null)throw n}}function $p(n,l,i,u){qS=!1;var m=n.updateQueue;Ko=!1;var h=m.firstBaseUpdate,T=m.lastBaseUpdate,H=m.shared.pending;if(H!==null){m.shared.pending=null;var te=H,pe=te.next;te.next=null,T===null?h=pe:T.next=pe,T=te;var je=n.alternate;je!==null&&(je=je.updateQueue,H=je.lastBaseUpdate,H!==T&&(H===null?je.firstBaseUpdate=pe:H.next=pe,je.lastBaseUpdate=te))}if(h!==null){var Ae=m.baseState;T=0,je=pe=te=null,H=h;do{var ue=H.lane&-536870913,ye=ue!==H.lane;if(ye?(It&ue)===ue:(u&ue)===ue){ue!==0&&ue===Nc&&(qS=!0),je!==null&&(je=je.next={lane:0,tag:H.tag,payload:H.payload,callback:null,next:null});e:{var Le=n,We=H;ue=l;var xt=i;switch(We.tag){case 1:if(Le=We.payload,typeof Le=="function"){Ae=Le.call(xt,Ae,ue);break e}Ae=Le;break e;case 3:Le.flags=Le.flags&-65537|128;case 0:if(Le=We.payload,ue=typeof Le=="function"?Le.call(xt,Ae,ue):Le,ue==null)break e;Ae=M({},Ae,ue);break e;case 2:Ko=!0}}ue=H.callback,ue!==null&&(n.flags|=64,ye&&(n.flags|=8192),ye=m.callbacks,ye===null?m.callbacks=[ue]:ye.push(ue))}else ye={lane:ue,tag:H.tag,payload:H.payload,callback:H.callback,next:null},je===null?(pe=je=ye,te=Ae):je=je.next=ye,T|=ue;if(H=H.next,H===null){if(H=m.shared.pending,H===null)break;ye=H,H=ye.next,ye.next=null,m.lastBaseUpdate=ye,m.shared.pending=null}}while(!0);je===null&&(te=Ae),m.baseState=te,m.firstBaseUpdate=pe,m.lastBaseUpdate=je,h===null&&(m.shared.lanes=0),ni|=T,n.lanes=T,n.memoizedState=Ae}}function HP(n,l){if(typeof n!="function")throw Error(o(191,n));n.call(l)}function UP(n,l){var i=n.callbacks;if(i!==null)for(n.callbacks=null,n=0;nh?h:8;var T=oe.T,H={};H.types=T!==null?T.types:null,oe.T=H,dN(n,!1,l,i);try{var te=m(),pe=oe.S;if(pe!==null&&pe(H,te),te!==null&&typeof te=="object"&&typeof te.then=="function"){var je=mee(te,u);Yp(n,l,je,qr(n))}else Yp(n,l,u,qr(n))}catch(Ae){Yp(n,l,{then:function(){},status:"rejected",reason:Ae},qr())}finally{ee.p=h,T!==null&&H.types!==null&&(T.types=H.types),oe.T=T}}function yee(){}function cN(n,l,i,u){if(n.tag!==5)throw Error(o(476));var m=v_(n).queue;b_(n,m,l,de,i===null?yee:function(){return y_(n),i(u)})}function v_(n){var l=n.memoizedState;if(l!==null)return l;l={memoizedState:de,baseState:de,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Kl,lastRenderedState:de},next:null};var i={};return l.next={memoizedState:i,baseState:i,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Kl,lastRenderedState:i},next:null},n.memoizedState=l,n=n.alternate,n!==null&&(n.memoizedState=l),l}function y_(n){var l=v_(n);l.next===null&&(l=n.alternate.memoizedState),Yp(n,l.next.queue,{},qr())}function uN(){return qs(Td)}function j_(){return fs().memoizedState}function w_(){return fs().memoizedState}function jee(n){for(var l=n.return;l!==null;){switch(l.tag){case 24:case 3:var i=qr();n=Yo(i);var u=Xo(l,n,i);u!==null&&(Tr(u,l,i),Vp(u,l,i)),l={cache:zS()},n.payload=l;return}l=l.return}}function wee(n,l,i){var u=qr();i={lane:u,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},pb(n)?N_(l,i):(i=RS(n,l,i,u),i!==null&&(Tr(i,n,u),k_(i,l,u)))}function S_(n,l,i){var u=qr();Yp(n,l,i,u)}function Yp(n,l,i,u){var m={lane:u,revertLane:0,gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null};if(pb(n))N_(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,H=h(T,i);if(m.hasEagerState=!0,m.eagerState=H,Hr(H,T))return $x(n,l,m,0),An===null&&Fx(),!1}catch{}if(i=RS(n,l,m,u),i!==null)return Tr(i,n,u),k_(i,l,u),!0}return!1}function dN(n,l,i,u){if(u={lane:2,revertLane:tk(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},pb(n)){if(l)throw Error(o(479))}else l=RS(n,i,u,2),l!==null&&Tr(l,n,2)}function pb(n){var l=n.alternate;return n===gt||l!==null&&l===gt}function N_(n,l){ld=lb=!0;var i=n.pending;i===null?l.next=l:(l.next=i.next,i.next=l),n.pending=l}function k_(n,l,i){if((i&4194048)!==0){var u=l.lanes;u&=n.pendingLanes,i|=u,l.lanes=i,lc(n,i)}}var mb={readContext:qs,use:cb,useCallback:as,useContext:as,useEffect:as,useImperativeHandle:as,useLayoutEffect:as,useInsertionEffect:as,useMemo:as,useReducer:as,useRef:as,useState:as,useDebugValue:as,useDeferredValue:as,useTransition:as,useSyncExternalStore:as,useId:as,useHostTransitionStatus:as,useFormState:as,useActionState:as,useOptimistic:as,useMemoCache:as,useCacheRefresh:as,useEffectEvent:as},C_={readContext:qs,use:cb,useCallback:function(n,l){return pr().memoizedState=[n,l===void 0?null:l],n},useContext:qs,useEffect:c_,useImperativeHandle:function(n,l,i){i=i!=null?i.concat([n]):null,db(4194308,4,p_.bind(null,l,n),i)},useLayoutEffect:function(n,l){return db(4194308,4,n,l)},useInsertionEffect:function(n,l){db(4,2,n,l)},useMemo:function(n,l){var i=pr();l=l===void 0?null:l;var u=n();if(Rc){rs(!0);try{n()}finally{rs(!1)}}return i.memoizedState=[u,l],u},useReducer:function(n,l,i){var u=pr();if(i!==void 0){var m=i(l);if(Rc){rs(!0);try{i(l)}finally{rs(!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=wee.bind(null,gt,n),[u.memoizedState,n]},useRef:function(n){var l=pr();return n={current:n},l.memoizedState=n},useState:function(n){n=rN(n);var l=n.queue,i=S_.bind(null,gt,l);return l.dispatch=i,[n.memoizedState,i]},useDebugValue:oN,useDeferredValue:function(n,l){var i=pr();return iN(i,n,l)},useTransition:function(){var n=rN(!1);return n=b_.bind(null,gt,n.queue,!0,!1),pr().memoizedState=n,[!1,n]},useSyncExternalStore:function(n,l,i){var u=gt,m=pr();if(Nt){if(i===void 0)throw Error(o(407));i=i()}else{if(i=l(),An===null)throw Error(o(349));(It&127)!==0||KP(u,l,i)}m.memoizedState=i;var h={value:i,getSnapshot:l};return m.queue=h,c_(XP.bind(null,u,h,n),[n]),u.flags|=2048,id(9,{destroy:void 0},YP.bind(null,u,h,i,l),null),i},useId:function(){var n=pr(),l=An.identifierPrefix;if(Nt){var i=sl,u=nl;i=(u&~(1<<32-St(u)-1)).toString(32)+i,l="_"+l+"R_"+i,i=ob++,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[Es]=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&&Xl(l)}}return In(l),l.subtreeFlags&=-33554433,NN(l,l.type,n===null?null:n.memoizedProps,l.pendingProps,i),null;case 6:if(n&&l.stateNode!=null)n.memoizedProps!==u&&Xl(l);else{if(typeof u!="string"&&l.stateNode===null)throw Error(o(166));if(n=ke.current,nd(l)){if(n=l.stateNode,i=l.memoizedProps,u=null,m=Ps,m!==null)switch(m.tag){case 27:case 5:u=m.memoizedProps}n[Es]=l,n=!!(n.nodeValue===i||u!==null&&u.suppressHydrationWarning===!0||XL(n.nodeValue,i)),n||$o(l,!0)}else n=om(n).createTextNode(u),n[Es]=l,l.stateNode=n}return In(l),null;case 31:if(i=l.memoizedState,n===null||n.memoizedState!==null){if(u=nd(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[Es]=l}else yc(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;In(l),n=!1}else i=PS(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=i),n=!0;if(!n)return l.flags&256?(Ur(l),l):(Ur(l),null);if((l.flags&128)!==0)throw Error(o(558))}return In(l),null;case 13:if(u=l.memoizedState,n===null||n.memoizedState!==null&&n.memoizedState.dehydrated!==null){if(m=nd(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[Es]=l}else yc(),(l.flags&128)===0&&(l.memoizedState=null),l.flags|=4;In(l),m=!1}else m=PS(),n!==null&&n.memoizedState!==null&&(n.memoizedState.hydrationErrors=m),m=!0;if(!m)return l.flags&256?(Ur(l),l):(Ur(l),null)}return Ur(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),yb(l,l.updateQueue),In(l),null);case 4:return ge(),n===null&&ak(l.stateNode.containerInfo),l.flags|=67108864,In(l),null;case 10:return ql(l.type),In(l),null;case 19:if(XS(l),u=l.memoizedState,u===null)return In(l),null;if(m=(l.flags&128)!==0,h=u.rendering,h===null)if(m)Qp(u,!1);else{if(ls!==0||n!==null&&(n.flags&128)!==0)for(n=l.child;n!==null;){if(h=ab(n),h!==null){for(l.flags|=128,Qp(u,!1),n=h.updateQueue,l.updateQueue=n,yb(l,n),l.subtreeFlags=0,n=i,i=l.child;i!==null;)SP(i,n),i=i.sibling;return qp(l,Ks.current&1|2),Nt&&Fl(l,u.treeForkCount),l.child}n=n.sibling}u.tail!==null&&Bt()>Mb&&(l.flags|=128,m=!0,Qp(u,!1),l.lanes=4194304)}else{if(!m)if(n=ab(h),n!==null){if(l.flags|=128,m=!0,n=n.updateQueue,l.updateQueue=n,yb(l,n),Qp(u,!0),u.tail===null&&u.tailMode!=="collapsed"&&u.tailMode!=="visible"&&!h.alternate&&!Nt)return In(l),null}else 2*Bt()-u.renderingStartTime>Mb&&i!==536870912&&(l.flags|=128,m=!0,Qp(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=Bt(),n.sibling=null,h=Ks.current,h=m?h&1|2:h&1,u.tailMode==="visible"||u.tailMode==="collapsed"||!i||Nt?qp(l,h):(i=h,we(Gs,l),we(Ks,i),rr===null&&(rr=l)),Nt&&Fl(l,u.treeForkCount),n}return In(l),null;case 22:case 23:return Ur(l),KS(),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&&(In(l),l.subtreeFlags&6&&(l.flags|=8192)):In(l),i=l.updateQueue,i!==null&&yb(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&&ce(kc),null;case 24:return i=null,n!==null&&(i=n.memoizedState.cache),l.memoizedState.cache!==i&&(l.flags|=2048),ql(bs),In(l),null;case 25:return null;case 30:return l.flags|=33554432,In(l),null}throw Error(o(156,l.tag))}function Ree(n,l){switch(DS(l),l.tag){case 1:return n=l.flags,n&65536?(l.flags=n&-65537|128,l):null;case 3:return ql(bs),ge(),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(Ur(l),l.alternate===null)throw Error(o(340));yc()}return n=l.flags,n&65536?(l.flags=n&-65537|128,l):null;case 13:if(Ur(l),n=l.memoizedState,n!==null&&n.dehydrated!==null){if(l.alternate===null)throw Error(o(340));yc()}return n=l.flags,n&65536?(l.flags=n&-65537|128,l):null;case 19:return XS(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 ge(),null;case 10:return ql(l.type),null;case 22:case 23:return Ur(l),KS(),n!==null&&ce(kc),n=l.flags,n&65536?(l.flags=n&-65537|128,l):null;case 24:return ql(bs),null;case 25:return null;default:return null}}function Z_(n,l){switch(DS(l),l.tag){case 3:ql(bs),ge();break;case 26:case 27:case 5:Oe(l);break;case 4:ge();break;case 31:l.memoizedState!==null&&Ur(l);break;case 13:Ur(l);break;case 19:XS(l);break;case 10:ql(l.type);break;case 22:case 23:Ur(l),KS(),n!==null&&ce(kc);break;case 24:ql(bs)}}function Zp(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(H){mn(l,l.return,H)}}function Jo(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,H=T.destroy;if(H!==void 0){T.destroy=void 0,m=l;var te=i,pe=H;try{pe()}catch(je){mn(m,te,je)}}}u=u.next}while(u!==h)}}catch(je){mn(l,l.return,je)}}function W_(n){var l=n.updateQueue;if(l!==null){var i=n.stateNode;try{UP(l,i)}catch(u){mn(n,n.return,u)}}}function J_(n,l,i){i.props=Ac(n.type,n.memoizedProps),i.state=n.memoizedState;try{i.componentWillUnmount()}catch(u){mn(n,l,u)}}function rl(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=Hl(n.memoizedProps,m);(m.ref===null||m.ref.name!==h)&&(m.ref=l3(h)),u=m.ref;break;case 7:if(n.stateNode===null){var T=new Gr(n);b(n.child,!1,vte,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(H){mn(n,l,H)}}function Ys(n,l){var i=n.ref,u=n.refCleanup;if(i!==null)if(typeof u=="function")try{u()}catch(m){mn(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){mn(n,l,m)}else i.current=null}function jb(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[Es]=n,xs(u),l=u;break e;case"link":if(h=S3("link","href",m).get(l+(i.href||""))){for(T=0;Txt&&(T=xt,xt=We,We=T);var fe=dP(H,We),le=dP(H,xt);if(fe&&le&&(ye.rangeCount!==1||ye.anchorNode!==fe.node||ye.anchorOffset!==fe.offset||ye.focusNode!==le.node||ye.focusOffset!==le.offset)){var xe=Ae.createRange();xe.setStart(fe.node,fe.offset),ye.removeAllRanges(),We>xt?(ye.addRange(xe),ye.extend(le.node,le.offset)):(xe.setEnd(le.node,le.offset),ye.addRange(xe))}}}}for(Ae=[],ye=H;ye=ye.parentNode;)ye.nodeType===1&&Ae.push({element:ye,left:ye.scrollLeft,top:ye.scrollTop});for(typeof H.focus=="function"&&H.focus(),H=0;Hi?32:i,oe.T=null,i=qN,qN=null;var h=Ha,T=ul;if(Wn=0,Ic=Ha=null,ul=0,(nn&6)!==0)throw Error(o(331));var H=nn;if(nn|=4,wL(h.current),vL(h,h.current,T,i),nn=H,rm(0,!1),Qt&&typeof Qt.onPostCommitFiberRoot=="function")try{Qt.onPostCommitFiberRoot(Tn,h)}catch{}return!0}finally{ee.p=m,oe.T=u,LL(n,l)}}function zL(n,l,i){l=ha(i,l),l=mN(n.stateNode,l,2),n=Xo(n,l,2),n!==null&&(Po(n,2),dl(n))}function mn(n,l,i){if(n.tag===3)zL(n,n,i);else for(;l!==null;){if(l.tag===3){zL(l,n,i);break}else if(l.tag===1){var u=l.stateNode;if(typeof l.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(si===null||!si.has(u))){n=ha(i,n),i=I_(2),u=Xo(l,i,2),u!==null&&(P_(i,u,l,n),Po(u,2),dl(u));break}}l=l.return}}function WN(n,l,i){var u=n.pingCache;if(u===null){u=n.pingCache=new Dee;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)||(VN=!0,m.add(i),n=Uee.bind(null,n,l,i),l.then(n,n))}function Uee(n,l,i){var u=n.pingCache;u!==null&&u.delete(l),n.pingedLanes|=n.suspendedLanes&i,n.warmLanes&=~i,An===n&&(It&i)===i&&((ls===4||ls===3&&(It&62914560)===It&&300>Bt()-Ob)&&(nn&2)===0?vd(n,0):Ab|=i,md===It&&(md=0)),dl(n)}function BL(n,l){l===0&&(l=ur()),n=bc(n,l),n!==null&&(Po(n,l),dl(n))}function Vee(n){var l=n.memoizedState,i=0;l!==null&&(i=l.retryLane),BL(n,i)}function Fee(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),BL(n,i)}function $ee(n,l){return us(n,l)}var jd=null,wd=null,JN=!1,Bb=!1,ek=!1,ai=0;function dl(n){n!==wd&&n.next===null&&(wd===null?jd=wd=n:wd=wd.next=n),Bb=!0,JN||(JN=!0,Gee())}function rm(n,l){if(!ek&&Bb){ek=!0;do for(var i=!1,u=jd;u!==null;){if(n!==0){var m=u.pendingLanes;if(m===0)var h=0;else{var T=u.suspendedLanes,H=u.pingedLanes;h=(1<<31-St(42|n)+1)-1,h&=m&~(T&~H),h=h&201326741?h&201326741|1:h?h|2:0}h!==0&&(i=!0,FL(u,h))}else h=It,h=el(u,u===An?h:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(h&3)===0||tn(u,h)||(i=!0,FL(u,h));u=u.next}while(i);ek=!1}}function qee(){HL()}function HL(){Bb=JN=!1;var n=0;ai!==0&&ste()&&(n=ai);for(var l=Bt(),i=null,u=jd;u!==null;){var m=u.next,h=UL(u,l);h===0?(u.next=null,i===null?jd=m:i.next=m,m===null&&(wd=i)):(i=u,(n!==0||(h&3)!==0)&&(Bb=!0)),u=m}Wn!==0&&Wn!==5||rm(n),ai!==0&&(ai=0)}function UL(n,l){for(var i=n.suspendedLanes,u=n.pingedLanes,m=n.expirationTimes,h=n.pendingLanes&-62914561;0H)break;var je=te.transferSize,Ae=te.initiatorType;je&&QL(Ae)&&(te=te.responseEnd,T+=je*(te$b){We.length=Le;break}xe=new Promise(cte.bind(xe)),We.push(xe)}}}if(0"u"?null:document;function v3(n,l,i){var u=Nd;if(u&&typeof l=="string"&&l){var m=fr(l);m='link[rel="'+n+'"][href="'+m+'"]',typeof i=="string"&&(m+='[crossorigin="'+i+'"]'),b3.has(m)||(b3.add(m),n={rel:n,crossOrigin:i,href:l},u.querySelector(m)===null&&(l=u.createElement("link"),Xs(l,"link",n),xs(l),u.head.appendChild(l)))}}function Ete(n){Zl.D(n),v3("dns-prefetch",n,null)}function Rte(n,l){Zl.C(n,l),v3("preconnect",n,l)}function Ate(n,l,i){Zl.L(n,l,i);var u=Nd;if(u&&n&&l){var m='link[rel="preload"][as="'+fr(l)+'"]';l==="image"&&i&&i.imageSrcSet?(m+='[imagesrcset="'+fr(i.imageSrcSet)+'"]',typeof i.imageSizes=="string"&&(m+='[imagesizes="'+fr(i.imageSizes)+'"]')):m+='[href="'+fr(n)+'"]';var h=m;switch(l){case"style":h=kd(n);break;case"script":h=Cd(n)}if(!(ja.has(h)||(n=M({rel:"preload",href:l==="image"&&i&&i.imageSrcSet?void 0:n,as:l},i),ja.set(h,n),u.querySelector(m)!==null||l==="style"&&u.querySelector(cm(h))||l==="script"&&u.querySelector(um(h))))){var T=u.createElement("link");Xs(T,"link",n),l==="style"&&(T[Rs]=!0,T.onload=T.onerror=function(){yp(T)}),xs(T),u.head.appendChild(T)}}}function Ote(n,l){Zl.m(n,l);var i=Nd;if(i&&n){var u=l&&typeof l.as=="string"?l.as:"script",m='link[rel="modulepreload"][as="'+fr(u)+'"][href="'+fr(n)+'"]',h=m;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":h=Cd(n)}if(!ja.has(h)&&(n=M({rel:"modulepreload",href:n},l),ja.set(h,n),i.querySelector(m)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(i.querySelector(um(h)))return}u=i.createElement("link"),Xs(u,"link",n),xs(u),i.head.appendChild(u)}}}function Mte(n,l,i){Zl.S(n,l,i);var u=Nd;if(u&&n){var m=Bo(u).hoistableStyles,h=kd(n);l=l||"default";var T=m.get(h);if(!T){var H={loading:0,preload:null};if(T=u.querySelector(cm(h)))H.loading=5;else{n=M({rel:"stylesheet",href:n,"data-precedence":l},i),(i=ja.get(h))&&jk(n,i);var te=T=u.createElement("link");xs(te),Xs(te,"link",n),te._p=new Promise(function(pe,je){te.onload=pe,te.onerror=je}),te.addEventListener("load",function(){H.loading|=1}),te.addEventListener("error",function(){H.loading|=2}),H.loading|=4,Vb(T,l,u)}T={type:"stylesheet",instance:T,count:1,state:H},m.set(h,T)}}}function Dte(n,l){Zl.X(n,l);var i=Nd;if(i&&n){var u=Bo(i).hoistableScripts,m=Cd(n),h=u.get(m);h||(h=i.querySelector(um(m)),h||(n=M({src:n,async:!0},l),(l=ja.get(m))&&wk(n,l),h=i.createElement("script"),xs(h),Xs(h,"link",n),i.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},u.set(m,h))}}function Ite(n,l){Zl.M(n,l);var i=Nd;if(i&&n){var u=Bo(i).hoistableScripts,m=Cd(n),h=u.get(m);h||(h=i.querySelector(um(m)),h||(n=M({src:n,async:!0,type:"module"},l),(l=ja.get(m))&&wk(n,l),h=i.createElement("script"),xs(h),Xs(h,"link",n),i.head.appendChild(h)),h={type:"script",instance:h,count:1,state:null},u.set(m,h))}}function y3(n,l,i,u){var m=(m=ke.current)?im(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=kd(i.href),l=Bo(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=kd(i.href);var h=Bo(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(cm(n)))?h._p||(T.instance=h,T.state.loading=5):(h=ja.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},ja.set(n,h)),Pte(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=Cd(i),l=Bo(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 kd(n){return'href="'+fr(n)+'"'}function cm(n){return'link[rel="stylesheet"]['+n+"]"}function j3(n){return M({},n,{"data-precedence":n.precedence,precedence:null})}function Pte(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=yp.bind(null,l),Xs(l,"link",i),xs(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 Cd(n){return'[src="'+fr(n)+'"]'}function um(n){return"script[async]"+n}function w3(n,l,i){if(l.count++,l.instance===null)switch(l.type){case"style":var u=n.querySelector('style[data-href~="'+fr(i.href)+'"]');if(u)return l.instance=u,xs(u),u;var m=M({},i,{"data-href":i.href,"data-precedence":i.precedence,href:null,precedence:null});return u=(n.ownerDocument||n).createElement("style"),xs(u),Xs(u,"style",m),Vb(u,i.precedence,n),l.instance=u;case"stylesheet":m=kd(i.href);var h=n.querySelector(cm(m));if(h)return l.state.loading|=4,l.instance=h,xs(h),h;u=j3(i),(m=ja.get(m))&&jk(u,m),h=(n.ownerDocument||n).createElement("link"),xs(h);var T=h;return T._p=new Promise(function(H,te){T.onload=H,T.onerror=te}),Xs(h,"link",u),l.state.loading|=4,Vb(h,i.precedence,n),l.instance=h;case"script":return h=Cd(i.src),(m=n.querySelector(um(h)))?(l.instance=m,xs(m),m):(u=i,(m=ja.get(h))&&(u=M({},i),wk(u,m)),n=n.ownerDocument||n,m=n.createElement("script"),xs(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,Vb(u,i.precedence,n));return l.instance}function Vb(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 _te(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 N3(n,l){return n==="img"&&l.src!=null&&l.src!==""&&l.onLoad==null&&l.loading!=="lazy"}function k3(n){return!(n.type==="stylesheet"&&(n.state.loading&3)===0)}function C3(n){return(n.width||100)*(n.height||100)*(typeof devicePixelRatio=="number"?devicePixelRatio:1)*.25}function T3(n,l){typeof l.decode=="function"&&(n.imgCount++,l.complete||(n.imgBytes+=C3(l),n.suspenseyImages.push(l)),n=Bte.bind(n),l.decode().then(n,n))}function Lte(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=kd(u.href),h=l.querySelector(cm(m));if(h){l=h._p,l!==null&&typeof l=="object"&&typeof l.then=="function"&&(n.count++,n=dm.bind(n),l.then(n,n)),i.state.loading|=4,i.instance=h,xs(h);return}h=l.ownerDocument||l,u=j3(u),(m=ja.get(m))&&jk(u,m),h=h.createElement("link"),xs(h);var T=h;T._p=new Promise(function(H,te){T.onload=H,T.onerror=te}),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=dm.bind(n),l.addEventListener("load",i),l.addEventListener("error",i))}}var $b=0;function zte(n,l){return n.stylesheets&&n.count===0&&Gb(n,n.stylesheets),0$b?50:800)+l);return n.unsuspend=i,function(){n.unsuspend=null,clearTimeout(u),clearTimeout(m)}}:null}function E3(n){if(n.count===0&&(n.imgCount===0||!n.waitingForImages)){if(n.stylesheets)Gb(n,n.stylesheets);else if(n.unsuspend){var l=n.unsuspend;n.unsuspend=null,l()}}}function dm(){this.count--,E3(this)}function Bte(){this.imgCount--,E3(this)}var qb=null;function Gb(n,l){n.stylesheets=null,n.unsuspend!==null&&(n.count++,qb=new Map,l.forEach(Hte,n),qb=null,dm.call(n))}function Hte(n,l){if(!(l.state.loading&4)){var i=qb.get(n);if(i)var u=i.get(null);else{i=new Map,qb.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(),tj.exports=m$(),tj.exports}var wn=h$();const Hh=[20,50,100,200],Uh=[20,50,100,200,"all"],lu=50,eA="workbuddy-desktop-table-size:";function tA(e){return e==="all"?r("全部"):String(e)}function Vh(e,t=Uh,a=lu){t.includes(a)||(a=t.includes(lu)?lu:t[0]);let o=null;try{o=localStorage.getItem(eA+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 Fh(e,t){try{localStorage.setItem(eA+e,String(t))}catch{}}function $h(e,t,a={}){const o=a.sizes??Uh,c=a.defaultSize??lu,[d,f]=x.useState(()=>Vh(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),Fh(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 Di({total:e,page:t,pageCount:a,size:o,sizes:c=Uh,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 R=Math.min(Math.max(1,Math.round(E)),a);j(String(R)),R!==t&&f(R)},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(ut,{value:String(o),onValueChange:k=>d(k==="all"?"all":Number(k)),children:[s.jsx(ft,{className:"h-[26px] w-[86px]",disabled:g,"aria-label":r("每页条数"),children:s.jsx(dt,{children:tA(o)})}),s.jsx(pt,{children:c.map(k=>s.jsx(Xe,{value:String(k),children:tA(k)},String(k)))})]}),r("条")]}),s.jsxs("span",{className:"table-foot-jump",children:[r("跳至"),s.jsx(Ye,{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(z6,{page:t,pageCount:a,onPageChange:f,disabled:g})]})]})}const rj=[{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"}],nA="agent2api-accounts-col-widths",xf={pick:47,order:84,proxy:186,connections:56,status:80,limits:148,expiry:80,usage:132,actions:200},aj=new Set(["account"]),g$=300,lj=56,x$=new Set([...Object.keys(xf),...aj]),ou=(()=>{try{const e=JSON.parse(localStorage.getItem(nA)||"{}"),t={};for(const[a,o]of Object.entries(e||{})){const c=Number(o);x$.has(a)&&Number.isFinite(c)&&c>=lj&&(t[a]=Math.round(c))}return t}catch{return{}}})();function sA(){try{localStorage.setItem(nA,JSON.stringify(ou))}catch{}}function b$(){return{...xf,...ou}}function v$(e){let t=0;for(const a of e){const o=ou[a];o?t+=o:aj.has(a)?t+=g$:xf[a]?t+=xf[a]:t+=lj}return Math.round(t)}function rA(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 y$(e,t,a){const o=Math.max(lj,Math.round(a));e.style.width=o+"px",aj.has(t)||o!==xf[t]?ou[t]=o:delete ou[t]}let oj=()=>{};function j$(e,t){if(oj=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=rA(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}y$(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),sA(),oj()}}),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=rA(f,p);g&&(delete ou[g.key],sA(),oj())})}function Ct(){return window}function Ws(e,t){Ct().wbApp?.toast?.(e,t)}function qh(e){return e instanceof Error&&e.message?e.message:String(e??"").trim()||r("未知错误")}function aA(e){return(Ct().wbApp?.getState?.()?.accounts?.accounts||[]).filter(a=>(a?.provider||"workbuddy")===e).length}async function lA(e){const t=Ct().__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 oA(e){return e?.name||e?.uid||e?.userId||""}function ij(){Ct().wbAddAccountModal?.close?.()}async function Gh(e,t){ij(),await Ct().wbApp?.refresh?.(),Ws(r("✅ {label}账号已添加{name}",{label:t,name:e?`:${e}`:""}))}const iu=new Map;function El(e){return{defaultValue:iu.get(e)??"",onChange:t=>{const a=t.currentTarget.value;a?iu.set(e,a):iu.delete(e)}}}function Ii(e,t){t?iu.set(e,t):iu.delete(e);const a=document.getElementById(e);(a instanceof HTMLInputElement||a instanceof HTMLTextAreaElement)&&(a.value=t)}function ra(e){const t=document.getElementById(e);return t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?t.value.trim():(iu.get(e)??"").trim()}function cj(e){for(const t of e)Ii(t,"")}const Pi={edition:"cn",loginMode:"embedded",socialRestore:!1},w$=100,S$=256,N$=e=>e.key==="name"?w$:S$,k$={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」同步。")},C$={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 客户端登录")},T$={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},E$={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 iA(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 R$=iA({provider:"qoder",label:r("中国版"),siteNote:"qoder.com.cn"}),A$=iA({provider:"qoder-intl",label:r("国际版"),siteNote:"qoder.com"});function cA(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 uA(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 dA(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 O$={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")}]},M$={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("可选,留空自动用昵称")}]},D$={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},I$={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 fA(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 P$=fA({provider:"monkeycode",label:r("MonkeyCode"),siteNote:r("这里填国内站(monkeycode-ai.com)的账号:请粘贴国内站的 session。国际站(monkeycode-ai.net)是另一家 provider、另一套账号,两边的凭证不通用。")}),_$=fA({provider:"monkeycode-intl",label:r("MonkeyCode 国际版"),siteNote:r("这里填国际站(monkeycode-ai.net)的账号:请粘贴国际站的 session。国内站(monkeycode-ai.com)是另一家 provider、另一套账号,两边的凭证不通用。")}),L$={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 尾号")}]},z$={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("可选,留空则用邮箱或令牌尾号")}]},B$={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 果办」")}]},pA=[k$,C$,T$,E$,R$,A$,cA({provider:"cline-free",label:"Cline Free",poolNote:r("(免费额度池,模型名带 cline-free/ 前缀)。")}),cA({provider:"cline-pass",label:"Cline Pass",poolNote:r("(订阅池,模型名带 cline-pass/ 前缀,需要账号有对应订阅)。")}),uA({provider:"accio",label:r("国际版"),site:"www.accio.com",siteNote:r("国际版与国内版是**两套独立的账号**(同一账号体系的两个站点),凭证不通用。")}),uA({provider:"accio-cn",label:r("国内版"),site:"www.accio-ai.com",siteNote:r("国内版的登录站点是 www.accio-ai.com,与国际版不是同一站。")}),dA({provider:"zcode",label:r("国内版"),site:"open.bigmodel.cn",planNote:r("国内版与**国际版是两套独立的账号与套餐**,凭证与领取的套餐都不通用。")}),dA({provider:"zcode-intl",label:r("国际版"),site:"api.z.ai",planNote:r("国际版的推理站点是 api.z.ai,与国内版不是同一站;套餐也各自独立。")}),O$,M$,D$,I$,P$,_$,L$,z$,B$],_i="workbuddy",cu="custom",uj="WorkBuddy";function H$(e){return pA.find(t=>t.provider===e)}const mA=[{id:"oauth",label:r("网页登录(Zai / Google)")},{id:"sms",label:r("手机验证码登录")},{id:"web",label:r("网页登录")},{id:"manual",label:r("填写凭证")},{id:"desktop",label:r("导入桌面端登录态")}],hA=()=>Ct().workbuddyDesktop?.platform||"";function gA(e){return!(e.desktop===!1||hA()==="web"||e.desktopWindowsOnly&&hA()==="macos")}function xA(e,t){return mA.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"?gA(e):!0).map(a=>a.id)}const U$=e=>e.manualTitle||r("填写凭证添加"),V$=e=>e.manualNoteHtml?{html:e.manualNoteHtml}:{text:e.manualNote||""},F$=e=>e.addButton||r("添加 {name} 账号",{name:e.label}),dj=(e,t)=>`${e.provider}-${t.inputKey||t.key}-input`,bf="max-w-full flex-wrap [&_[data-slot=segmented-item]]:h-7 [&_[data-slot=segmented-item]]:px-3 [&_[data-slot=segmented-item]]:text-[12.5px]",$$=r("登录态文件路径:~/.box-agent/config/auth.json(Windows:C:\\Users\\<你的用户名>\\.box-agent\\config\\auth.json)");let fj=!1;async function bA(e,t){if(!fj){fj=!0,e(!0);try{await t()}finally{fj=!1,e(!1)}}}function Kh({html:e,text:t}){return e?s.jsx("p",{dangerouslySetInnerHTML:{__html:e}}):s.jsx("p",{children:t||""})}function q$(e,t,a){let o;try{o=JSON.parse(t)}catch(c){return Ws(r("{name} 不是合法 JSON:{reason}",{name:e.label,reason:qh(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 G$({config:e,region:t,visible:a}){const o=e.provider,[c,d]=x.useState(!1),[f,p]=x.useState(""),g=V$(e),v=e.fields.map(b=>dj(e,b));async function y(){const b={provider:e.provider};e.regionOptions?.length&&(b.mode=t);for(const j of e.fields){const w=ra(dj(e,j));if(!j.optional&&!w){Ws(r("请填写 {label}",{label:j.label}),"err");return}if(w){if(j.jsonExpand){if(!q$(j,w,b))return;continue}b[j.key]=w}}await bA(d,async()=>{try{const j=await lA(b);cj(v),p(""),await Gh(oA(j?.account),e.label)}catch(j){Ws(r("添加失败:{reason}",{reason:qh(j)}),"err")}})}return s.jsxs(Hn,{hidden:!a,onClick:b=>{b.target.closest("[data-raccoon-hint]")&&(b.preventDefault(),p($$))},children:[s.jsx("h3",{children:U$(e)}),s.jsx(Kh,{...g}),e.fields.map(b=>{const j=dj(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(Fd,{id:j,rows:b.rows,placeholder:b.placeholder,...El(j)}):s.jsx(Ye,{id:j,type:"text",maxLength:N$(b),placeholder:b.placeholder,...El(j)})]},j)}),s.jsxs("div",{className:"field-row",children:[s.jsx(se,{id:`${o}-add-button`,onClick:()=>{y()},disabled:c,children:c?r("添加中…"):F$(e)}),s.jsx("span",{className:"detail",id:`${o}-add-hint`,children:f})]})]})}function K$({config:e,visible:t}){const a=e.provider,[o,c]=x.useState(!1);if(!gA(e)||!e.desktopNote)return null;async function d(){await bA(c,async()=>{try{const f=await lA({provider:e.provider,importDesktop:!0});await Gh(f?.account?.name||"",e.label)}catch(f){Ws(r("导入失败:{reason}",{reason:qh(f)}),"err")}})}return s.jsxs(Hn,{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 Y$({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=Ct().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:()=>Ct().workbuddyDesktop?.startLogin(d.edition||g.current||"cn",p.current||"embedded",f),onSuccess:async j=>{ij(),await Ct().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(Hn,{hidden:!c,children:[s.jsx("h3",{children:r("网页登录")}),s.jsx(Kh,{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(Pn,{"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 X$({config:e,visible:t}){const a=e.smsLogin,o=e.provider;return x.useEffect(()=>{a&&Ct().wbSmsLogin?.create({provider:o,onSuccess:c=>Gh(oA(c?.account),e.label)})},[]),a?s.jsxs(Hn,{hidden:!t,children:[s.jsx("h3",{children:r("手机验证码登录")}),s.jsx(Kh,{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(ji,{children:[s.jsx(Si,{id:`${o}-sms-phone`,type:"text",maxLength:11,placeholder:r("11 位大陆手机号"),...El(`${o}-sms-phone`)}),s.jsx(wi,{align:"inline-end",children:s.jsx(w4,{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(Ye,{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(Ye,{id:`${o}-sms-name`,className:"sms-name",type:"text",placeholder:r("可选,留空则用脱敏手机号"),...El(`${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 Q$({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=Ct().wbAutoclawOauth;!v||!c||(p.current=v.create({provider:d,mode:()=>f.current||"embedded",hint:g,cancelId:`${d}-oauth-cancel`,onSuccess:()=>Gh("",e.label)})??null)},[]),x.useEffect(()=>{p.current?.syncTexts()},[t]),c?s.jsxs(Hn,{hidden:!o,children:[s.jsx("h3",{children:c.title||r("网页登录")}),s.jsx(Kh,{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(Pn,{"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 Z$({config:e,active:t}){const a=e.regionOptions?.[0]?.value??"",[o,c]=x.useState(a),[d,f]=x.useState(()=>xA(e,a)[0]),[p,g]=x.useState(e.webLogin?.modes?.[0]?.value??""),[v,y]=x.useState(e.oauthLogin?.modes?.[0]?.value??""),b=xA(e,o),j=b.includes(d)?d:b[0],w=x.useMemo(()=>mA.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(Hn,{children:[s.jsx("h3",{children:r("地区")}),s.jsx(Pn,{"aria-label":r("{label} 账号地区",{label:e.label}),className:bf,options:e.regionOptions,value:o,onValueChange:c})]}):null,s.jsxs(Hn,{children:[s.jsx("h3",{children:r("添加方式")}),s.jsx(Pn,{"aria-label":r("{label} 账号的添加方式",{label:e.label}),className:bf,options:w,value:j,onValueChange:S=>f(S)})]}),s.jsx(Q$,{config:e,mode:v,onModeChange:y,visible:j==="oauth"}),s.jsx(X$,{config:e,visible:j==="sms"}),s.jsx(Y$,{config:e,mode:p,onModeChange:g,region:o,visible:j==="web"}),s.jsx(G$,{config:e,region:o,visible:j==="manual"}),s.jsx(K$,{config:e,visible:j==="desktop"})]})}function vA(e){return e==="intl"?"workbuddy-intl":"workbuddy"}function W$({active:e}){const[t,a]=x.useState(Pi.edition),[o,c]=x.useState(Pi.loginMode),[d,f]=x.useState(Pi.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=Ct().wbWebLogin;E&&(y.current=E.create({get provider(){return vA(p.current)},buttonId:"web-login-button",cancelId:"web-login-cancel",hintId:"web-login-hint",busyText:r("等待网页登录…"),texts:()=>{const R=g.current==="external";return{button:r(R?"在浏览器中打开登录页":"打开网页登录"),hint:r(R?"系统浏览器打开(复用已登录账号);完成后自动加入列表":"内嵌窗口打开;完成后自动加入列表,关窗即取消等待")}},start:()=>Ct().workbuddyDesktop?.startLogin(p.current,g.current,vA(p.current),v.current),onSuccess:async()=>{const R=p.current==="intl"?r("国际版"):r("国内版");ij(),await Ct().wbApp?.refresh?.(),Ws(r("✅ 登录成功,{edition}账号已加入列表",{edition:R}))}})??null)},[]),x.useEffect(()=>{y.current?.syncTexts()},[t,o]);function b(E){const R=E==="intl"?"external":"embedded";a(E),Pi.edition=E,c(R),Pi.loginMode=R}function j(E){const R=E==="external"?"external":"embedded";c(R),Pi.loginMode=R}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(Hn,{children:[s.jsx("h3",{children:r("账号版本")}),s.jsx("p",{children:r("两版账号可同时保存,各自一份模型清单(国内版与国际版是两家提供商,可分别启用与映射)。")}),s.jsx(Pn,{"aria-label":r("账号版本"),className:bf,options:[{value:"cn",label:r("国内版(WorkBuddy)")},{value:"intl",label:r("国际版(WorkBuddy AI)")}],value:t,onValueChange:E=>b(E)})]}),s.jsxs(Hn,{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(Pn,{"aria-label":r("网页登录的打开方式"),className:bf,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(ps,{checked:d,disabled:!N,onCheckedChange:E=>{f(E),Pi.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 pj="proxy",mj="preset",Yh="custom",J$="import",vf="preset:",hj="__new__";function e8(e){return e===mj||e===Yh?e:pj}const Xh={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"},t8=new Set(["monkeycode","monkeycode-intl","commandcode","antigravity"]);function n8(e){const t=Ct().wbProviders;if(e===mj){const g=new Set((t?.customList?.()||[]).map(v=>v.name||""));return(Ct().wbPresetProviders?.list||[]).filter(v=>!g.has(v.name)).map(v=>({id:vf+v.key,label:v.name,count:0,preset:!0}))}if(e===Yh)return(t?.customList?.()||[]).map(g=>({id:g.id,label:g.name||g.id,count:aA(g.id),custom:!0}));const a=t?.all?.()||[],o=(g,v)=>g===_i?uj:Ct().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:t8.has(v)}}):[{id:_i,label:uj,count:aA(_i)}]).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 s8({item:e}){const t=e.id.startsWith(vf)?Ct().wbPresetProviders?.iconOf?.(e.id.slice(vf.length))||"":Xh[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 r8(e){return e.preset?r("点开即预填,填 Key 接入"):e.custom?e.count?r("{n} 个账号,点击添加",{n:e.count}):r("点击添加账号"):e.count?r("{n} 个账号",{n:e.count}):r("还没有账号")}function a8({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(s8,{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:r8(e)})]}),s.jsx("span",{className:"add-provider-go",children:"›"})]})}function l8({onPick:e}){return s.jsxs("button",{type:"button",className:"add-provider-card is-new","data-provider":hj,role:"option",onClick:()=>e(hj),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 o8({accountType:e,onAccountTypeChange:t,search:a,onSearchChange:o,onPick:c,version:d,importing:f,importPanel:p}){const g=x.useMemo(()=>n8(e),[e,d]),v=a.trim().toLowerCase(),y=g.filter(j=>!v||j.label.toLowerCase().includes(v)),b=e===Yh&&!v;return s.jsxs(Hn,{children:[s.jsx("h3",{children:r("选择提供商")}),s.jsxs("div",{className:"add-pick-row",style:f?{display:"none"}:void 0,children:[s.jsx(Pn,{"aria-label":r("账号类型"),className:bf,options:[{value:pj,label:"Agent"},{value:mj,label:r("预置 API")},{value:Yh,label:r("自定义")}],value:e,onValueChange:j=>t(e8(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(ji,{children:[s.jsx(wi,{children:"⌕"}),s.jsx(Si,{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(l8,{onPick:c}):null,y.map(j=>s.jsx(a8,{item:j,onPick:c},j.id)),!y.length&&v?s.jsx("div",{className:"add-provider-empty",children:r("没有匹配「{keyword}」的提供商",{keyword:a.trim()})}):null]})]})}function Qh(e,t){return Pe().wbIcons?.icon?.(e,t)||""}function i8({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:Qh("gripVertical",14)}}),s.jsx("span",{className:"order-rank",title:a,children:`#${t}`})]})}function c8({group:e,ids:t,collapsed:a}){const[o,c]=x.useState(!1),d="w-full justify-start px-2 font-normal";return s.jsxs(rf,{open:o,onOpenChange:c,children:[s.jsx(wh,{render:s.jsx("button",{type:"button",className:"grp-iconbtn",title:r("本组操作")}),children:"⋯"}),s.jsx(af,{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),UR(t,!0)},children:r("全部启用({n})",{n:t.length})}),s.jsx(se,{variant:"ghost",size:"sm",className:d,title:r("禁用这一组里的全部账号(含被筛选隐藏的)"),onClick:()=>{c(!1),UR(t,!1)},children:r("全部禁用({n})",{n:t.length})}),s.jsx(se,{variant:"ghost",size:"sm",className:d,title:r("打开批量操作弹窗,并预选这一组的账号(改代理等动作在弹窗里挑参数)"),onClick:()=>{c(!1),Wy(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),jR(e.provider)},children:r(a?"展开这一组":"折叠这一组")})]})})]})}function u8({group:e,collapsed:t,colSpan:a}){const o=Xh[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:Qh("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:()=>jR(e.provider),dangerouslySetInnerHTML:{__html:Qh("chevronDown",14)}}),s.jsx(c8,{group:e,ids:e.accounts.map(c=>c.id),collapsed:t})]})})})}function d8({account:e}){const t=or(e),a=cF(e);!t&&W6(e,Cl(e))&&a.push({text:r("Token 限额 · 已禁用"),kind:"bad",title:r("本周期 Token 消耗达到限制器的上限,账号已被自动禁用(窗口重置也不恢复,需手动启用)")});const o=ru(e)||e.id;return s.jsxs(s.Fragment,{children:[s.jsx(ps,{checked:t,"aria-label":r("{action}{who}",{action:r(t?"禁用":"启用"),who:o}),title:r(t?"已启用,点击禁用(不参与转发)":"已禁用,点击启用"),onCheckedChange:c=>{BR(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 f8({account:e,open:t}){const a=qy(e);if(!a.length)return kh(e,Ya(e))?s.jsx(ze,{variant:"warning",shape:"tag",title:r("余额低于限制器的阈值,转发时会跳过该账号(余额回升自动恢复)"),children:r("余额不足")}):Hy(e,Cl(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(Uv,{}),r("正常")]});const o=Yy(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:()=>NR(e.id,"limits",!t),children:r("{n} 个模型 ▾",{n:a.length})}),s.jsx("span",{className:"lim-sub",title:r("最早恢复"),children:r("最早 {soonest} 恢复",{soonest:o===Ky?r("待定"):o})})]})}function p8({account:e}){const t=lr(On(e)),a=qE(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=Us(a);return s.jsx("span",{title:d?r("{text}过期({full})",{text:c,full:d}):r("{text}过期",{text:c}),children:c})}function m8({account:e}){const t=AR(e.id);return t<=0?null:s.jsx("span",{className:"conn-count",title:r("{n} 个请求正在使用该账号(含还在下发内容的流式请求)",{n:t}),children:t})}function br(e){if(e==null||e==="")return"—";const t=Number(e);return Number.isFinite(t)?String(t):String(e)}function h8(e){return!e||typeof e!="object"||Array.isArray(e)?"":yA(e.subscription)}function yA(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(rR(t.state));const o=t.expireAt;if(o!=null&&o!==""){const c=Number(o),d=Number.isFinite(c)&&c>1e11?Us(c):String(o);d&&a.push(r("到期 {time}",{time:d}))}return Number.isFinite(Number(t.remainQuota))&&a.push(r("余量 {value}",{value:br(t.remainQuota)})),Number.isFinite(Number(t.totalQuota))&&a.push(r("总量 {value}",{value:br(t.totalQuota)})),a.join(" ")}function g8(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 x8(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:Us(c*1e3)}):o});return r(`已领到、还没到生效时间的套餐(生效后余额列会按它显示): {lines}`,{lines:t.join(` -`)})}function o8(e){if(e===void 0)return{text:l("未查询"),kind:"muted",title:l("尚未查询该账号的余额")};if(e===null)return{text:l("查询中…"),kind:"muted",title:l("正在查询")};const t=au(e);if(t)return t.notConfigured?{text:l("未配置"),kind:"muted",title:l("{message}(去该账号的「设置」里填上查询凭证即可)",{message:t.message})}:{text:l("查询失败"),kind:"bad",title:t.message};if(typeof e!="object"||e===null)return{text:l("无数据"),kind:"muted",title:String(e)};const r=e;if(Object.prototype.hasOwnProperty.call(r,"totalLeft")){const o=r.unlimited?"∞":br(r.totalLeft);return{text:l("可用 {total}",{total:o}),kind:"ok",title:l("总剩余 {total} · 套餐 {plan} · 奖励 {bonus}",{total:o,plan:br(r.planLeft),bonus:br(r.bonusLeft)})}}if(Object.prototype.hasOwnProperty.call(r,"available")||Array.isArray(r.wallets)){const o=String(r.unit||l("积分")),c=Array.isArray(r.wallets)?r.wallets:[],d=c.map(j=>`${j?.displayName||j?.type||l("明细")} ${j?.balanceView?String(j.balanceView):br(j?.balance)}`).join(" · "),f=mA(r.subscription),p=[];if(c.length===0&&Array.isArray(r.plans)&&r.plans.length>0){const j=hA(r);p.push(j&&gA(j)?l("读数里没有额度桶,这里按套餐权益里的已用 / 总量显示(上游给的数)"):l("上游的余额读数里没有这个套餐的额度桶,剩余量读不到;余额列显示的是套餐发放的权益额度,不是剩余量"))}String(r.walletsFrom||"")==="monitor"&&p.push(l("额度窗口读数来自开放平台监控通道(套餐 JWT 那条通道没有额度桶):读的是每 N 小时 / 每周窗口的剩余比例"));const g=r.available==null?c.find(j=>j?.balance!=null):void 0,v=r.availableView?String(r.availableView):g?l("可用 {value} {unit}",{value:br(g.balance),unit:String(g.unit||o)}):l("可用 {value} {unit}",{value:br(r.available),unit:o}),y=[r.statisticsError?l("订阅统计未读到:{error}",{error:String(r.statisticsError)}):"",r.benefitError?l("福利网关未读到:{error}",{error:String(r.benefitError)}):""].filter(Boolean),b=r.benefitAbsent?[l("该账号没有福利模型额度(福利按活动下发,不是每个账号都有)")]:[];return{text:v+(y.length?" ⚠":""),kind:y.length?"warn":"ok",title:[v,d,f,...p,...b,...y].filter(Boolean).join(" · ")}}return{text:l("无数据"),kind:"muted",title:l("未返回可识别的余额数据")}}function hA(e){const t=Array.isArray(e.plans)?e.plans:[],r=o=>String(o?.state||"");return t.find(o=>r(o)==="active")||t.find(o=>r(o)==="pending")||t[0]||null}function i8(e){const t=Array.isArray(e.entitlements)?e.entitlements:[];let r=null;for(const o of t){const c=Number(o?.grantUnits);if(!Number.isFinite(c)||c<=0)continue;const d=String(o?.unitType||"").trim();(!r||c>r.units)&&(r={units:c,unit:d})}return r}function gA(e){const t=Array.isArray(e.entitlements)?e.entitlements:[];for(const r of t){const o=ra(r?.totalUnits);if(o===null||o<=0)continue;const c=ra(r?.usedUnits),d=ra(r?.remainingUnits),f=c===null?d===null?null:Math.max(0,o-d):c;if(f!==null)return{used:f,total:o,unit:String(r?.unitType||"").trim()}}return null}function c8(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,r=Array.isArray(t.wallets)?t.wallets:[];let o=null;for(const p of r){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 r){const w=ra(j?.remainingPercent);w!==null&&(!p||w0,N=S?Math.max(0,Math.min(100,y/b*100)):null;c.push({name:v,view:S?l("剩 {remaining} / {total}",{remaining:br(y),total:br(b)}):l("剩 {remaining}",{remaining:br(y)}),tone:y<=0?"muted":N!==null&&N<20?"warn":"ok",percent:N,over:!1,title:S?void 0:l("上游未给总量,画不出剩余比例")});continue}if(w!==null||ra(g.allowanceTokens)!==null){const S=ra(g.usedTokens)??0,N=ra(g.allowanceTokens),C=N!==null&&N>1,E=C&&S>N,R=g.unlimited===!0,k=C?Math.max(0,Math.min(100,(1-S/N)*100)):null,A=R?l("无上限 · 已用 {used}",{used:bo(S)}):C?l("剩 {remaining} / {total}",{remaining:bo(Math.max(0,N-S)),total:bo(N)}):S>0?l("已用 {used}",{used:bo(S)}):l("未使用");d.push({name:u8(v),view:A,tone:E?"bad":!C&&!R?"muted":k!==null&&k<20?"warn":"ok",percent:k,over:E,title:[j,R?l("无上限按日计(上游到达上限后仍继续计数,超额如实显示)"):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?l("订阅统计未读到:{error}",{error:String(t.statisticsError)}):"",t.benefitError?l("福利网关未读到:{error}",{error:String(t.benefitError)}):""].filter(Boolean);return{credit:c,token:d,total:ra(t.available),unit:o,plan:Y6(f.planName),free:eR(f.planName),resetDate:String(f.resetDate||""),missing:p,benefitAbsent:t.benefitAbsent===!0}}function f8(e){const t=Cl(e);let r=null;for(const b of B6(e)){if(b.enabled===!1)continue;const j=of(b,t);if(!j)continue;const w=b.threshold>0?j.used/b.threshold:0;if(w>=1){r={rule:b,reading:j,ratio:w};break}(!r||w>r.ratio)&&(r={rule:b,reading:j,ratio:w})}if(!r)return null;const{rule:o,reading:c}=r,d=c.used>=o.threshold,f=Ly(o),p=d?"":` · ${Nh(f.remainingMs,f.daily)}`,g=f.daily?l("今日已用"):l("周期 Token"),v=o.reset==="daily"?l("今天(本地 0 点重置)"):l("{period}窗口",{period:KE(o.period??0)}),y=l("限制器:{window}已用 {used} / {threshold} Token",{window:v,used:Math.round(c.used).toLocaleString("en-US"),threshold:Math.round(o.threshold).toLocaleString("en-US")})+(d?l(",已达到上限"):l(",{countdown}重置",{countdown:Nh(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:Sl(c.used)})," ","/ ",Sl(o.threshold),p]})}function p8({account:e}){if(!Na(e))return s.jsx("span",{className:"muted",title:l("该提供商没有余额查询"),children:"—"});const t=Ka(e),r=o8(t),o=Sh(e,t)?s.jsx(ze,{variant:"warning",shape:"tag",title:l("余额低于限制器的阈值,转发时会跳过该账号(余额回升自动恢复)"),children:l("余额不足 · 已跳过")}):_y(e,Cl(e))?s.jsx(ze,{variant:"warning",shape:"tag",title:l("本周期 Token 消耗达到限制器的上限,转发时会跳过该账号(窗口重置自动恢复)"),children:l("Token 限额 · 已跳过")}):null,c=f8(e),d=r.kind==="ok"||r.kind==="warn"?a8(t):[],f=d.length?s.jsx(ze,{variant:"warning",shape:"tag",title:l8(d),children:l("待生效 {n} 份",{n:d.length})}):null,p=r.kind==="ok"||r.kind==="warn"?A6(t):[],g=JE(e)&&p.length?{rows:p,subscriptionLine:r8(t),kind:r.kind,title:r.title}:null;if(K6(e)){const j=r.kind==="ok"||r.kind==="warn"?d8(t):null;return j?s.jsx(m8,{summary:r,detail:j,blockedBadge:o,tokenSub:c}):s.jsxs("span",{className:"usage-sum-wrap",children:[s.jsx("span",{className:`usage-sum ${r.kind}`,title:r.title,children:r.text}),o,f,c]})}const v=r.kind==="ok"||r.kind==="warn"?c8(t):null;if(!v)return s.jsxs("span",{className:"usage-sum-wrap",children:[g?s.jsx(LE,{variant:"sum",...g,children:r.text}):s.jsx("span",{className:`usage-sum ${r.kind}`,title:r.title,children:r.text}),o,f,c]});const y=s.jsxs(s.Fragment,{children:[v.percent!==null?s.jsx(qd,{value:v.percent,className:"usage-pool-bar"}):null,s.jsx("span",{className:`usage-pool-view ${r.kind}`,children:v.text})]});return s.jsxs("span",{className:"usage-pool",title:r.title,children:[v.planName?s.jsx("span",{className:"usage-pool-name",children:v.planName}):null,g?s.jsx(LE,{variant:"pool",...g,children:y}):s.jsx("span",{className:"usage-pool-line",children:y}),o,f,c]})}function m8({summary:e,detail:t,blockedBadge:r,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:l("套餐积分的重置日期"),children:l("重置 {date}",{date:t.resetDate})}):null]}),s.jsxs(rf,{open:c,onOpenChange:d,children:[s.jsxs(yh,{render:s.jsx("button",{type:"button",className:`usage-toggle ${e.kind}`,title:e.title,"aria-label":l("积分明细")}),children:[s.jsx("span",{className:"val",children:e.text}),s.jsx("span",{className:"caret","aria-hidden":!0,children:"▾"})]}),s.jsxs(af,{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:l("积分")}),t.credit.map(p=>s.jsx(h8,{row:p},p.name))]}):null,t.total!==null?s.jsxs("div",{className:"usage-pop-total",children:[s.jsx("span",{className:"k",children:l("可用合计")}),s.jsxs("span",{className:"v",children:[br(t.total)," ",s.jsx("small",{children:t.unit})]})]}):null,!t.credit.length&&t.total===null?s.jsx("div",{className:"usage-pop-empty",title:l("该账号的额度只有福利 token 池(见余额格那两行),订阅统计没有积分类计量表"),children:l("该账号没有积分类读数(额度只有福利 token 池)")}):null]})]}),t.token.map(p=>s.jsxs("span",{className:"usage-flat-line",title:p.title,children:[s.jsxs("span",{className:"usage-flat-head",children:[s.jsx("span",{className:"usage-flat-name",children:p.name}),s.jsx("span",{className:`usage-flat-view ${p.tone}`,children:p.view})]}),p.percent!==null?s.jsx("span",{className:`usage-flat-track${p.over?" over":""}`,children:s.jsx("i",{style:{width:`${p.percent}%`},"aria-label":l("剩余 {percent}%",{percent:Math.round(p.percent)})})}):null]},p.name)),t.benefitAbsent?s.jsxs("span",{className:"usage-flat-line",title:l("福利按限时活动下发,不是每个账号都有 —— 正常状态,不是查询失败"),children:[s.jsx("span",{className:"usage-flat-name",children:l("福利日额度")}),s.jsx("span",{className:"usage-flat-view muted",children:l("无福利额度")})]}):null,r,o]})}function h8({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":l("剩余 {percent}%",{percent:Math.round(e.percent)})})}):null]})}function g8({account:e,namesHidden:t}){const r=wh(e),o=lr(Rn(e)),c=ru(e)||l("未命名账号"),d=String(e.email||"").trim(),f=String(e.nickname||"").trim(),p=String(e.name||"").trim(),g=w=>t?m$(w):w,v=[d&&d!==c?l("邮箱 {email}",{email:g(d)}):"",r?`${o.identifier} ${r}`:"",!e.nameCustom&&p&&p!==d&&p!==f?l("备注名 {name}",{name:g(p)}):"",f&&f!==c&&f!==d?l("昵称 {name}",{name:g(f)}):"",cf(e)?l("桌面端实时登录态(凭证每次从客户端登录态文件读取)"):"",e.updatedAt?l("更新于 {time}",{time:Bs(e.updatedAt)}):"",e.source?l("来源 {source}",{source:e.source==="imported"?l("旧数据导入"):l("手动添加")}):""].filter(Boolean),y=d&&d!==c,b=e.proxy?.error,j=v.length?s.jsx(qH,{delay:0,children:s.jsxs(Ri,{children:[s.jsx(Ai,{render:s.jsx("div",{className:"acct-name"}),children:s.jsx("span",{className:"name",children:g(c)})}),s.jsxs(Oi,{children:[s.jsx(GH,{}),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:l("账号邮箱"),children:g(d)})}):null,b?s.jsx("div",{className:"acct-note bad",title:l("代理不可用:{error}",{error:b}),children:l("代理不可用:{error}",{error:b})}):null]})}function x8({account:e}){const t=e.proxy,r=t?.config?.source||t?.source,o=t?.label||l(r==="custom"?"自定义代理":"已设置"),c=t?.error,d=x$(),f=Array.isArray(d)?d:[];let p="";r==="pool"&&t?.config?.proxyId?p=`${Ga}${t.config.proxyId}`:t&&(p=_h);const g=[{value:"",label:l("直连")}];for(const b of f)g.push({value:`${Ga}${b.id}`,label:lf(b)});if(d===null?g.push({value:"__hint_pool__",label:l("正在读取代理列表…"),disabled:!0}):f.length||g.push({value:"__hint_pool__",label:b$()?l("代理列表读取失败(重试中)"):l("还没有代理(去「网络代理」页添加)"),disabled:!0}),p===_h){const b=r==="clash"?l("Clash 出口:"):r==="custom"?l("自定义:"):"";g.push({value:_h,label:`${b}${o}${c?l("(不可用)"):""}`})}else r==="pool"&&!f.some(b=>`${Ga}${b.id}`===p)&&g.push({value:p,label:`${o}${c?l("(不可用)"):""}`});g.push({value:_R,label:l("自定义代理…")});const v=c?l("代理不可用:{error}(转发时会回退直连);选「自定义代理…」去修改",{error:c}):r==="clash"||r==="custom"?l("当前:{label}(未经过代理池 —— 可在「网络代理」页把出口同步进池后来这里改选)",{label:o}):l("当前:{label};选项来自「网络代理」页;「自定义代理…」打开完整设置",{label:t?o:l("直连")}),y=g.find(b=>b.value===p);return s.jsxs(ct,{value:p,onValueChange:b=>{E$(e.id,String(b),p)},children:[s.jsx(dt,{className:Ue("w-full",c&&"border-destructive-bd"),title:v,"aria-label":l("出网代理"),children:s.jsx(ut,{children:y?.label||l("直连")})}),s.jsx(ft,{children:g.map(b=>s.jsx(Ye,{value:b.value,disabled:b.disabled,children:b.label},b.value))})]})}function b8({account:e,atFront:t}){const[r,o]=x.useState(!1),c=Na(e),d=QE(e);return s.jsxs("div",{className:"acct-actions",children:[d?s.jsx(se,{variant:"outline",size:"xs",title:q6(e)?G6(e):l("查看可领取的套餐与名下已有的套餐(每天一期,领取需过一次人机验证)"),onClick:()=>LR(e.id),children:l("领套餐")}):null,c?s.jsx(se,{variant:"outline",size:"xs",disabled:r,title:l("查询该账号剩余余额(读数显示在余额列)"),onClick:()=>{o(!0),k$(e.id).finally(()=>o(!1))},children:l("余额")}):null,s.jsx(se,{variant:"outline",size:"xs",title:l("备注名 / 启用 / 代理"),onClick:()=>Dh(e.id),children:l("设置")}),s.jsx(v8,{account:e,atFront:t})]})}function v8({account:e,atFront:t}){const[r,o]=x.useState(!1),c=or(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(rf,{open:r,onOpenChange:o,children:[s.jsx(yh,{render:s.jsx(se,{variant:"outline",size:"xs",title:l("更多操作")}),children:"⋯"}),s.jsx(af,{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),DR(e.id,!c)},children:l(c?"禁用":"启用")}),s.jsx(se,{variant:"ghost",size:"sm",className:f,disabled:t,title:l(t?"已在全局队列第一位":"仅将优先级调整到全局第一位,不改变启用状态"),onClick:()=>{o(!1),Pe().wbApp?.runAccountAction?.("switch",e.id)},children:l("设为首选")}),s.jsx(se,{variant:"ghost",size:"sm",className:f,title:l("在账号设置的「基本」分组里设置该账号同时最多处理的请求数"),onClick:()=>{o(!1),Dh(e.id)},children:l("并发上限:{value}",{value:d>0?d:l("不限")})}),e.hasRefreshToken?s.jsx(se,{variant:"ghost",size:"sm",className:f,onClick:()=>{o(!1),Pe().wbApp?.runAccountAction?.("refresh",e.id)},children:l("刷新 Token")}):null,s.jsx("div",{className:"my-1 h-px bg-hairline"}),s.jsx(se,{variant:"ghost",size:"sm",className:p,title:cf(e)?l("删除这条账号记录(不会影响客户端自己的登录态;之后可再点「导入桌面端登录态」加回来)"):void 0,onClick:()=>{o(!1),Pe().wbApp?.runAccountAction?.("remove",e.id)},children:l("删除账号")})]})})]})}function y8({account:e,onClose:t,onClear:r}){const o=Uy(e),c=s.jsx(se,{variant:"ghost",size:"icon-xs",className:"panel-close",title:l("收起"),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:ru(e)}),s.jsx("span",{className:"muted",children:l("{n} 个模型限流中 · 记录来自上游 429 / 限额码,到恢复时间自动解除",{n:o.length})}),s.jsx(se,{variant:"outline",size:"xs",title:l("清掉该账号全部模型的限流标记"),onClick:()=>r(""),children:l("全部清除")})]}),o.map(d=>{const f=Fy(d.resetAt),p=d.message||(d.status?l("上游返回 {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:l("限流中")}),s.jsx("span",{className:"lp-reset",title:l("到恢复时间后自动解除,无需手动操作"),children:f===$y?l("恢复时间未知"):l("{time} 恢复",{time:f})}),s.jsx("span",{className:"lp-reason",title:p,children:p}),s.jsx(se,{variant:"outline",size:"2xs",title:l("清掉本机的限流标记,立刻重新尝试该模型(上游若仍在限流会再次被标记)"),onClick:()=>r(d.model),children:l("清除标记")})]},d.model)})]}):s.jsxs("div",{className:"row-panel limit-panel",children:[l("当前没有限流中的模型。"),c]})}function j8({account:e,colSpan:t,limitsOpen:r,onClear:o}){return r?s.jsx("tr",{className:"acct-panels","data-panels-for":e.id,children:s.jsx("td",{colSpan:t,children:s.jsx(y8,{account:e,onClose:()=>bR(e.id,"limits",!1),onClear:c=>o(e.id,c)})})}):null}function w8({namesHidden:e,allPicked:t,somePicked:r,disabled:o,onToggleAll:c}){const d=s.jsx("span",{className:"col-grip",title:l("拖动调整列宽(双击还原)")});return s.jsx("thead",{children:s.jsxs("tr",{children:[s.jsx("th",{className:"cell-pick","data-col":"pick",children:s.jsx(ea,{id:"acct-select-all",checked:t,indeterminate:!t&&r,disabled:o,"aria-label":l("全选当前筛选结果"),title:l("全选 / 取消全选当前筛选结果(与批量栏同一个选择)"),onCheckedChange:f=>c(f)})}),s.jsxs("th",{className:"cell-order","data-col":"order",children:[s.jsx("span",{className:"th-label",title:l("组内先后:按住左边的把手上下拖动即可调整;整组的先后拖分组带的把手"),children:l("顺序")}),d]}),s.jsxs("th",{className:"cell-account","data-col":"account",children:[s.jsxs("span",{className:"th-label",children:[l("账号"),s.jsx(S8,{hidden:e})]}),d]}),s.jsxs("th",{className:"cell-proxy","data-col":"proxy",children:[s.jsx("span",{className:"th-label",title:l("该账号出网走的代理(Clash 出口 / 自定义 / 直连);点击可修改"),children:l("代理")}),d]}),s.jsxs("th",{className:"cell-connections","data-col":"connections",children:[s.jsx("span",{className:"th-label",title:l("此刻正在使用这个账号的请求数(含还在下发内容的流式请求);为 0 时不显示"),children:l("连接数")}),d]}),s.jsxs("th",{className:"cell-status","data-col":"status",children:[s.jsx("span",{className:"th-label",children:l("状态")}),d]}),s.jsxs("th",{className:"cell-limits","data-col":"limits",children:[s.jsx("span",{className:"th-label",title:l("该账号当前限流中的模型;点徽章看明细"),children:l("限流")}),d]}),s.jsxs("th",{className:"cell-expiry","data-col":"expiry",children:[s.jsx("span",{className:"th-label",children:l("有效期")}),d]}),s.jsxs("th",{className:"cell-usage","data-col":"usage",children:[s.jsx("span",{className:"th-label",children:l("余额")}),d]}),s.jsx("th",{className:"cell-actions","data-col":"actions",children:s.jsx("span",{className:"th-label",children:l("操作")})})]})})}function S8({hidden:e}){const t=l(e?"显示账号名":"隐藏账号名(名字显示为星号)");return s.jsx("button",{type:"button",className:`name-eye${e?" on":""}`,title:t,"aria-label":t,"aria-pressed":e,onClick:()=>p$(),dangerouslySetInnerHTML:{__html:Yh(e?"eyeOff":"eye",13)}})}const xA="dragging",yf=["drop-before","drop-after"];let Ya=null;function bA(e){e.querySelectorAll(`.${yf[0]}, .${yf[1]}`).forEach(t=>{t.classList.remove(...yf)})}function N8(e,t){if(t==="group"){const o=e.parentElement;return o?[...o.children].filter(c=>c.classList.contains("acct-group")):[]}const r=e.parentElement;return r?[...r.children].filter(o=>o.classList.contains("acct-row")):[]}function vA(e,t){for(let r=0;rr!==e.item);bA(e.container),t.length&&(e.index>=t.length?t[t.length-1].classList.add(yf[1]):t[e.index].classList.add(yf[0]))}function yA(e){if(!Ya)return;if(e.buttons===0){Xh(!1);return}const t=Ya.items.filter(o=>o!==Ya.item),r=vA(t,e.clientY);r!==Ya.index&&(Ya.index=r,C8(Ya))}function Xh(e){const t=Ya;t&&(Ya=null,window.removeEventListener("pointermove",yA),window.removeEventListener("pointerup",jA),window.removeEventListener("pointercancel",wA),window.removeEventListener("keydown",SA),document.body.classList.remove("queue-dragging"),t.item.classList.remove(xA),bA(t.container),e&&(t.kind==="group"?fj?.onDrop({kind:"group",provider:t.provider,index:t.index}):fj?.onDrop({kind:"row",provider:t.provider,accountId:t.accountId,index:t.index})))}function jA(){Xh(!0)}function wA(){Xh(!1)}function SA(e){e.key==="Escape"&&Xh(!1)}let fj=null;function k8(e,t){fj=t,e&&e.dataset.queueDragBound!=="1"&&(e.dataset.queueDragBound="1",e.addEventListener("pointerdown",r=>{if(r.button!==0||Ya)return;const o=r.target,c=o?.closest?.(".queue-grip"),d=o?.closest?.(".order-grip");if(!c&&!d)return;if(r.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=N8(f,p);if(y.length<2)return;const b=y.filter(j=>j!==f);Ya={kind:p,provider:g,accountId:v,item:f,container:f.parentElement||e,items:y,index:vA(b,r.clientY)},f.classList.add(xA),document.body.classList.add("queue-dragging"),window.addEventListener("pointermove",yA),window.addEventListener("pointerup",jA),window.addEventListener("pointercancel",wA),window.addEventListener("keydown",SA)}))}let Qh=null,NA=!1,pj=0,Zh=null,CA="";function kA(){return Qh?Qh.apply(ej):ej}function TA(){window.wbAccountsView?.render?.()}function T8(){const e=kA(),t=`${Zh?"T":"F"}|${e.map(o=>`${o.key}:${o.align}`).join("|")}`;if(t===CA)return;CA=t,Pe().wbColSettings?.syncStaticHead("accounts",Zh);const r=[...Zh?.querySelectorAll("thead th")||[]];r.forEach((o,c)=>{const d=o.querySelector(".col-grip");d&&(d.style.display=c===r.length-1?"none":"")})}function E8(){const e=x.useSyncExternalStore(uR,Qs),t=x.useRef(null),[,r]=x.useReducer(U=>U+1,0),o=!!Gy(),c=Nl(),{groups:d,allGroups:f}=n$(Ka,Cl),p=s$(Ka,Cl),g=[{value:"all",label:l("全部({n})",{n:c.length})}].concat(dR().map(U=>({value:U.id,label:l("{label}({count})",{label:U.label,count:U.count})}))),v=d.flatMap(U=>U.accounts),y=r$(),b=kA(),j=Vh(v.length,"accounts",{defaultSize:"all"}),w=j.paged?j.slice(v):v,S=Rh()||j.paged,N=Rh()?l("清除筛选"):l("把每页调回「全部」");x.useEffect(()=>{v$()}),x.useEffect(()=>{o$()},[e.version]),x.useLayoutEffect(()=>{if(!NA){if(!Pe().wbColSettings?.register){window.clearTimeout(pj),pj=window.setTimeout(()=>C(U=>U+1),50);return}NA=!0,Qh=Pe().wbColSettings?.register({id:"accounts",label:l("账号表"),columns:ej.map(U=>({key:U.key,label:U.label,align:U.align,legacyAlign:U.legacyAlign})),mount:()=>document.querySelector("#batch-bar .batch-actions"),onChange:TA})||null,Qh&&r();return}T8()});const[,C]=x.useState(0);x.useEffect(()=>()=>window.clearTimeout(pj),[]),x.useEffect(()=>{uF(t.current,TA)},[]);const E=v.map(U=>U.id),R=E.length>0&&E.every(U=>e.selected.has(U)),k=E.some(U=>e.selected.has(U)),A=[...e.selected].filter(U=>!E.includes(U)).length,D=e.selected.size>0,I=f.length>0&&f.every(U=>e.collapsed.has(U.provider)),M=new Map;for(const U of d)M.set(U.provider,w.filter(B=>Rn(B)===U.provider).map(B=>B.id));const O=x.useRef({displayed:d,all:f,renderedRows:M});x.useEffect(()=>{O.current={displayed:d,all:f,renderedRows:M}});const _=x.useRef({locked:!1,lockReason:"",onDrop:U=>{}}),L=x.useCallback(U=>{const{displayed:B,all:Q}=O.current;if(U.kind==="group"){const J=Q.findIndex(K=>K.provider===U.provider);if(J<0)return;const ie=Q[J],me=Q.filter((K,be)=>be!==J),he=U.indexK.provider===he),oe=he===null||ae<0?me.length:ae;if(oe===J)return;const de=[...me.slice(0,oe),ie,...me.slice(oe)].flatMap(K=>K.members.map(be=>be.id));IR(de,l("{name} 移到第 {rank} 顺位",{name:ie.label,rank:oe+1}));return}const W=Q.find(J=>J.provider===U.provider);if(!W)return;const Z=W.members.findIndex(J=>J.id===U.accountId);if(Z<0)return;const Y=W.members[Z],q=W.members.filter((J,ie)=>ie!==Z),G=O.current.renderedRows.get(U.provider)||[],$=U.indexJ.id===$),X=$===null||F<0?q.length:F;if(X===Z)return;const re=[...q.slice(0,X),Y,...q.slice(X)],V=Q.map(J=>J.provider===U.provider?{...J,members:re}:J).flatMap(J=>J.members.map(ie=>ie.id));IR(V,l("{name} 移到 {group} 组内第 {rank} 位",{name:String(Y.name||Y.id),group:W.label,rank:X+1}))},[]);x.useEffect(()=>{_.current={locked:S,lockReason:N,onDrop:L}}),x.useEffect(()=>{k8(t.current,{isLocked:()=>_.current.locked,onLockedAttempt:()=>He(l("当前视图不能调整组顺位:{reason} 之后再拖动",{reason:_.current.lockReason}),"err"),onDrop:U=>_.current.onDrop(U)})},[]);function z(U,B,Q){switch(U){case"pick":return s.jsx(ea,{checked:Q.picked,"data-pick":B.id,title:l("勾选后可批量操作"),"aria-label":l("勾选后可批量操作"),onCheckedChange:W=>u$(B.id,W)});case"order":return s.jsx(ZF,{account:B,rank:Q.rank});case"account":return s.jsx(g8,{account:B,namesHidden:e.namesHidden});case"proxy":return s.jsx(x8,{account:B});case"connections":return s.jsx(s8,{account:B});case"status":return s.jsx(e8,{account:B});case"limits":return s.jsx(t8,{account:B,open:Q.limitsOpen});case"expiry":return s.jsx(n8,{account:B});case"usage":return s.jsx(p8,{account:B});case"actions":return s.jsx(b8,{account:B,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:l("提供商")}),s.jsxs(ct,{value:e.filter.provider,onValueChange:U=>l$(String(U)),children:[s.jsx(dt,{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":l("按提供商筛选账号"),children:s.jsx(ut,{children:g.find(U=>U.value===e.filter.provider)?.label||l("全部")})}),s.jsx(ft,{children:g.map(U=>s.jsx(Ye,{value:U.value,children:U.label},U.value))})]})]}),s.jsx("div",{className:"divider","data-provider-divider":"1"}),s.jsxs("div",{className:"group",children:[s.jsx("span",{className:"label",children:l("搜索")}),s.jsx(Ke,{className:"acct-search",type:"search",value:e.filter.q,placeholder:l("账号名 / 邮箱 / 备注"),"aria-label":l("搜索账号"),onChange:U=>a$(U.currentTarget.value)})]}),s.jsx("div",{className:"divider"}),s.jsxs("div",{className:"group",children:[s.jsx("span",{className:"label",children:l("状态")}),s.jsx(Gn,{options:[{value:"all",label:l("全部"),count:p.enabledAll??0},{value:"enabled",label:l("启用"),count:p.enabled??0},{value:"disabled",label:l("禁用"),count:p.disabled??0}],value:e.filter.enabled,onValueChange:U=>fR("enabled",U),"aria-label":l("启用状态")})]}),s.jsxs("div",{className:"group",children:[s.jsx("span",{className:"label",children:l("限额")}),s.jsx(Gn,{options:[{value:"all",label:l("全部"),count:p.limitAll??0},{value:"normal",label:l("正常"),count:p.normal??0,disabled:e.filter.enabled==="disabled"},{value:"limited",label:l("已限流"),count:p.limited??0,disabled:e.filter.enabled==="disabled"}],value:e.filter.limit,onValueChange:U=>fR("limit",U),"aria-label":l("限额状态")})]}),s.jsxs("div",{className:"actions",children:[s.jsx(se,{id:"btn-fold-groups",variant:"outline",disabled:!f.length,title:l(I?"展开全部分组":"折叠全部分组(只留组头)"),onClick:()=>i$(f.map(U=>U.provider),!I),children:l(I?"展开全部":"折叠全部")}),s.jsx(se,{id:"btn-add-account-2",variant:"default",title:l("登录 / 导入一个新账号"),onClick:()=>{Pe().wbAddAccountModal?.open?.(),Pe().wbAccountAddForms?.syncAddProvider?.()},children:l("添加账号")}),s.jsx(se,{id:"btn-query-usage",variant:"outline",disabled:e.usageBusy||!c.some(Na),title:l("查询全部账号的余额(含已禁用账号 —— 禁用只表示不参与转发)"),onClick:()=>{OR()},children:e.usageBusy?l("查询中…"):l("查询余额")})]})]}),s.jsxs("div",{className:Ue("batch-bar",D&&"active"),id:"batch-bar",children:[s.jsxs("label",{className:"batch-select-all",children:[s.jsx(ea,{id:"batch-select-all",checked:R,indeterminate:!R&&k,disabled:!E.length,"aria-label":l("全选当前筛选结果"),onCheckedChange:U=>gR(E,U)}),s.jsx("span",{id:"batch-select-label",children:E.length?l("全选当前筛选结果({n} 个)",{n:E.length}):l("没有可全选的账号")})]}),s.jsxs("span",{className:"batch-count",children:[l("已选")," ",s.jsx("b",{id:"batch-count",children:e.selected.size})," ",l("个 · 共")," ",s.jsx("b",{id:"accounts-count",children:c.length})," ",l("个")]}),s.jsx("span",{className:"batch-summary",id:"accounts-group-summary",children:d.length?l("{groups} 家 · 显示 {rows} 行",{groups:d.length,rows:E.length}):""}),S?s.jsx("span",{className:"batch-hidden",title:l("筛选 / 搜索 / 分页生效时组顺位不可拖动(别家的组整组不可见,落点没法定位)"),children:l("组顺位已锁定")}):null,Rh()?s.jsx(se,{id:"btn-clear-filter",variant:"ghost",size:"xs",title:l("清空搜索与三个筛选档位,回到全部账号"),onClick:()=>pR(),children:l("清除筛选")}):null,A?s.jsx("span",{className:"batch-hidden",id:"batch-hidden-hint",children:l("另有 {n} 个已勾选账号被当前筛选隐藏,仍会参与操作",{n:A})}):null,s.jsxs("div",{className:"batch-actions",children:[s.jsx(se,{id:"btn-batch-open",variant:"outline",disabled:!D,onClick:()=>Yy([...e.selected],"enable"),children:l("批量操作")}),s.jsx(se,{id:"btn-batch-clear",variant:"outline",disabled:!D,onClick:()=>d$(),children:l("取消选择")})]})]}),s.jsx("div",{className:"acct-scroll",id:"account-list",ref:t,children:o?c.length?v.length?s.jsxs("table",{className:"acct-table",ref:R8,style:{minWidth:`${iF(b.map(U=>U.key))}px`},children:[s.jsx(A8,{}),s.jsx(w8,{namesHidden:e.namesHidden,allPicked:R,somePicked:k,disabled:!E.length,onToggleAll:U=>gR(E,U)}),d.map(U=>{const B=e.collapsed.has(U.provider),Q=w.filter(W=>Rn(W)===U.provider);return s.jsxs("tbody",{className:"acct-group","data-provider":U.provider,children:[s.jsx(JF,{group:U,collapsed:B,colSpan:b.length}),B?null:Q.map(W=>{const Z=U.members.findIndex(q=>q.id===W.id)+1,Y=R$(W,y,Z>0?Z:1);return s.jsxs(x.Fragment,{children:[s.jsx("tr",{className:Ue("acct-row",!or(W)&&"disabled",Y.picked&&"selected"),"data-id":W.id,"data-provider":U.provider,"data-desktop":cf(W)?"1":void 0,children:b.map(q=>s.jsx("td",{className:`cell-${q.key} ta-${q.align}`,children:z(q.key,W,Y)},q.key))}),s.jsx(j8,{account:W,colSpan:b.length,limitsOpen:xR(W.id,"limits"),onClear:(q,G)=>{T$(q,G)}})]},W.id)})]},U.provider)})]}):s.jsxs("div",{className:"empty",children:[l("当前筛选条件下没有账号"),Rh()?s.jsx("button",{type:"button",className:"link-btn",onClick:()=>pR(),children:l("清除筛选")}):null]}):s.jsx("div",{className:"empty",children:l("暂无账号,请点击右上角「添加账号」")}):s.jsxs("div",{className:"empty",children:[s.jsx("span",{className:"spinner"}),l("正在加载…")]})}),s.jsx(Di,{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(eF,{})]})}function R8(e){Zh=e}function A8(){const e=oF(),t=r=>s.jsx("col",{"data-col":r,style:e[r]?{width:`${e[r]}px`}:void 0},r);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 EA='.page[data-page="accounts"]';let mj=null;function RA(){if(mj)return;const e=document.querySelector(EA);e&&(e.replaceChildren(),mj=jn.createRoot(e),ys.flushSync(()=>{mj.render(s.jsx(E8,{}))}))}O$(),w$(),document.querySelector(EA)?RA():document.addEventListener("DOMContentLoaded",RA,{once:!0});const O8=64,M8=100,D8=l("OpenAI 兼容填到 /v1;Anthropic 填根地址"),I8=l("Anthropic 协议填根地址,不要带 /v1"),P8="https://open.bigmodel.cn/api/paas/v4",_8="https://api.anthropic.com",L8=[{value:"chat_completions",label:"OpenAI - Chat Completions"},{value:"responses",label:"OpenAI - Responses"},{value:"anthropic",label:"Anthropic - Messages"}],uu="custom-protocol-select",du="custom-name-input",fu="custom-baseurl-input",jf="custom-apikey-input",wf="custom-noauth-check",pu="custom-existing-select",Sf="custom-existing-apikey-input",Wh="custom-existing-noauth-check",Nf="custom-existing-name-input",z8="custom-create-button",B8="custom-existing-button",H8="custom-existing-remove";let hj=!1;const AA=()=>kt().wbProviders?.PROTOCOL_OPTIONS||L8,OA=()=>kt().wbProviders?.customList?.()||[];async function gj(e,t){if(!hj){hj=!0,e(!0);try{await t()}finally{hj=!1,e(!1)}}}async function MA(e){kt().wbAddAccountModal?.close?.(),kt().wbProviders?.refreshCustom?.(),await kt().wbApp?.refresh?.(),Zs(e)}function Jh(e,t){Ii(e,t?"1":"")}function eg(e){return sa(e)==="1"}function DA({checked:e,note:t,onChange:r}){return s.jsxs("div",{className:"add-field",children:[s.jsx(tt,{children:l("鉴权")}),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(ea,{checked:e,"aria-label":l("该上游无需鉴权"),onCheckedChange:o=>r(o===!0)}),s.jsx("span",{className:"text-xs text-subtle",children:l("该上游无需鉴权(不发送鉴权头)")})]})}),s.jsx("span",{className:"hint",children:t})]})}function U8({mode:e,providerHint:t,presetKey:r,showToken:o,version:c}){const d=AA(),[f,p]=x.useState(()=>sa(uu)||d[0].value),[g,v]=x.useState(""),[y,b]=x.useState(()=>sa(pu)),[j,w]=x.useState(()=>eg(wf)),[S,N]=x.useState(()=>eg(Wh)),C=x.useMemo(()=>OA(),[c]),R=(t&&C.some(M=>M.id===t)?t:"")||(C.some(M=>M.id===y)?y:C[0]?.id||""),k=C.find(M=>M.id===R)?.name||l("该提供商");x.useEffect(()=>{Ii(pu,R)},[R]),x.useEffect(()=>{if(e!=="create"||!r)return;const M=kt().wbPresetProviders?.presetOf?.(r);if(!M)return;Ii(du,M.name||""),Ii(fu,M.baseUrl||""),M.protocol&&(p(M.protocol),Ii(uu,M.protocol));const O=M.account?.noAuth===!0;w(O),Jh(wf,O),v(M.hint||"")},[e,r,t,o]);const A=f==="anthropic",D=g||(A?I8:D8),I=(M,O)=>_=>{O(_),Jh(M,_)};return s.jsxs(s.Fragment,{children:[s.jsxs(zn,{hidden:e!=="create",children:[s.jsxs("div",{className:"add-panel-head",children:[s.jsx("h3",{children:l("上游信息")}),s.jsx("span",{children:l("创建这个提供商,并同时建立它的第一个账号。")})]}),s.jsxs("div",{className:"add-form",children:[s.jsxs("div",{className:"add-field",children:[s.jsxs(tt,{htmlFor:du,children:[l("名称"),s.jsx("i",{className:"req","aria-hidden":"true",children:"*"})]}),s.jsx(Ke,{id:du,type:"text",maxLength:O8,"aria-required":"true",placeholder:l("如:智谱 GLM"),...Tl(du)}),s.jsx("span",{className:"hint",children:l("1~64 个字符,账号列表里按它分组显示")})]}),s.jsxs("div",{className:"add-field",children:[s.jsx(tt,{htmlFor:uu,children:l("协议")}),s.jsxs(ct,{value:f,onValueChange:M=>{const O=String(M);p(O),Ii(uu,O),v("")},children:[s.jsx(dt,{id:uu,className:"col-start-2 row-start-1 w-full",children:s.jsx(ut,{children:d.find(M=>M.value===f)?.label||f})}),s.jsx(ft,{children:d.map(M=>s.jsx(Ye,{value:M.value,children:M.label},M.value))})]})]}),s.jsxs("div",{className:"add-field",children:[s.jsxs(tt,{htmlFor:fu,children:["Base URL",s.jsx("i",{className:"req","aria-hidden":"true",children:"*"})]}),s.jsx(Ke,{id:fu,type:"text","aria-required":"true",placeholder:A?_8:P8,...Tl(fu)}),s.jsx("span",{className:"hint",id:"custom-baseurl-hint",children:D})]}),s.jsxs("div",{className:"add-field",children:[s.jsx(tt,{htmlFor:jf,children:"API Key"}),s.jsx(Ke,{id:jf,type:"password",autoComplete:"new-password",placeholder:"sk-…",disabled:j,...Tl(jf)}),s.jsx("span",{className:"hint",children:l(j?"不需要 Key:转发与拉取模型都不发送鉴权头":"上游不要鉴权时留空,并勾选下面一项(留空又不勾会被当成未配置凭证)")})]}),s.jsx(DA,{checked:j,note:l(j?"已声明无需鉴权:账号会被正常选路,出网时不带任何鉴权头":"本地 Ollama、OpenCode Zen 免费档这类上游要勾上,否则账号不可用"),onChange:I(wf,w)})]})]}),s.jsxs(zn,{hidden:e!=="existing",children:[s.jsxs("div",{className:"add-panel-head",children:[s.jsx("h3",{children:l("账号信息")}),s.jsxs("span",{children:[l("添加到 "),s.jsx("b",{children:k}),l(" 同一家可以放多把 key,按优先级轮换。")]})]}),s.jsxs("div",{className:"add-form",children:[s.jsxs("div",{className:"add-field",children:[s.jsx(tt,{htmlFor:pu,children:l("提供商")}),s.jsxs(ct,{value:R,onValueChange:M=>b(String(M)),children:[s.jsx(dt,{id:pu,className:"col-start-2 row-start-1 w-full",children:s.jsx(ut,{children:k})}),s.jsx(ft,{children:C.map(M=>s.jsx(Ye,{value:M.id,children:M.name||M.id},M.id))})]})]}),s.jsxs("div",{className:"add-field",children:[s.jsx(tt,{htmlFor:Sf,children:"API Key"}),s.jsx(Ke,{id:Sf,type:"password",autoComplete:"new-password",placeholder:"sk-…",disabled:S,...Tl(Sf)}),s.jsx("span",{className:"hint",children:l(S?"不需要 Key:转发与拉取模型都不发送鉴权头":"上游不要鉴权时留空,并勾选下面一项(留空又不勾会被当成未配置凭证)")})]}),s.jsx(DA,{checked:S,note:l(S?"已声明无需鉴权:账号会被正常选路,出网时不带任何鉴权头":"同一家可以混着放:有 Key 的账号与无鉴权账号各按各的规则走"),onChange:I(Wh,N)}),s.jsxs("div",{className:"add-field",children:[s.jsx(tt,{htmlFor:Nf,children:l("备注名")}),s.jsx(Ke,{id:Nf,type:"text",maxLength:M8,placeholder:l("可选"),...Tl(Nf)}),s.jsx("span",{className:"hint",children:l("留空则用提供商名称")})]})]})]})]})}function IA(e,t){const r=$h(t);Zs(l("添加失败:{reason}",{reason:r}),"err"),e.setHint(r)}async function V8(e){const t=sa(du),r=sa(uu)||AA()[0].value,o=sa(fu),c=sa(jf),d=eg(wf);if(!t){Zs(l("请填写名称"),"err");return}if(!o){Zs(l("请填写 Base URL"),"err");return}await gj(e.setBusy,async()=>{const f={name:t,protocol:r,baseUrl:o},p=e.presetKey?kt().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),d?f.noAuth=!0:c&&(f.apiKey=c),e.setHint("");try{const v=await kt().wbProviders?.customRequest?.("POST","/api/custom-providers",f);aj([du,fu,jf]),Jh(wf,!1);const y=v?.provider?.name||t;await MA(l("✅ 已创建自定义提供商「{name}」并添加账号",{name:y}))}catch(v){IA(e,v)}})}async function $8(e){const t=sa(pu);if(!t){Zs(l("请先选择一个自定义提供商"),"err");return}const r=sa(Sf),o=eg(Wh),c=sa(Nf);await gj(e.setBusy,async()=>{const d={provider:t};o?d.noAuth=!0:r&&(d.apiKey=r),c&&(d.name=c),e.setHint("");try{const f=await kt().wbProviders?.customRequest?.("POST","/api/accounts",d);aj([Sf,Nf]),Jh(Wh,!1);const p=f?.account?.name||OA().find(g=>g.id===t)?.name||"";await MA(l("✅ {label}账号已添加{name}",{label:"",name:p?`:${p}`:""}))}catch(f){IA(e,f)}})}async function F8(){const e=sa(pu);if(!e){Zs(l("请先选择一个自定义提供商"),"err");return}const t=kt().wbCustomProvidersUi?.remove;if(typeof t!="function"){Zs(l("删除功能不可用(脚本未就绪)"),"err");return}await gj(()=>{},async()=>{await t(e)&&kt().wbAddAccountModal?.close?.()})}function q8({mode:e,presetKey:t}){const[r,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:H8,variant:"destructive",title:l("级联删除名下全部账号,不可恢复"),onClick:()=>{F8()},children:l("删除此提供商")}):null,s.jsx(se,{id:z8,hidden:e!=="create",disabled:r,onClick:()=>{V8(f)},children:l(r&&e==="create"?"提交中…":"创建并添加账号")}),s.jsx(se,{id:B8,hidden:e!=="existing",disabled:r,onClick:()=>{$8(f)},children:l(r&&e==="existing"?"提交中…":"添加账号")})]})]})}const xj={step:"pick",accountType:cj,search:"",provider:_i,providerHint:"",presetKey:"",showToken:0},PA=()=>kt().wbProviders?.customList?.()||[];function G8({onClose:e,onReady:t}){const[r,o]=x.useState(xj),[c,d]=x.useState(0),f=x.useCallback(()=>d(k=>k+1),[]),p=x.useCallback(()=>{o(xj);const k=kt().wbProviders;(k?.all?.()||[]).length||k?.load?.().then(f),k?.refreshCustom?.().then(f)},[f]),g=x.useCallback(()=>{p(),o({...xj,step:"form",provider:cu})},[p]);x.useEffect(()=>(t({reset:p,openNewCustomForm:g}),()=>t(null)),[t,p,g]),x.useEffect(()=>{kt().wbWebLogin?.refresh?.()},[]),x.useEffect(()=>{kt().wbProviders?.refreshCustom?.().then(f)},[f]),x.useEffect(()=>{r.step!=="form"||r.provider!==cu||kt().wbProviders?.refreshCustom?.().then(f)},[r.step,r.provider,r.showToken,f]);const v=RF(r.provider),y=r.provider===cu,b=r.provider===_i||y||!!v,j=r.providerHint?"existing":"create",w=r.providerHint?PA().find(k=>k.id===r.providerHint)?.name||"":r.presetKey&&kt().wbPresetProviders?.presetOf?.(r.presetKey)?.name||"",S=r.provider===_i?lj:kt().wbProviders?.labelOf?.(r.provider)||r.provider,N=y?r.providerHint||r.presetKey?l("登录 / 添加 {name} 账号",{name:w||l("自定义提供商")}):l("新建自定义提供商"):l("登录 / 添加 {name} 账号",{name:S});function C(k){if(!k)return;const A={step:"form",showToken:r.showToken+1};k===dj?o(D=>({...D,...A,provider:cu,providerHint:"",presetKey:""})):k.startsWith(vf)?o(D=>({...D,...A,provider:cu,providerHint:"",presetKey:k.slice(vf.length)})):PA().some(D=>D.id===k)?o(D=>({...D,...A,provider:cu,providerHint:k,presetKey:""})):o(D=>({...D,...A,provider:k,providerHint:"",presetKey:""}))}const E=()=>o(k=>({...k,step:"pick"})),R=r.accountType===VF;return s.jsx(Kt,{open:!0,onOpenChange:k=>{k||e()},children:s.jsxs(Yt,{className:"w-[min(880px,calc(100vw-48px))]",children:[s.jsx(Ft,{children:s.jsx($t,{children:l("添加账号")})}),s.jsx(Ht,{children:s.jsx(QF,{accountType:r.accountType,onAccountTypeChange:k=>o(A=>({...A,accountType:k})),search:r.search,onSearchChange:k=>o(A=>({...A,search:k})),onPick:C,version:c,importing:R,importPanel:void 0})}),null,s.jsx(Kt,{open:r.step==="form",onOpenChange:k=>{k||E()},children:s.jsxs(Yt,{keepMounted:!0,overlayForceRender:!0,className:"w-[min(620px,calc(100vw-48px))]",children:[s.jsx(Ft,{children:s.jsx($t,{children:N})}),s.jsxs(Ht,{children:[s.jsx(UF,{active:r.provider===_i}),oA.map(k=>s.jsx(HF,{config:k,active:r.provider===k.provider},k.provider)),s.jsx("div",{className:"add-provider-block",style:y?void 0:{display:"none"},children:s.jsx(U8,{mode:j,providerHint:r.providerHint,presetKey:r.presetKey,showToken:r.showToken,version:c})}),b?null:s.jsx("div",{className:"add-provider-block",children:s.jsxs(zn,{children:[s.jsx("h3",{children:l("该提供商账号添加功能即将上线")}),s.jsx("p",{children:l("「{name}」的账号添加功能还在开发中,敬请期待。",{name:S})})]})})]}),y?s.jsx(sn,{children:s.jsx(q8,{mode:j,presetKey:r.presetKey})}):null]})})]})})}let vo=null,mu=null,Li=null,tg=null;function K8(){vo&&(vo.unmount(),vo=null),mu&&(mu.remove(),mu=null),Li=null}function _A(){mu=document.createElement("div"),document.body.append(mu),vo=jn.createRoot(mu),vo.render(s.jsx(G8,{onClose:LA,onReady:e=>{if(Li=e,!e)return;const t=tg;tg=null,t?.()}}))}function LA(){kt().wbWebLogin?.cancelIfActive?.(""),kt().wbAutoclawOauth?.cancel?.(),K8()}function bj(){if(vo){Li?.reset();return}tg=()=>Li?.reset(),_A()}function Y8(){if(vo){Li?.openNewCustomForm();return}tg=()=>Li?.openNewCustomForm(),_A()}for(const e of["btn-add-account","btn-add-account-2"])document.getElementById(e)?.addEventListener("click",bj);const zA=window;zA.wbAddAccountModal={open:bj,close:LA},zA.wbAccountAddForms={syncAddProvider:()=>{vo?Li?.reset():bj()},openNewCustomForm:Y8};function Rr(){return Pe().workbuddyDesktop??{}}function BA(){return window}const HA="workbuddy-desktop-checkin-tab",X8=["center","schedule","records"];function Q8(){try{const e=localStorage.getItem(HA);return X8.includes(e)?e:"center"}catch{return"center"}}function UA(e){if(e!==is.tab){try{localStorage.setItem(HA,e)}catch{}Ws({tab:e})}}async function ng(e){UA(e),is.loaded||await El()}let is={version:0,tab:Q8(),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 vj=new Set;function Z8(){for(const e of vj)e()}function Ws(e){is={...is,...e,version:is.version+1},Z8()}function ir(){return is}function VA(e){return vj.add(e),()=>vj.delete(e)}function W8(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 yj(e){return(Array.isArray(e)?e:[]).map(W8).filter(r=>r!==null)}function ss(e){return Number(e)||0}async function El(){try{const e=await Rr().getCheckinCenter?.();if(!e)throw new Error(l("后端未返回签到中心数据"));Ws({snapshot:e,loaded:!0,loadError:"",autoTimeDraft:null,keepaliveDraft:null}),J8(e.extras?.onboarding??[])}catch(e){Ws({loaded:!0,loadError:pt(e)})}}function J8(e){for(const t of e){const r=t.settled;if(!r||typeof r!="object")continue;const o=is.onboarding.get(t.id);if(o?.status==="loaded"&&o.unclaimed>0)continue;const c=yj(r.tasks),d=ss(r.at);yo(t.id,{status:"loaded",error:void 0,checkedAt:void 0,settled:!0,settledAt:d>0?d:void 0,tasks:c,unclaimed:0,earned:ss(r.earned),total:ss(r.total)})}}function $A(e){const t=new Set(is.expanded);t.has(e)?t.delete(e):t.add(e),Ws({expanded:t})}function jj(e){const t=`onb:${e}`,r=new Set(is.expanded);r.has(t)?r.delete(t):r.add(t),Ws({expanded:r})}function FA(e){return is.expanded.has(`onb:${e}`)}async function eq(){if(!is.runningAll){Ws({runningAll:!0});try{const e=await Rr().runAutoCheckinNow?.();if(e){const t=ss(e.succeeded),r=ss(e.active),o=ss(e.total),c=ss(e.failedCount),d=r>0?l(",日活保活 {n} 个",{n:r}):"";c>0?He(l("签到完成:{succeeded}/{total} 成功{active},{failed} 个失败",{succeeded:t,total:o,active:d,failed:c}),"err"):He(l("✅ 签到完成:{succeeded}/{total} 个账号成功领取{active}",{succeeded:t,total:o,active:d})),BA().wbAccountsView?.refreshUsageAfterCheckin?.(null)}}catch(e){He(l("签到失败:{error}",{error:pt(e)}),"err")}finally{Ws({runningAll:!1}),await El(),qA(ir().snapshot?.extras.onboarding??[]),Pe().wbApp?.refresh?.()}}}async function sg(e,t="checkin"){const r=`${e}:${t}`;if(is.signing.has(r))return;const o=new Set(is.signing);o.add(r),Ws({signing:o});try{let c;t==="checkin"?c=(await Rr().checkinAllAccounts?.(e))?.results?.[0]:c=await Rr().runCheckinActivity?.(e,t)??void 0;const d=c?.claim,f=c?.activity,p=f?.report?.succeeded===!0;c?.error?He(l("签到失败:{error}",{error:String(c.error)}),"err"):t==="keepalive"?f?.pokeSucceeded===!0||p?He(l("✅ {message}",{message:d?.msg||l("活跃保活完成")})):He(d?.msg||l("活跃保活失败"),"err"):d?.success===!0?He(l("✅ {message}",{message:d.msg||l("签到成功")})):d?.alreadyCompleted===!0?He(d?.msg||l("今日已领取"),"err"):p?He(l("✅ {message}",{message:d?.msg||l("活跃上报完成,但活动未开启")})):f?.pokeSucceeded===!0?He(l("✅ {message}",{message:d?.msg||l("活跃保活完成,但活动未开启")})):He(d?.msg||l("未领取"),"err"),BA().wbAccountsView?.refreshUsageAfterCheckin?.(e)}catch(c){He(l("签到失败:{error}",{error:pt(c)}),"err")}finally{const c=new Set(ir().signing);c.delete(r),Ws({signing:c}),await El();const d=(ir().snapshot?.extras.onboarding??[]).filter(f=>f.id===e);qA(d),Pe().wbApp?.refresh?.()}}function rg(e){Ws({keepaliveDraft:e.map(t=>t.trim()).filter(Boolean)})}async function tq(e){const t=e.map(r=>r.trim()).filter(Boolean);if(!ir().keepaliveSaving){Ws({keepaliveSaving:!0});try{const r=await Rr().saveCheckinKeepalive?.(t);if(r){const o=ir().snapshot;Ws({snapshot:o&&{...o,keepalive:r},keepaliveDraft:null}),He(l("已保存:保活模型链"))}}catch(r){He(l("保存失败:{error}",{error:pt(r)}),"err")}finally{Ws({keepaliveSaving:!1})}}}async function qA(e){for(const t of e)nq(t.id)||await wj(t.id);for(const t of e){const r=ir().onboarding.get(t.id);r?.status!=="loaded"||r.claiming||r.settled||(t.provider==="officeace"||r.unclaimed>0)&&await GA(t.id)}}function nq(e){return is.onboarding.get(e)?.settled===!0}function hu(e){return is.onboarding.get(e)??{status:"idle",tasks:[],unclaimed:0,earned:0,total:0,claiming:!1}}function yo(e,t){const r=new Map(is.onboarding);r.set(e,{...hu(e),...t}),Ws({onboarding:r})}async function wj(e,t){const r=hu(e);if(!(r.status==="loading"||r.claiming)){yo(e,{status:"loading",error:void 0,settled:!1});try{const o=await Rr().getOnboardingTasks?.(e,t?.refresh===!0),c=yj(o?.tasks),d=o?.settled===!0;yo(e,{status:"loaded",checkedAt:Date.now(),tasks:c,unclaimed:c.filter(f=>!f.done&&!f.blocked).length,earned:ss(o?.earned),total:ss(o?.total),settled:d,settledAt:d&&ss(o?.settledAt)||void 0}),t?.expand===!0&&c.length>0&&!FA(e)&&jj(e)}catch(o){yo(e,{status:"error",error:pt(o),settled:!1})}}}async function GA(e){const t=hu(e);if(!(t.claiming||t.status!=="loaded")){yo(e,{claiming:!0});try{yo(e,{tasks:hu(e).tasks.map(b=>b.done?b:{...b,claiming:!0,error:void 0})});const r=await Rr().claimOnboardingTasks?.(e),o=new Map,c=Array.isArray(r?.results)?r.results:[];for(const b of c){const j=typeof b?.key=="string"?b.key:"";j&&b?.ok!==!0&&o.set(j,String(b?.error||l("领取失败")))}const d=yj(r?.tasks),f=(d.length?d:hu(e).tasks).map(b=>({...b,claiming:!1,error:o.get(b.key)})),p=f.filter(b=>b.done&&!o.has(b.key)).length,g=r?.settled===!0;yo(e,{claiming:!1,checkedAt:Date.now(),tasks:f,unclaimed:f.filter(b=>!b.done&&!b.blocked).length,earned:ss(r?.earned),total:ss(r?.total),settled:g,settledAt:g&&ss(r?.settledAt)||void 0});const v=f.filter(b=>b.error&&!b.done).length,y=typeof r?.message=="string"?r.message.trim():"";v?He(l("新手福利有 {n} 项领取失败,可重试",{n:v}),"err"):y?He(y,"ok"):p&&He(l("✅ 新手福利领取完成,累计 {n} 积分",{n:ss(r?.earned)}))}catch(r){const o=pt(r);yo(e,{claiming:!1,tasks:hu(e).tasks.map(c=>({...c,claiming:!1,error:c.done?void 0:o}))}),He(l("领取失败:{error}",{error:o}),"err")}finally{await El()}}}function KA(e){return(Array.isArray(e)?e:[]).map(r=>{const o=r??{},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:ss(o.current),target:ss(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(r=>r!==null)}function YA(e){return(Array.isArray(e)?e:[]).map(r=>{const o=r??{},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:ss(o.credit),energy:ss(o.energy)}:null}).filter(r=>r!==null)}function zi(e){return is.growth.get(e)??{status:"idle",energy:null,streak:null,tasks:[],travel:null,school:null,running:!1,runningSchool:!1,runningTravel:!1}}function Ar(e,t){const r=new Map(is.growth);r.set(e,{...zi(e),...t}),Ws({growth:r})}function sq(e){return is.expanded.has(`growth:${e}`)}function XA(e){const t=`growth:${e}`,r=new Set(is.expanded);r.has(t)?r.delete(t):r.add(t),Ws({expanded:r})}async function ag(e){const t=zi(e);if(!(t.status==="loading"||t.running)){Ar(e,{status:"loading",error:void 0});try{const r=await Rr().getGrowthStatus?.(e),o=r?.tasks??{},c=r?.travel??null,d=r?.school??null;Ar(e,{status:"loaded",checkedAt:Date.now(),energy:r?.energy===null||r?.energy===void 0?null:ss(r.energy),streak:r?.streak===null||r?.streak===void 0?null:ss(r.streak),tasks:KA(o.tasks),travel:c,school:d?{...d,tasks:KA(d.tasks)}:null,error:typeof o.error=="string"?o.error:void 0})}catch(r){Ar(e,{status:"error",error:pt(r)})}}}async function QA(e,t){const r=zi(e);if(r.running)return;const o=(r.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){He(l("没有需要执行的任务"));return}Ar(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 Rr().runGrowthTask?.(e,g.code,t),y=YA([v])[0];y&&(Ar(e,{results:[...zi(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,Ar(e,{results:[...zi(e).results??[],{code:g.code,outcome:"failed",message:pt(v),credit:0,energy:0}]})}Ar(e,{running:!1}),p>0?He(l("成长任务完成({done} 项成功、{failed} 项失败),积分 +{credit} 能量 +{energy}",{done:f,failed:p,credit:c,energy:d}),"err"):He(l("✅ 成长任务执行完成:积分 +{credit} 能量 +{energy}",{credit:c,energy:d})),await ag(e)}async function rq(e,t){if(!zi(e).runningSchool){Ar(e,{runningSchool:!0,error:void 0});try{const o=await Rr().runGrowthSchool?.(e,t),c=YA(o?.results),d=o?.lottery??null;Ar(e,{runningSchool:!1,results:c,schoolText:c.length?c.map(f=>`${f.code}:${f.message}`).join(";"):void 0,lotteryText:d?String(d.message??l("已抽 {n} 次",{n:ss(d.drawn)})):void 0,checkedAt:Date.now()}),He(d?l("开学季执行完成:{message}",{message:String(d.message??"")}):l("✅ 开学季任务执行完成")),await ag(e)}catch(o){Ar(e,{runningSchool:!1,error:pt(o)}),He(l("开学季执行失败:{error}",{error:pt(o)}),"err")}}}async function aq(e){if(!zi(e).runningTravel){Ar(e,{runningTravel:!0,error:void 0});try{const r=await Rr().runGrowthTravel?.(e),o=String(r?.message??""),c=String(r?.outcome??"");Ar(e,{runningTravel:!1,checkedAt:Date.now()}),c==="failed"?He(l("猫猫旅行失败:{message}",{message:o}),"err"):He(l("猫猫旅行:{message}",{message:o})),await ag(e)}catch(r){Ar(e,{runningTravel:!1,error:pt(r)}),He(l("猫猫旅行失败:{error}",{error:pt(r)}),"err")}}}function lq(e){return e.totalCount?e.doneCount>=e.totalCount?"done":e.doneCount>0?"part":"todo":"none"}function oq(e){const r=(Array.isArray(e?.schedules)?e.schedules:[]).filter(o=>o.enabled===!0).map(o=>Number(o.nextRunAt)).filter(o=>Number.isFinite(o)&&o>0);return r.length?Math.min(...r):null}let jo={version:0,data:null,loaded:!1,loadError:"",saving:!1,runningId:null,editingId:null};const Sj=new Set;function iq(){for(const e of Sj)e()}function Or(e){jo={...jo,...e,version:jo.version+1},iq()}function ZA(){return jo}function cq(e){return Sj.add(e),()=>Sj.delete(e)}function gu(){return Pe().workbuddyDesktop??{}}async function WA(){try{const e=await gu().getCheckinSchedules?.();if(!e)throw new Error(l("后端未返回定时签到数据"));Or({data:e,loaded:!0,loadError:""})}catch(e){Or({loaded:!0,loadError:pt(e)})}}function lg(e){e&&Or({data:e,loadError:""}),El()}async function uq(e){if(!jo.saving){Or({saving:!0});try{const t=await gu().saveAutoCheckin?.({enabled:e});lg(t),He(l(e?"✅ 定时签到已开启":"定时签到已关闭"))}catch(t){He(l("保存失败:{error}",{error:pt(t)}),"err")}finally{Or({saving:!1})}}}async function JA(e){if(!jo.saving){Or({saving:!0});try{const t=await gu().saveCheckinSchedule?.(e);lg(t),Or({editingId:null}),He(l("已保存:定时条目"))}catch(t){He(l("保存失败:{error}",{error:pt(t)}),"err")}finally{Or({saving:!1})}}}async function dq(e,t){await JA({id:e.id,label:e.label??"",enabled:t,time:e.time??"",providers:Array.isArray(e.providers)?e.providers:[]})}async function fq(e){if(!jo.saving){Or({saving:!0});try{await gu().deleteCheckinSchedule?.(e),lg(await gu().getCheckinSchedules?.()),He(l("已删除定时条目"))}catch(t){He(l("删除失败:{error}",{error:pt(t)}),"err")}finally{Or({saving:!1})}}}async function pq(e){if(!jo.runningId){Or({runningId:e});try{const t=await gu().runCheckinSchedule?.(e)??void 0,r=o=>Number(o)||0;if(t){const o=r(t.succeeded),c=r(t.active),d=r(t.total),f=r(t.failedCount),p=c>0?l(",日活保活 {n} 个",{n:c}):"";f>0?He(l("签到完成:{succeeded}/{total} 成功{active},{failed} 个失败",{succeeded:o,total:d,active:p,failed:f}),"err"):He(l("✅ 签到完成:{succeeded}/{total} 个账号成功领取{active}",{succeeded:o,total:d,active:p})),lg(t)}}catch(t){He(l("执行失败:{error}",{error:pt(t)}),"err")}finally{Or({runningId:null}),await El()}}}function Nj(e){Or({editingId:e})}const mq=l("到点后自动签到勾选提供商的可用账号(WorkBuddy 国内版走每日签到接口,国际版走每日活跃任务:探测活动、领日活奖励、再用免费模型保活;小浣熊走桌面端每日积分链路;AutoClaw 走官方客户端的每日签到任务;Qoder 中国版走活动领取,没被下发活动的账号会得到中性提示;Qoder 国际版要先带设备风控身份(本机 Qoder 客户端 / qodercli 的 UMID 组件生成)才能看到「每日 100 Credits」活动,缺组件时会得到明确的说明而不是报错;Trae 领 SOLO 的每日签到积分(按自然日 0 点重置),上游没对该账号开活动、或凭据里没有设备号时得到的是「未领取 + 具体原因」而不是报错;Loomy 每天替账号打一次首次登录积分;KukuAI 领「免费领积分」的每日任务;CodeArts 领当日的运营福利(领取 → 确认 → 回读核实,自动执行受每天 6 次 / 间隔 10 分钟的写请求限流);OfficeAce 果办一次领当天全部奖励(每日签到 + 新人礼))。错过时点开机后会自动补签,不会因为当时没开机而漏掉。各家签到接口都是幂等的,重复执行不会重复领取。");function hq(){const[e,t]=x.useState(ZA());return x.useEffect(()=>cq(()=>t(ZA())),[]),e}function gq(){const[e,t]=x.useState(ir());return x.useEffect(()=>VA(()=>t(ir())),[]),e}function eO(e,t){const r=Array.isArray(e.providers)?e.providers:[];return t.filter(o=>r.includes(o.id)).map(o=>o.label)}function xq(e,t){const r=eO(e,t);return r.length?t.length>0&&r.length>=t.length?l("全部 {n} 家",{n:t.length}):r.join(l("、")):l("未勾选提供商")}function bq(e,t){const r=eO(e,t);return r.length?r.join(l("、")):l("未勾选提供商")}function vq(e){const t=e.lastResult;if(!t)return l("还没执行过");const r=f=>Number(f)||0,o=[l("成功 {n}",{n:r(t.succeeded)})],c=r(t.active);c>0&&o.push(l("保活 {n}",{n:c}));const d=r(t.failedCount);return d>0&&o.push(l("失败 {n}",{n:d})),`${t.at?Bs(t.at):"—"}${t.reason?` · ${t.reason}`:""} —— ${o.join(l(" · "))}`}function tO({entry:e,store:t}){const r=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?r.map(S=>S.id):e?.providers??[]));x.useEffect(()=>{o&&r.length>0&&v(new Set(r.map(S=>S.id)))},[]);const y=f.trim()!==""&&g.size>0,b=()=>v(new Set(r.map(S=>S.id))),j=()=>v(new Set),w=async()=>{await JA({id:e?.id,label:c.trim(),enabled:e?.enabled??!0,time:f.trim(),providers:r.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:l("名称")}),s.jsx("span",{className:"ck-set-v",children:s.jsx(Ke,{type:"text",className:"max-w-[220px]",placeholder:l("可选 · 缺省显示时刻"),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:l("每天时刻")}),s.jsxs("span",{className:"ck-set-v flex items-center gap-2",children:[s.jsx(Ke,{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:l("北京时间 · 错过时点开机后会自动补签")})]})]}),s.jsxs("div",{className:"ck-set-line ck-set-line-top",children:[s.jsx("span",{className:"ck-set-k",children:l("签到范围")}),s.jsxs("span",{className:"ck-set-v",children:[s.jsxs("div",{className:"ck-mini-row",children:[s.jsx("span",{className:"ck-mini-note",children:l("到点时逐个签到,已勾 {n} / {total} 家",{n:g.size,total:r.length})}),s.jsx("button",{type:"button",className:"ck-mini-btn",disabled:t.saving,onClick:b,children:l("全选")}),s.jsx("button",{type:"button",className:"ck-mini-btn",disabled:t.saving||g.size===0,onClick:j,children:l("清空")})]}),s.jsx("div",{className:"ck-range",children:r.map(S=>s.jsxs("label",{className:"ck-range-item",children:[s.jsx(ea,{checked:g.has(S.id),disabled:t.saving,onCheckedChange:N=>{const C=new Set(g);N===!0?C.add(S.id):C.delete(S.id),v(C)}}),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:l("至少勾一家才能保存(不勾等于这条条目不签到)")}):null]})]}),s.jsxs("div",{className:"ck-sched-actions",children:[s.jsx(se,{size:"sm",variant:"outline",disabled:t.saving,onClick:()=>Nj(null),children:l("取消")}),s.jsx(se,{size:"sm",variant:"default",disabled:!y||t.saving,onClick:()=>{w()},children:t.saving?l("保存中…"):l("保存")})]})]})}function yq({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:l("新建定时条目")}),s.jsx("div",{className:"ck-prov-desc",children:l("填好时刻与签到范围后点「保存」;名称可以留空(界面显示时刻)")})]})]}),s.jsx(tO,{entry:null,store:e})]})}function jq({entry:e,store:t}){const r=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:l("删除定时条目"),html:l("确定删除「{name}」?删除后到点不再执行。",{name:y}),okText:l("删除"),okClass:"danger"})&&await fq(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(Rs,{checked:e.enabled===!0,disabled:t.saving,onCheckedChange:g=>{dq(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:l("已停用")})]}),s.jsx("div",{className:"ck-prov-desc ck-sched-scope",title:bq(e,r),children:l("每天 {time} · {scope}",{time:e.time??"—",scope:xq(e,r)})}),s.jsx("div",{className:"ck-prov-desc",children:l("上次执行:{line}",{line:vq(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?l("下次 {date}",{date:Bs(f)}):"—"}),s.jsx(se,{size:"sm",variant:"ghost",disabled:c||t.runningId!==null,onClick:()=>{pq(e.id)},children:l(c?"执行中…":"立即执行")}),s.jsx(se,{size:"sm",variant:"ghost",onClick:()=>Nj(o?null:e.id),children:l(o?"收起":"编辑")}),s.jsx(se,{size:"sm",variant:"ghost",className:"text-destructive",disabled:t.saving,onClick:()=>{p()},children:l("删除")})]})]}),o?s.jsx(tO,{entry:e,store:t}):null]})}function wq(e,t){return e.length===t.length&&e.every((r,o)=>r===t[o])}let Cf=null;function Sq(e,t){for(let r=0;rg!==t.row),d=Sq(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 kf(){const e=Cf;Cf=null,window.removeEventListener("pointermove",nO),window.removeEventListener("pointerup",kf),window.removeEventListener("pointercancel",kf),document.body.classList.remove("ck-chain-dragging"),e?.row.classList.remove("dragging")}function Nq(e,t,r,o){if(e.button!==0||Cf||r.length<2)return;const c=e.currentTarget.closest(".ck-chain-row");c&&(e.preventDefault(),Cf={list:[...r],from:t,row:c,onChange:o},c.classList.add("dragging"),document.body.classList.add("ck-chain-dragging"),window.addEventListener("pointermove",nO),window.addEventListener("pointerup",kf),window.addEventListener("pointercancel",kf))}function Cq({models:e,defaultModels:t,dirty:r,saving:o}){const[c,d]=x.useState(""),f=()=>{const p=c.trim();if(p){if(e.includes(p)){He(l("清单里已经有「{name}」",{name:p}),"err");return}rg([...e,p]),d("")}};return s.jsxs("section",{className:"panel ck-chain-panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:l("保活模型链")}),s.jsx("span",{className:"panel-sub",children:l("WorkBuddy 国际版日活任务的免费模型 · 全局一份,与条目无关")}),s.jsx(se,{size:"sm",variant:"default",className:"ml-auto",disabled:!r||o,onClick:()=>{tq(e)},children:l(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:l("模型清单")}),s.jsxs("span",{className:"ck-set-v",children:[s.jsxs("div",{className:"ck-mini-row",children:[s.jsx("span",{className:"ck-mini-note",children:l("按序逐个尝试,共 {n} 个",{n:e.length})}),s.jsx("button",{type:"button",className:"ck-mini-btn",disabled:o||t.length===0,title:l("把缺省链填进清单,再点「保存」生效"),onClick:()=>rg([...t]),children:l("填入缺省链")})]}),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":l("按住拖动调整顺序"),title:l("按住拖动,调整这个模型在链里的顺序"),onPointerDown:v=>Nq(v,g,e,rg),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":l("移除 {name}",{name:p}),title:l("从清单里移除"),onClick:()=>rg(e.filter((v,y)=>y!==g)),children:"×"})]},p)),e.length===0?s.jsx("div",{className:"ck-chain-empty",children:l("清单为空 —— 保存后恢复缺省链")}):null]}),s.jsxs("div",{className:"ck-chain-add",children:[s.jsx(Ke,{type:"text",className:"max-w-[260px] font-mono text-xs",placeholder:l("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:l("添加模型")}),r?s.jsx("span",{className:"ck-chain-dirty",children:l("有未保存的改动")}):null]})]})]}),s.jsx("div",{className:"ck-note",children:l("「保活模型链」是 WorkBuddy 国际版领日活时用来保活的免费模型,按顺序逐个尝试、 第一个成功即止;清空清单并保存 = 恢复缺省链(当前缺省:{defaults})。 当天去重 + 幂等领取:重复执行只会拿到「已领取」,不会重复加分。",{defaults:t.join(l("、"))})})]})]})}function kq(){const e=hq(),t=gq();if(x.useEffect(()=>{WA()},[]),!e.loaded)return s.jsxs("div",{className:"ck-loading",children:[s.jsx(Fd,{className:"size-5"}),s.jsx("span",{children:l("正在读取定时签到数据…")})]});const r=e.data,o=r?.enabled===!0,c=Array.isArray(r?.schedules)?r.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&&!wq(g,f);return s.jsxs("div",{children:[e.loadError?s.jsxs("div",{className:"ck-page-error",children:[s.jsx("span",{children:l("读取定时签到数据失败:{error}",{error:e.loadError})}),s.jsx(se,{size:"sm",variant:"outline",onClick:()=>{WA()},children:l("重试")})]}):null,s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:l("定时签到")}),s.jsx("span",{className:"tip-q","data-tip":mq}),s.jsx("span",{className:"panel-sub",children:l("每条条目各有时刻与范围 · 各自当天去重 · 错过时点开机自动补签")}),s.jsx(se,{size:"sm",variant:"outline",className:"ml-auto flex-none",disabled:e.saving,onClick:()=>Nj(e.editingId==="new"?null:"new"),children:e.editingId==="new"?l("收起新建"):l("添加条目")})]}),s.jsx("div",{className:"p-4",children:s.jsxs("div",{className:"ck-set-line",children:[s.jsx("span",{className:"ck-set-k",children:l("总开关")}),s.jsxs("span",{className:"ck-set-v flex items-center gap-2",children:[s.jsx(Rs,{checked:o,disabled:e.saving,onCheckedChange:b=>{uq(b===!0)}}),s.jsx("span",{className:"text-subtle text-xs",children:l(o?"开着:启用的条目按各自时刻执行":"关着:所有条目都不执行")})]})]})}),s.jsxs("div",{children:[e.editingId==="new"?s.jsx(yq,{store:e}):null,c.map(b=>s.jsx(jq,{entry:b,store:e},b.id)),c.length===0?s.jsx("div",{className:"ck-empty",children:l("还没有定时条目 —— 点「添加条目」建一条,或到「签到中心」手动签到。")}):null]})]}),s.jsx(Cq,{models:v,defaultModels:p,dirty:y,saving:t.keepaliveSaving})]})}const og="checkin-records",sO=["today","7","30","month","all"],xu="all",Tq=[{value:"today",label:l("今天")},{value:"7",label:l("7 天")},{value:"30",label:l("30 天")},{value:"month",label:l("本月")},{value:"all",label:l("全部")}],rO="workbuddy-desktop-checkin-records-range";function ig(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function aO(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 Eq(){try{const e=localStorage.getItem(rO);return e!==null&&sO.includes(e)?e:xu}catch{return xu}}function lO(e){try{localStorage.setItem(rO,e)}catch{}}function oO(e){return typeof e=="number"&&e>0?e:lu}const Cj={success:{label:"成功领取",variant:"success"},already:{label:"今日已领",variant:"brand"},pending:{label:"等待窗口",variant:"warning"},failed:{label:"失败",variant:"destructive"}},Rq={schedule:"定时",startup:"补签",manual:"手动",single:"单签",activity:"活动"},kj=[{key:"time",label:l("时间")},{key:"account",label:l("账号")},{key:"provider",label:l("提供商")},{key:"source",label:l("来源")},{key:"outcome",label:l("结果")},{key:"detail",label:l("说明")}];let Tj=null;function iO(){return Tj?Tj.apply([...kj]):kj.map(e=>({...e,align:e.align??"left"}))}function cO(){window.wbTableColumns?.repaint?.(og)}function uO(e){return(ir().snapshot?.auto?.providerOptions??[]).find(r=>r.id===e)?.label??e}function Aq(e,t){const r=`ck-col-${t.key} ta-${t.align}`;switch(t.key){case"time":return s.jsxs("td",{className:r,children:[e.ts?Bs(e.ts):"—",s.jsx("span",{className:"ck-record-date",children:e.date||""})]},t.key);case"account":return s.jsx("td",{className:r,children:e.accountName||e.accountId||"—"},t.key);case"provider":return s.jsx("td",{className:r,children:e.provider?uO(e.provider):"—"},t.key);case"source":return s.jsxs("td",{className:r,children:[s.jsx("span",{className:"ck-record-source",children:Rq[e.source??""]??e.source??"—"}),e.reason?s.jsx("span",{className:"ck-record-reason",children:e.reason}):null]},t.key);case"outcome":{const o=Cj[e.outcome??""]??{label:e.outcome||"—",variant:"outline"};return s.jsxs("td",{className:r,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:l("保活")}):null]},t.key)}case"detail":return s.jsx("td",{className:e.error?`${r} ck-record-detail-fail`:r,children:e.error||e.message||"—"},t.key);default:return null}}function Oq(){const[e,t]=x.useState([]),[r,o]=x.useState(0),[c,d]=x.useState(1),[f,p]=x.useState(()=>Eq()),[g,v]=x.useState(()=>oO(Hh(og,zh))),[y,b]=x.useState({outcome:"",provider:"",keyword:""}),[j,w]=x.useState(""),[S,N]=x.useState(!1),[C,E]=x.useState(""),[R,k]=x.useState(0),A=x.useRef(null),D=x.useRef(0),[,I]=x.useReducer(G=>G+1,0),M=ir().snapshot?.auto?.providerOptions??[],O=iO(),_=Math.max(1,Math.ceil(r/g)),L=Math.min(c,_),z=y.outcome!==""||y.provider!==""||y.keyword!==""||f!==xu,U=r?{start:(L-1)*g+1,end:Math.min(r,L*g)}:null,B=x.useCallback(async G=>{const $=D.current+1;D.current=$,N(!0),E("");try{const X=await Pe().workbuddyDesktop?.getCheckinRecords?.({limit:G.size,offset:(G.page-1)*G.size,outcome:G.filters.outcome,provider:G.filters.provider,keyword:G.filters.keyword,start:aO(G.range)});if($!==D.current)return;t(Array.isArray(X?.records)?X.records:[]),o(Number(X?.total)||0)}catch(F){if($!==D.current)return;E(F instanceof Error?F.message:String(F))}finally{$===D.current&&N(!1)}},[]);x.useEffect(()=>{B({page:c,size:g,range:f,filters:y})},[B,c,g,f,y]),x.useEffect(()=>{c>_&&d(_)},[c,_]),x.useLayoutEffect(()=>{const G=Pe().wbColSettings;if(!G?.register){const $=window.setTimeout(()=>k(F=>F+1),50);return()=>window.clearTimeout($)}Tj=G.register({id:og,label:l("签到记录表"),columns:kj.map($=>({key:$.key,label:$.label,align:$.align??"left"})),mount:()=>A.current,onChange:()=>{ys.flushSync(()=>I()),cO()}}),I()},[R]),x.useLayoutEffect(()=>{cO()}),x.useEffect(()=>()=>{Pe().wbColSettings?.close()},[]);const Q=G=>{b(G),d(1)},W=G=>{const $=sO.includes(G)?G:xu;$!==f&&(lO($),p($),d(1))},Z=G=>{v(oO(G)),Uh(og,G),d(1)},Y=()=>{w(""),lO(xu),p(xu),Q({outcome:"",provider:"",keyword:""})},q=async()=>{const G=Pe().wbConfirm?.ask;if(!G)return;const $=l(z?"确定清空当前筛选出的签到记录?清空后无法恢复。":"确定清空全部签到记录?清空后无法恢复。");if(await G({title:l("清空签到记录"),html:$,okText:l("清空"),okClass:"danger"}))try{await Pe().workbuddyDesktop?.clearCheckinRecords?.(z?{outcome:y.outcome,provider:y.provider,keyword:y.keyword,start:aO(f)}:{all:"1"}),dO("签到记录已清空"),await B({page:1,size:g,range:f,filters:y}),d(1)}catch(F){dO(l("清空失败:{error}",{error:F instanceof Error?F.message:String(F)}),"err")}};return s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:l("签到记录")}),s.jsx("span",{className:"panel-sub",children:l("每执行一次签到 · 每个账号一条明细 · 结果与收益以后端落账为准")}),s.jsxs("div",{ref:A,className:"ml-auto flex items-center gap-2",children:[s.jsx(se,{size:"sm",variant:"outline",disabled:S,onClick:()=>{B({page:c,size:g,range:f,filters:y})},children:l(S?"刷新中…":"刷新")}),s.jsx(se,{size:"sm",variant:"ghost",className:"text-destructive",onClick:()=>{q()},children:l("清空")})]})]}),s.jsxs("div",{className:"ck-records-filters",children:[s.jsx(Gn,{options:Tq,value:f,onValueChange:W,"aria-label":l("签到记录时间范围"),className:"shrink-0"}),s.jsxs(ct,{value:y.outcome,onValueChange:G=>Q({...y,outcome:G??""}),children:[s.jsx(dt,{className:"w-[128px] shrink-0","aria-label":l("按结果筛选"),children:s.jsx(ut,{children:y.outcome?Cj[y.outcome]?.label??y.outcome:l("全部结果")})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"",children:l("全部结果")}),Object.entries(Cj).map(([G,$])=>s.jsx(Ye,{value:G,children:$.label},G))]})]}),s.jsxs(ct,{value:y.provider,onValueChange:G=>Q({...y,provider:G??""}),children:[s.jsx(dt,{className:"w-[148px] shrink-0","aria-label":l("按提供商筛选"),children:s.jsx(ut,{children:y.provider?uO(y.provider):l("全部提供商")})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"",children:l("全部提供商")}),M.map(G=>s.jsx(Ye,{value:G.id,children:G.label},G.id))]})]}),s.jsx("div",{className:"spacer"}),s.jsx(Ke,{type:"search",className:"ck-records-search w-[200px] basis-[200px] min-w-[150px] grow-0 shrink",placeholder:l("搜账号 / 收益 / 错误 / 触发原因"),value:j,onChange:G=>w(G.currentTarget.value),onBlur:()=>{j!==y.keyword&&Q({...y,keyword:j.trim()})},onKeyDown:G=>{G.key==="Enter"&&G.currentTarget.blur(),G.key==="Escape"&&(w(y.keyword),G.currentTarget.blur())}}),z?s.jsx(se,{size:"sm",variant:"ghost",onClick:Y,children:l("清除筛选")}):null,s.jsx("span",{className:"panel-sub",children:S?l("读取中…"):l("{n} 条",{n:r})})]}),C?s.jsxs("div",{className:"ck-page-error",children:[s.jsx("span",{children:l("读取签到记录失败:{error}",{error:C})}),s.jsx(se,{size:"sm",variant:"outline",onClick:()=>{B({page:c,size:g,range:f,filters:y})},children:l("重试")})]}):null,e.length===0&&!S?s.jsx("div",{className:"ck-empty",children:l(z?"没有符合筛选条件的签到记录":"还没有签到记录 —— 手动签到或等定时条目执行后,明细会出现在这里。")}):s.jsx("div",{className:"ck-records-scroll",children:s.jsxs("table",{className:"ck-table ck-records-table",children:[s.jsx("colgroup",{children:O.map(G=>s.jsx("col",{"data-col":G.key,className:`ck-col-${G.key}`},G.key))}),s.jsx("thead",{children:s.jsx("tr",{children:O.map(G=>s.jsx("th",{"data-col":G.key,className:`ck-col-${G.key} ta-${G.align}`,children:G.label},G.key))})}),s.jsx("tbody",{children:e.map(G=>s.jsx("tr",{children:O.map($=>Aq(G,$))},G.rowId))})]})}),s.jsx(Di,{total:r,range:U,page:L,pageCount:_,size:g,sizes:zh,onSizeChange:Z,onPageChange:d,disabled:S})]})}function dO(e,t){Pe().wbApp?.toast?.(e,t)}window.wbCheckinRecords={visibleColumns:()=>iO().map(e=>({key:e.key}))};const fO={workbuddy:l("腾讯每日签到接口 · 仅国内版"),"workbuddy-intl":l("每日活跃任务 · 领取才加积分,保活只维持活跃 · 两者可分开执行"),raccoon:l("桌面端每日积分链路"),autoclaw:l("官方客户端的每日签到任务"),"autoclaw-intl":l("与国内版同一套任务接口 · 站点不同"),qoder:l("活动(campaign)领取 · 每天 10:00 刷新"),"qoder-intl":l("带设备风控身份领取「每日 100 Credits」 · 需要 UMID 组件"),trae:l("SOLO 的 checkin_credits 领取 · 按自然日 0 点刷新"),loomy:l("无独立签到接口 · 每天替账号打一次首次登录积分"),kuku:l("「免费领积分」的每日任务 · 逐个领取"),officeace:l("一次领当天全部奖励(每日签到 + 新人礼) · 幂等由上游保证"),codearts:l("每日福利 · 领取 → 确认 → 回读核实 · 按北京时间自然日重置")},Mq=[{value:"center",label:l("签到中心")},{value:"schedule",label:l("定时签到")},{value:"records",label:l("签到记录")}];function Dq(e){return e==="raccoon"?"小浣熊":e==="loomy"?"Loomy":e==="codearts"?"CodeArts":e==="officeace"?"OfficeAce 果办":e}function Iq(){const[e,t]=x.useState(ir());return x.useEffect(()=>VA(()=>t(ir())),[]),e}function Pq({group:e}){const t=lq(e);return t==="none"?s.jsx(ze,{variant:"outline",shape:"tag",children:l("无账号")}):t==="done"?s.jsx(ze,{variant:"success",shape:"tag",children:l("已签")}):t==="part"?s.jsx(ze,{variant:"warning",shape:"tag",children:l("部分")}):s.jsx(ze,{variant:"brand",shape:"tag",children:l("待签")})}function Tf({id:e,label:t}){const r=Kh[e==="workbuddy-intl"?"workbuddy":e];return s.jsx("span",{className:"ck-prov-logo",children:r?s.jsx("img",{src:r,alt:""}):t.slice(0,1)||"·"})}function _q({group:e}){const t=ir().signing,r=(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:l("账号")}),s.jsx("th",{children:l("今日签到")}),s.jsx("th",{children:l("上次签到时间")}),s.jsx("th",{"aria-label":l("操作")})]})}),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:l("已签")}):s.jsx(ze,{variant:"brand",shape:"tag",children:l("待签")})}),s.jsx("td",{className:"text-subtle",children:o.checkinAt?Bs(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:r(o.id,"keepalive"),title:l("用免费模型维持账号活跃 · 不领取奖励"),onClick:()=>{sg(o.id,"keepalive")},children:r(o.id,"keepalive")?l("保活中…"):l("保活")}),s.jsx(se,{size:"sm",variant:"ghost",disabled:r(o.id,"claim"),title:l("探测活动并领取日活奖励 · 不做保活"),onClick:()=>{sg(o.id,"claim")},children:r(o.id,"claim")?l("领取中…"):l("领取")}),s.jsx(se,{size:"sm",variant:"ghost",disabled:r(o.id,"full"),title:l("探测 + 领取 + 保活 · 与定时签到同一套组合"),onClick:()=>{sg(o.id,"full")},children:r(o.id,"full")?l("执行中…"):l("保活+领取")})]}):s.jsx(se,{size:"sm",variant:"ghost",disabled:r(o.id,"checkin"),onClick:()=>{sg(o.id)},children:r(o.id,"checkin")?l("签到中…"):o.checkedInToday?l("重签"):l("签到")})})]},o.id)})})]})}function Lq({group:e,expanded:t}){const r=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:()=>r&&$A(e.id),onKeyDown:o=>{r&&(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),$A(e.id))},role:r?"button":void 0,tabIndex:r?0:-1,"aria-expanded":r?t:void 0,children:[s.jsx(Tf,{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:fO[e.id]??""})]}),s.jsxs("div",{className:"ck-prov-right",children:[s.jsx("span",{className:"ck-prov-count",children:r?l("{total} 账号 · {done} 已签",{total:e.totalCount,done:e.doneCount}):"—"}),s.jsx(Pq,{group:e}),r?s.jsx("span",{className:"ck-chev","aria-hidden":!0,children:"›"}):null]})]}),e.id==="qoder-intl"?s.jsx(pO,{}):null,t?s.jsx("div",{className:"ck-prov-detail",children:s.jsx(_q,{group:e})}):null]})}function pO(){const[e,t]=x.useState(null),r=x.useCallback(async()=>{try{t(await Rr().getQoderUmid?.()??null)}catch{}},[]);x.useEffect(()=>{r()},[r]);const o=e?.installing===!0&&e.available!==!0;if(x.useEffect(()=>{if(!o)return;const d=window.setInterval(()=>{r()},3e3);return()=>{window.clearInterval(d)}},[o,r]),!e||e.available)return null;const c=async()=>{try{t(d=>d&&{...d,installing:!0}),await Rr().installQoderUmid?.(),Pe().wbApp?.toast?.(l("✅ UMID 组件已安装,下轮签到即可领取国际版积分"))}catch(d){Pe().wbApp?.toast?.(l("UMID 组件安装失败:{error}",{error:d instanceof Error?d.message:String(d)}),"err")}finally{r()}};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:l("国际版签到需要 UMID 组件生成设备风控身份(本机未检测到)。")}),e.installSupported?s.jsx(se,{variant:"outline",size:"sm",disabled:e.installing===!0,onClick:()=>{c()},children:e.installing?l("安装中…"):l("一键安装组件")}):s.jsx("span",{children:l("安装 Qoder 客户端或 qodercli 后即可(无需重启网关)。")})]})}function zq({row:e}){const t=e.provider??"loomy",r=ir().onboarding.get(e.id),o=r?.tasks??[],c=r?.unclaimed??0,d=r?.status==="loaded"&&o.length>0,f=d&&FA(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?()=>jj(e.id):void 0,onKeyDown:p=>{d&&(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),jj(e.id))},role:d?"button":void 0,tabIndex:d?0:-1,"aria-expanded":d?f:void 0,children:[s.jsx(Tf,{id:t,label:Dq(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:[r?.status==="loaded"?l("已领 {claimed}/{total} · 累计 {earned} 积分",{claimed:o.length-c,total:o.length,earned:r.total?`${r.earned} / ${r.total}`:r.earned}):l("尚未查询任务状态"),r?.settled&&r.settledAt?` · ${l("结算于 {time}",{time:Bs(r.settledAt)})}`:r?.checkedAt?` · ${l("查询于 {time}",{time:Bs(r.checkedAt)})}`:""]})]}),s.jsxs("div",{className:"ck-prov-right",onClick:p=>p.stopPropagation(),children:[r?.status==="loaded"&&c>0?s.jsx(ze,{variant:"warning",shape:"tag",children:l("{n} 项待领",{n:c})}):r?.status==="loaded"?s.jsx(ze,{variant:"success",shape:"tag",children:l("全部领取")}):r?.status==="error"?s.jsx(ze,{variant:"destructive",shape:"tag",children:l("查询失败")}):null,s.jsx(se,{size:"sm",variant:"outline",disabled:r?.status==="loading"||r?.claiming===!0,onClick:()=>{wj(e.id,{expand:!0,refresh:!0})},children:r?.status==="loading"?l("查询中…"):l("查询任务")}),s.jsx(se,{size:"sm",variant:"outline",disabled:r?.status!=="loaded"||t!=="officeace"&&c===0||r?.claiming===!0,onClick:()=>{GA(e.id)},children:r?.claiming?l("领取中…"):c>0?l("一键领取({n})",{n:c}):l("领取")}),d?s.jsx("span",{className:"ck-chev","aria-hidden":!0,children:"›"}):null]})]}),r?.status==="error"?s.jsx("div",{className:"ck-fold-note",children:l("查询失败:{error}",{error:r.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:l("领取中")}):p.done?s.jsx(ze,{variant:"success",shape:"tag",children:l("已领取")}):p.blocked?s.jsx(ze,{variant:"outline",shape:"tag",children:l("暂不可领")}):p.error?s.jsx(ze,{variant:"destructive",shape:"tag",children:p.error}):s.jsx(ze,{variant:"brand",shape:"tag",children:l("可领取")})})]},p.key))}):null]})}function Bq({row:e}){const t=Th({claimPlans:e.claimPlans}),r=t.length>0;return s.jsxs("div",{className:"ck-welfare-row",children:[s.jsx(Tf,{id:"zcode",label:"ZCode"}),s.jsxs("div",{className:"ck-prov-info",children:[s.jsxs("div",{className:"ck-prov-name",children:[e.name||e.id,r?s.jsx(ze,{variant:"success",shape:"tag",title:l("本地台账里今天(北京时间)领过的套餐:{plans}",{plans:t.join(l("、"))}),children:l("今天已领 {n} 份",{n:t.length})}):s.jsx(ze,{variant:"outline",shape:"tag",title:l("本地台账里今天还没领过;活动期内每天发一份新套餐"),children:l("今天未领")})]}),s.jsx("div",{className:"ck-prov-desc",children:r?l("点「套餐明细」看领到了哪几份、什么时候生效;活动期内每天可再领"):e.claimAt?l("上次领取 {time} · 领取需通过滑块验证码",{time:Bs(e.claimAt)}):l("限时体验套餐(start-plan),活动期内每天一份 · 领取需滑块验证码")})]}),s.jsx("div",{className:"ck-prov-right",children:s.jsx(se,{size:"sm",variant:"outline",onClick:()=>LR(e.id,e.name),children:l(r?"套餐明细":"去领取")})})]})}function Hq({row:e}){const t=ir().growth.get(e.id),r=t?.tasks??[],o=r.filter(b=>b.supported&&!b.unforgeable),c=o.filter(b=>b.status!=="claimed"&&b.current0,f=d&&sq(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?()=>XA(e.id):void 0,onKeyDown:b=>{d&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),XA(e.id))},role:d?"button":void 0,tabIndex:d?0:-1,"aria-expanded":d?f:void 0,children:[s.jsx(Tf,{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"?l("{total} 项任务 · {pending} 项可完成",{total:o.length,pending:c.length}):l("查询任务树并一键点亮 / 领奖(含开学季与猫猫旅行)"),t?.checkedAt?` · ${l("查询于 {time}",{time:Bs(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:l("{n} 项可完成",{n:c.length})}):s.jsx(ze,{variant:"success",shape:"tag",children:l("全部完成")}):t?.status==="error"?s.jsx(ze,{variant:"destructive",shape:"tag",children:l("查询失败")}):null,s.jsx(se,{size:"sm",variant:"outline",disabled:t?.status==="loading"||t?.running===!0,onClick:()=>{ag(e.id)},children:t?.status==="loading"?l("查询中…"):l("查询任务")}),s.jsx(se,{size:"sm",variant:"outline",disabled:t?.status!=="loaded"||t?.running===!0,title:l("接单 + 点亮 + 领奖(只处理已实测沉淀的任务)"),onClick:()=>{QA(e.id,"full")},children:t?.running?l("执行中…"):l("一键完成")}),s.jsx(se,{size:"sm",variant:"ghost",disabled:t?.status!=="loaded"||t?.running===!0,title:l("只领取已完成任务的奖励(幂等,重复点不会重复入账)"),onClick:()=>{QA(e.id,"claim")},children:l("领取")}),d?s.jsx("span",{className:"ck-chev","aria-hidden":!0,children:"›"}):null]})]}),t?.status==="error"?s.jsx("div",{className:"ck-fold-note",children:l("查询失败:{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?l("能量 {n}",{n:t.energy}):"",t?.streak!==null&&t?.streak!==void 0?` · ${l("连登 {n} 天",{n:t.streak})}`:"",t?.energy===null&&t?.streak===null?l("(能量 / 连登读数本次未取到)"):""]}),r.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:l("需真实操作")}):b.supported?b.status==="claimed"?s.jsx(ze,{variant:"success",shape:"tag",children:l("已领取")}):b.status==="completed"?s.jsx(ze,{variant:"brand",shape:"tag",children:l("可领取")}):b.locked?s.jsx(ze,{variant:"outline",shape:"tag",children:l("未解锁")}):s.jsx(ze,{variant:"warning",shape:"tag",children:l("可完成")}):s.jsx(ze,{variant:"outline",shape:"tag",children:l("暂不支持")})})]},b.code)}),s.jsxs("div",{className:"ck-task-line",children:[s.jsx("span",{className:"ck-task-tick",children:"🐾"}),s.jsxs("span",{children:[l("猫猫旅行"),p&&p.hasBuddy===!0?`:${p.buddyName||l("已领养")} · ${p.state==="traveling"?l("在途"):p.state==="arrived"?l("可领奖"):p.state==="idle"?p.dailyLimitReached?l("今日已派出"):l("可派出"):p.state??""}`:p&&p.hasBuddy===!1?`:${l("未领养(领养需先完成当日对话量)")}`:":"+(p?.error?String(p.error):l("尚未查询"))]}),s.jsx("span",{className:"ck-task-st",children:s.jsx(se,{size:"sm",variant:"ghost",disabled:t?.runningTravel===!0||t?.status!=="loaded",onClick:()=>{aq(e.id)},children:t?.runningTravel?l("执行中…"):l("巡检一次")})})]}),s.jsxs("div",{className:"ck-task-line",children:[s.jsx("span",{className:"ck-task-tick",children:"🎓"}),s.jsxs("span",{children:[l("开学季活动"),g&&g.inPeriod===!0?`:${l("进行中")}${g.lottery?.balance!==void 0&&g.lottery?.balance!==null?` · ${l("抽奖机会 {n} 次",{n:g.lottery.balance})}`:""}`:g&&g.inPeriod===!1?`:${l("非活动期")}`:":"+(g?.error?String(g.error):l("尚未查询"))]}),s.jsx("span",{className:"ck-task-st",children:s.jsx(se,{size:"sm",variant:"ghost",disabled:t?.runningSchool===!0||t?.status!=="loaded",title:l("执行开学季任务并抽空抽奖机会(分享 / 对话 / 专家事件)"),onClick:()=>{rq(e.id,!0)},children:t?.runningSchool?l("执行中…"):l("执行并抽奖")})})]}),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 Uq({group:e}){return s.jsxs("div",{className:"ck-prov-row",children:[s.jsxs("div",{className:"ck-prov-main",style:{cursor:"default"},children:[s.jsx(Tf,{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:fO[e.id]??""})]}),s.jsx("div",{className:"ck-prov-right",children:s.jsx(ze,{variant:"outline",shape:"tag",children:l("无账号")})})]}),e.id==="qoder-intl"?s.jsx(pO,{}):null]})}function Vq({store:e}){const t=e.snapshot,[r,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,C)=>N+(Number(C.count)||0),0),p=t?.extras.onboarding??[],g=p.filter(N=>e.onboarding.get(N.id)?.status==="loaded"),v=p.reduce((N,C)=>N+(e.onboarding.get(C.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=oq(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:l("今日签到进度")}),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(qd,{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?l("另有 {n} 个账号不参与每日签到",{n:f}):l("全部账号均可签到")})]}),s.jsxs("div",{className:"ck-stat ck-stat-link",onClick:()=>{ng("schedule")},role:"button",tabIndex:0,onKeyDown:N=>{N.key==="Enter"&&ng("schedule")},children:[s.jsx("div",{className:"ck-stat-label",children:l("定时签到")}),s.jsx("div",{className:"ck-stat-value",children:d?s.jsxs(s.Fragment,{children:[w,s.jsxs("small",{children:[" / ",j.length," ",l("条启用")]})]}):s.jsx("span",{className:"ck-pending",children:"—"})}),s.jsx("div",{className:"ck-stat-foot",children:d?.enabled!==!0?l("总开关已关闭 · 在「定时签到」页打开"):S?l("下次 {date} · 点此管理条目",{date:Bs(S)}):l("暂无启用的条目 · 点此添加")})]}),s.jsxs("div",{className:"ck-stat",children:[s.jsx("div",{className:"ck-stat-label",children:l("待领新手福利")}),s.jsx("div",{className:"ck-stat-value",children:p.length?s.jsxs(s.Fragment,{children:[v,s.jsxs("small",{children:[" ",l("项")]})]}):s.jsx("span",{className:"ck-pending",children:l("无")})}),s.jsx("div",{className:"ck-stat-foot",children:p.length?l("已有结果 {checked} / 共 {total} 个账号",{checked:g.length,total:p.length}):l("没有支持新手福利的账号")})]}),s.jsxs("div",{className:"ck-stat ck-stat-link",onClick:()=>{ng("records")},role:"button",tabIndex:0,onKeyDown:N=>{N.key==="Enter"&&ng("records")},children:[s.jsx("div",{className:"ck-stat-label",children:l("累计签到记录")}),s.jsx("div",{className:"ck-stat-value",children:r===null?s.jsx("span",{className:"ck-pending",children:"—"}):r}),s.jsx("div",{className:"ck-stat-foot",children:l("每账号一条明细 · 点此查看「签到记录」")})]})]}),s.jsxs("div",{className:"ck-main",children:[s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:l("每日签到")}),s.jsx("span",{className:"panel-sub",children:l("点击行展开账号明细 · 单账号签到不受范围限制")}),s.jsx(se,{size:"sm",variant:"default",className:"ml-auto",disabled:e.runningAll||d?.running===!0,onClick:()=>{eq()},children:e.runningAll||d?.running===!0?l("签到中…"):l("立即全部签到")})]}),s.jsxs("div",{children:[(c?.providers??[]).map(N=>N.totalCount>0?s.jsx(Lq,{group:N,expanded:e.expanded.has(N.id)},N.id):s.jsx(Uq,{group:N},N.id)),(c?.outOfScope??[]).length>0?s.jsx("div",{className:"ck-fold-note",children:l("不参与每日签到:{list}。CodeArts 的一次性奖励在下方「新手福利」,它的每日福利就在上方「每日签到」里;ZCode 的套餐领取见「活动福利」。",{list:c.outOfScope.map(N=>l("{label} ×{count}({reason})",{label:N.label,count:N.count,reason:N.reason})).join(l(";"))})}):null]})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:l("新手福利")}),s.jsx("span",{className:"panel-sub",children:l("一次性福利 · 签到后自动查询并领取,领完记在本机不再查上游 · 点击行展开任务清单")}),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"||wj(N.id)},children:l("全部查询")}):null]}),p.length?s.jsx("div",{children:p.map(N=>s.jsx(zq,{row:N},N.id))}):s.jsx("div",{className:"ck-empty",children:l("没有支持新手福利的账号 —— 目前有 Loomy、小浣熊、CodeArts 三家。")})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:l("活动福利")}),s.jsx("span",{className:"panel-sub",children:l("限时体验套餐 · 领取需滑块验证码 · 逐份查看与领取")})]}),y.length>0?s.jsx("div",{children:y.map(N=>s.jsx(Bq,{row:N},N.id))}):s.jsx("div",{className:"ck-empty",children:l("没有可领套餐的账号(ZCode 未添加)。")})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:l("成长任务")}),s.jsx("span",{className:"panel-sub",children:l("WorkBuddy 国内版 · 查询任务树后一键点亮 / 领奖 · 含开学季与猫猫旅行 · 点击行展开明细")})]}),b.length>0?s.jsx("div",{children:b.map(N=>s.jsx(Hq,{row:N},N.id))}):s.jsx("div",{className:"ck-empty",children:l("没有支持成长任务的账号(需要 WorkBuddy 国内版)。")})]})]})]})}function $q(){const e=Iq(),t=e.snapshot;if(x.useEffect(()=>{El()},[]),x.useEffect(()=>{window.wbApp?.renderTopbarStatus?.()},[e.version]),!e.loaded)return s.jsxs("div",{className:"ck-loading",children:[s.jsx(Fd,{className:"size-5"}),s.jsx("span",{children:l("正在读取签到数据…")})]});const r=t?.auto,o=r?.enabled===!0;return s.jsxs("div",{children:[e.loadError?s.jsxs("div",{className:"ck-page-error",children:[s.jsx("span",{children:l("读取签到数据失败:{error}",{error:e.loadError})}),s.jsx(se,{size:"sm",variant:"outline",onClick:()=>{El()},children:l("重试")})]}):null,s.jsxs("div",{className:"ck-tabs",children:[s.jsx(Gn,{options:Mq,value:e.tab,onValueChange:c=>UA(c),"aria-label":l("签到中心分区")}),s.jsx(ze,{id:"checkin-badge",className:"ml-auto",variant:r?o?"success":"outline":"destructive","data-tone":r?o?"ok":"":"bad",children:r?o?r?.lastFiredToday?l("今日已执行"):l("已开启"):l("已关闭"):l("不可用")})]}),e.tab==="center"?s.jsx(Vq,{store:e}):null,e.tab==="schedule"?s.jsx(kq,{}):null,e.tab==="records"?s.jsx(Oq,{}):null]})}const mO='.page[data-page="checkin"]';let hO=!1;function gO(){if(hO)return;const e=document.querySelector(mO);e&&(hO=!0,e.replaceChildren(),jn.createRoot(e).render(s.jsx($q,{})))}const xO=()=>El();window.wbCheckinPanel={load:xO},document.querySelector(mO)?gO():document.addEventListener("DOMContentLoaded",gO,{once:!0}),Pe().wbApp?.currentPage==="checkin"&&xO();function Fq(e){return String(e??"").replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}function qq({options:e,onSettle:t}){const{title:r="确认操作",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(hU,{open:!0,onOpenChange:y=>{y||t(!1)},children:s.jsxs(vU,{initialFocus:v,showCloseButton:!0,children:[s.jsx(yU,{className:"pr-10",children:s.jsx(xU,{children:r})}),s.jsx(jU,{children:s.jsx(SU,{tone:p==="danger-zone"?"danger":"neutral",dangerouslySetInnerHTML:{__html:o||Fq(c).replace(/\n/g,"
")}})}),s.jsxs(wU,{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 Ef=null,bu=null,cg=null;function Gq(){Ef&&(Ef.unmount(),Ef=null),bu&&(bu.remove(),bu=null)}function bO(e){const t=cg;cg=null,Gq(),t?.(e)}function Kq(e={}){return new Promise(t=>{cg&&bO(!1),cg=t,bu=document.createElement("div"),document.body.append(bu),Ef=jn.createRoot(bu),Ef.render(s.jsx(qq,{options:e,onSettle:bO}))})}window.wbConfirm={ask:Kq};const Yq=l("Base URL 填进客户端的「API 地址 / Base URL」栏;对话协议按客户端支持的类型三选一(Chat Completions / Responses / Anthropic Messages),三者共用同一套模型与账号池,可随时切换;鉴权用「网关 Key」页里任一启用 Key。");function Rf({id:e,name:t,note:r}){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:r})]}),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:l("复制地址"),children:"⧉"})]})]})}function Xq(){return s.jsxs("section",{className:"panel ep-panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:l("接口地址")}),s.jsx("span",{className:"tip-q","data-tip":Yq})]}),s.jsxs("div",{className:"ep-list",children:[s.jsx(Rf,{id:"api-base",name:"Base URL",note:l("填进客户端的「API 地址 / Base URL」")}),s.jsx("div",{className:"ep-group",children:l("对话协议(按客户端支持的类型选一行)")}),s.jsx(Rf,{id:"api-chat",name:"OpenAI Chat Completions",note:l("多数 OpenAI 兼容客户端的默认协议")}),s.jsx(Rf,{id:"api-responses",name:"OpenAI Responses",note:l("OpenAI 新协议(Codex、新版 SDK)")}),s.jsx(Rf,{id:"api-messages",name:"Anthropic Messages",note:l("Claude Code / Anthropic SDK(token 计数:/v1/messages/count_tokens)")}),s.jsx("div",{className:"ep-group",children:l("模型清单")}),s.jsx(Rf,{id:"api-models",name:l("模型列表"),note:l("客户端自动拉取可用模型;不受鉴权限制,配 Key 之前就能拉")})]}),s.jsx("div",{className:"panel-foot",children:s.jsxs("span",{children:[l("鉴权用「网关 Key」页里任一"),s.jsx("b",{children:l("启用")}),l("的 Key:请求带 "),s.jsx("code",{children:"Authorization: Bearer "}),l(" 或 "),s.jsx("code",{children:"x-api-key: "}),l("。一把启用的 Key 都没有时不鉴权(默认网关只监听 127.0.0.1;在设置页开启「局域网访问」后监听所有网卡,鉴权与安全闸门随之启用)。")]})})]})}const vO='.page[data-page="docs"]';let yO=!1;function jO(){if(yO)return;const e=document.querySelector(vO);e&&(yO=!0,e.replaceChildren(),jn.createRoot(e).render(s.jsx(Xq,{})))}document.querySelector(vO)?jO():document.addEventListener("DOMContentLoaded",jO,{once:!0});function aa(){return window}function Ej(e){return e instanceof Error?e.message:String(e)}function Af(e,t){aa().wbApp?.toast?.(e,t)}function Qq(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}const Rj=[{key:"name",label:l("名称")},{key:"key",label:"Key"},{key:"time",label:l("创建时间")},{key:"state",label:l("启用")},{key:"act",label:l("操作"),align:"right"}],Zq={name:"cell-name",key:"cell-key",time:"cell-time",state:"cell-state state",act:"cell-act r"},wO='.page[data-page="keys"]';let ug=null,Aj=null;function SO(){return ug?ug.apply([...Rj]):Rj.map(e=>({...e,align:e.align??"left"}))}function NO(){aa().wbColSettings?.syncStaticHead?.("keys",document.querySelector("table.keys-table"))}function Wq(){if(ug)return;const e=aa().wbColSettings?.register({id:"keys",label:l("网关 Key 表"),columns:Rj,mount:()=>document.querySelector('.page[data-page="keys"] .panel-head .head-actions'),onChange:()=>{NO(),Aj?.()}});e&&(ug=e,NO())}function Jq(e){return Array.isArray(e?.keys)?e.keys:[]}function eG(e){return Array.isArray(e?.providers)?e.providers:[]}function tG(e){const t=e?.modelsByProvider;return t&&typeof t=="object"?t:{}}function Oj(e){return aa().wbProviders?.labelOf?.(e)||e}function nG(e,t,r){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)}),r.forEach(c);const d=[...o.values()].map(f=>({value:f,label:l(f)}));return d.sort((f,p)=>f.value.toLowerCase()String(t)):[]}function kO(e,t){const r=new Map(t.map(c=>[c.value.toLowerCase(),c.value])),o=new Set;return e.forEach(c=>{const d=r.get(String(c).toLowerCase());d&&o.add(d)}),t.filter(c=>o.has(c.value)).map(c=>c.value)}function lG({target:e,providers:t,modelsByProvider:r,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),[C,E]=x.useState(()=>CO(e?.allowedProviders)),[R,k]=x.useState(()=>CO(e?.allowedModels)),A=x.useMemo(()=>t.map(z=>({value:String(z.id),label:l(String(z.label??z.id))})),[t]),D=x.useMemo(()=>kO(C,A),[C,A]),I=x.useMemo(()=>nG(r,D,R),[r,D,R]),M=x.useMemo(()=>kO(R,I),[R,I]),O=I.length?l("没有匹配的选项"):D.length?l("这几家当前没有可用模型(账号未登录或清单为空)"):l("请先在上面选择可用提供商");function _(){N.current=!1,S(!1)}async function L(){if(!N.current){N.current=!0,S(!0),j(l("保存中…"));try{const z=aa().workbuddyDesktop;if(!z)throw new Error(l("后端桥不可用"));if(d){const Q=await z.updateKey(d,{allowedProviders:D,allowedModels:M});_(),c(Q),o(),Af(l("✅ 可用范围已保存"));return}const U=v.trim();if(U&&U.length<8){j(l("Key 至少需要 8 个字符"));return}const B=await z.createKey({name:p.trim(),key:U||void 0,allowedProviders:D,allowedModels:M});_(),c(B,B?.created?.id),o(),Af(l("✅ Key 已创建,记得复制给客户端"))}catch(z){j(l("保存失败:{reason}",{reason:Ej(z)}))}finally{_()}}}return s.jsx(Kt,{open:!0,onOpenChange:(z,U)=>{if(!z){if(N.current){U.cancel();return}o()}},children:s.jsxs(Yt,{children:[s.jsx(Ft,{children:s.jsx($t,{children:f?l("可用范围 · {name}",{name:e?.name||l("未命名")}):l("新建 API Key")})}),s.jsxs(Ht,{children:[s.jsxs(zn,{children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(tt,{htmlFor:"key-name",className:"text-[12.5px] whitespace-nowrap text-subtle",children:l("名称")}),s.jsx(Ke,{id:"key-name",type:"text",maxLength:60,placeholder:l("例如 Cursor / 公司电脑"),autoComplete:"off",value:p,disabled:f,onChange:z=>g(z.currentTarget.value)})]}),!f&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(tt,{htmlFor:"key-value",className:"text-[12.5px] whitespace-nowrap text-subtle",children:"Key"}),s.jsx(Ke,{id:"key-value",type:"text",placeholder:l("留空自动生成;手填至少 8 个字符"),autoComplete:"off",spellCheck:!1,value:v,onChange:z=>y(z.currentTarget.value),onKeyDown:z=>{z.key==="Enter"&&L()}})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(tt,{className:"text-[12.5px] whitespace-nowrap text-subtle",children:l("可用提供商")}),s.jsx(My,{value:D,onValueChange:E,options:A,placeholder:l("留空 = 不限制"),searchPlaceholder:l("搜索提供商…"),"aria-label":l("可用提供商"),className:"flex-auto min-w-[180px] max-w-[260px]"})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(tt,{className:"text-[12.5px] whitespace-nowrap text-subtle",children:l("可用模型")}),s.jsx(My,{value:M,onValueChange:k,options:I,placeholder:l("留空 = 不限制"),emptyHint:O,searchPlaceholder:l("搜索模型…"),"aria-label":l("可用模型"),className:"flex-auto min-w-[180px] max-w-[260px]"})]}),s.jsx("p",{children:l("留空表示不限制;同时设置时请求需同时满足两个条件(模型在白名单内且路由到允许的提供商)。 「可用模型」的候选跟着上面勾选的提供商走:没勾提供商时它是空的(还没有约束范围), 勾了几家就列出这几家能收的全部对外名。")}),s.jsx("p",{id:"key-restrict-summary",children:aG(D,M)})]}),s.jsx("div",{className:"min-h-[18px] text-[11.5px] text-muted-foreground",children:b})]}),s.jsxs(sn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:o,disabled:w,children:l("取消")}),s.jsx(se,{variant:"default",disabled:w,onClick:()=>{L()},children:l(f?"保存范围":"创建")})]})]})})}let dg=null;async function oG(){await dg?.load()}function iG(){dg?.render()}function cG(){const[e,t]=x.useState(null),[r,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=aa().workbuddyDesktop;if(!L)throw new Error(l("后端桥不可用"));b(await L.getKeys()??null)}catch(L){Af(l("读取 Key 列表失败:{reason}",{reason:Ej(L)}),"err")}finally{y.current=!1}}},[b]);async function S(L,z,U){if(!v.current.has(L)){v.current.add(L),d(new Set(v.current));try{j(await z()),U&&Af(U)}catch(B){Af(l("操作失败:{reason}",{reason:Ej(B)}),"err")}finally{v.current.delete(L),d(new Set(v.current))}}}function N(L){o(z=>{const U=new Set(z);return U.has(L)?U.delete(L):U.add(L),U})}async function C(L){const z=aa().workbuddyDesktop,U=aa().wbConfirm?.ask;if(!z||!U)return;const B=Qq(L.name||L.masked||L.id);await U({title:l("删除网关 Key"),html:l("确定删除 Key「{name}」?使用它的客户端会立刻无法访问。",{name:B}),okText:l("删除"),okClass:"danger"})&&S(L.id,()=>z.deleteKey(L.id),l("Key 已删除"))}function E(L,z){const U=aa().workbuddyDesktop;U&&S(L.id,()=>U.updateKey(L.id,{enabled:z}),l(z?"Key 已启用":"Key 已停用"))}x.useLayoutEffect(()=>(dg={load:w,render:()=>g(L=>L+1)},Aj=()=>g(L=>L+1),Wq(),g(L=>L+1),()=>{dg=null,Aj=null}),[w]),x.useEffect(()=>{aa().wbApp?.currentPage==="keys"&&w()},[w]),x.useEffect(()=>{aa().wbApp?.renderTopbarStatus?.()},[e]);const R=Jq(e),k=Vh(R.length,"keys"),A=k.paged?k.slice(R):R,D=SO(),I=e?.authRequired===!0,M=A.filter(L=>L.enabled).length,O=I?l("已启用鉴权 · {n} 把 Key 生效",{n:M}):l("未启用鉴权");function _(L,z,U){switch(L){case"name":return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mid",children:s.jsx("span",{className:"t",children:z.name||l("未命名")})}),s.jsx("div",{className:"mname",title:rG(z),children:sG(z)})]});case"key":{const B=r.has(z.id);return s.jsxs("div",{className:"keycell",children:[s.jsx("code",{className:"kv",children:B?z.key:z.masked}),s.jsx(se,{size:"sm",variant:"ghost",onClick:()=>N(z.id),children:l(B?"隐藏":"显示")}),s.jsx(se,{size:"sm",variant:"ghost","data-copy":z.key,title:l("复制 Key"),children:l("复制")})]})}case"time":return s.jsx("span",{className:"muted",children:z.createdAt?aa().wbApp?.formatTime?.(z.createdAt):"—"});case"state":return s.jsx(Rs,{checked:z.enabled===!0,disabled:U,"aria-label":l("启用「{name}」",{name:z.name||l("未命名")}),onCheckedChange:B=>E(z,B)});case"act":return s.jsxs("div",{className:"row-actions",children:[s.jsx(se,{size:"sm",variant:"ghost",disabled:U,onClick:()=>p({key:z}),children:l("可用范围")}),s.jsx(se,{size:"sm",variant:"destructive",disabled:U,onClick:()=>{C(z)},children:l("删除")})]});default:return null}}return s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:l("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:l("+ 新建 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:l("名称")}),s.jsx("th",{"data-col":"key",children:"Key"}),s.jsx("th",{"data-col":"time",children:l("创建时间")}),s.jsx("th",{"data-col":"state",children:l("启用")}),s.jsx("th",{className:"r","data-col":"act",children:l("操作")})]})}),s.jsx("tbody",{children:A.length?A.map(L=>{const z=c.has(L.id);return s.jsx("tr",{className:L.enabled?"":"off","data-id":L.id,children:D.map(U=>s.jsx("td",{className:`${Zq[U.key]??""} ta-${U.align}`,children:_(U.key,L,z)},U.key))},L.id)}):s.jsx("tr",{children:s.jsx("td",{colSpan:D.length,className:"empty",children:l(e?"还没有 Key,当前不鉴权":"加载中…")})})})]})}),s.jsx(Di,{leading:s.jsxs("span",{children:[l("客户端请求需带 "),s.jsx("code",{children:"Authorization: Bearer "}),l(" 或 "),s.jsx("code",{children:"x-api-key: "}),l("; 修改后立即生效,本程序自身会自动使用第一把启用的 Key。每把 Key 可单独限制"),s.jsx("b",{children:l("可用提供商")}),l("与"),s.jsx("b",{children:l("可用模型")}),l("(行内「可用范围」):留空 = 不限制,两个都设时 按交集生效 —— 被限制的模型对这把 Key 表现为「不存在」(拉 /v1/models 也看不到它), 提供它的家不在可用列表里时请求同样被拒。")]}),total:R.length,range:k.paged?{start:k.rangeStart,end:k.rangeEnd}:null,page:k.page,pageCount:k.pageCount,size:k.size,onSizeChange:k.setSize,onPageChange:k.goto}),f?s.jsx(lG,{target:f.key,providers:eG(e),modelsByProvider:tG(e),onClose:()=>p(null),onSaved:(L,z)=>{z&&o(U=>new Set(U).add(z)),j(L)}}):null]})}let TO=!1;function EO(){if(TO)return;const e=document.querySelector(wO);e&&(TO=!0,e.replaceChildren(),jn.createRoot(e).render(s.jsx(cG,{})))}document.querySelector(wO)?EO():document.addEventListener("DOMContentLoaded",EO,{once:!0}),window.wbKeysPanel={load:oG,render:iG,visibleColumns:SO};const uG="login-app",dG=x.createElement("panel-captcha",{id:"captcha"});function fG(){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:l("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(tt,{htmlFor:"username",className:"mt-3.5 mb-[5px] text-[12.5px]",children:l("账号")}),s.jsx(Ke,{id:"username",autoComplete:"username",placeholder:l("管理员账号")}),s.jsx(tt,{htmlFor:"password",className:"mt-3.5 mb-[5px] text-[12.5px]",children:l("密码")}),s.jsx(Ke,{id:"password",type:"password",autoComplete:"new-password",placeholder:l("至少 8 位")}),dG,s.jsx(se,{id:"submit",type:"submit",size:"lg",className:"w-full",children:l("继续")}),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:l("登录后可在「网关 Key」页为 API 客户端创建密钥")})]})}function pG(){const e=document.getElementById(uG);e&&ys.flushSync(()=>{jn.createRoot(e).render(s.jsx(fG,{}))})}pG();function Mr(){return window}function Mj(e){return e instanceof Error?e.message:String(e)}function fg(e,t){Mr().wbApp?.toast?.(e,t)}const RO=1e3,mG=Bh,hG=500,AO="workbuddy-desktop-logs-range",Dj="workbuddy-desktop-logs-filters",gG=300,xG="~/.agent2api/logs.jsonl",Ij=["today","7","30","month","all"],Pj="all",bG={today:l("今天"),7:l("7 天"),30:l("30 天"),month:l("本月"),all:l("全部")},vG=Ij.map(e=>({value:e,label:bG[e]})),_j=[{value:"",label:l("全部级别")},{value:"debug",label:l("debug 及以上")},{value:"info",label:l("info 及以上")},{value:"warn",label:l("warn 及以上")},{value:"error",label:l("仅 error")}],yG=l("全部级别"),OO=l("全部分类"),jG={debug:l("调试"),info:l("信息"),warn:l("警告"),error:l("错误")};let pg=RO,mg=!0,Lj=!1,zj=!1,Bj=!1,Hj=null,wo=null,Uj=null,hg=null,Vj=!1,$j=!1;const Fj={level:"",category:"",keyword:""};function wG(){const e=Mr().wbFilterMemory;if(!e)return{...Fj};Vj=!0;const t=e.load(Dj,{...Fj});return{level:_j.some(r=>r.value===t.level)?t.level:"",category:t.category,keyword:t.keyword}}function gg(e){Mr().wbFilterMemory?.save(Dj,{level:e.level||"",category:e.category||"",keyword:e.keyword.trim()||""})}function SG(){try{const e=localStorage.getItem(AO);return e!==null&&Ij.includes(e)?e:Pj}catch{return Pj}}function NG(e){try{localStorage.setItem(AO,e)}catch{}}function xg(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function CG(e){const t=new Date;switch(e){case"today":return xg(t);case"7":return xg(new Date(t.getFullYear(),t.getMonth(),t.getDate()-6));case"30":return xg(new Date(t.getFullYear(),t.getMonth(),t.getDate()-29));case"month":return xg(new Date(t.getFullYear(),t.getMonth(),1));default:return null}}function kG(e){if(!e)return"—";const t=new Date(e),r=d=>String(d).padStart(2,"0"),o=`${r(t.getHours())}:${r(t.getMinutes())}:${r(t.getSeconds())}`,c=`${r(t.getMonth()+1)}-${r(t.getDate())}`;return t.getFullYear()===new Date().getFullYear()?`${c} ${o}`:`${t.getFullYear()}-${c} ${o}`}function TG(e){const t=e.data;if(!t)return"";const r=[];return(t.from||t.to)&&r.push([t.from,t.to].filter(Boolean).join(" → ")),t.model&&r.push(l("模型 {model}",{model:t.model})),t.resetAtText?r.push(l("{time} 恢复",{time:t.resetAtText})):t.status&&!t.from&&!t.to&&r.push(`HTTP ${t.status}`),r.length?r.join(" · "):""}function qj(e){return Array.isArray(e?.entries)?e.entries:[]}function bg(e,t,r){const o=Math.max(1,r==="all"?1:Math.ceil(t.length/r));return Math.min(Math.max(1,e),o)}function Gj(e,t){return Object.hasOwn(e,t)}function EG(e){const t={};if(e&&typeof e=="object")for(const[r,o]of Object.entries(e))typeof o=="string"&&(t[r]=o);return t}function MO(e,t){const r=new URLSearchParams,o=e.keyword.trim(),c=CG(t);return e.level&&r.set("level",e.level),e.category&&r.set("category",e.category),o&&r.set("keyword",o),c!==null&&r.set("start",String(c)),r}function RG(e,t){const r=MO(e,t);return r.set("limit",String(hG)),r.toString()}function AG(e,t){return MO(e,t).toString()}function OG(e){Hj=e||null,Mr().wbApp?.updateLogsBadge?.(Hj)}async function MG(){if(!Lj)try{const e=await Mr().workbuddyDesktop?.getScheduledTasks(),t=(e?.tasks||[]).find(r=>r.id==="logsAutoRefresh");Kj(t||null),Lj=Array.isArray(e?.tasks)}catch(e){console.warn("读取日志自动刷新间隔失败,按默认 10 秒:",Mj(e)),Kj(null)}}function Kj(e){Lj=!0;const t=Number(e?.interval);!!e&&typeof e=="object"&&Number.isFinite(t)&&t>0&&(e.unit==="seconds"||e.unit==="minutes")?(mg=e.enabled!==!1,pg=e.unit==="minutes"?t*6e4:t*1e3):(mg=!0,pg=RO),wo?.applyAutoConfig(pg,mg)}async function DG(e={}){await wo?.load(e)}function IG(e){if(!wo){hg={data:e??null};return}wo.render(e)}function PG(){return Hj}async function _G(e){if(!wo){Uj=e;return}await wo.showCategory(e)}const LG={entries:[],total:0,matched:0,file:xG,categories:{},loaded:!1};function Yj(e,t){return{entries:qj(e),total:Number(e?.total)||0,matched:Number(e?.matched)||0,file:e?.file||t.file,categories:Object.keys(t.categories).length?t.categories:EG(e?.categories),loaded:!0}}function zG(e){return e.loaded?e.total?l("没有符合筛选条件的日志"):l("暂无日志"):l("正在加载日志…")}function BG(){const[e,t]=x.useState(LG),[r,o]=x.useState(wG),[c,d]=x.useState(SG),[f,p]=x.useState(1),[g,v]=x.useState(()=>Hh("logs")),[y,b]=x.useState(null),[j,w]=x.useState(()=>({ms:pg,enabled:mg})),S=x.useRef(null),N=x.useRef(null),C=x.useRef(null),E=x.useRef(null),R=x.useRef(r),k=x.useRef(c),A=x.useRef(f),D=x.useRef(g),I=x.useRef(e),M=x.useCallback(ne=>{const ce={...R.current,...ne};return R.current=ce,o(ce),ce},[]),O=x.useCallback(ne=>{k.current=ne,d(ne)},[]),_=x.useCallback(ne=>{A.current=ne,p(ne)},[]),L=x.useCallback(ne=>{D.current=ne,v(ne),Uh("logs",ne)},[]),z=x.useCallback(ne=>{I.current=ne,t(ne)},[]),U=x.useCallback(()=>{if(Vj)return;const ne=Mr().wbFilterMemory;if(!ne||(Vj=!0,$j))return;const ce=ne.load(Dj,{...Fj});M({level:ce.level,category:ce.category,keyword:ce.keyword})},[M]),B=x.useCallback(async(ne={})=>{const{silent:ce=!1,resetPage:we=!1}=ne;we&&_(1),MG(),U();const Ee=RG(R.current,k.current),ve=A.current;try{const Ce=Mr().workbuddyDesktop;if(!Ce)throw new Error(l("后端桥不可用"));const[ke,Se]=await Promise.all([Ce.getLogs(Ee),Ce.getLogStats()]),ge=we?0:S.current?.scrollTop??0,Te=Yj(ke,I.current);z(Te),_(bg(A.current,qj(ke),D.current)),N.current=A.current===ve?ge:0,OG(Se),Object.keys(Te.categories).length&&R.current.category&&!Gj(Te.categories,R.current.category)&&(gg(M({category:""})),B({resetPage:!0}))}catch(Ce){ce||(console.warn("读取运行日志失败:",Mj(Ce)),z(Yj(null,I.current)),_(bg(A.current,[],D.current)))}},[z,_,U]),Q=x.useCallback(ne=>{ne!==void 0&&(z(Yj(ne,I.current)),_(bg(A.current,qj(ne),D.current)))},[z,_]),W=x.useCallback(async ne=>{if(Gj(I.current.categories,ne)||await B({silent:!0}),!Gj(I.current.categories,ne))return;const ce=M({category:ne});gg(ce),_(1),await B({resetPage:!0}),Mr().wbApp?.showPage?.("logs",{persist:!0})},[M,_,B]);x.useEffect(()=>{if(wo={load:B,render:Q,showCategory:W,applyAutoConfig:(ce,we)=>w({ms:ce,enabled:we})},hg){const ce=hg;hg=null,Q(ce.data)}const ne=Uj;return ne!==null?(Uj=null,W(ne)):B({silent:!0}),()=>{wo=null,C.current!==null&&window.clearTimeout(C.current),C.current=null}},[B,Q,W]),x.useEffect(()=>{if(!j.enabled||j.ms<=0)return;const ne=window.setInterval(()=>{document.hidden||Mr().wbApp?.currentPage!=="logs"||zj||(zj=!0,B({silent:!0}).finally(()=>{zj=!1}))},j.ms);return()=>{window.clearInterval(ne)}},[j,B]),x.useLayoutEffect(()=>{const ne=N.current;if(ne===null)return;N.current=null;const ce=S.current;ce&&(ce.scrollTop=ne)});async function Z(ne,ce,we){if(!Bj){Bj=!0,b({which:ne,label:ce});try{await we()}catch(Ee){fg(l("操作失败:{error}",{error:Mj(Ee)}),"err")}finally{Bj=!1,b(null)}}}async function Y(){const ne=AG(R.current,k.current),ce=ne.length>0,we=ce?l("确定清空当前筛选出的 {count} 条日志?清空后无法恢复。",{count:Number(I.current.matched)||0}):l("确定清空全部运行日志?清空后无法恢复。"),Ee=Mr().wbConfirm?.ask;Ee&&await Ee({title:l("清空运行日志"),html:we,okText:l("清空"),okClass:"danger"})&&await Z("clear",l("清空中…"),async()=>{const ve=Mr().workbuddyDesktop;if(!ve)throw new Error(l("后端桥不可用"));await ve.clearLogs(ce?ne:"all=1"),await B({resetPage:!0}),fg(l("运行日志已清空"))})}async function q(){await Z("export",l("导出中…"),async()=>{const ne=Mr().workbuddyDesktop;if(!ne)throw new Error(l("后端桥不可用"));const ce=await ne.exportLogs();if(!(!ce||ce.canceled)){if(ce.count===0){fg(l("暂无日志可导出"),"err");return}fg(l("✅ 已导出 {count} 条日志到 {file}",{count:String(ce.count),file:String(ce.file)}))}})}function G(ne){const ce=bg(ne,I.current.entries,D.current);ce!==A.current&&(_(ce),N.current=0)}function $(ne){if(ne===D.current)return;const ce=I.current.entries.length,we=ce?(A.current-1)*(D.current==="all"?ce:D.current):0;L(ne),_(ne==="all"?1:Math.floor(we/ne)+1),N.current=0}function F(ne){$j=!0,gg(M(ne)),B({resetPage:!0})}function X(ne){$j=!0,M({keyword:ne}),C.current!==null&&window.clearTimeout(C.current),C.current=window.setTimeout(()=>{C.current=null,gg(R.current),B({resetPage:!0})},gG)}function re(ne){const ce=Ij.includes(ne)?ne:Pj;ce!==k.current&&(O(ce),NG(ce),B({resetPage:!0}))}const P=e.entries,V=g!=="all",J=Math.max(1,V?Math.ceil(P.length/g):1),ie=Math.min(Math.max(1,f),J),me=V?P.slice((ie-1)*g,ie*g):P,he=P.length?V?(ie-1)*g+1:1:0,ae=P.length?V?he+me.length-1:P.length:0,oe=e.categories,ee=e.matched===e.total?l("{n} 条",{n:e.total}):l("{matched} / {total} 条",{matched:e.matched,total:e.total});x.useEffect(()=>{const ne=e.loaded?ee:"—";E.current!==ne&&(E.current=ne,Mr().wbApp?.renderTopbarStatus?.())},[e.loaded,ee]);function de(ne,ce){const we=ne.level||"",Ee=TG(ne);return s.jsxs("div",{className:`log-row ${we}`,children:[s.jsx("span",{className:"log-rail",children:s.jsx("span",{className:`log-dot ${we}`})}),s.jsxs("div",{className:"log-main",children:[s.jsxs("div",{className:"log-line",children:[s.jsx("span",{className:"log-cat",children:oe[ne.category||""]||ne.category}),s.jsx("span",{className:`log-lvl ${we}`,children:jG[we]||ne.level}),s.jsx("span",{className:"msg",children:ne.message})]}),Ee?s.jsx("div",{className:"log-extra-wrap",children:s.jsx("span",{className:"extra",children:Ee})}):null]}),s.jsx("span",{className:"time",children:kG(ne.ts)})]},ne.id??ce)}const K=y?.which==="export",be=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:l("系统事件")}),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:()=>{q()},children:K?y?.label:l("导出")}),s.jsx(se,{id:"btn-logs-clear",variant:"destructive",disabled:y!==null,onClick:()=>{Y()},children:be?y?.label:l("清空")})]})]}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"log-filters",children:[s.jsx(Gn,{options:vG,value:c,onValueChange:re,"aria-label":l("事件日志时间范围"),className:"shrink-0"}),s.jsxs(ct,{value:r.level,onValueChange:ne=>F({level:String(ne??"")}),children:[s.jsx(dt,{id:"logs-level",className:"min-w-[120px]",title:l("按最低级别筛选"),"aria-label":l("按最低级别筛选"),children:s.jsx(ut,{children:_j.find(ne=>ne.value===r.level)?.label??yG})}),s.jsx(ft,{children:_j.map(ne=>s.jsx(Ye,{value:ne.value,children:ne.label},ne.value))})]}),s.jsxs(ct,{value:r.category,onValueChange:ne=>F({category:String(ne??"")}),children:[s.jsx(dt,{id:"logs-category",className:"min-w-[120px]",title:l("按分类筛选"),"aria-label":l("按分类筛选"),children:s.jsx(ut,{children:r.category?oe[r.category]||r.category:OO})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"",children:OO}),Object.entries(oe).map(([ne,ce])=>s.jsx(Ye,{value:ne,children:ce},ne))]})]}),s.jsxs(ji,{className:"w-auto flex-auto",children:[s.jsx(Si,{id:"logs-keyword",type:"search",placeholder:l("搜索消息关键词…"),autoComplete:"off","aria-label":l("搜索消息关键词"),value:r.keyword,onChange:ne=>X(ne.currentTarget.value)}),s.jsx(wi,{"aria-hidden":"true",children:"⌕"})]})]}),s.jsx("div",{className:"log-list",id:"log-list",ref:S,children:me.length?me.map((ne,ce)=>de(ne,ce)):s.jsx("div",{className:"log-empty",children:zG(e)})})]}),s.jsx(Di,{total:P.length,range:V?{start:he,end:ae}:null,page:ie,pageCount:J,size:g,sizes:mG,onSizeChange:$,onPageChange:G})]})}const DO='.page[data-page="logs"]';let IO=!1;function PO(){if(IO)return;const e=document.querySelector(DO);e&&(IO=!0,e.replaceChildren(),jn.createRoot(e).render(s.jsx(BG,{})))}document.querySelector(DO)?PO():document.addEventListener("DOMContentLoaded",PO,{once:!0}),window.wbLogsPanel={load:DG,render:IG,lastStats:PG,applyAutoRefresh:Kj,showCategory:_G};const vu=["maxInputTokens","maxOutputTokens","supportsToolCall","supportsImages","supportsVideo","supportsReasoning"],Of=["maxInputTokens","maxOutputTokens"],_O=["supportsToolCall","supportsImages","supportsVideo","supportsReasoning"],yu={maxInputTokens:l("上下文窗口"),maxOutputTokens:l("最大输出 Token"),supportsToolCall:l("工具调用"),supportsImages:l("图片识别"),supportsVideo:l("视频识别"),supportsReasoning:l("支持思考")};l("工具"),l("图片"),l("视频"),l("思考");const HG=1e8;function Xj(e){return Of.includes(e)}function Qj(e,t){if(Xj(e)){const r=typeof t=="number"?t:Number(t);return!Number.isFinite(r)||r<1||r>HG?null:Math.trunc(r)}return typeof t=="boolean"?t:null}function LO(e){const t={};if(!e||typeof e!="object")return t;const r=e;for(const o of vu){const c=Qj(o,r[o]);c!==null&&(t[o]=c)}return t}function Zj(e){return Array.isArray(e)?vu.filter(t=>e.some(r=>r===t)):[]}function Wj(e){return LO(e?.capabilities)}function zO(e){const t=Number(e);if(!Number.isFinite(t)||t<=0)return"—";const r=o=>o.toFixed(1).replace(/\.0$/,"");return t>=1e6?`${r(t/1e6)}M`:t>=1e3?`${r(t/1e3)}K`:String(Math.round(t))}function Mf(e){const t=Number(e);return!Number.isFinite(t)||t<=0?l("未声明"):Math.round(t).toLocaleString("en-US")}function Jj(e){return e===!0?"on":e===!1?"off":"unset"}function UG(e){const t=e?.reasoningLevels;if(!Array.isArray(t))return null;const r=t.filter(c=>typeof c=="string"&&c.trim()!=="");if(!r.length)return null;const o=e?.reasoningDefaultLevel;return{levels:r,defaultLevel:typeof o=="string"?o.trim():""}}function VG(e,t,r,o=""){const c=yu[e],d=r?l("(已被手动覆盖,弹窗里可恢复继承)"):"",f=$G(o);if(Xj(e))return t==null?l("{label}:上游未声明{suffix}",{label:c,suffix:d}):l("{label}:{value}(对下游声明的精确值){origin}{suffix}",{label:c,value:Mf(t),origin:f,suffix:d});const p=Jj(t);return p==="on"?l("{label}:支持{origin}{suffix}",{label:c,origin:f,suffix:d}):p==="off"?l("{label}:不支持{origin}{suffix}",{label:c,origin:f,suffix:d}):l("{label}:上游未声明(下游会按不支持处理){suffix}",{label:c,suffix:d})}function ju(e,t){const r=e?.capSources?.[t];return r==="upstream"||r==="modelsdev"||r==="user"?r:""}function $G(e){return e==="modelsdev"?l("(由 models.dev 补齐)"):e==="user"?l("(手动设定)"):""}function FG(e){const t={};for(const r of vu){const o=e[r];Xj(r)?t[r]=Qj(r,o.trim()):t[r]=o==="on"?!0:o==="off"?!1:null}return t}function Df(){return window}const BO=e=>String(e??"").trim().toLowerCase(),Hs=(e,t)=>BO(e)===BO(t);function Qn(e){return typeof e=="string"&&e.startsWith("custom-")}function Bi(){return(Df().wbProviders?.customList?.()||[]).filter(e=>Qn(e?.id))}function HO(){return Df().wbProviders?.customList?.()||[]}function So(e){return Bi().find(t=>t.id===e)||null}function qG(e){const t=LO(e),r={};for(const o of vu){const c=t[o];(typeof c=="number"||typeof c=="boolean")&&(r[o]=c)}return Object.keys(r).length?r:void 0}function UO(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=qG(c?.capabilities),d}).filter(c=>c.id),r=(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=r.find(f=>Hs(f.alias,c.id)&&Hs(f.target,c.id));d&&(c.enabled=c.enabled&&d.enabled,c.reasoning=d.reasoning||c.reasoning)}const o=r.filter(c=>!(Hs(c.alias,c.target)&&t.some(d=>Hs(d.id,c.target))));return{models:t,mappings:o}}function VO(e){const t=So(e);if(!t)return null;const r=UO(t),o=t.name||e,c=[],d=[];for(const f of r.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 r.mappings){const p=c.find(g=>Hs(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 Hi(e,t){const r=Df().wbProviders;if(!r?.customRequest)throw new Error(l("目录模块未就绪"));const o=So(e);if(!o)throw new Error(l("该自定义提供商已不存在(可能已被删除),请刷新后重试"));const c=UO(o),d=t(c);return await r.customRequest("POST","/api/custom-providers/models",{providerId:e,models:c.models,mappings:c.mappings}),await r.refreshCustom?.(),d}async function $O(e,t,r,o={}){const{enabled:c,reasoning:d}=o;await Hi(e,f=>{if(Hs(t,r)){const g=f.models.find(v=>Hs(v.id,r));if(!g)throw new Error(l("该提供商的清单里没有模型「{name}」",{name:r}));return c!==void 0&&(g.enabled=!!c),d!==void 0&&(g.reasoning=String(d??"")),null}const p=f.mappings.find(g=>Hs(g.alias,t)&&Hs(g.target,r));if(p)return c!==void 0&&(p.enabled=!!c),d!==void 0&&(p.reasoning=String(d??"")),null;if(c===!1)throw new Error(l("映射「{alias} → {target}」不存在",{alias:t,target:r}));return f.mappings.push({alias:t,target:r,enabled:c??!0,reasoning:String(d??"")}),null})}async function FO(e,t,r){await Hi(e,o=>{const c=o.mappings.length;if(o.mappings=o.mappings.filter(d=>!(Hs(d.alias,t)&&Hs(d.target,r))),o.mappings.length===c)throw new Error(l("映射「{alias} → {target}」不存在",{alias:t,target:r}));return null})}async function qO(e,t){const r=String(t??"").trim();if(!r)throw new Error(l("请填写模型 ID"));await Hi(e,o=>{if(o.models.some(c=>Hs(c.id,r)))throw new Error(l("模型「{name}」已存在(忽略大小写判重)",{name:r}));return o.models.push({id:r,enabled:!0,reasoning:""}),null})}async function GG(e,t){const r=(Array.isArray(t)?t:[]).map(o=>String(o??"").trim()).filter(Boolean);if(!r.length)throw new Error(l("没有选中任何模型"));return Hi(e,o=>{let c=0;for(const d of r)o.models.some(f=>Hs(f.id,d))||(o.models.push({id:d,enabled:!0,reasoning:""}),c++);return c})}async function GO(e,t,r){await Hi(e,o=>{const c=o.models.find(f=>Hs(f.id,t));if(!c)throw new Error(l("该提供商的清单里没有模型「{name}」",{name:t}));const d={...c.capabilities||{}};for(const[f,p]of Object.entries(r))p==null?delete d[f]:d[f]=p;return c.capabilities=Object.keys(d).length?d:void 0,null})}async function KO(e,t){return Hi(e,r=>{const o=r.mappings.length;r.mappings=r.mappings.filter(d=>!Hs(d.target,t));const c=o-r.mappings.length;return r.models=r.models.filter(d=>!Hs(d.id,t)),{removedMappings:c}})}async function KG(e){const t=Df().wbProviders;if(!t?.customRequest)throw new Error(l("目录模块未就绪"));const r=await t.customRequest("POST","/api/custom-providers/fetch-models",{providerId:e}),o=(Array.isArray(r?.models)?r.models:[]).map(d=>String(d??"").trim()).filter(Boolean),c=await Hi(e,d=>{let f=0;for(const p of o)d.models.some(g=>Hs(g.id,p))||(d.models.push({id:p,enabled:!0,reasoning:""}),f++);return f});return{total:o.length,added:Number(c)||0}}Df().wbModelsCustom={isCustom:Qn,list:Bi,listSource:HO,record:So,buildView:VO,setBinding:$O,removeMapping:FO,addModel:qO,addModels:GG,removeModel:KO,setCapabilities:GO,fetchModels:KG};const la="__custom__",YG=["off","none","minimal","low","medium","high","xhigh","max"];function If(e,t){const r=YO(t);if(r.length)return r;const o=e?.reasoningLevels;return Array.isArray(o)&&o.length?o.filter(c=>typeof c=="string"):[...YG]}function YO(e){const t=e?.reasoningLevels;return Array.isArray(t)?t.filter(r=>typeof r=="string"&&r.trim()!==""):[]}function XG(e,t){const r=t.map(YO).filter(f=>f.length>0);if(!r.length||r.length!==t.length)return If(e);const[o,...c]=r,d=o.filter(f=>c.every(p=>p.includes(f)));return d.length?d:If(e)}function XO(e,t,r){return`${String(e??"").trim().toLowerCase()}${String(t??"").trim().toLowerCase()}${String(r??"").trim().toLowerCase()}`}function QG(e){const t=new Map;for(const r of Array.isArray(e)?e:[]){const o=typeof r?.reasoning=="string"?r.reasoning.trim():"";o&&t.set(XO(r.alias,r.target,r.provider),o)}return(r,o,c)=>t.get(XO(r,o,c))||""}function qt(){return window}function No(e){return e instanceof Error?e.message:String(e)}function vr(e,t){qt().wbApp?.toast?.(e,t)}function ew(e){const t=qt().wbApp?.esc;return t?t(e):String(e??"").replace(/[&<>"']/g,r=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[r]||r)}function ZG(e){const t=qt().formatTime??qt().wbApp?.formatTime;return String(t?.(e)??"")}const QO=e=>String(e??"").trim().toLowerCase(),Co=(e,t)=>QO(e)===QO(t),ZO=8,WO="workbuddy-desktop-models-filters",tw=["all","enabled","disabled","mapped"],WG={all:l("全部"),enabled:l("已启用"),disabled:l("已禁用"),mapped:l("有映射")},JG=tw.map(e=>({value:e,label:WG[e]})),nw=["default","rate-asc","rate-desc"],e7={default:l("默认"),"rate-asc":l("倍率升序"),"rate-desc":l("倍率降序")},t7=nw.map(e=>({value:e,label:e7[e]})),sw=[{key:"check",label:l("选择"),align:"center"},{key:"model",label:l("上游模型")},{key:"rate",label:l("倍率")},{key:"source",label:l("来源")},{key:"budget",label:l("上下文 / 输出")},{key:"caps",label:l("能力")},{key:"alias",label:l("模型映射")},{key:"act",label:l("操作"),align:"right"}],JO=new Set(["rate","source"]),Pf="custom-all",rw={models:[],mappings:[]},eM={provider:"all",state:"all",search:"",sort:"default"};function tM(){const e=qt().wbFilterMemory;if(!e)return{...eM};const t=e.load(WO,{...eM});return{provider:String(t.provider||"all"),state:tw.includes(t.state)?t.state:"all",search:String(t.search||""),sort:nw.includes(t.sort)?t.sort:"default"}}const vg=tM();let nM=!!qt().wbFilterMemory,yg=!1,Zn={provider:vg.provider,stateFilter:vg.state,search:vg.search,sort:vg.sort,data:null,expanded:new Set,pending:new Set,mapping:null,customModel:null,capability:null};const aw=new Set;function _f(){return Zn}function n7(e){return aw.add(e),()=>{aw.delete(e)}}function As(e){const t={...Zn,...e},r=wg(t),o=wg(Zn)!==r;Zn=r===t.provider?t:{...t,provider:r},r7(),o&&Sg();for(const c of aw)c()}function jg(e){qt().wbFilterMemory?.save(WO,e)}function sM(){if(nM||yg||!qt().wbFilterMemory)return;nM=!0;const e=tM();(e.provider!==Zn.provider||e.state!==Zn.stateFilter||e.search!==Zn.search||e.sort!==Zn.sort)&&As(e)}function wg(e){const t=e.provider;return t==="all"||t===Pf||Bi().some(r=>r.id===t)||Array.isArray(e.data?.models)&&e.data.models.some(r=>(r.provider||"")===t)||!e.data||!lw()?t:"all"}function wu(){return wg(Zn)}function lw(){return!!qt().wbProviders}function Su(){return wu()===Pf}function rM(){return Su()||Qn(wu())}let Lf=null;function ow(e){const t=So(e);return(!Lf||Lf.id!==e||Lf.record!==t)&&(Lf={id:e,record:t,view:VO(e)||rw}),Lf.view}let zf=null;function s7(){const e=HO();if(zf&&zf.directory===e)return zf.view;const t=[],r=[];for(const o of Bi()){const c=ow(String(o.id||""));t.push(...c.models||[]),r.push(...c.mappings||[])}return zf={directory:e,view:t.length||r.length?{models:t,mappings:r}:rw},zf.view}function iw(){const e=wu();return Qn(e)?ow(e):e===Pf?s7():Zn.data||rw}function Bf(){const e=iw();return Array.isArray(e.models)?e.models:[]}function aM(){const e=iw();return Array.isArray(e.mappings)?e.mappings:[]}let lM=(e,t,r)=>"";function r7(){lM=QG(aM())}function cw(){const e=new Map,t=Array.isArray(Zn.data?.models)?Zn.data.models:[];for(const r of t){const o=r.provider||"";if(!o)continue;const c=e.get(o)||{label:r.providerLabel||o,n:0};c.n++,e.set(o,c)}return e}function a7(){const e=new Map;for(const t of Bi()){const r=String(t.id||"");if(!r)continue;const o=ow(r);e.set(r,{label:String(t.name||r),n:(o.models||[]).length})}return e}function l7(){return[...cw().keys()]}function o7(e){const r=(Array.isArray(Zn.data?.models)?Zn.data.models:[]).find(o=>o.provider===e);return Number(r?.refreshedAt)||0}function uw(){const e=new Map;for(const t of Bf()){const r=t.provider||"";r&&!e.has(r)&&e.set(r,t.providerLabel||r)}return[...e].map(([t,r])=>({id:t,label:r}))}function oM(e){return e?Bf().filter(t=>(t.provider||"")===e).sort((t,r)=>+(t.enabled===!1)-+(r.enabled===!1)).map(t=>({id:t.id,label:t.name&&t.name!==t.id?l("{id}({name})",{id:t.id,name:t.name}):t.id,off:t.enabled===!1})):[]}function i7(){const e=[],t=qt().wbProviders?.all?.();if(Array.isArray(t))for(const r of t){const o=String(r?.id||"");o&&e.push({id:o,label:String(r?.label||o)})}for(const r of Bi()){const o=String(r.id||"");o&&e.push({id:o,label:String(r.name||o)})}return e.length?e:uw()}let Hf=null,dw=null;function iM(){const e=Hf?Hf.apply(sw):sw;return rM()?e.filter(t=>!JO.has(t.key)):e}function Sg(){qt().wbColSettings?.syncStaticHead("models",dw,rM()?JO:null)}function c7(){if(Hf)return;Hf=qt().wbColSettings?.register({id:"models",label:l("模型管理表"),columns:sw,mount:()=>document.querySelector('.page[data-page="gateway"] .panel-head .head-actions'),buttonPlacement:"last",onChange:()=>{Sg(),Ui()}})||null,Hf&&Ui()}let Ng=0,fw=!1;async function Cg({force:e=!1}={}){if(fw&&!e)return;const t=++Ng;fw=!0,sM();try{const r=await qt().workbuddyDesktop?.getModelManage();if(t!==Ng)return;As({data:r&&Array.isArray(r.models)?r:null})}catch(r){if(t!==Ng)return;Ui(),vr(l("读取模型清单失败:{message}",{message:No(r)}),"err")}finally{t===Ng&&(fw=!1)}}async function cM(){try{await qt().wbProviders?.refreshCustom?.()}catch{}await Cg({force:!0})}function Ui(){As({})}function Vi(e){const t=e;if(t&&Array.isArray(t.models)){As({data:t});return}Ui()}async function kg(e,t,r,o){if(Qn(e))return $O(e,t,r,o);const c=qt().workbuddyDesktop;if(!c)throw new Error(l("后端桥不可用"));return c.addModelMapping(t,r,e,o.reasoning,o.enabled)}async function u7(e,t,r){if(Qn(e))return FO(e,t,r);const o=qt().workbuddyDesktop;if(!o)throw new Error(l("后端桥不可用"));return o.removeModelMapping(t,r,e)}async function d7(e,t){if(Qn(e))return qO(e,t);const r=qt().workbuddyDesktop;if(!r)throw new Error(l("后端桥不可用"));return r.addCustomModel(e,t)}async function uM(e,t){if(Qn(e))return KO(e,t);const r=qt().workbuddyDesktop;if(!r)throw new Error(l("后端桥不可用"));return r.removeCustomModel(e,t)}async function f7(e,t,r){if(Qn(e))return GO(e,t,r);const o=qt().workbuddyDesktop;if(!o)throw new Error(l("后端桥不可用"));return o.setModelCapabilities(e,t,r)}async function pw(e,t,r){if(!Zn.pending.has(e)){As({pending:new Set(Zn.pending).add(e)});try{Vi(await t()),r&&vr(r)}catch(o){vr(l("操作失败:{message}",{message:No(o)}),"err")}finally{const o=new Set(Zn.pending);o.delete(e),As({pending:o})}}}function Uf(e){return Nu(e).some(t=>t.enabled!==!1)}function Nu(e){const t=e.provider||"",r=aM().filter(p=>Co(p.target,e.id)&&(!p.provider||Co(p.provider,t))),o=new Map;for(const p of r){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 $i=e=>`${e.provider||""}:${e.id}`,mw=(e,t,r)=>`${e}:${t}:${r||""}`;function p7(e){As({expanded:new Set(Zn.expanded).add(e)})}function m7(e){const t=new Set(Zn.expanded);t.delete(e),As({expanded:t})}function h7(e){const t=tw.includes(e)?e:"all";t!==Zn.stateFilter&&(yg=!0,As({stateFilter:t}),jg({state:t}))}function g7(e){const t=nw.includes(e)?e:"default";t!==Zn.sort&&(yg=!0,As({sort:t}),jg({sort:t}))}function x7(e){yg=!0,As({search:e}),jg({search:e})}function Vf(e){As({provider:String(e??"").trim()||"all"}),jg({provider:Zn.provider}),Sg()}async function b7(e){const t=qt().wbCustomProvidersUi;if(!t?.remove){vr(l("删除入口未就绪,请重试或重启应用"),"err");return}await t.remove(e)&&await Cg({force:!0})}function v7(){qt().wbAccountAddForms?.openNewCustomForm?.()}function dM(e){As({mapping:e})}function y7(){As({mapping:null})}function j7(){const e=wu(),t=Qn(e);As({customModel:{provider:t||e!=="all"&&e!==Pf?e:"",locked:t}})}function w7(){As({customModel:null})}function fM(e,t){As({capability:{provider:e,id:t}})}function S7(){As({capability:null})}function pM(e,t){return Bf().find(r=>(r.provider||"")===e&&Co(r.id,t))||null}function hw(e){if(Qn(e)){const t=So(e)?.name;return typeof t=="string"&&t||e}return qt().wbProviders?.labelOf?.(e)||e}function mM(){const e=wu(),t=Qn(e),r=t?So(e)?.name||e:l("内置提供商");qt().wbModelsFetchModal?.open({providerId:e===Pf?"":e,custom:t,name:r,onDone:()=>Ui(),onRefreshed:()=>{Cg({force:!0})}})}window.wbModelsPanel={render:Ui,load:Cg,refreshAll:cM,refreshModels:mM,visibleColumns:iM,selectProvider:Vf,builtinProviders:l7,providerRefreshedAt:o7};function gw(e,t,r){return lM(e,t,r)}function N7(e){dw=e}function C7(){const e=dw;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 r=e.querySelector("tbody#models");if(r)for(const o of[...r.children])t(o)||o.remove()}const k7=e=>[{value:"inherit",label:e},{value:"on",label:l("支持")},{value:"off",label:l("不支持")}];function T7(e){const t=Jj(e);return l(t==="on"?"支持":t==="off"?"不支持":"未声明")}function hM(e,t,r,o,c=""){const d=t!=null,f=Of.includes(e)?Mf(t):T7(t);return r?o?l("已填写:对下游声明 {value}",{value:f}):l("已覆盖:对下游声明 {value}",{value:f}):o?l("未填写(下游按未声明处理)"):d?c==="modelsdev"?l("models.dev 补齐:对下游声明 {value}",{value:f}):l("继承上游:{value}",{value:f}):l("上游未声明(下游会按不支持处理)")}function E7(e,t,r){return r?vu.filter(o=>{const c=e[o];return c!=null}):t}function R7(e,t){const r={};for(const o of vu){const c=t.includes(o),d=e[o];Of.includes(o)?r[o]=c&&typeof d=="number"?String(d):"":r[o]=c?d===!0?"on":"off":"inherit"}return r}function A7({context:e,onClose:t}){const r=Qn(e.provider),o=pM(e.provider,e.id),c=UG(o),d=Wj(o),f=E7(d,Zj(o?.capOverrides),r),[p,g]=x.useState(()=>R7(d,f)),[v,y]=x.useState(""),[b,j]=x.useState(!1);if(!o)return s.jsx(Kt,{open:!0,onOpenChange:D=>{D||t()},children:s.jsxs(Yt,{children:[s.jsx(Ft,{children:s.jsx($t,{children:l("模型能力")})}),s.jsx(Ht,{children:s.jsx("p",{className:"text-sm leading-[1.7] text-subtle",children:l("这一行已不在当前清单里(模型被移除、或目录刷新后上游不再提供它)。关闭后刷新列表再试。")})}),s.jsxs(sn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:l("关闭")})]})]})});const w=o.id,S=o.providerLabel||hw(e.provider),N=l(r?"未声明":"继承上游"),C=l(r?"清除":"恢复继承");function E(D){const I=d[D];return R(D)?"":r?l("未填写"):typeof I=="number"?l("继承上游 {value}",{value:Mf(I)}):l("上游未声明")}function R(D){return f.includes(D)}function k(D,I){g(M=>({...M,[D]:I}))}async function A(){if(!b){for(const D of Of){const I=p[D].trim();if(I&&Qj(D,I)===null){y(l("{label}要填 1 ~ 1 亿之间的整数(留空 = {inherit})",{label:yu[D],inherit:N}));return}}j(!0),y(l("保存中…"));try{Vi(await f7(e.provider,e.id,FG(p))),t(),vr(l("✅ 已保存 {id} 的能力位({provider})",{id:w,provider:S}))}catch(D){y(l("保存失败:{message}",{message:No(D)})),j(!1)}}}return s.jsx(Kt,{open:!0,onOpenChange:(D,I)=>{if(!D){if(b){I.cancel();return}t()}},children:s.jsxs(Yt,{children:[s.jsx(Ft,{children:s.jsx($t,{children:l("模型能力")})}),s.jsxs(Ht,{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}),l("({provider})",{provider:S})]}),Of.map(D=>s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-[7px]",children:[s.jsx(tt,{htmlFor:`cap-${D}`,children:yu[D]}),R(D)?s.jsx(se,{variant:"ghost",size:"2xs",disabled:b,title:l(r?"清除这一项(回到未声明)":"清除覆盖,回到上游声明值"),onClick:()=>k(D,""),children:C}):null]}),s.jsx(Ke,{id:`cap-${D}`,inputMode:"numeric",autoComplete:"off",spellCheck:!1,placeholder:E(D),disabled:b,value:p[D],onChange:I=>k(D,I.currentTarget.value),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),A())}}),s.jsx("p",{className:"text-xs leading-[1.6] text-subtle",children:hM(D,d[D]??null,R(D),r,ju(o,D))})]},D)),_O.map(D=>s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(tt,{children:yu[D]}),s.jsx(Gn,{options:k7(N),value:p[D],"aria-label":yu[D],className:"self-start",onValueChange:I=>k(D,String(I))}),s.jsx("p",{className:"text-xs leading-[1.6] text-subtle",children:hM(D,d[D]??null,R(D),r,ju(o,D))})]},D)),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:l("可配思考档位")}),s.jsx("span",{className:"font-mono text-[12px] text-primary-fg",children:c.levels.join(" / ")}),c.defaultLevel?s.jsxs("span",{children:[l("(默认 "),s.jsx("span",{className:"font-mono text-[12px] text-primary-fg",children:c.defaultLevel}),l(")")]}):null]}),s.jsx("div",{className:"mt-1",children:l("这是模型自己能配的档位(来自上游目录),只读;要改某一档请到映射弹窗里选。")})]}):null,s.jsxs("p",{className:"text-xs leading-[1.65] text-subtle",children:[l("这几项是给"),s.jsx("b",{children:l("下游客户端")}),l("看的能力声明("),s.jsx("code",{children:"/v1/models"}),l(" 里的 "),s.jsx("code",{children:"max_input_tokens"})," / ",s.jsx("code",{children:"supports_*"}),l(" 与 "),s.jsx("code",{children:"input_modalities"}),l("),下游按它们决定发不发图片、按多大的窗口堆历史。"),s.jsx("b",{children:l("不影响网关的转发与路由")}),l("。上游清单给的值不准时,在这里改;"),l(r?"这家的清单是你自己登记的,不填的项下游按未声明处理。":"「恢复继承」会把这一项交还给上游清单的值。")]}),s.jsx("div",{className:"min-h-[18px] text-xs text-subtle",children:v})]}),s.jsxs(sn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:b,onClick:t,children:l("取消")}),s.jsx(se,{variant:"default",disabled:b,onClick:()=>{A()},children:l("保存")})]})]})})}function $f(){return window}const O7="你好",gM=4e3,M7=[{value:"chat_completions",label:"OpenAI - Chat Completions"},{value:"responses",label:"OpenAI - Responses"},{value:"anthropic",label:"Anthropic - Messages"}],D7={chat_completions:"Chat Completions",responses:"Responses",anthropic:"Anthropic Messages"},I7="direct",P7={remote:l("远程目录"),builtin:l("内置清单"),manual:l("手动登记")},_7=[{test:e=>e===429,hint:l("该账号对这个模型正在限额冷却,等一会儿自己会好;也可以先测别的账号。")},{test:e=>e===401||e===403,hint:l("上游拒绝了这条登录态:重新登录一次,或把这条账号删掉。")},{test:e=>e===404,hint:l("上游不认识这个模型名:先点「获取模型」刷新清单,或核对默认绑定指向的上游模型。")},{test:e=>e===504,hint:l("上游没在预算内给完回答。可以只勾一个账号再测一次,看是普遍慢还是某一个账号慢。")},{test:e=>e>=500,hint:l("多半是上游自己的问题,过一会儿再试。同一个错误出现在所有账号上时,先查模型目录与映射。")}];function xM(){return $f().wbApp?.getState?.()?.accounts?.accounts||[]}function bM(e){return xM().filter(t=>(t.provider||nu)===e&&t.available!==!1&&t.enabled!==!1).sort(Ch)}function vM(e){const t=String(e.email||"").trim();return t&&lr(e.provider).emailAsName?t:ru(e)||t||l("未命名账号")}function L7(){const e=globalThis.crypto?.randomUUID?.();if(e)return e;const t=r=>Array.from({length:r},()=>Math.floor(Math.random()*16).toString(16)).join("");return`${t(8)}-${t(4)}-4${t(3)}-a${t(3)}-${t(12)}`}function xw(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 z7(e,t){return bM(e).length?"":l("该提供商没有可用账号(要在账号页启用一个、且凭证完整),一行都发不出去")}function yM({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 B7({open:e,label:t,text:r,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:r})}):null]})}function H7(e){const[t,r]=x.useState(()=>Date.now());return x.useEffect(()=>{if(!e)return;r(Date.now());const o=window.setInterval(()=>r(Date.now()),400);return()=>window.clearInterval(o)},[e]),t}function jM(e){if(e.transport||!e.result||e.result.error)return!1;const t=Number(e.result.status)||0;return t>=200&&t<300}function U7({target:e,onClose:t}){const r=e.provider,o=pM(r,e.id),c=bM(r),d=Vy(xM()),[f,p]=x.useState(""),[g,v]=x.useState(O7),[y,b]=x.useState("chat_completions"),[j,w]=x.useState(""),[S,N]=x.useState(null),[C,E]=x.useState(""),[R,k]=x.useState(""),[A,D]=x.useState(!0),[I,M]=x.useState(()=>{const K=c.find(be=>!uf(be,e.id))||c[0];return K?[K.id]:[]}),[O,_]=x.useState([]),[L,z]=x.useState(()=>new Set),U=x.useRef(0),B=x.useRef([]);B.current=O;const Q=O.some(K=>K.state==="running"),W=H7(Q);x.useEffect(()=>{let K=!0;return(async()=>{try{const be=$f().workbuddyDesktop?.getProxyPool;if(typeof be!="function")throw new Error(l("当前环境不支持代理池"));const ne=await be();if(!K)return;if(!ne||typeof ne!="object"||!Array.isArray(ne.items))throw new Error(l("代理池响应异常"));N(ne.items),E("")}catch(be){if(!K)return;N([]),E(No(be))}})(),()=>{K=!1}},[]);const Z=x.useCallback((K=!1)=>{const be=B.current.filter(ne=>ne.state==="running");U.current+=1;for(const ne of be)$f().workbuddyDesktop?.terminateStatsRequest?.(ne.testId)?.catch(()=>{});_([]),be.length&&!K&&vr(l("已中止在途测试({n} 个账号)",{n:be.length}))},[]);x.useEffect(()=>()=>{Z(!0)},[Z]);async function Y(K,be){const ne={provider:r,model:e.id,account_id:K.accountId,prompt:g.trim(),system_prompt:f.trim(),reasoning:R,stream:A,protocol:y,...j?{proxy:j}:{},test_id:K.testId},ce=we=>{U.current===be&&_(Ee=>Ee.map(ve=>ve.testId===K.testId?{...ve,...we}:ve))};try{const we=await $f().workbuddyDesktop?.testModel(ne);if(!we){ce({state:"done",transport:l("桥接调用返回空(本机网关没有响应这次测试)")});return}ce({state:"done",result:we})}catch(we){ce({state:"done",transport:No(we)})}}function q(){const K=c.filter(we=>I.includes(we.id));if(!K.length){vr(l("至少选一个测试账号"),"err");return}const be=U.current+1;U.current=be;const ne=Date.now(),ce=K.map(we=>({accountId:we.id,label:vM(we),position:d.get(we.id)?.position||0,testId:L7(),startedAt:ne,state:"running"}));z(new Set),_(ce);for(const we of ce)Y(we,be)}function G(){Q?Z():_([])}const $=s.jsx("span",{className:"ml-2 font-mono text-[12px] font-normal text-subtle",children:e.id});if(!o)return s.jsx(Kt,{open:!0,onOpenChange:K=>{K||t()},children:s.jsxs(Yt,{children:[s.jsx(Ft,{children:s.jsx($t,{children:l("测试模型")})}),s.jsx(Ht,{children:s.jsx("p",{className:"text-sm leading-[1.7] text-subtle",children:l("这一行已不在当前清单里(模型被移除、或目录刷新后上游不再提供它)。关闭后刷新列表再试。")})}),s.jsxs(sn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:l("关闭")})]})]})});const F=Nu(o).find(K=>K.isDefault)?.enabled===!1,X=gw(o.id,o.id,r),re=Nu(o).filter(K=>!K.isDefault).map(K=>K.alias),P=If(_f().data,o).filter(K=>K!=="off"&&K!=="none"),V=F?l("跟随映射(该行未启用,本次不注入)"):X?l("跟随映射(当前 {level})",{level:X}):l("跟随映射(未绑定等级)"),J=[l("以模型本名直发"),re.length?l("另有 {n} 条别名映射({aliases}),别名不参与本次",{n:re.length,aliases:re.join(l("、"))}):"",F?l("该行当前未启用:测试照常按本名直发(「先测通、再决定要不要启用」正是这颗按钮的用法),但本行的思考等级绑定不参与本次,生产路由也要等绑定打开后才会放行"):X?l("映射上绑定的思考等级是 {level},「跟随映射」按它注入",{level:X}):l("映射上未绑定思考等级,「跟随映射」等于这次不注入")].filter(Boolean).join(l(";"))+l("。"),ie=$f().wbProviders?.PROTOCOL_OPTIONS||M7,me=ie.find(K=>K.value===y)?.label||y,he=[{value:"",label:l("跟随账号配置")},{value:I7,label:l("直连(不使用代理)")},...(S??[]).map(K=>({value:`${Ga}${K.id}`,label:lf(K)}))];S===null?he.push({value:"__hint_pool__",label:l("正在读取代理列表…"),disabled:!0}):S.length||he.push({value:"__hint_pool__",label:l(C?"代理列表读取失败":"还没有代理(去「网络代理」页添加)"),disabled:!0});const ae=he.find(K=>K.value===j)?.label||l("跟随账号配置"),oe=c.map(K=>({value:K.id,label:`#${d.get(K.id)?.position||0} ${vM(K)}`+(uf(K,e.id)?l(" · 限额中"):"")}));function ee(K){const be=(Ce,ke)=>s.jsxs("div",{className:"flex items-center gap-2.5 border-b border-hairline px-3 py-2",children:[Ce,s.jsx("b",{className:"min-w-0 truncate text-[12.5px] text-foreground",title:K.label,children:K.label}),K.position?s.jsxs("span",{className:"flex-none text-xs text-subtle",children:["#",K.position]}):null,s.jsx("span",{className:"ml-auto flex-none font-mono text-[11.5px] tabular-nums text-subtle",children:ke})]},"head");if(K.state==="running"){const Ce=(W-K.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(Fd,{className:"flex-none"}),s.jsxs("span",{className:"min-w-0 truncate",children:[l("账号 "),s.jsx("b",{className:"text-foreground",children:K.label}),l(" 已发出,等待上游首帧…")]}),s.jsx("span",{className:"ml-auto flex-none font-mono tabular-nums",children:l("已等待 {seconds}s",{seconds:Ce.toFixed(1)})})]},K.testId)}const ne=K.result;if(!jM(K)){const Ce=Number(ne?.status)||0,ke=_7.find(Se=>Se.test(Ce))?.hint??(K.transport?l("确认桌面端还在运行,再重试一次。"):"");return s.jsxs("div",{className:"rounded-md border border-border bg-surface-2",children:[be(s.jsx(ze,{shape:"tag",variant:"destructive",className:"flex-none",children:Ce||l("失败")}),l("用时 {time}",{time:xw(ne?.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:[K.transport?s.jsxs(s.Fragment,{children:[s.jsx("b",{className:"text-destructive",children:l("本机网关没有返回结论")}),l(":"),K.transport]}):s.jsxs(s.Fragment,{children:[s.jsx("b",{className:"text-destructive",children:l("测试未通过")}),l(":"),ne?.error||l("上游没有给出可读的错误说明")]}),Number(ne?.attempts)>1?l("(中间共尝试 {n} 次)",{n:Number(ne?.attempts)}):""]}),ke?s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:ke}):null]})]},K.testId)}const ce=String(ne?.reply??""),we=String(ne?.reasoning??""),Ee=`think-${K.testId}`,ve=[ne?.upstream_model&&ne.upstream_model!==e.id?l("上游 {model}",{model:ne.upstream_model}):"",ne?.upstream_reasoning?l("思考等级 {level}",{level:ne.upstream_reasoning}):"",ne?.protocol&&ne.protocol!=="chat_completions"?D7[ne.protocol]||ne.protocol:"",ne?.proxy?l("节点 {proxy}",{proxy:ne.proxy}):"",Number(ne?.attempts)>1?l("尝试 {n} 次",{n:Number(ne?.attempts)}):""].filter(Boolean).join(" · ");return s.jsxs("div",{className:"rounded-md border border-border bg-surface-2",children:[be(s.jsx(ze,{shape:"tag",variant:"success",className:"flex-none",children:Number(ne?.status)||200}),l("用时 {time} · 首字 {ttfb}",{time:xw(ne?.duration_ms),ttfb:xw(ne?.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:l("回复")}),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":ce,children:l("复制")})]}),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:ce||s.jsx("span",{className:"text-subtle",children:l("(上游这一次返回了空正文)")})}),we?s.jsx(B7,{open:L.has(Ee),label:l("思考过程({n} 字)",{n:we.length}),text:we,onToggle:()=>z(Ce=>{const ke=new Set(Ce);return ke.has(Ee)?ke.delete(Ee):ke.add(Ee),ke})}):null]})]},K.testId)}function de(){if(Q){const be=O.length-O.filter(ne=>ne.state==="running").length;return s.jsxs(s.Fragment,{children:[O.length>1?s.jsxs("p",{className:"text-xs text-subtle",children:[l("正在测 "),s.jsx("b",{className:"text-foreground",children:O.length}),l(" 个账号"),be?s.jsxs(s.Fragment,{children:[l(",已完成 "),s.jsx("b",{className:"text-foreground",children:be})]}):null,l("。")]}):null,O.map(ne=>ee(ne))]})}const K=O.filter(jM).length;return s.jsxs(s.Fragment,{children:[O.length>1?s.jsxs("p",{className:"text-xs text-subtle",children:[s.jsx("b",{className:K?"text-success":"text-foreground",children:K}),l(" 成功 ·"),s.jsxs("b",{className:O.length-K?"text-destructive":"text-foreground",children:[" ",O.length-K]}),l(" 失败")]}):null,O.map(be=>ee(be)),K===0?s.jsxs(yM,{children:[l("两边原因不一样时各自处理。如果"),s.jsx("b",{className:"text-foreground",children:l("同一条错误出现在所有账号上")}),l(",通常就不是账号问题了:先确认这个模型还在上游目录里(「获取模型」刷一次),再看默认绑定指向的上游模型对不对。")]}):null]})}return s.jsx(Kt,{open:!0,onOpenChange:K=>{K||t()},children:s.jsxs(Yt,{children:[s.jsx(Ft,{children:s.jsxs($t,{children:[l("测试模型"),$]})}),s.jsxs(Ht,{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:hw(r)}),s.jsx(ze,{shape:"tag",variant:"outline",children:Qn(r)?l("自定义家"):P7[o.source]||l("来源未知")}),s.jsxs(Ri,{children:[s.jsx(Ai,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":l("本次测试的发送口径")}),children:"?"}),s.jsx(Oi,{children:J})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(tt,{htmlFor:"model-test-system",children:l("系统提示词")}),s.jsx($d,{id:"model-test-system",rows:2,maxLength:gM,placeholder:l("留空则不携带;设置页的提示词模式照常生效"),value:f,onChange:K=>p(K.currentTarget.value)})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(tt,{htmlFor:"model-test-prompt",children:l("用户提示词")}),s.jsx($d,{id:"model-test-prompt",rows:2,maxLength:gM,placeholder:l("留空用默认问候「你好」"),value:g,onChange:K=>v(K.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(tt,{htmlFor:"model-test-protocol",children:l("对话协议")}),s.jsxs(Ri,{children:[s.jsx(Ai,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":l("对话协议的说明")}),children:"?"}),s.jsx(Oi,{children:l("按所选网关对话协议组装请求并校验响应转换(Chat Completions / Responses / Anthropic Messages)。")})]})]}),s.jsxs(ct,{value:y,onValueChange:K=>b(String(K)),children:[s.jsx(dt,{id:"model-test-protocol",className:"w-full",children:s.jsx(ut,{className:"min-w-0 truncate",children:me})}),s.jsx(ft,{children:ie.map(K=>s.jsx(Ye,{value:K.value,children:K.label},K.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(tt,{htmlFor:"model-test-proxy",children:l("测试节点")}),s.jsxs(Ri,{children:[s.jsx(Ai,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":l("测试节点的说明")}),children:"?"}),s.jsx(Oi,{children:l("仅本次测试临时生效,不修改账号保存的代理配置。可选「网络代理」页里的节点或强制直连。")})]})]}),s.jsxs(ct,{value:j,onValueChange:K=>w(String(K)),children:[s.jsx(dt,{id:"model-test-proxy",className:"w-full",children:s.jsx(ut,{className:"min-w-0 truncate",children:ae})}),s.jsx(ft,{children:he.map(K=>s.jsx(Ye,{value:K.value,disabled:K.disabled,children:K.label},K.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(tt,{htmlFor:"model-test-reasoning",children:l("思考等级")}),s.jsxs(ct,{value:R,onValueChange:K=>k(String(K)),children:[s.jsx(dt,{id:"model-test-reasoning",className:"w-full",children:s.jsx(ut,{children:R?l("{level}(本次指定)",{level:R}):V})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"",children:V}),P.map(K=>s.jsx(Ye,{value:K,children:l("{level}(本次指定)",{level:K})},K))]})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(tt,{htmlFor:"model-test-stream",children:l("流式请求")}),s.jsxs(Ri,{children:[s.jsx(Ai,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":l("流式请求的说明")}),children:"?"}),s.jsx(Oi,{children:l("默认开,与真实请求一致:可同时验证 SSE 链路与首字延迟。")})]})]}),s.jsx(Rs,{id:"model-test-stream",checked:A,onCheckedChange:K=>D(!!K)})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(tt,{htmlFor:"model-test-accounts",children:l("测试账号")}),s.jsxs(Ri,{children:[s.jsx(Ai,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":l("测试账号的说明")}),children:"?"}),s.jsx(Oi,{children:l("勾几个就并行测几次;默认选队列里最靠前的一个。")})]}),s.jsx(se,{variant:"ghost",size:"xs",className:"ml-auto",disabled:!c.length||I.length===c.length,onClick:()=>M(c.map(K=>K.id)),children:l("全选({n})",{n:c.length})})]}),s.jsx(My,{id:"model-test-accounts",value:I,onValueChange:M,options:oe,placeholder:l("选一个账号(至少一个)"),searchPlaceholder:l("搜索账号…"),emptyHint:l("这家没有可用账号(要在账号页启用一个、且凭证完整)")})]}),s.jsx(yM,{plain:!0,children:l("真实链路 · 消耗少量额度 · 日志带「测试」标记,不计报表")})]}),s.jsxs(sn,{className:"justify-end",children:[s.jsx(se,{variant:"outline",onClick:t,children:l("关闭")}),s.jsx(se,{variant:"default",disabled:!I.length||!c.length,onClick:q,children:l("开始测试")})]}),s.jsx(Kt,{open:O.length>0,onOpenChange:K=>{K||G()},children:s.jsxs(Yt,{overlayForceRender:!0,className:"w-[min(680px,calc(100vw-48px))]",children:[s.jsx(Ft,{children:s.jsxs($t,{children:[l(Q?"测试中…":"测试结果"),$]})}),s.jsx(Ht,{children:de()}),s.jsx(sn,{className:"justify-end",children:Q?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mr-auto text-xs text-subtle",children:l("关闭即中止")}),s.jsx(se,{variant:"outline",onClick:()=>Z(),children:l("中止测试")}),s.jsx(se,{variant:"default",disabled:!0,children:l("测试中…")})]}):s.jsxs(s.Fragment,{children:[s.jsx(se,{variant:"outline",onClick:G,children:l("关闭")}),s.jsx(se,{variant:"default",onClick:q,children:l("再测一次")})]})})]})})]})})}const wM=[{value:"enable",label:l("启用")},{value:"disable",label:l("禁用")},{value:"reasoning",label:l("设置思考等级")},{value:"delete",label:l("删除")}];function SM(e){return e.source==="manual"||Qn(e.provider)}function V7(e){return(e.name&&e.name!==e.id?l("{name}({id})",{name:e.name,id:e.id}):e.id)||e.id}function $7({models:e,onClose:t,onDone:r}){const[o,c]=x.useState("enable"),d=XG(_f().data,e),[f,p]=x.useState(()=>({select:d[0]||"",custom:""})),[g,v]=x.useState(!1),[y,b]=x.useState(""),j=f.select===la?f.custom.trim():f.select,w=e.filter(SM).length,S=wM.find(E=>E.value===o)?.label||l("操作");async function N(E){return Promise.resolve(qt().wbConfirm?.ask?.({title:l("删除选中的模型"),html:l("确定删除选中的 {count} 个模型登记?删除后 /v1/models 不再广告它们、请求也会被拒。",{count:E})+(e.length>E?"
"+l("另有 {n} 个非手动登记的模型将被跳过。",{n:e.length-E}):""),okText:l("删除"),okClass:"danger"})??!1)}async function C(){if(g)return;if(!e.length){vr(l("没有选中的模型"),"err");return}if(o==="reasoning"&&f.select===la&&!j){b(s.jsx("span",{className:"text-destructive",children:l("请填写自定义思考等级,或改选候选档 / 「清除」")}));return}if(o==="delete"){if(w===0){b(s.jsx("span",{className:"text-destructive",children:l("选中的模型都不是手动登记,无法删除(开关映射才是它们的手段)")}));return}if(!await N(w))return}v(!0),b("");let E=0,R=0,k=0,A="";for(const D of e){const I=D.provider||"";try{if(o==="delete"){if(!SM(D)){R+=1;continue}Vi(await uM(I,D.id))}else if(o==="enable"||o==="disable"){const M=o==="enable";for(const O of Nu(D))Vi(await kg(I,O.alias,D.id,{enabled:M}))}else for(const M of Nu(D))Vi(await kg(I,M.alias,D.id,{reasoning:j}));E+=1}catch(M){k+=1,A||(A=No(M)),b(s.jsx("span",{className:"text-destructive",children:l("失败 {n} 个 · 首个失败:{error}",{n:k,error:A})}))}}k===0?(vr(R?l("✅ 批量{action}完成:共 {n} 个模型(跳过不可删除的 {skipped} 个)",{action:S,n:E,skipped:R}):l("✅ 批量{action}完成:共 {n} 个模型",{action:S,n:E})),r()):(vr(l("批量{action}完成:成功 {ok} 个,失败 {failed} 个",{action:S,ok:E,failed:k}),"err"),b(s.jsxs("span",{className:"text-destructive",children:[l("成功 {ok} 个,失败 {failed} 个",{ok:E,failed:k}),R?l(",跳过 {n} 个",{n:R}):"",A?l(";首个失败:{error}",{error:A}):""]}))),v(!1)}return s.jsx(Kt,{open:!0,onOpenChange:E=>{E||g||t()},children:s.jsxs(Yt,{children:[s.jsx(Ft,{children:s.jsx($t,{children:l("批量操作 · 已选 {n} 个模型",{n:e.length})})}),s.jsxs(Ht,{children:[s.jsxs(zn,{children:[s.jsx("h3",{children:l("将作用于以下模型")}),s.jsx("p",{style:{maxHeight:84,overflowY:"auto"},children:e.map(V7).join(l("、"))})]}),s.jsxs(zn,{children:[s.jsx("h3",{children:l("操作")}),s.jsx(ch,{value:o,onValueChange:E=>c(E),className:"flex-row flex-wrap items-center gap-5","aria-label":l("批量动作"),children:wM.map(E=>s.jsxs(tt,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(Mi,{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:l("思考等级")}),s.jsxs(ct,{value:f.select,onValueChange:E=>p(R=>({...R,select:String(E)})),children:[s.jsx(dt,{id:"batch-model-reasoning",className:"min-w-[220px]",children:s.jsx(ut,{children:f.select===la?l("自定义等级…"):f.select||l("清除(不覆盖)")})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"",children:l("清除(不覆盖)")}),d.map(E=>s.jsx(Ye,{value:E,children:E},E)),s.jsx(Ye,{value:la,children:l("自定义等级…")})]})]})]}),f.select===la?s.jsxs("div",{className:"field-row mt-2",children:[s.jsx("label",{htmlFor:"batch-model-reasoning-custom",children:l("自定义等级")}),s.jsx(Ke,{id:"batch-model-reasoning-custom",maxLength:32,value:f.custom,onChange:E=>p(R=>({...R,custom:E.currentTarget.value}))})]}):null,s.jsxs("p",{className:"detail mt-1.5",children:[l("设置 / 清除会应用到选中模型的"),s.jsx("b",{children:l("全部映射")}),l("(默认绑定与别名 chips);「清除」= 不给这些映射指定等级(选「不覆盖」的口径与映射弹窗一致)")]})]}):null,o==="delete"?s.jsx("p",{className:"detail mt-2",children:w===0?l("选中的都不是手动登记的模型,删除不可用(上游目录带回来的行由清单决定存在性)"):l("可删除 {n} 个(手动登记 / 自定义家);",{n:w})+(e.length>w?l("其余 {n} 个会被跳过。",{n:e.length-w}):"")}):null]}),s.jsx("div",{className:"detail",style:{minHeight:18},children:y})]}),s.jsxs(sn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:g,onClick:t,children:l("关闭")}),s.jsx(se,{variant:o==="delete"?"destructive":"default",disabled:g,onClick:()=>{C()},children:g?l("执行中…"):l("执行{action}",{action:S})})]})]})})}function Js(){return window}const NM={intl:"fm-table-intl",custom:"fm-table-custom"},CM={intl:"fetch-models",custom:"fetch-models-custom"},bw=["provider","source","state","count","note","updated","op"],vw=["pick","model","state"],F7={provider:"w-[13%]",source:"w-[21%]",state:"w-[9%]",count:"w-[6%]",note:"w-[20%]",updated:"w-[16%]",op:"w-[15%]"},q7={pick:"w-[8%]",model:"w-[74%]",state:"w-[18%]"},G7={pick:"",provider:l("提供商"),source:l("模型来源"),state:l("状态"),count:l("模型数"),note:l("说明"),updated:l("更新日期"),model:l("上游模型"),op:l("操作")},K7={refreshed:{variant:"brand",label:l("已刷新")},failed:{variant:"destructive",label:l("失败")},skipped:{variant:"outline",label:l("跳过")}},kM=new Set(["cline-free","cline-pass"]),TM="workbuddy-desktop-fetch-model-source";function Ff(e){return String(e??"").trim().toLowerCase()}function yw(e,t){Js().wbApp?.toast?.(e,t)}function jw(e){return e instanceof Error?e.message:String(e)}function EM(e){const t=Js().formatTime??Js().wbApp?.formatTime;return String(t?.(e)??"")}function RM(){return Js().wbApp?.getState?.()?.accounts?.accounts||[]}function Y7(e){const r=(Js().wbProviders?.customList?.()||[]).find(o=>o.id===e)?.models;return new Set((Array.isArray(r)?r:[]).map(o=>Ff(o?.id)).filter(Boolean))}function AM(e){if(e?.nameCustom===!0&&e?.name)return e.name;const t=String(e?.email||"").trim();return Js().wbAccountsModel?.providerFeatures?.(e?.provider)?.emailAsName&&t?t:String(e?.nickname||e?.name||t||e?.id||"").trim()||l("未命名账号")}function X7(e){if(kM.has(e))return[];const t=Js().wbAccountsModel?.byPriorityOrder,r=RM().filter(o=>(o?.provider||"workbuddy")===e&&o?.available!==!1&&o?.enabled!==!1);return t?r.sort(t):r}function OM(){const e=new Set(Js().wbModelsPanel?.builtinProviders?.()||[]);for(const t of RM())t?.available===!1||t?.enabled===!1||e.add(t?.provider||"workbuddy");return[...e]}function Q7(){const e=new Set(OM());return(Js().wbProviders?.all?.()||[]).filter(t=>e.has(t?.id??""))}function Z7(e){return EM(Number(e.refreshedAt)||0)||"—"}function W7(e){return K7[String(e.status)]??{variant:"outline",label:String(e.status||l("未知"))}}function J7(){try{const e=JSON.parse(localStorage.getItem(TM)||"{}");if(!e||typeof e!="object")return{};const t={};for(const[r,o]of Object.entries(e))typeof o=="string"&&o&&(t[r]=o);return t}catch{return{}}}function eK(e){Js().wbFilterMemory?.save?.(TM,e)}function tK({options:e,onClose:t}){const r=e.providerId,o=!!e.custom,c=e.name||r,{onDone:d,onRefreshed:f}=e,[p,g]=x.useState("idle"),[v,y]=x.useState(""),[b,j]=x.useState(""),[w,S]=x.useState(null),[N,C]=x.useState(""),E=w!==null,[R,k]=x.useState(!1),[A,D]=x.useState([]),[I,M]=x.useState(()=>new Set),[O,_]=x.useState(()=>new Set),[L,z]=x.useState([]),[U,B]=x.useState(""),[Q,W]=x.useState(J7);x.useEffect(()=>{Js().wbTableColumns?.repaint?.(o?CM.custom:CM.intl)},[o]);const Z=o?[]:Q7(),Y=o?[]:F(),q=U.trim().toLowerCase(),G=A.filter(ve=>!q||ve.toLowerCase().includes(q)),$=o?R?l("已选 {picked} 个 · 上游共 {upstream} 个 · 清单已有 {managed} 个",{picked:O.size,upstream:A.length,managed:I.size}):l("尚未获取"):X(Y);function F(){const ve=new Map(L.map(Se=>[String(Se.provider||""),Se])),Ce=Z.map(Se=>{const ge=String(Se.id||"");return{provider:ge,label:String(Se.label||ge),item:ve.get(ge)}}),ke=new Set(Ce.map(Se=>Se.provider));for(const Se of L){const ge=String(Se.provider||"");ke.has(ge)||Ce.push({provider:ge,label:String(Se.providerLabel||ge),item:Se})}return Ce}function X(ve){if(p==="loading")return l("正在刷新…");if(p==="error")return"";const Ce=ve.map(ge=>ge.item).filter(ge=>!!ge);if(!Ce.length)return R?l("刷新完成,但没有得到任何结果"):ve.length?l("共 {n} 家 · 点「获取模型」开始",{n:ve.length}):l("0 家");const ke=Ce.filter(ge=>ge.status==="refreshed").length,Se=Ce.filter(ge=>ge.status==="failed").length;return Se?l("{total} 家 · 成功 {done} · 失败 {failed}",{total:ve.length,done:ke,failed:Se}):l("{total} 家 · 成功 {done}",{total:ve.length,done:ke})}function re(ve,Ce){const ke=X7(ve);if(!ke.length)return{list:ke,selected:""};const Se=String(Q[ve]||""),ge=String(Ce||""),Te=Oe=>ke.some(Ne=>String(Ne.id)===Oe);return{list:ke,selected:Te(Se)?Se:Te(ge)?ge:String(ke[0].id)}}function P(ve){const Ce={};for(const[ke,Se]of Object.entries(Q))Se&&(Ce[ke]=Se);for(const ke of ve){const{selected:Se}=re(ke.provider,ke.reported);Se&&(Ce[ke.provider]=Se)}return Ce}const V=Y.map(ve=>({provider:ve.provider,reported:ve.item?.accountId}));function J(ve,Ce){W(ke=>({...ke,[ve]:Ce})),eK({[ve]:Ce})}async function ie(){if(!E){S("load"),j(""),y(""),g("loading");try{if(o){const Ce=await Js().wbProviders?.customRequest?.("POST","/api/custom-providers/fetch-models",{providerId:r}),ke=new Set,Se=(Array.isArray(Ce?.models)?Ce.models:[]).map(Te=>String(Te??"").trim()).filter(Te=>{const Oe=Ff(Te);return!Te||ke.has(Oe)?!1:(ke.add(Oe),!0)}),ge=Y7(r);D(Se),M(ge),_(new Set(Se.filter(Te=>!ge.has(Ff(Te))))),k(!0),g("ready");return}const ve=await Js().workbuddyDesktop?.refreshModels({accounts:P(V),providers:OM()});z(Array.isArray(ve?.results)?ve.results:[]),k(!0),g("ready"),Number(ve?.refreshed)>0&&f?.()}catch(ve){const Ce=jw(ve);y(Ce),g("error"),j(Ce)}finally{S(null)}}}async function me(ve){if(!(E||!ve.provider)){S("row"),C(ve.provider),j("");try{const Ce=await Js().workbuddyDesktop?.refreshModels({accounts:P([{provider:ve.provider,reported:ve.item?.accountId}]),providers:[ve.provider]});z(ke=>he(ke,Array.isArray(Ce?.results)?Ce.results:[])),k(!0),g("ready"),Number(Ce?.refreshed)>0&&f?.()}catch(Ce){const ke=jw(Ce);j(ke),yw(l("获取失败:{message}",{message:ke}),"err")}finally{S(null),C("")}}}function he(ve,Ce){const ke=new Map(Ce.map(Te=>[String(Te.provider||""),Te])),Se=ve.map(Te=>ke.get(String(Te.provider||""))??Te),ge=new Set(Se.map(Te=>String(Te.provider||"")));for(const Te of Ce)ge.has(String(Te.provider||""))||Se.push(Te);return Se}async function ae(){if(!o||E||!O.size)return;const ve=[...O];S("import"),j("");try{const Ce=Number(await Js().wbModelsCustom?.addModels?.(r,ve))||0;yw(l("✅ 已导入 {added} 个模型({skipped} 个已存在,跳过)",{added:Ce,skipped:ve.length-Ce})),S(null),t(),d?.()}catch(Ce){const ke=jw(Ce);yw(l("导入失败:{message}",{message:ke}),"err"),j(ke),S(null)}}function oe(){E||t()}function ee(){const ve=new Set(O);for(const Ce of A)I.has(Ff(Ce))||ve.add(Ce);_(ve)}function de(ve){return s.jsx(yl,{children:s.jsx(vn,{colSpan:o?vw.length:bw.length,className:"py-[26px] text-center text-muted-foreground",children:ve})})}function K(ve){return s.jsx("span",{className:"font-mono text-[11.5px] tabular-nums text-muted-foreground",children:ve})}function be(ve){return s.jsx("div",{className:"truncate font-mono text-[12px] font-semibold",children:ve})}function ne(ve,Ce){const{list:ke,selected:Se}=re(ve,Ce);if(!ke.length){const Te=kM.has(ve)?l("这家的模型清单是全局的,不跟账号走"):l("这家还没有可用账号,刷新会使用默认登录态");return s.jsx("span",{className:"text-[11.5px] text-muted-foreground",title:Te,children:"—"})}const ge=ke.find(Te=>String(Te.id)===Se);return s.jsxs(ct,{value:Se,onValueChange:Te=>J(ve,String(Te)),children:[s.jsx(dt,{className:"w-full",title:l("用哪个账号去拉这家的模型清单"),"aria-label":l("模型来源"),children:s.jsx(ut,{children:ge?AM(ge):"—"})}),s.jsx(ft,{children:ke.map(Te=>s.jsx(Ye,{value:String(Te.id),children:AM(Te)},String(Te.id)))})]})}function ce(){return p==="idle"?de(l("点右侧「获取模型」从上游拉取这家的模型清单")):p==="loading"?de(l("正在获取…")):p==="error"?de(l("获取失败:{message}",{message:v})):G.length?G.map(ve=>{const Ce=I.has(Ff(ve));return s.jsxs(yl,{className:Ce?"opacity-50":void 0,children:[s.jsx(vn,{children:s.jsx(ea,{checked:O.has(ve),disabled:Ce,"aria-label":ve,onCheckedChange:ke=>_(Se=>{const ge=new Set(Se);return ke?ge.add(ve):ge.delete(ve),ge})})}),s.jsx(vn,{children:be(ve)}),s.jsx(vn,{children:Ce?s.jsx(ze,{variant:"brand",title:l("这个模型已经在这家的清单里,不重复导入"),children:l("已添加")}):s.jsx(ze,{variant:"outline",title:l("勾上它,导入后即进入这家的清单"),children:l("未添加")})})]},ve)}):de(A.length?l("没有匹配「{keyword}」的模型",{keyword:q}):l("上游没有返回任何模型"))}function we(ve){const Ce=w==="row"&&N===ve.provider;return s.jsx(se,{variant:"outline",size:"sm",className:"w-full",disabled:E,title:l("只刷新这一家的模型清单"),onClick:()=>{me(ve)},children:Ce?l("获取中…"):ve.item?l("重新获取"):l("获取")})}function Ee(){return p==="loading"?de(l("正在获取…")):p==="error"?de(l("获取失败:{message}",{message:v})):Y.length?Y.map(ve=>{const Ce=ve.item;if(!Ce){const Te=EM(Number(Js().wbModelsPanel?.providerRefreshedAt?.(ve.provider))||0);return s.jsxs(yl,{children:[s.jsx(vn,{children:be(ve.label)}),s.jsx(vn,{children:ne(ve.provider)}),s.jsx(vn,{children:s.jsx(ze,{variant:"outline",children:l("待获取")})}),s.jsx(vn,{children:K("—")}),s.jsx(vn,{children:K("—")}),s.jsx(vn,{children:K(Te||"—")}),s.jsx(vn,{children:we(ve)})]},ve.provider)}const ke=W7(Ce),Se=Number(Ce.count),ge=Ce.status==="refreshed"?l("远程目录已更新,「来源」列会显示为「远程」"):Ce.message||(Ce.fixed?l("这家用固定模型清单,无可刷新"):l("本次没有取到新内容"));return s.jsxs(yl,{children:[s.jsx(vn,{children:be(ve.label)}),s.jsx(vn,{children:ne(ve.provider,Ce.accountId)}),s.jsx(vn,{children:s.jsx(ze,{variant:ke.variant,children:ke.label})}),s.jsx(vn,{children:K(Se?l("{n} 个",{n:Se}):"—")}),s.jsx(vn,{children:s.jsx("span",{className:"text-[11.5px] leading-[1.5] text-muted-foreground",children:ge})}),s.jsx(vn,{children:K(Z7(Ce))}),s.jsx(vn,{children:we(ve)})]},ve.provider)}):de(l("还没有可刷新的提供商:先在账号页添加一个账号"))}return s.jsx(Kt,{open:!0,onOpenChange:(ve,Ce)=>{if(!ve){if(E){Ce.cancel();return}t()}},children:s.jsxs(Yt,{className:o?"w-[min(552px,calc(100vw-48px))]":"w-[min(920px,calc(100vw-48px))]",children:[s.jsx(Ft,{children:s.jsx($t,{children:l("获取模型 — {name}",{name:c})})}),s.jsxs(Ht,{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:$}),o&&s.jsxs(ji,{className:"w-[240px] flex-none",children:[s.jsx(Si,{type:"search",placeholder:l("搜索模型 ID…"),autoComplete:"off",value:U,onChange:ve=>B(ve.currentTarget.value)}),s.jsx(wi,{"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:l("全选未添加")}),s.jsx(se,{variant:"ghost",size:"sm",onClick:()=>_(new Set),children:l("清空")})]}),s.jsx(se,{variant:"outline",size:"sm",title:l("刷新全部家(逐家打上游)"),disabled:E,onClick:()=>{ie()},children:l(w==="load"?"获取中…":R?"重新获取":"获取模型")})]}),s.jsxs(yy,{id:o?NM.custom:NM.intl,className:"table-fixed",containerClassName:"max-h-[min(48vh,460px)]",children:[s.jsx("colgroup",{children:(o?vw:bw).map(ve=>s.jsx("col",{"data-col":ve,className:o?q7[ve]:F7[ve]},ve))}),s.jsx(LT,{children:s.jsx(yl,{children:(o?vw:bw).map(ve=>s.jsx(zT,{"data-col":ve,children:G7[ve]},ve))})}),s.jsx(jy,{className:"[&_tr:last-child>td]:border-b-0",children:o?ce():Ee()})]})]}),s.jsxs(sn,{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:oe,children:l(o?"取消":"完成")}),o&&s.jsx(se,{variant:"default",disabled:!O.size||E,onClick:()=>{ae()},children:w==="import"?l("导入中…"):O.size?l("导入选中的 {n} 个模型",{n:O.size}):l("导入")})]})]})})}let qf=null,Cu=null;function MM(){qf&&(qf.unmount(),qf=null),Cu&&(Cu.remove(),Cu=null)}function nK(e){e?.providerId&&(MM(),Cu=document.createElement("div"),document.body.append(Cu),qf=jn.createRoot(Cu),qf.render(s.jsx(tK,{options:e,onClose:MM})))}window.wbModelsFetchModal={open:nK};const ko=(e,t)=>t?`${e} ta-${t}`:e;function DM(e,t){const r=(t||"").trim();if(r)return Bf().find(o=>Co(o.provider,e)&&Co(o.id,r))}const sK="[.pv-row:hover_&_[data-slot=nav-item-count]]:invisible";function rK(e){const t=/x\s*([\d.]+)/i.exec(String(e||""));return t?`${t[1]}x`:String(e||"")}function IM(e){const t=/x\s*([\d.]+)/i.exec(String(e||""));if(!t)return null;const r=Number(t[1]);return Number.isFinite(r)?r:null}const aK={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 lK(e){const t=aK[e];if(t!==void 0)return t;let r=0;for(let o=0;o>>0;return r%360}function oK(e){const t=String(e||"").trim();if(!t)return"?";const r=t.match(/[A-Za-z]/);return(r?r[0]:t[t.length-1]).toUpperCase()}const iK=e=>({"--av-h":String(lK(e))}),ww=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 cK(e){if(!e)return"";const t=qt().wbPresetProviders?.list;if(!Array.isArray(t))return"";const r=t.find(o=>o.name===e);return r&&qt().wbPresetProviders?.iconOf?.(String(r.key||""))||""}function uK(e,t){return Qn(e)?cK(t):Kh[e==="workbuddy-intl"?"workbuddy":e]||""}function ku(e,t,r){const o=r?"":uK(e,t),c=e==="all"||e==="custom-all";return s.jsx("span",{className:Ue("pv-ico",c&&"mute",o&&"img"),style:o?void 0:iK(e),"aria-hidden":"true",children:o?s.jsx("img",{src:o,alt:""}):r??oK(t)})}const dK={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 fK(e,t,r,o){return o==="enabled"&&!Uf(e)||o==="disabled"&&Uf(e)||o==="mapped"&&!(e.aliases||[]).length||r!=="all"&&(e.provider||"")!==r?!1:t?[e.id,e.name,...e.aliases||[]].join(" ").toLowerCase().includes(t):!0}function pK(){const e=x.useSyncExternalStore(n7,_f),t=wg(e),r=Qn(t)||t==="custom-all",[o,c]=x.useState(null),[d,f]=x.useState(!1),[p,g]=x.useState(new Set),v=r&&!Su()&&lw()&&!So(t);x.useEffect(()=>{c7(),Sg(),sM(),qt().wbApp?.currentPage==="gateway"&&cM().then(()=>qt().wbProviders?.refreshCustom?.()).then(()=>{Ui()})},[]),x.useEffect(()=>{C7()});const y=iw(),b=Array.isArray(y.models)?y.models:[],j=e.search.trim().toLowerCase(),w=b.filter(F=>fK(F,j,t,e.stateFilter)),S=e.sort,N=iM(),C=N.length,E=t==="all"?l("全部"):t==="custom-all"?l("自定义 · 全部"):r?String(So(t)?.name||t):cw().get(t)?.label||hw(t),R=b.filter(Uf).length,k=b.filter(F=>(F.aliases||[]).length>0).length,A=Vh(w.length,"models"),D=b.filter(F=>p.has($i(F))),I=(F,X)=>{const re=new Set(p);X?re.add(F):re.delete(F),g(re)},M=w.map($i),O=M.length>0&&M.every(F=>p.has(F)),_=M.some(F=>p.has(F)),L=s.jsx(ea,{checked:O,indeterminate:!O&&_,disabled:!M.length,"aria-label":l("全选当前筛选结果"),title:l("全选当前筛选出的模型(跨分页);再点取消"),onCheckedChange:F=>{const X=new Set(p);for(const re of M)F===!0?X.add(re):X.delete(re);g(X)}});function z(){const F=cw(),X=Bi(),re=a7(),P=[...F.values()].reduce((me,he)=>me+he.n,0),V=l("全部({n} 家)",{n:F.size}),J=[...re.values()].reduce((me,he)=>me+he.n,0),ie=l("全部({n} 家)",{n:[...re.values()].filter(me=>me.n>0).length});return s.jsxs("aside",{className:"prov-rail",id:"prov-rail","aria-label":l("按提供商选择"),children:[s.jsxs("div",{className:"rail-scroll",children:[s.jsx("div",{className:"rail-label",children:l("内置提供商")}),s.jsx(eu,{active:t==="all","data-provider":"all",title:V,count:P,icon:ku("all","",ww),className:"shadow-none",onClick:()=>Vf("all"),children:V}),[...F].map(([me,he])=>s.jsx(eu,{active:t===me,"data-provider":me,title:he.label,count:he.n,icon:ku(me,he.label),className:"shadow-none",onClick:()=>Vf(me),children:he.label},me)),s.jsx("div",{className:"rail-label",children:l("自定义提供商")}),X.length?[...J>0?[s.jsx(eu,{active:Su(),"data-provider":"custom-all",title:ie,count:J,icon:ku("custom-all","",ww),className:"shadow-none",onClick:()=>Vf("custom-all"),children:ie},"custom-all")]:[],...X.map(me=>{const he=String(me.id||""),ae=String(me.name||he);return s.jsxs("div",{className:"pv-row",children:[s.jsx(eu,{active:t===he,"data-provider":he,title:ae,count:re.get(he)?.n??0,icon:ku(he,ae),className:Ue("shadow-none",sK),onClick:()=>Vf(he),children:ae}),s.jsx("button",{type:"button",className:"pv-del","aria-label":l("删除自定义提供商"),title:l("删除这个自定义提供商(连同名下账号)"),onClick:()=>{b7(he)},children:"×"})]},he)})]:s.jsx("div",{className:"rail-empty",children:l("还没有自定义提供商")})]}),s.jsx("div",{className:"rail-foot",children:s.jsx(eu,{variant:"add",id:"rail-add-custom",title:l("新建一个自定义提供商(同时创建它的第一个账号)"),onClick:()=>v7(),children:l("+ 新建自定义提供商")})})]})}function U(F,X,re,P){const V=gw(F,X,re);return s.jsx(se,{variant:V?"secondary":"dashed",size:"2xs",disabled:P,className:"font-mono font-bold shadow-none",title:V?l("思考等级 {level}(点击修改)",{level:V}):l("设置思考等级(当前未绑定)"),onClick:()=>dM({alias:F,target:X,provider:re}),children:V||l("+等级")})}function B(F){const X=F.provider||"",re=Nu(F),[P,...V]=re;async function J(me){await qt().wbConfirm?.ask?.({title:l("删除映射"),html:l("确定删除映射「{alias} → {target}」?",{alias:ew(me),target:ew(F.id)}),okText:l("删除"),okClass:"danger"})&&pw(mw(me,F.id,X),()=>u7(X,me,F.id),l("映射已删除"))}const ie=me=>{const he=me.alias,ae=me.enabled!==!1,oe=e.pending.has(mw(he,F.id,X));return s.jsxs("span",{className:Ue("alias",!ae&&"map-off"),children:[s.jsx(Rs,{size:"sm",checked:ae,disabled:oe,title:l(ae?"映射已启用,点击关闭":"映射已关闭,点击启用"),"aria-label":l("{action}映射 {alias}",{action:l(ae?"关闭":"启用"),alias:he}),onCheckedChange:ee=>{pw(mw(he,F.id,X),()=>kg(X,he,F.id,{enabled:ee}),l(ee?"映射已启用":"映射已关闭"))}}),s.jsx("span",{className:"t","data-copy":he,title:l("点击复制:{name}",{name:he}),children:he}),me.isDefault?s.jsx("span",{className:"binding-default",children:l("默认")}):null,U(he,F.id,X,oe),me.isDefault?null:s.jsx(se,{variant:"ghost",size:"icon-2xs",className:"text-[12px] leading-none",disabled:oe,title:l("删除映射 {alias}",{alias:he}),onClick:()=>{J(he)},children:"×"})]},`${he}${me.isDefault?"d":"m"}`)};return s.jsxs("div",{className:"aliases",children:[s.jsxs("div",{className:"alias-row",children:[P?ie(P):null,s.jsx(se,{variant:"dashed",size:"xs",onClick:()=>dM({target:F.id,provider:X}),children:l("+ 映射")})]}),V.map(ie)]})}function Q(F){if(F.source==="manual")return s.jsxs("span",{className:"src manual",title:l("手动登记的上游模型;移除它会直接删掉这条登记"),children:[s.jsx("i",{"aria-hidden":"true"}),l("手动")]});if(!F.source&&Qn(F.provider))return s.jsxs("span",{className:"src manual",title:l("用户登记的自定义模型;整份清单只属于这一家"),children:[s.jsx("i",{"aria-hidden":"true"}),l("自定义")]});if(F.source!=="remote"&&F.source!=="builtin")return s.jsx("span",{className:"rate",children:"—"});const X=F.source==="remote",re=ZG(Number(F.refreshedAt)||0),P=X?re?l("来自上游目录接口,清单拉取于 {at};刷新失败时保留上一份成功结果",{at:re}):l("来自上游目录接口;刷新失败时保留上一份成功结果"):l("上游目录尚未拉到,用的是内置静态清单;点「刷新模型清单」可重试");return s.jsxs("span",{className:Ue("src",X?"remote":"builtin"),title:P,children:[s.jsx("i",{"aria-hidden":"true"}),l(X?"远程":"内置")]})}function W(F){const X=Wj(F),re=Zj(F.capOverrides),P=typeof X.maxInputTokens=="number"?X.maxInputTokens:null,V=typeof X.maxOutputTokens=="number"?X.maxOutputTokens:null,J=l("上下文窗口 {input} / 最大输出 Token {output} —— 点击修改模型能力",{input:Mf(P),output:Mf(V)})+Z(F);return s.jsxs("button",{type:"button",className:"caps-open",title:J,onClick:()=>fM(F.provider||"",F.id),children:[s.jsxs("span",{className:Ue("cap-num",P===null&&"unset",ju(F,"maxInputTokens")==="modelsdev"&&"filled"),children:[zO(P),re.includes("maxInputTokens")?s.jsx("i",{className:"cap-mark",title:l("已覆盖上游值")}):null]}),s.jsx("span",{className:"cap-sep",children:"/"}),s.jsxs("span",{className:Ue("cap-num",V===null&&"unset",ju(F,"maxOutputTokens")==="modelsdev"&&"filled"),children:[zO(V),re.includes("maxOutputTokens")?s.jsx("i",{className:"cap-mark",title:l("已覆盖上游值")}):null]})]})}function Z(F){const X=["maxInputTokens","maxOutputTokens"].filter(re=>ju(F,re)==="modelsdev").map(re=>yu[re]);return X.length?l(";其中 {keys} 由 models.dev 补齐",{keys:X.join(l("、"))}):""}function Y(F){const X=Wj(F),re=Zj(F.capOverrides);return s.jsx("button",{type:"button",className:"caps-open caps-badges",title:l("对下游声明的能力(工具调用 / 图片识别 / 视频识别 / 支持思考)—— 点击修改"),onClick:()=>fM(F.provider||"",F.id),children:_O.map(P=>{const V=X[P]??null,J=Jj(V),ie=re.includes(P),me=ju(F,P);return s.jsxs("span",{className:Ue("cap-dot",J,me==="modelsdev"&&"filled",ie&&"marked"),title:VG(P,V,ie,me),children:[dK[P],ie?s.jsx("i",{className:"cap-mark"}):null]},P)})})}function q(F,X,re){async function P(){await qt().wbConfirm?.ask?.({title:l("移除自定义模型"),html:l("确定移除自定义模型「{id}」?这条登记会被直接移除,之后 /v1/models 不再广告它、请求它也会被拒。",{id:ew(X.id)}),okText:l("移除"),okClass:"danger"})&&pw($i(X),()=>uM(X.provider||"",X.id),Qn(X.provider||"")?l("模型已移除"):l("自定义模型已移除"))}switch(F.key){case"check":return s.jsx("td",{className:ko("cell-check",F.align),children:s.jsx(ea,{checked:p.has($i(X)),title:l("勾选后可批量操作"),"aria-label":l("勾选后可批量操作"),onCheckedChange:V=>I($i(X),V===!0)})});case"model":return s.jsxs("td",{className:ko("cell-model",F.align),children:[s.jsx("div",{className:"mid",children:s.jsx("span",{className:"t","data-copy":X.id,title:l("点击复制:{name}",{name:X.id}),children:X.id})}),X.name&&X.name!==X.id?s.jsx("div",{className:"mname",children:X.name}):null]});case"rate":return s.jsx("td",{className:ko("cell-rate",F.align),children:s.jsx("span",{className:"rate",children:X.credits?rK(X.credits):"—"})});case"source":return s.jsx("td",{className:ko("cell-source",F.align),children:Q(X)});case"budget":return s.jsx("td",{className:ko("cell-budget",F.align),children:W(X)});case"caps":return s.jsx("td",{className:ko("cell-caps",F.align),children:Y(X)});case"alias":return s.jsx("td",{className:ko("cell-alias",F.align),children:B(X)});case"act":{const V=z7(X.provider||""),J=X.source==="manual"||Qn(X.provider||"");return s.jsx("td",{className:ko("cell-act r",F.align),children:s.jsxs("div",{className:"row-actions",children:[s.jsx(se,{variant:"ghost",size:"sm",disabled:!!V,title:V||l("以这个上游模型发一次最小请求,走真实转发链路"),onClick:()=>c({provider:X.provider||"",id:X.id}),children:l("测试")}),J?s.jsx(se,{variant:"ghost",size:"sm",className:"text-destructive",disabled:re,onClick:()=>{P()},children:l("移除")}):null]})})}default:return null}}function G(F){const X=e.pending.has($i(F)),re=p.has($i(F));return s.jsx("tr",{className:Ue(re&&"sel"),children:N.map(P=>s.jsx(x.Fragment,{children:q(P,F,X)},P.key))},`${F.provider||""}${F.id}`)}function $(){if(!b.length){const J=r?lw()?Su()?l("自定义提供商还没有模型:先在左栏选一家,点「添加模型」登记,或「获取上游模型」从上游拉取"):l(v?"该提供商已不存在(可能已被删除),请刷新列表":"这家还没有模型:点「添加模型」登记,或「获取上游模型」从上游拉取"):l("加载中…"):e.data?l("暂无模型(请先添加账号)"):l("加载中…");return s.jsx("tr",{children:s.jsx("td",{colSpan:C,className:"empty",children:J})})}if(!w.length)return s.jsx("tr",{children:s.jsx("td",{colSpan:C,className:"empty",children:j?l("没有匹配「{keyword}」的模型",{keyword:j}):l("没有匹配当前筛选的模型")})});const F=t==="all"||Su(),X=F&&!j&&e.stateFilter==="all"&&!A.paged,re=new Map;for(const J of w){const ie=J.provider||"";re.has(ie)||re.set(ie,{label:J.providerLabel||ie||l("未知"),items:[]}),re.get(ie)?.items.push(J)}const P=[];let V=0;for(const[J,ie]of re){ie.items.sort((K,be)=>{const ne=+!Uf(K)-+!Uf(be);if(ne!==0||S==="default")return ne;const ce=IM(K.credits),we=IM(be.credits);return ce===null||we===null?ce===we?0:ce===null?1:-1:S==="rate-asc"?ce-we:we-ce});const me=e.expanded.has(J)||!X,he=me?ie.items:ie.items.slice(0,ZO),ae=ie.items.length-he.length,oe=A.paged?Math.max(0,A.rangeStart-1-V):0,ee=A.paged?Math.min(he.length,A.rangeEnd-V):he.length,de=oe0?l("(续)"):"",l("{n} 个模型",{n:ie.items.length})]})},`group:${J}`));for(const K of de)P.push(G(K));V+=he.length,ae>0?P.push(s.jsx("tr",{className:"tr-more",children:s.jsx("td",{colSpan:C,children:s.jsx(se,{variant:"ghost",size:"sm",onClick:()=>p7(J),children:l("展开其余 {n} 个模型 ▾",{n:ae})})})},`more:${J}`)):me&&X&&ie.items.length>ZO&&P.push(s.jsx("tr",{className:"tr-more",children:s.jsx("td",{colSpan:C,children:s.jsx(se,{variant:"ghost",size:"sm",onClick:()=>m7(J),children:l("收起 ▴")})})},`collapse:${J}`))}return P}return s.jsxs(s.Fragment,{children:[s.jsx("section",{className:"panel",children:s.jsxs("div",{className:"mm",children:[z(),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"?ku(t,"",ww):ku(t,E),s.jsx("h2",{children:E}),s.jsxs("span",{className:"mm-meta",children:[s.jsx("b",{children:b.length}),l(" 个模型 · 已启用 "),s.jsx("b",{children:R}),l(" · 有映射 "),s.jsx("b",{children:k})]})]}),s.jsxs("div",{className:"head-actions",children:[s.jsx(se,{id:"btn-refresh-models",title:Qn(t)?l("从这一家的上游拉一份模型清单,勾选要哪些再导入(已添加的不会重复导入)"):l("刷新模型管理页里各提供商的远程模型目录,逐家结果列在弹窗里"),onClick:()=>mM(),children:l("获取模型")}),s.jsx(se,{id:"btn-add-custom-model",variant:"outline",size:"sm",onClick:()=>j7(),children:l("+ 添加模型")})]})]}),s.jsxs("div",{className:"mm-filters",children:[s.jsx(Gn,{options:JG,value:e.stateFilter,onValueChange:h7,"aria-label":l("按状态筛选"),className:"shrink-0"}),s.jsx(Gn,{options:t7,value:e.sort,onValueChange:g7,"aria-label":l("按倍率排序"),className:"shrink-0"}),s.jsxs(ji,{className:"w-full min-[768px]:w-[240px] flex-none min-[768px]:flex-none",id:"models-search",children:[s.jsx(Si,{type:"search",placeholder:l("搜索模型 ID / 名称 / 映射名…"),"aria-label":l("搜索模型"),autoComplete:"off",value:e.search,onChange:F=>x7(F.currentTarget.value)}),s.jsx(wi,{"aria-hidden":"true",children:"⌕"})]}),D.length>0?s.jsxs("span",{className:"batch-chip",children:[l("已选 "),s.jsx("b",{children:D.length}),l(" 个"),s.jsx(se,{id:"btn-batch-models",variant:"outline",size:"xs",title:l("对选中的 {n} 个模型执行批量操作",{n:D.length}),onClick:()=>f(!0),children:l("批量操作")})]}):null]})]}),s.jsx("div",{className:"models-table-wrap",children:s.jsxs("table",{className:"models-table",ref:F=>N7(F),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:l("上游模型")}),s.jsx("th",{"data-col":"rate",children:l("倍率")}),s.jsx("th",{"data-col":"source",children:l("来源")}),s.jsxs("th",{"data-col":"budget",children:[l("上下文 / 输出"),s.jsx("span",{className:"th-help","aria-hidden":"true",title:l("数字带虚线底 = 由 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:[l("能力"),s.jsx("span",{className:"th-help","aria-hidden":"true",title:l("圆点带内侧描边 = 由 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:[l("模型映射"),s.jsx("span",{className:"th-help","aria-hidden":"true",title:l("每条映射 = 对外名 → 上游模型;原始 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:l("操作")})]})}),s.jsx("tbody",{id:"models",children:$()})]})}),s.jsx(Di,{className:"models-panel-foot",leading:Su()?s.jsxs(s.Fragment,{children:[l("这里是"),s.jsx("b",{children:l("全部自定义提供商")}),l("的模型合集:每家的清单互相独立,别名也只在自己那家内生效;要改名称 / 协议 / Base URL,到账号页该家账号的「设置」→ 提供商一栏。")]}):r?s.jsxs(s.Fragment,{children:[l("自定义提供商的清单"),s.jsx("b",{children:l("只属于这一家")}),l(":这里的模型不会出现在其他家,别名也只在这一家内生效。改名称 / 协议 / 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(hK,{context:e.mapping,onClose:y7}):null,e.customModel?s.jsx(gK,{initial:e.customModel,onClose:w7}):null,e.capability?s.jsx(A7,{context:e.capability,onClose:S7}):null,o?s.jsx(U7,{target:o,onClose:()=>c(null)}):null,d?s.jsx($7,{models:D,onClose:()=>f(!1),onDone:()=>{g(new Set),f(!1)}}):null]})}const mK=l("绑定在「对外名 → 上游模型」这一条映射上的思考等级(列表照抄 OmniProxy 的手动绑定),选「不覆盖」表示不给这条映射指定等级。它会跟着这条映射注入转发,由承载的那家翻译成自己的档位字段(CatPaw 归并成 low/high/max,Qoder 按模型声明的档位归一)。以下几种情况故意不注入:① off / none(关闭思考)—— 本项目没有安全的表达方式;② 表外的自定义等级(各家能力范围不同,无法判断上游收不收);③ 客户端请求体里已经自己指定了档位(那是更明确的意图,绑定不覆盖);④ 这家上游不认识档位字段(如 WorkBuddy / 小浣熊 / AutoClaw / Cline)。注入与跳过都会写进详细日志。");function PM(e,t,r){const o=oM(e),c=(t||"").trim(),d=o.find(f=>f.id.toLowerCase()===c.toLowerCase());return d?d.id:c||o[0]?.id||""}function hK({context:e,onClose:t}){const r=!!e.alias,[o,c]=x.useState(()=>e.provider||uw()[0]?.id||""),[d,f]=x.useState(e.alias||""),[p,g]=x.useState(()=>PM(o,e.target)),[v,y]=x.useState(""),[b,j]=x.useState(!1),[w,S]=x.useState(()=>{const _=If(_f().data,DM(o,p)),L=r?gw(e.alias,e.target,e.provider):"";return L&&_.includes(L)?{select:L,custom:""}:{select:L?la:"",custom:L}}),N=If(_f().data,DM(o,p)),C=(()=>{const _=uw();for(const L of[e.provider,o])L&&!_.some(z=>z.id===L)&&_.push({id:L,label:qt().wbProviders?.labelOf?.(L)||L});return _})(),E=(()=>{const _=oM(o),L=(p||"").trim();return L&&!_.some(z=>z.id.toLowerCase()===L.toLowerCase())&&_.unshift({id:L,label:l("{name}(不在该家当前清单里)",{name:L}),off:!0}),_})(),R=C.find(_=>_.id===o)?.label||o||l("(全局)"),k=w.select&&w.select!==la&&!N.includes(w.select)?{select:la,custom:w.custom||w.select}:w,A=k.select===la?k.custom.trim():k.select,D=k.select===la;function I(_){c(_),g(PM(_,p))}async function M(){if(b)return;const _=r?e.alias||"":d.trim(),L=p;if(!_){y(l("请填写对外映射名"));return}if(!L){y(l("该提供商当前没有可选的上游模型"));return}if(!o){y(l("请选择提供商"));return}if(!r&&Co(_,L)&&Bf().some(z=>Co(z.id,L)&&Co(z.provider,o))){y(l("原始 ID 已作为默认绑定,请直接使用该绑定的开关或等级按钮"));return}j(!0),y(l("保存中…"));try{Vi(await kg(o,_,L,{reasoning:A})),j(!1),t();const z=A?l(" · 思考等级 {level}",{level:A}):"",U=qt().wbProviders?.labelOf?.(o)||o;vr(r?l("✅ 已更新 {name} 的思考等级",{name:_}):l("✅ 已添加映射 {name} → {target}({label}){suffix}",{name:_,target:L,label:U,suffix:z}))}catch(z){y(l("保存失败:{message}",{message:No(z)})),j(!1)}}const O=_=>{_.key==="Enter"&&(_.preventDefault(),M())};return s.jsx(Kt,{open:!0,onOpenChange:(_,L)=>{if(!_){if(b){L.cancel();return}t()}},children:s.jsxs(Yt,{children:[s.jsx(Ft,{children:s.jsx($t,{children:l(r?"设置思考等级":"添加模型映射")})}),s.jsxs(Ht,{children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(tt,{htmlFor:"mapping-provider",children:l("提供商")}),s.jsxs(ct,{value:o,disabled:!0,onValueChange:_=>I(String(_)),children:[s.jsx(dt,{id:"mapping-provider",className:"w-full",children:s.jsx(ut,{children:C.find(_=>_.id===o)?.label||o})}),s.jsx(ft,{children:C.map(_=>s.jsx(Ye,{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(tt,{htmlFor:"mapping-alias",children:l("对外映射名(下游请求时用)")}),s.jsx(Ke,{id:"mapping-alias",maxLength:128,placeholder:l("例如 gpt-4o"),autoComplete:"off",autoFocus:!r,value:d,disabled:r,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(tt,{htmlFor:"mapping-upstream",children:l("转发到上游模型")}),s.jsxs(ct,{value:p,disabled:!0,onValueChange:_=>g(String(_)),children:[s.jsx(dt,{id:"mapping-upstream",className:"w-full",children:s.jsx(ut,{children:E.find(_=>_.id===p)?.label||p})}),s.jsx(ft,{children:E.map(_=>s.jsxs(Ye,{value:_.id,children:[_.label,_.off?l("(已禁用)"):""]},_.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:[l("下游请求 "),s.jsx("b",{className:"text-primary-fg",children:d.trim()||l("<对外名>")}),l(" → 转发")," ",s.jsx("b",{className:"text-primary-fg",children:p||l("<上游模型>")}),l("({label})",{label:R}),A?s.jsxs(s.Fragment,{children:[l(" · 思考等级 "),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(tt,{htmlFor:"mapping-reasoning",children:l("思考等级")}),s.jsxs(Ri,{children:[s.jsx(Ai,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":l("思考等级的注入规则")}),children:"?"}),s.jsx(Oi,{children:mK})]})]}),s.jsxs(ct,{value:k.select,onValueChange:_=>{const L=String(_);S(z=>({...z,select:L}))},children:[s.jsx(dt,{id:"mapping-reasoning",className:"w-full",autoFocus:r,children:s.jsx(ut,{children:k.select===la?l("自定义等级…"):k.select||l("不覆盖")})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"",children:l("不覆盖")}),N.map(_=>s.jsx(Ye,{value:_,children:_},_)),s.jsx(Ye,{value:la,children:l("自定义等级…")})]})]}),D?s.jsx(Ke,{id:"mapping-reasoning-custom",maxLength:32,autoFocus:!0,placeholder:l("自定义等级(例如 custom-high)"),autoComplete:"off",disabled:b,value:k.custom,onChange:_=>S(L=>({...L,custom:_.currentTarget.value})),onKeyDown:O}):null]}),s.jsxs("p",{className:"text-xs leading-[1.65] text-subtle",children:[l("对外名可自由命名,允许与上游模型 ID 同名(同名时该上游的原生路由优先,映射作兜底); 支持字母、数字与 "),s.jsx("code",{children:"- _ . / :"}),l("。同一对外名可在多个提供商各添加一条: 下游用同一个名字请求,网关按账号优先级主备切换,失败自动落到下一个提供商。")]}),s.jsx("div",{className:"min-h-[18px] text-xs text-subtle",children:v})]}),s.jsxs(sn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:l("取消")}),s.jsx(se,{variant:"default",disabled:b,onClick:()=>{M()},children:l(r?"保存等级":"保存映射")})]})]})})}function gK({initial:e,onClose:t}){const[r,o]=x.useState(e.provider),[c,d]=x.useState(""),[f,p]=x.useState(""),[g,v]=x.useState(!1),y=(()=>{const N=i7();return r&&!N.some(C=>C.id===r)&&N.push({id:r,label:qt().wbProviders?.labelOf?.(r)||r}),N})(),b=y.some(N=>N.id===r)?r:y[0]?.id||"",j=y.find(N=>N.id===b)?.label||b||l("(未选)");async function w(){if(g)return;const N=c.trim();if(!b){p(l("请选择提供商"));return}if(!N){p(l("请填写上游模型 ID"));return}v(!0),p(l("保存中…"));try{const C=await d7(b,N);Vi(C),v(!1),t();const E=y.find(R=>R.id===b)?.label||b;if(Qn(wu()))vr(l("✅ 已登记模型 {name}({label})",{name:N,label:E}));else{const R=C;Array.isArray(R?.models)&&R.models.some(A=>A.id===N&&(A.provider||"")===b)?vr(l("✅ 已登记自定义模型 {name}({label})",{name:N,label:E})):vr(l("✅ 已登记 {name}({label}),但该提供商还没有可用账号,这一行要加上账号后才会显示",{name:N,label:E}),"err")}}catch(C){p(l("保存失败:{message}",{message:No(C)})),v(!1)}}const S=N=>{N.key==="Enter"&&(N.preventDefault(),w())};return s.jsx(Kt,{open:!0,onOpenChange:(N,C)=>{if(!N){if(g){C.cancel();return}t()}},children:s.jsxs(Yt,{children:[s.jsx(Ft,{children:s.jsx($t,{children:l("添加自定义模型")})}),s.jsxs(Ht,{children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(tt,{htmlFor:"custom-model-provider",children:l("提供商")}),s.jsxs(ct,{value:b,disabled:e.locked,onValueChange:N=>o(String(N)),children:[s.jsx(dt,{id:"custom-model-provider",className:"w-full",children:s.jsx(ut,{children:j})}),s.jsx(ft,{children:y.map(N=>s.jsx(Ye,{value:N.id,children:N.label},N.id))})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(tt,{htmlFor:"custom-model-id",children:l("上游模型 ID")}),s.jsx(Ke,{id:"custom-model-id",maxLength:128,placeholder:l("例如 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:[l("在 "),s.jsx("b",{className:"text-primary-fg",children:j}),l(" 上登记上游模型")," ",s.jsx("b",{className:"text-primary-fg",children:c.trim()||l("<上游模型 ID>")}),l("(登记后即可用这个名字请求)")]}),s.jsxs("p",{className:"text-xs leading-[1.65] text-subtle",children:[l("填上游真正认识的那个模型 ID(不是给下游用的名字)。登记后它会进入该家的模型清单: 表格里出现这一行、"),s.jsx("code",{children:"/v1/models"}),l(" 会广告它、请求它也会被转发到这家。 支持字母、数字与 "),s.jsx("code",{children:"- _ . / :"}),l("。")]}),s.jsxs("p",{className:"text-xs leading-[1.65] text-subtle",children:[l("「来源」列会标成"),s.jsx("b",{children:l("手动")}),l(",与远程目录 / 内置清单区分开。删除自定义模型是"),s.jsx("b",{children:l("直接移除")}),l("这条登记(不像内置模型那样只是隐藏),因为它的存在完全由这次登记决定。")]}),s.jsx("div",{className:"min-h-[18px] text-xs text-subtle",children:f})]}),s.jsxs(sn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:l("取消")}),s.jsx(se,{variant:"default",disabled:g,onClick:()=>{w()},children:l("保存")})]})]})})}const _M='.page[data-page="gateway"]';let Sw=null;function LM(){if(Sw)return;const e=document.querySelector(_M);e&&(e.replaceChildren(),Sw=jn.createRoot(e),Sw.render(s.jsx(pK,{})))}document.querySelector(_M)?LM():document.addEventListener("DOMContentLoaded",LM,{once:!0});const zM=3065;function xK(){if(Xa().workbuddyDesktop?.platform!=="web")return null;const e=typeof window>"u"?"":window.location?.origin;return e&&e!=="null"?e:null}function BM(e,t){return xK()??(e?`http://127.0.0.1:${e}`:t)}function Xa(){return window}function Tg(e){return e instanceof Error?e.message:String(e)}function Tu(e,t){Xa().wbApp?.toast?.(e,t)}let Gf={backend:null,gatewayBase:BM(0,`http://127.0.0.1:${zM}`)};const Nw=new Set;function Cw(){return Gf}function bK(e){return Nw.add(e),()=>{Nw.delete(e)}}function vK(e){Gf=e;for(const t of Nw)t()}function HM(){return Gf.gatewayBase.replace(/^https?:\/\//,"")}function yK(){return Gf.backend?.ready===!0}function UM(e){const t=(r,o)=>{const c=document.getElementById(r);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 kw=!1;async function Eu(){if(!kw){kw=!0;try{const e=Xa().workbuddyDesktop;if(!e)throw new Error("后端桥不可用");const t=await e.getBackendStatus(),r=Number(t?.port)||0,o=Cw(),c={backend:t??null,gatewayBase:BM(r,o.gatewayBase)};c.gatewayBase!==o.gatewayBase&&UM(c.gatewayBase),vK(c),Xa().wbApp?.renderTopbarStatus?.()}catch(e){console.warn("读取后端状态失败:",Tg(e))}finally{kw=!1}}}function jK(){UM(Gf.gatewayBase),Eu()}async function VM(e){Tu(e||l("正在重启…"));try{await Xa().workbuddyDesktop?.restartApp()}catch(t){Tu(l("重启失败:{reason}",{reason:Tg(t)}),"err")}}const wK={idle:l("结束占用进程"),querying:l("查询中…"),ending:l("结束中…")};function SK({container:e}){const{backend:t,gatewayBase:r}=x.useSyncExternalStore(bK,Cw),[o,c]=x.useState("idle"),d=t?.failure||null,f=HM(),p=t?.ready;let g="live off",v=l("正在检查… · {port}",{port:f});p===!0?(g="live pulse",v=l("网关运行中 · {port}",{port:f})):d?(g="live bad",v=l("{label} · {port}",{label:d.label||l("网关启动失败"),port:f})):p===!1&&(v=l("网关启动中… · {port}",{port:f}));const y=d?d.message??"":p===!0?l("本地网关正在监听 {url},可直接调用 OpenAI 兼容接口",{url:r}):l("正在确认网关是否已就绪");x.useEffect(()=>{Eu()},[]),x.useEffect(()=>{const j=Xa().workbuddyDesktop?.onBackendError?.(()=>{Eu()});return typeof j=="function"?j:void 0},[]),x.useEffect(()=>{e.title=y},[e,y]);async function b(){if(o!=="idle")return;const j=Xa().workbuddyDesktop;if(j){c("querying");try{const w=await j.getPortOccupant(),S=w?.occupant;if(!S){Tu(l("端口 {port} 上没有查到监听进程,请改用「更换端口」",{port:w?.port??""}),"err");return}const N=[l("即将结束以下进程:"),"",l("进程名:{name}",{name:String(S.name)}),l("PID:{pid}",{pid:String(S.pid)}),l("路径:{path}",{path:S.path||l("(未知)")}),"",l("结束它会强制退出该程序未保存的数据。确认继续?")],C=Xa().wbConfirm?.ask;if(!C||!await C({title:l("结束占用端口的进程"),text:N.join(` -`),okText:l("结束进程"),okClass:"danger"}))return;c("ending"),(await j.endPortOccupant())?.released?(Tu(l("已结束进程 {name}(PID {pid}),端口已释放",{name:String(S.name),pid:String(S.pid)})),await C({title:l("重启程序"),text:l("端口已释放。现在重启程序让网关用这个端口启动?"),okText:l("重启")})?await VM(l("重启中…")):await Eu()):(Tu(l("进程已结束,但端口仍被占用,建议改用「更换端口」"),"err"),await Eu())}catch(w){Tu(l("结束失败:{reason}",{reason:Tg(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:wK[o]}):null,s.jsx(se,{size:"sm",onClick:()=>{kK()},children:l("更换端口")})]}):null]})}let Tw=null;function $M(){if(Tw)return;const e=document.getElementById("sidebar-status");e&&(e.replaceChildren(),Tw=jn.createRoot(e),Tw.render(s.jsx(SK,{container:e})))}const NK={idle:l("保存并重启"),checking:l("校验中…"),saving:l("保存中…")};function CK({status:e,onClose:t}){const r=Number(e?.port)||zM,[o,c]=x.useState(()=>r<65535?String(r+1):String(r-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||l("当前端口 {port},网关运行正常。",{port:r});async function S(){if(d!=="idle")return;const N=Xa().workbuddyDesktop;if(!N)return;const C=Number(o)||0;if(!C||C<1024||C>65535){y(l("端口需在 1024-65535 之间"));return}f("checking"),y(""),g("");try{const E=await N.checkPort(C);if(!E?.ok){g(E?.message||l("该端口不可用"));return}if(E.same){g(E.message??"");return}if(f("saving"),(await N.changePort(C))?.changed===!1){g(l("与当前端口相同,无需重启"));return}t(),await VM(l("端口已改为 {port},正在重启…",{port:C}))}catch(E){y(Tg(E))}finally{f("idle")}}return s.jsx(Kt,{open:!0,onOpenChange:N=>{N||t()},children:s.jsxs(Yt,{children:[s.jsx(Ft,{children:s.jsx($t,{children:l("更换网关端口")})}),s.jsxs(Ht,{children:[s.jsxs(zn,{children:[s.jsx("h3",{children:l("当前状态")}),s.jsx("p",{children:w})]}),s.jsxs(zn,{children:[s.jsx("h3",{children:l("新端口")}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(tt,{htmlFor:"port-input",className:"text-[12.5px] whitespace-nowrap text-subtle",children:l("端口号")}),s.jsx(Ke,{id:"port-input",type:"number",min:1024,max:65535,step:1,placeholder:l("例如 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:l("端口需在 1024-65535 之间。1023 及以下是系统保留范围,普通程序无法监听。")})]}),s.jsxs(zn,{children:[s.jsx("h3",{children:l("换端口后要改的地方")}),s.jsxs("p",{children:[l("网关地址会变成 "),s.jsx("code",{children:`http://127.0.0.1:${j||"—"}`}),l("。已经把这个地址填进其它工具(Claude Code、Cherry Studio 等)的,需要一并改成新地址,否则那些工具会连不上。")]})]}),s.jsx("p",{className:"min-h-[18px] text-[11.5px] text-muted-foreground",children:v})]}),s.jsxs(sn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:l("取消")}),s.jsx(se,{variant:"default",disabled:d!=="idle",onClick:()=>{S()},children:NK[d]})]})]})})}let Kf=null,Ru=null;function FM(){Kf&&(Kf.unmount(),Kf=null),Ru&&(Ru.remove(),Ru=null)}async function kK(){let e=Cw().backend;e||(e=await Xa().workbuddyDesktop?.getBackendStatus().catch(()=>null)??null),FM(),Ru=document.createElement("div"),document.body.append(Ru),Kf=jn.createRoot(Ru),Kf.render(s.jsx(CK,{status:e,onClose:FM}))}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",$M,{once:!0}):$M(),window.wbPortPanel={render:jK,sync:Eu,portLabel:HM,isReady:yK};function Ew(e){return e.source==="subscription"&&(e.port===null||e.port===void 0)}function Us(){return window}function Bn(e,t){Us().wbApp?.toast?.(e,t)}function ka(e){return e instanceof Error?e.message:String(e)}function qM(e){return Us().wbApp?.formatTime?.(e)||""}function Rw(e){const t=Number(e);return!Number.isFinite(t)||t<0?"":t<1e3?`${Math.round(t)}ms`:`${(t/1e3).toFixed(1)}s`}function Aw(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]||t)}function Au(e){return String(e?.name||e?.id||"")}function TK(e){return e.source==="clash"}function Ow(e){return e.source==="subscription"}function Yf(e){return TK(e)||Ow(e)}function Mw(e){return Ow(e)&&e.orphan===!0}function GM(e){return!Yf(e)||Mw(e)}const EK=l("来自 Clash Verge 同步(名称 / 端口 / 启用都跟随 Clash),请到 Clash Verge 中修改"),RK=l("该节点来自订阅(名称 / 端口 / 启用跟随订阅与内核),请在「订阅管理」里修改"),AK=l("该节点所属订阅已删除,不会再被同步更新,可手动删除清理");function Eg(e){return Mw(e)?AK:Ow(e)?RK:EK}let cs={data:null,loading:!1,error:"",testing:null,pending:new Set,syncing:!1,batchBusy:!1,batchProgress:null,selected:new Set};const Dw=new Set;function OK(e){return Dw.add(e),()=>{Dw.delete(e)}}function MK(){return cs}function Kn(e){cs={...cs,...e},Dw.forEach(t=>t())}function Iw(){return cs.data?.items??[]}function DK(e){return cs.selected.has(e)}function IK(e,t){const r=new Set(cs.selected);t?r.add(e):r.delete(e),Kn({selected:r})}function PK(e,t){const r=new Set(cs.selected);for(const o of e)t?r.add(o):r.delete(o);Kn({selected:r})}function _K(){Kn({selected:new Set})}function To(e){if(!e||typeof e!="object"||!Array.isArray(e.items))return;const t=new Set(e.items.map(o=>o.id)),r=new Set([...cs.selected].filter(o=>t.has(o)));Kn({data:e,error:"",selected:r})}async function Xf(e=!1){const t=Us().workbuddyDesktop;if(typeof t?.getProxyPool!="function"){Kn({error:l("当前环境不支持代理池(桥接方法缺失)")});return}e||Kn({loading:!0});try{To(await t.getProxyPool())}catch(r){Kn({error:ka(r)}),e||Bn(l("代理列表加载失败:{reason}",{reason:ka(r)}),"err")}finally{Kn({loading:!1})}}async function LK(){const e=Us().workbuddyDesktop;if(typeof e?.syncClashToProxyPool!="function"){Bn(l("当前环境不支持同步(桥接方法缺失)"),"err");return}if(!cs.syncing){Kn({syncing:!0});try{const t=await e.syncClashToProxyPool();To(t),t?.syncError?Bn(l("没能同步:{reason}",{reason:t.syncError}),"err"):t?.changes?Bn(l("✅ 已同步 Clash Verge 出口({n} 项变更)",{n:t.changes})):Bn(l("已是最新,没有需要同步的变更"))}catch(t){Bn(l("同步失败:{reason}",{reason:ka(t)}),"err")}finally{Kn({syncing:!1})}}}async function zK(e){const t=Us().workbuddyDesktop;if(typeof t?.testProxyPoolItem!="function"){Bn(l("当前环境不支持代理测试(桥接方法缺失)"),"err");return}if(!cs.testing){Kn({testing:e.id});try{const r=await t.testProxyPoolItem(e.id);if(r?.items&&To({items:r.items}),r?.success){Ew(e)&&Xf(!0);const o=Rw(r.durationMs);Bn(l("✅ 「{name}」出口可用{ip}{took}",{name:Au(e),ip:r.ip?l(" 出口 IP {ip}",{ip:r.ip}):"",took:o?` ${o}`:""}))}else Bn(l("❌ 「{name}」{error}",{name:Au(e),error:r?.error||l("连接失败")}),"err");r?.saveError&&Bn(l("测试结果没能记下:{reason}",{reason:r.saveError}),"err")}catch(r){Bn(l("测试失败:{reason}",{reason:ka(r)}),"err")}finally{Kn({testing:null})}}}async function BK(e,t){const r=Us().workbuddyDesktop;if(typeof r?.updateProxyPoolItem!="function")return;if(Yf(e)){Bn(Eg(e),"err");return}const o=new Set(cs.pending);o.add(e.id),Kn({pending:o});try{To(await r.updateProxyPoolItem({...$K(e),enabled:t}));const c=Au(e);Bn(t?l("已启用「{name}」",{name:c}):l("已禁用「{name}」",{name:c}))}catch(c){Bn(l("保存失败:{reason}",{reason:ka(c)}),"err")}finally{const c=new Set(cs.pending);c.delete(e.id),Kn({pending:c})}}async function KM(e){const t=Us().workbuddyDesktop;if(typeof t?.removeProxyPoolItem!="function")return;if(!GM(e)){Bn(Eg(e),"err");return}const r=e.usedBy||[],o=r.length?`

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

`:"";if(!await Us().wbConfirm?.ask?.({title:l("删除代理"),html:l("确定删除「{name}」?{used}",{name:Aw(Au(e)),used:o}),okText:l("删除"),okClass:"danger"}))return;const d=new Set(cs.pending);d.add(e.id),Kn({pending:d});try{const f=await t.removeProxyPoolItem(e.id);To(f),Bn(l("已删除「{name}」",{name:Au(e)}))}catch(f){Bn(l("删除失败:{reason}",{reason:ka(f)}),"err")}finally{const f=new Set(cs.pending);f.delete(e.id),Kn({pending:f})}}async function HK(){const e=Us().workbuddyDesktop;if(typeof e?.testProxyPoolItem!="function"){Bn(l("当前环境不支持代理测试(桥接方法缺失)"),"err");return}if(cs.batchBusy||cs.testing)return;const t=Iw().filter(p=>cs.selected.has(p.id));if(!t.length)return;Kn({batchBusy:!0,batchProgress:{done:0,total:t.length}});const r=t.filter(Ew).map(p=>p.id);if(r.length){const{ready:p}=await FK(r);if(!p){Kn({testing:null,batchBusy:!1,batchProgress:null}),Bn(l("这些节点的监听器还没建好(内核可能卡在拉取订阅),批量测试已中止;稍后重试,或看「订阅」区块的内核状态与日志"),"err");return}}let o=0,c=0,d="";for(const[p,g]of t.entries()){Kn({testing:g.id,batchProgress:{done:p,total:t.length}});try{const v=await e.testProxyPoolItem(g.id);v?.items&&To({items:v.items}),v?.success?o+=1:c+=1,v?.saveError&&!d&&(d=v.saveError)}catch{c+=1}}Kn({testing:null,batchBusy:!1,batchProgress:null});const f=c?l("批量测试完成:{ok} 个可用、{failed} 个失败(共 {total} 个)",{ok:o,failed:c,total:t.length}):l("批量测试完成:{ok} 个可用(共 {total} 个)",{ok:o,total:t.length});Bn(c?f:`✅ ${f}`,c?"err":"ok"),d&&Bn(l("部分测试结果没能记下:{reason}",{reason:d}),"err")}async function UK(){const e=Us().workbuddyDesktop;if(typeof e?.removeProxyPoolItem!="function"||cs.batchBusy||cs.testing)return;const t=Iw().filter(S=>cs.selected.has(S.id)),r=t.filter(S=>GM(S)),o=t.length-r.length;if(!r.length){Bn(o?l("选中的 {n} 条都是同步来的只读条目(Clash / 订阅),不能删除",{n:o}):l("没有可删除的条目"),"err");return}const c=r.slice(0,8).map(S=>Aw(Au(S))).join(l("、")),d=r.length>8?l("{names} 等 {n} 条",{names:c,n:r.length}):c,f=r.filter(S=>(S.usedBy||[]).length).length,p=f?`

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

`:"",g=o?`

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

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

${d}

${p}${g}`,okText:l("删除"),okClass:"danger"}))return;Kn({batchBusy:!0,batchProgress:{done:0,total:r.length}});let y=0,b=0,j="";for(const[S,N]of r.entries()){Kn({batchProgress:{done:S,total:r.length}});try{const C=await e.removeProxyPoolItem(N.id);To(C),y+=1}catch(C){b+=1,j||(j=ka(C))}}Kn({batchBusy:!1,batchProgress:null});const w=[l("已删除 {n} 个代理",{n:y})];o&&w.push(l("跳过 {n} 个(同步只读条目)",{n:o})),b&&w.push(l("失败 {n} 个({reason})",{n:b,reason:j})),Bn(b?w.join(l(",")):`✅ ${w.join(l(","))}`,b?"err":"ok")}async function VK(e,t){const r=Us().workbuddyDesktop,o=e?{...t,id:e.id}:t,c=e?await r?.updateProxyPoolItem?.(o):await r?.createProxyPoolItem?.(o);return To(c),c}function $K(e){return{name:e.name,source:"manual",protocol:e.protocol,host:e.host,port:e.port,username:e.username,password:e.password,enabled:e.enabled}}async function YM(){const e=Us().workbuddyDesktop;if(typeof e?.getProxySettings!="function")throw new Error(l("当前环境不支持代理设置(桥接方法缺失)"));const t=await e.getProxySettings();if(!t||typeof t!="object")throw new Error(l("代理设置响应异常"));return t}async function FK(e=[]){const t=Us().workbuddyDesktop;if(typeof t?.provisionProxyPool!="function")return{pending:!1,ready:!0};try{const r=await t.provisionProxyPool(e.length?{ids:e}:{});return{pending:r?.pending===!0,ready:r?.ready!==!1}}catch{return{pending:!1,ready:!0}}}async function qK(e){const t=Us().workbuddyDesktop;if(typeof t?.saveProxySettings!="function")throw new Error(l("当前环境不支持代理设置(桥接方法缺失)"));const r=await t.saveProxySettings(e);if(!r||typeof r!="object")throw new Error(l("代理设置响应异常"));return r}function GK({item:e,onClose:t}){const r=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,C]=x.useState(e?e.enabled:!0),[E,R]=x.useState(!1),[k,A]=x.useState(!1),[D,I]=x.useState(null);function M(){const L=o.trim();if(!L)return{error:l("请填写代理名称")};const z=p.trim();if(!z)return{error:l("请填写代理主机地址")};const U=Number(v);return!Number.isInteger(U)||U<1||U>65535?{error:l("代理端口必须是 1-65535 的整数")}:{payload:{name:L,source:"manual",protocol:d,host:z,port:U,username:b.trim(),password:w,enabled:N}}}async function O(){if(k)return;const L=M();if("error"in L){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",L.error]}));return}const z=L.payload,U={source:"custom",protocol:z.protocol,host:z.host,port:z.port,username:z.username,password:z.password};A(!0),I(l("正在连接上游…"));try{const B=await Us().workbuddyDesktop?.testProxy?.({proxy:U});if(B?.success){const Q=Rw(B.durationMs);I(s.jsxs("span",{className:"text-success",children:[l("✅ 出口可用"),B.ip?l(" 出口 IP {ip}",{ip:B.ip}):"",Q?` ${Q}`:""]}))}else I(s.jsxs("span",{className:"text-destructive",children:["❌ ",B?.error||l("连接失败")]}))}catch(B){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",ka(B)]}))}finally{A(!1)}}async function _(){if(E)return;const L=M();if("error"in L){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",L.error]}));return}R(!0),I(null);try{await VK(e,L.payload),Bn(r?l("已保存「{name}」",{name:o.trim()}):l("已新增「{name}」",{name:o.trim()})),t()}catch(z){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",ka(z)]})),R(!1)}}return s.jsx(Kt,{open:!0,onOpenChange:L=>{!L&&!E&&t()},children:s.jsxs(Yt,{className:"max-w-[560px]",children:[s.jsx(Ft,{children:s.jsx($t,{children:l(r?"编辑代理":"新增代理")})}),s.jsxs(Ht,{className:"flex flex-col gap-3.5",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(tt,{htmlFor:"proxy-name",children:l("名称")}),s.jsx(Ke,{id:"proxy-name",maxLength:60,autoComplete:"off",spellCheck:!1,placeholder:l("例如:香港 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(tt,{htmlFor:"proxy-protocol",children:l("协议")}),s.jsxs(ct,{value:d,onValueChange:L=>f(L),children:[s.jsx(dt,{id:"proxy-protocol",className:"min-w-[110px]",children:s.jsx(ut,{children:d==="socks5"?"SOCKS5":"HTTP"})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"http",children:"HTTP"}),s.jsx(Ye,{value:"socks5",children:"SOCKS5"})]})]})]}),s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1.5",children:[s.jsx(tt,{htmlFor:"proxy-host",children:l("主机")}),s.jsx(Ke,{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(tt,{htmlFor:"proxy-port",children:l("端口")}),s.jsx(Ke,{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(tt,{htmlFor:"proxy-user",children:l("用户名")}),s.jsx(Ke,{id:"proxy-user",placeholder:l("可选"),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(tt,{htmlFor:"proxy-pass",children:l("密码")}),s.jsx(Ke,{id:"proxy-pass",placeholder:l("可选"),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(Rs,{checked:N,onCheckedChange:C,"aria-label":l("启用这条代理")}),s.jsx("span",{className:"text-[12.5px]",children:l("启用(禁用的条目不会被账号使用,被引用时账号回退直连;仍可测试)")})]}),s.jsxs("p",{className:"text-xs leading-[1.65] text-subtle",children:[l("想要 Clash Verge 的出口?那类条目由工具条的"),s.jsx("b",{children:l("「同步 Clash Verge」")}),l("整体 镜像进来(进本页时也会自动同步一次),名称与端口跟随 Clash、因此是只读的 —— 不必(也不能)在这里手工填。")]}),s.jsx("div",{className:"min-h-[18px] text-xs text-subtle",children:D})]}),s.jsxs(sn,{children:[s.jsx(se,{variant:"outline",disabled:k||E,onClick:()=>{O()},children:l(k?"测试中…":"测试出口")}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:E,onClick:t,children:l("取消")}),s.jsx(se,{variant:"default",disabled:E,onClick:()=>{_()},children:l(E?"保存中…":"保存")})]})]})})}function KK({onClose:e}){const[t,r]=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,C]=x.useState(!1);x.useEffect(()=>{let A=!0;return(async()=>{try{const D=await YM();if(!A||D===null)return;f(String(D.listenerPortBase??"")),g(String(D.listenerPortEnd??"")),y(String(D.testUrl??"")),j(D.defaults??{}),r(!1)}catch(D){if(!A)return;S(ka(D)),r(!1)}})(),()=>{A=!1}},[]);function E(){const A=Number(d),D=Number(p);if(!Number.isInteger(A)||A<1||A>65535||!Number.isInteger(D)||D<1||D>65535)return S(l("端口范围必须是 1-65535 的整数")),null;if(A>D)return S(l("起始端口不能大于结束端口")),null;const I=v.trim();return I&&!I.startsWith("http://")&&!I.startsWith("https://")?(S(l("测试网址要以 http:// 或 https:// 开头")),null):(S(""),{listenerPortBase:A,listenerPortEnd:D,testUrl:I})}async function R(){if(o||t)return;const A=E();if(A){c(!0);try{await qK(A),C(!0)}catch(D){S(ka(D))}finally{c(!1)}}}function k(){f(String(b.listenerPortBase??"")),g(String(b.listenerPortEnd??"")),y(String(b.testUrl??"")),C(!1),S("")}return s.jsx(Kt,{open:!0,onOpenChange:A=>{!A&&!o&&e()},children:s.jsxs(Yt,{className:"max-w-[560px]",children:[s.jsx(Ft,{children:s.jsx($t,{children:l("代理设置")})}),s.jsx(Ht,{className:"flex flex-col gap-3.5",children:t?s.jsx("p",{className:"text-xs text-subtle",children:l("加载中…")}):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(tt,{htmlFor:"proxy-settings-base",children:l("节点端口范围(起始)")}),s.jsx(Ke,{id:"proxy-settings-base",type:"number",min:1,max:65535,placeholder:String(b.listenerPortBase??""),autoComplete:"off",value:d,onChange:A=>{f(A.currentTarget.value),C(!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(tt,{htmlFor:"proxy-settings-end",children:l("节点端口范围(结束)")}),s.jsx(Ke,{id:"proxy-settings-end",type:"number",min:1,max:65535,placeholder:String(b.listenerPortEnd??""),autoComplete:"off",value:p,onChange:A=>{g(A.currentTarget.value),C(!1)}})]})]}),s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:l("订阅节点会在本机各占一个监听端口,从该范围里挑空闲的分配;节点多的大订阅把默认范围({base}-{end})用尽时会报「没有可用的节点端口」,这时把范围调大再重启内核。已分配出去的端口不会因改范围而失效。",{base:b.listenerPortBase??"",end:b.listenerPortEnd??""})}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(tt,{htmlFor:"proxy-settings-url",children:l("出口测试网址")}),s.jsx(Ke,{id:"proxy-settings-url",placeholder:b.testUrl||"",autoComplete:"off",spellCheck:!1,className:"font-mono text-[12px]",value:v,onChange:A=>{y(A.currentTarget.value),C(!1)}})]}),s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:l("「测试」与「批量测试」访问的目标;留空用默认(打 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:["✅ ",l("已保存。重启内核后,新分配的节点端口才会按新范围来。")]}):null]})]})}),s.jsxs(sn,{children:[s.jsx(se,{variant:"ghost",disabled:t||o,onClick:k,children:l("恢复默认")}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:o,onClick:e,children:l("关闭")}),s.jsx(se,{variant:"default",disabled:t||o,onClick:()=>{R()},children:l(o?"保存中…":"保存")})]})]})})}function An(){return window}function er(e,t){An().wbApp?.toast?.(e,t)}function Dr(e){return e instanceof Error?e.message:String(e)}function XM(e){const t=String(e||"").trim();return/^https?:\/\//i.test(t)?t:""}async function QM(e){const t=XM(e);if(!t){er(l("链接地址不受支持"),"err");return}try{await An().workbuddyDesktop?.openReleasePage(t)}catch(r){er(l("打开链接失败:{error}",{error:Dr(r)}),"err")}}const Rg="1127656296",YK=`assets/qq-group/${Rg}.jpg`;function ZM(e){return An().wbMarkdown?.render?.(e)||""}function WM(e){const r=e.target?.closest?.("[data-external]");r&&(e.preventDefault(),QM(r.dataset.external||""))}const Qf="__proxy_other__",JM={proxyChoice:null,pool:null,poolError:""};async function XK(){const e=An().workbuddyDesktop,t={...JM};if(!e?.getUpdateProxy)return t;try{t.proxyChoice=(await e.getUpdateProxy())?.proxy??null}catch{}try{if(typeof e.getProxyPool!="function")throw new Error("桥未提供代理池方法");const r=(await e.getProxyPool())?.items;if(!Array.isArray(r))throw new Error("代理池响应异常");t.pool=r}catch(r){t.pool=[],t.poolError=Dr(r)}return t}async function QK(e){if(e===Qf)return null;const t=An().workbuddyDesktop;if(!t?.setUpdateProxy)return null;const r=e===""?null:{source:"pool",proxyId:e.slice(Ga.length)};try{const o=await t.setUpdateProxy({proxy:r}),c=o?.proxy??null,d=o?.saved!==!1;return d?er(c?l("✅ 更新出网已切换为 {label}",{label:c.label||l("指定代理")}):l("✅ 更新出网已切换为直连")):er(l("出网线路已切换,但写入磁盘失败(重启后会恢复原线路)"),"err"),{choice:c,saved:d}}catch(o){return er(l("保存失败:{error}",{error:Dr(o)}),"err"),null}}function e2(e){const t=e.proxyChoice,r=t?.config?.source||t?.source,o=t?.label||l(r==="custom"?"自定义代理":"已设置"),c=!!t?.error,d=Array.isArray(e.pool)?e.pool:[];let f="";r==="pool"&&t?.config?.proxyId?f=`${Ga}${t.config.proxyId}`:t&&(f=Qf);const p=[{value:"",label:l("直连")}];for(const g of d)p.push({value:`${Ga}${g.id}`,label:lf(g)});if(e.pool===null?p.push({value:"__hint_pool__",label:l("正在读取代理列表…"),disabled:!0}):d.length||p.push({value:"__hint_pool__",label:e.poolError?l("代理列表读取失败"):l("还没有代理(去「网络代理」页添加)"),disabled:!0}),f===Qf){const g=r==="clash"?l("Clash 出口:"):r==="custom"?l("自定义:"):"";p.push({value:Qf,label:`${g}${o}${c?l("(不可用)"):""}`})}else r==="pool"&&!d.some(g=>`${Ga}${g.id}`===f)&&p.push({value:f,label:`${o}${c?l("(不可用)"):""}`});return{current:f,items:p,selected:p.find(g=>g.value===f),broken:c,title:c?l("当前线路不可用:{error};请重新选择代理或切回直连",{error:String(t?.error||"")}):l("检查更新与下载安装包走哪条线路(当前:{current});选择即保存。选项来自「网络代理」页;直连失败时会自动借 Clash 混合端口重试一次,选定指定代理后只走它",{current:t?o:l("直连")})}}function cr(){return window}function wn(e,t){cr().wbApp?.toast?.(e,t)}function oa(e){return e instanceof Error?e.message:String(e)}let cn={data:null,loading:!1,error:"",pending:!1,refreshing:null};const Pw=new Set;function Ag(e){return Pw.add(e),()=>{Pw.delete(e)}}function Og(){return cn}function Hn(e){cn={...cn,...e},Pw.forEach(t=>t())}function ZK(){return cn.data?.items??[]}function Ou(){return cn.data?.kernel??null}function Fi(e){!e||typeof e!="object"||!Array.isArray(e.items)||Hn({data:e,error:""})}function Eo(){Xf(!0)}async function qi(e=!1){const t=cr().workbuddyDesktop;if(typeof t?.getSubscriptions!="function"){Hn({error:l("当前环境不支持订阅(桥接方法缺失)")});return}e||Hn({loading:!0});try{Fi(await t.getSubscriptions())}catch(r){Hn({error:oa(r)})}finally{e||Hn({loading:!1})}}const WK=20;function JK(e){const t=e.kernel;if(!t||t.download.state==="downloading")return!1;if(!t.installed||t.lastError&&!t.running)return!0;const r=t.providerSync??{};return(e.items??[]).filter(o=>o.enabled!==!1).every(o=>!!r[o.id])}async function Gi(){const e=cr().workbuddyDesktop;if(typeof e?.getSubscriptions=="function")for(let t=0;tsetTimeout(o,1500)),Eo();let r;try{r=await e.getSubscriptions()}catch{return}if(Fi(r),t>=1&&r&&Array.isArray(r.items)&&JK(r))return}}async function e9(e,t){const o=await cr().workbuddyDesktop?.addSubscription?.({name:e.trim(),url:t.trim(),enabled:!0});return Fi(o),wn(l("已新增订阅「{name}」,内核正在同步节点…",{name:e.trim()})),Eo(),Gi(),o??null}async function t9(e,t){const o=await cr().workbuddyDesktop?.saveSubscription?.({id:e.id,...t});Fi(o),wn(l("已保存「{name}」",{name:t.name.trim()})),Eo(),Gi()}async function n9(e,t){const r=cr().workbuddyDesktop;if(!cn.pending){Hn({pending:!0});try{const o=await r?.saveSubscription?.({id:e.id,name:e.name,url:e.url,enabled:t});Fi(o),wn(t?l("已启用「{name}」",{name:e.name}):l("已禁用「{name}」",{name:e.name})),Eo(),Gi()}catch(o){wn(l("保存失败:{reason}",{reason:oa(o)}),"err")}finally{Hn({pending:!1})}}}async function s9(e){const t=cr().workbuddyDesktop;if(!(cn.refreshing||cn.pending)){Hn({refreshing:e.id});try{const r=await t?.refreshSubscription?.(e.id);Fi(r),wn(l("已刷新「{name}」,正在同步节点…",{name:e.name})),Eo(),Gi()}catch(r){wn(l("刷新失败:{reason}",{reason:oa(r)}),"err")}finally{Hn({refreshing:null})}}}async function r9(e){const t=cr().workbuddyDesktop;if(await window.wbConfirm?.ask?.({title:l("删除订阅"),html:l("确定删除「{name}」?它在代理池里的节点会一并移除,引用这些节点的账号会回退直连。",{name:e.name||e.id}),okText:l("删除"),okClass:"danger"})&&!cn.pending){Hn({pending:!0});try{const o=await t?.removeSubscription?.(e.id);Fi(o),wn(l("已删除「{name}」",{name:e.name||e.id})),Eo(),Gi()}catch(o){wn(l("删除失败:{reason}",{reason:oa(o)}),"err")}finally{Hn({pending:!1})}}}async function a9(e){const t=cr().workbuddyDesktop;if(typeof t?.downloadKernel!="function"){wn(l("当前环境不支持订阅(桥接方法缺失)"),"err");return}if(!cn.pending){Hn({pending:!0});try{const r=await t.downloadKernel(e);r&&cn.data&&Hn({data:{...cn.data,kernel:r}}),r?.saved===!1&&wn(l("下载线路 / 存放目录没能写进配置(本次下载已按新设置走,重启后会恢复原值)"),"err");for(let c=0;c<300;c+=1){await new Promise(f=>setTimeout(f,1e3));const d=await t.getKernelStatus?.();if(d&&cn.data&&Hn({data:{...cn.data,kernel:d}}),!d||d.download.state!=="downloading")break}const o=cn.data?.kernel;o?.download.state==="error"?wn(l("内核下载失败:{reason}",{reason:o.download.error||l("未知错误")}),"err"):o?.download.state==="canceled"?wn(l("已停止下载内核(未下载完的临时文件已删除)")):o?.download.state==="done"&&(wn(l("✅ 内核下载完成,正在启动…")),Gi())}catch(r){wn(l("内核下载失败:{reason}",{reason:oa(r)}),"err")}finally{Hn({pending:!1})}}}async function l9(){const e=cr().workbuddyDesktop;if(typeof e?.cancelKernelDownload!="function")return"none";try{const t=await e.cancelKernelDownload();if(t&&cn.data&&Hn({data:{...cn.data,kernel:t}}),t?.canceled===!1)return"none";for(let o=0;o<20;o+=1){const c=await e.getKernelStatus?.();if(c&&cn.data&&Hn({data:{...cn.data,kernel:c}}),c&&c.download.state!=="downloading")break;await new Promise(d=>setTimeout(d,250))}const r=cn.data?.kernel?.download.state;return r==="canceled"?"canceled":r==="done"?"done":"stalled"}catch(t){return wn(l("停止下载失败:{reason}",{reason:oa(t)}),"err"),"none"}}async function o9(){const e=cr().workbuddyDesktop;if(!cn.pending){Hn({pending:!0});try{const t=await e?.restartKernel?.();t&&cn.data&&Hn({data:{...cn.data,kernel:t}}),wn(l("内核正在启动…")),Eo(),Gi()}catch(t){wn(l("内核启动失败:{reason}",{reason:oa(t)}),"err")}finally{Hn({pending:!1})}}}async function i9(){const e=cr().workbuddyDesktop;if(typeof e?.removeKernel!="function"){wn(l("当前环境不支持订阅(桥接方法缺失)"),"err");return}const t=Ou()?.version;if(!await window.wbConfirm?.ask?.({title:l("删除内核"),html:l("确定删除已下载的内核{version}?内核文件与端口映射会被移除,订阅节点会变成「未分配端口」,引用它们的账号会暂时回退直连;订阅本身保留,重新下载内核后会重新分配端口。",{version:t?`(${t})`:""}),okText:l("删除内核"),okClass:"danger"})||cn.pending)return;Hn({pending:!0});const o=Ou()?.lastError||"";try{const c=await e.removeKernel();c&&cn.data&&Hn({data:{...cn.data,kernel:c}});for(let f=0;f<20;f+=1){const p=await e.getKernelStatus?.();if(p&&cn.data&&Hn({data:{...cn.data,kernel:p}}),p&&p.installed===!1||p?.lastError&&p.lastError!==o)break;await new Promise(g=>setTimeout(g,500))}const d=cn.data?.kernel;if(d?.installed===!1)wn(l("已删除内核(订阅与账号引用保留,重新下载后会重新分配端口)")),Eo();else{const f=d?.lastError&&d.lastError!==o?d.lastError:l("内核目录没能删掉(可能仍被进程占用),稍后重试一次");wn(l("删除内核失败:{reason}",{reason:f}),"err")}qi(!0)}catch(c){wn(l("删除内核失败:{reason}",{reason:oa(c)}),"err"),qi(!0)}finally{Hn({pending:!1})}}async function c9(e){const t=cr().workbuddyDesktop;if(typeof t?.decodeQrImage!="function")throw new Error(l("当前环境不支持订阅(桥接方法缺失)"));const r=await new Promise((d,f)=>{const p=new FileReader;p.onload=()=>d(String(p.result||"")),p.onerror=()=>f(new Error(l("图片读取失败"))),p.readAsDataURL(e)}),c=(await t.decodeQrImage({imageBase64:r}))?.url;if(!c)throw new Error(l("二维码里没有订阅链接"));return c}function t2(e){return(Math.max(0,Number(e)||0)/1024/1024).toFixed(1)}function u9(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")||e.startsWith("/")}function d9({onClose:e}){const t=x.useSyncExternalStore(Ag,Og),r=Ou(),o=r?.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(r?.kernelDir||""),[S,N]=x.useState(!1),[C,E]=x.useState(!1),[R,k]=x.useState("");x.useEffect(()=>{let z=!0;return(async()=>{try{const U=(await cr().workbuddyDesktop?.getProxyPool?.())?.items;if(!Array.isArray(U))throw new Error(l("代理池响应异常"));z&&p(U)}catch(U){if(!z)return;p([]),v(oa(U))}})(),()=>{z=!1}},[]),x.useEffect(()=>{r?.installed&&e()},[r?.installed]);const A=e2({proxyChoice:r?.downloadProxy??null,pool:f,poolError:g}),D=y??A.current,I=A.items.find(z=>z.value===D)??A.selected,M=r?.kernelDirDefault||"";async function O(){if(S)return;const z=j.trim();if(z&&!u9(z)){k(l("存放位置要填绝对路径,例如 D:\\proxy-kernel"));return}k(""),N(!0);try{const U={dir:z};D!==Qf&&(U.proxy=D===""?null:{source:"pool",proxyId:D.slice(Ga.length)}),a9(U)}finally{N(!1)}}async function _(){if(!C){E(!0);try{const z=await l9();z==="done"?wn(l("下载已经完成,停止没赶上(内核已安装)")):z==="none"?wn(l("当前没有正在进行的下载"),"err"):z==="stalled"&&wn(l("停止请求已发出,但下载还没收手,稍后再看一次进度"),"err")}finally{E(!1)}}}async function L(){const z=cr().workbuddyDesktop;if(typeof z?.pickFolder!="function"){wn(l("当前环境不支持选择文件夹,直接填写绝对路径即可"),"err");return}try{const U=await z.pickFolder(j.trim()||M||null);if(U?.unsupported){wn(l("当前环境不支持选择文件夹,直接填写绝对路径即可"),"err");return}if(U?.canceled||!U?.path)return;w(U.path)}catch(U){wn(l("打开文件夹选择框失败:{reason}",{reason:oa(U)}),"err")}}return s.jsx(Kt,{open:!0,onOpenChange:z=>{z||e()},children:s.jsxs(Yt,{className:"w-[min(520px,calc(100vw-48px))]",children:[s.jsxs(Ft,{children:[s.jsx($t,{children:l(c?"正在下载内核":"下载内核")}),s.jsx("span",{className:"text-[11.5px] text-subtle",children:l("内核 {version}({asset})",{version:r?.version||"—",asset:r?.asset||"—"})})]}),c?s.jsxs(Ht,{className:"flex flex-col gap-3",children:[s.jsx(qd,{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?l("{percent}%({received} / {total} MB)",{percent:d,received:t2(o?.received),total:t2(o?.total)}):l("正在连接 GitHub…")}),s.jsx("span",{className:"text-subtle",children:l("存放位置 {dir}",{dir:r?.kernelDir||"—"})})]}),s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:l("关掉这个窗口不会中断下载(它在后台继续跑)—— 要停下就点下面的「停止下载」,未下载完的临时文件会被删除。")})]}):s.jsxs(Ht,{className:"flex flex-col gap-3.5",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(tt,{htmlFor:"kernel-proxy",children:l("下载线路")}),s.jsxs(ct,{value:D,onValueChange:z=>b(String(z)),children:[s.jsx(dt,{id:"kernel-proxy",className:Ue("w-full",A.broken&&"border-destructive-bd"),children:s.jsx(ut,{className:"min-w-0 truncate",children:I?.label||l("直连")})}),s.jsx(ft,{children:A.items.map(z=>s.jsx(Ye,{value:z.value,disabled:z.disabled,children:z.label},z.value))})]}),s.jsx("div",{className:"text-[12px] text-subtle",children:A.broken?l("当前线路不可用:{error};重新选一条或切回直连",{error:String(r?.downloadProxy?.error||"")}):l("选项来自「网络代理」页(Clash Verge 同步的出口在这里可用;订阅节点要等内核起来才有端口)。选「直连」时连不上会自动借 Clash 混合端口重试一次;选定某条线路后只走它。")})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(tt,{htmlFor:"kernel-dir",children:l("存放位置")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ke,{id:"kernel-dir",className:"min-w-0 flex-1 font-mono text-[12px]",autoComplete:"off",spellCheck:!1,value:j,placeholder:M,onChange:z=>w(z.currentTarget.value)}),s.jsx(se,{variant:"outline",size:"sm",className:"flex-none",onClick:()=>{L()},children:l("选择目录…")}),M&&j.trim()!==M?s.jsx(se,{variant:"ghost",size:"sm",className:"flex-none",title:M,onClick:()=>w(M),children:l("恢复默认")}):null]}),s.jsx("div",{className:"text-[12px] text-subtle",children:l("内核二进制 / 配置 / 端口映射都会放在这里,默认 {dir};目录不存在会在下载开始时自动创建。",{dir:M||"—"})})]}),o?.state==="error"&&o.error?s.jsx("span",{className:"text-[12px] text-destructive",children:l("上次下载失败:{reason}",{reason:o.error})}):null,o?.state==="canceled"?s.jsx("span",{className:"text-[12px] text-subtle",children:l("上次下载已停止,未下载完的临时文件已删除")}):null,R?s.jsx("span",{className:"text-[12px] text-destructive",children:R}):null]}),s.jsx(sn,{children:c?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:e,children:l("后台继续")}),s.jsx(se,{variant:"destructive",disabled:C,onClick:()=>{_()},children:l(C?"正在停止…":"停止下载")})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:e,children:l("取消")}),s.jsx(se,{variant:"default",disabled:S||t.pending,onClick:()=>{O()},children:l(S?"正在开始…":"下载")})]})})]})})}function n2({showPortRange:e=!1}){const t=x.useSyncExternalStore(Ag,Og),r=Ou(),[o,c]=x.useState(null),[d,f]=x.useState(!1);x.useEffect(()=>{let v=!0;return(async()=>{try{const y=await YM();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=r?.download.state==="downloading",g=p&&r.download.total>0?Math.round(r.download.received/r.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:r?.running?"default":"secondary",children:r?.running?l("内核运行中"):r?.installed?l("内核已停止"):l("内核未安装")}),s.jsxs("span",{className:"text-[12.5px] text-text-2",children:[r?.installed?l("内核 {version}",{version:r.version})+" · ":"",r?.running?l("控制端口 {port} · {n} 个节点监听器",{port:r?.controllerPort??"—",n:r?.listenerCount??0}):r?.installed?l("内核已停止,点「启动内核」拉起"):l("按需下载(约 20-40MB)")]}),e&&o?s.jsx("span",{className:"text-[11.5px] text-subtle",children:l("节点端口范围 {base}–{end}",{base:o.base,end:o.end})}):null,s.jsx("div",{className:"ml-auto flex items-center gap-2",children:r?.installed?s.jsxs(s.Fragment,{children:[s.jsx(se,{size:"sm",variant:"outline",disabled:t.pending||p,onClick:()=>{o9()},children:r?.running?l("重启内核"):l("启动内核")}),s.jsx(se,{size:"sm",variant:"destructive",disabled:t.pending||p,onClick:()=>{i9()},children:l("删除内核")})]}):s.jsx(se,{size:"sm",variant:"outline",disabled:t.pending&&!p,onClick:()=>f(!0),children:l(p?"下载中…":"下载内核")})})]}),p?s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(qd,{className:"min-w-[200px] flex-1",value:g??null}),s.jsx("span",{className:"text-[11px] text-subtle",children:g!==null?l("{percent}%({received} / {total} MB)",{percent:g,received:s2(r.download.received),total:s2(r.download.total)}):l("下载中…")})]}):null,r?.lastError?s.jsx("span",{className:"text-[12px] text-destructive",children:r.lastError}):null,d?s.jsx(d9,{onClose:()=>f(!1)}):null]})}function f9({onClose:e}){const t=x.useSyncExternalStore(Ag,Og),r=ZK(),o=t.data!==null,[c,d]=x.useState(null);return x.useEffect(()=>{qi()},[]),s.jsxs(Kt,{open:!0,onOpenChange:f=>{f||e()},children:[s.jsxs(Yt,{className:"w-[min(880px,calc(100vw-48px))]",children:[s.jsxs(Ft,{children:[s.jsx($t,{children:l("订阅管理")}),s.jsxs("span",{className:"text-[11.5px] text-subtle",children:[o?l("{n} 条订阅",{n:r.length}):l("加载中…")," · ",l("节点由内核起成本地监听器,镜像进代理池")]})]}),s.jsxs(Ht,{className:"flex flex-col gap-3",children:[s.jsx(n2,{}),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:l("名称")}),s.jsx("th",{children:l("订阅链接")}),s.jsx("th",{className:"ta-center",children:l("节点")}),s.jsx("th",{children:l("上次同步")}),s.jsx("th",{className:"ta-center",children:l("启用")}),s.jsx("th",{className:"ta-right",children:l("操作")})]})}),s.jsx("tbody",{children:r.length?r.map(f=>{const p=Ou()?.providerSync?.[f.id];return s.jsxs("tr",{className:f.enabled?"":"off",children:[s.jsx("td",{children:s.jsx("b",{children:f.name||l("未命名")})}),s.jsx("td",{className:"group",children:s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"font-mono text-[12px] text-text-2",title:f.url,children:p9(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:l("复制订阅链接"),children:"⧉"})]})}),s.jsx("td",{className:"ta-center",children:r2(p,f)>0?s.jsx(ze,{variant:"secondary",children:l("{n} 个",{n:r2(p,f)})}):s.jsx("span",{className:"text-subtle",children:l("—")})}),s.jsx("td",{children:p?.at?s.jsx("span",{className:"text-[12px] text-text-2",children:qM(p.at)}):s.jsx("span",{className:"text-subtle",children:l("未同步")})}),s.jsx("td",{className:"ta-center",children:s.jsx(Rs,{checked:f.enabled,disabled:t.pending,"aria-label":l("启用订阅「{name}」",{name:f.name||l("未命名")}),onCheckedChange:g=>{n9(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,onClick:()=>{s9(f)},children:t.refreshing===f.id?l("更新中…"):l("立即更新")}),s.jsx(se,{size:"sm",variant:"ghost",disabled:t.pending,onClick:()=>d({item:f}),children:l("编辑")}),s.jsx(se,{size:"sm",variant:"destructive",disabled:t.pending,onClick:()=>{r9(f)},children:l("删除")})]})})]},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:l("还没有订阅:粘贴订阅链接,或从图片识别二维码导入。")}),s.jsx(se,{size:"sm",variant:"outline",disabled:t.pending,onClick:()=>d({item:null}),children:l("+ 新增订阅")}),s.jsx("span",{className:"text-[11px] text-subtle",children:l("订阅里的节点会自动同步进代理池,账号即可引用。")})]}):l("加载中…")})})})]})}),s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:l("订阅里的节点会被内核起成本地监听器,镜像到代理池(账号按 id 引用,与本页其它出口同一用法)。内核只在用到订阅时按需下载(约 20-40MB),不随安装包分发。")}),t.error?s.jsx("span",{className:"text-destructive",children:l("读取失败:{reason}",{reason:t.error})}):null]}),s.jsxs(sn,{children:[s.jsx(se,{variant:"default",disabled:t.pending,onClick:()=>d({item:null}),children:l("+ 新增订阅")}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:e,children:l("完成")})]})]}),c?s.jsx(m9,{item:c.item,onClose:()=>d(null)}):null]})}function s2(e){return!Number.isFinite(e)||e<=0?"—":(e/1e3/1e3).toFixed(1)}function p9(e){try{const t=new URL(e);return t.host+(t.pathname!=="/"?"/…":"")}catch{return e.slice(0,60)}}function r2(e,t){return e?.count??t.nodeCount}function m9({item:e,onClose:t}){const r=e!==null,[o,c]=x.useState(e?.name||""),[d,f]=x.useState(e?.url||""),[p,g]=x.useState(e?e.enabled:!0),[v,y]=x.useState(!1),[b,j]=x.useState(!1),[w,S]=x.useState(null),N=x.useRef(null);async function C(){if(v)return;const k=o.trim(),A=d.trim();if(!k){S(s.jsxs("span",{className:"text-destructive",children:["❌ ",l("请填写订阅名称")]}));return}if(!(A.startsWith("http://")||A.startsWith("https://"))){S(s.jsxs("span",{className:"text-destructive",children:["❌ ",l("订阅链接必须是 http:// 或 https:// 开头")]}));return}y(!0);try{r?await t9(e,{name:k,url:A,enabled:p}):await e9(k,A),t()}catch(D){S(s.jsxs("span",{className:"text-destructive",children:["❌ ",oa(D)]})),y(!1)}}async function E(k){if(!b){j(!0),S(l("正在识别二维码…"));try{const A=await c9(k);f(A),S(s.jsxs("span",{className:"text-success",children:["✅ ",l("已识别订阅链接")]}))}catch(A){S(s.jsxs("span",{className:"text-destructive",children:["❌ ",oa(A)]}))}finally{j(!1)}}}function R(k){const D=Array.from(k.clipboardData?.files||[]).find(I=>I.type.startsWith("image/"));D&&(k.preventDefault(),E(D))}return s.jsx(Kt,{open:!0,onOpenChange:k=>{!k&&!v&&t()},children:s.jsxs(Yt,{className:"max-w-[560px]",overlayForceRender:!0,onPaste:R,children:[s.jsx(Ft,{children:s.jsx($t,{children:l(r?"编辑订阅":"新增订阅")})}),s.jsxs(Ht,{className:"flex flex-col gap-3.5",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(tt,{htmlFor:"sub-name",children:l("名称")}),s.jsx(Ke,{id:"sub-name",maxLength:60,autoComplete:"off",spellCheck:!1,placeholder:l("例如:我的机场"),value:o,onChange:k=>c(k.currentTarget.value)})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(tt,{htmlFor:"sub-url",children:l("订阅链接")}),s.jsx(Ke,{id:"sub-url",autoComplete:"off",spellCheck:!1,placeholder:"https://…",value:d,onChange:k=>f(k.currentTarget.value)}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(se,{size:"sm",variant:"outline",disabled:b,onClick:()=>N.current?.click(),children:l(b?"识别中…":"从图片识别二维码")}),s.jsx("span",{className:"text-[11px] text-subtle",children:l("也可以把二维码截图直接粘贴到弹窗里(Ctrl+V)")}),s.jsx("input",{ref:N,type:"file",accept:"image/*",className:"hidden",onChange:k=>{const A=k.currentTarget.files?.[0];A&&E(A),k.currentTarget.value=""}})]})]}),s.jsxs("div",{className:"flex flex-row items-center gap-2.5",children:[s.jsx(Rs,{checked:p,onCheckedChange:g,"aria-label":l("启用这条订阅")}),s.jsx("span",{className:"text-[12.5px]",children:l("启用(禁用的订阅不参与内核同步,它的节点会从代理池移除)")})]}),s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:l("订阅内容由内核定时刷新(每 24 小时);节点数与同步状态在保存后由轮询刷新,稍等几秒。")}),s.jsx("div",{className:"min-h-[18px] text-xs text-subtle",children:w})]}),s.jsxs(sn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:v,onClick:t,children:l("取消")}),s.jsx(se,{variant:"default",disabled:v||b,onClick:()=>{C()},children:l(v?"保存中…":"保存")})]})]})})}const _w=[{key:"pick",label:l("选择"),align:"center"},{key:"name",label:l("节点")},{key:"addr",label:l("地址")},{key:"state",label:l("启用"),align:"center"},{key:"test",label:l("连通性")},{key:"act",label:l("操作"),align:"right"}],h9={pick:"p-pick",name:"",addr:"p-addr",state:"p-state",test:"p-test",act:"p-act"},a2="proxies";function Lw(){return window}let Mg=null,l2=null;function o2(){return Mg?Mg.apply([..._w]):_w.map(e=>({...e,align:e.align??"left"}))}function g9(){Lw().wbTableColumns?.repaint?.(a2)}function x9(e){if(l2=e,Mg)return!0;const t=Lw().wbColSettings;return t?.register?(Mg=t.register({id:a2,label:l("代理池表"),columns:_w.map(r=>({key:r.key,label:r.label,align:r.align??"left"})),mount:()=>document.querySelector('.page[data-page="proxies"] .panel-head .head-actions'),onChange:()=>l2?.()}),!0):!1}function b9(){Lw().wbColSettings?.close?.()}function v9(){const e=x.useSyncExternalStore(OK,MK),t=x.useSyncExternalStore(Ag,Og).data?.items??[],[r,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"),[C,E]=x.useState(0),[,R]=x.useReducer(ae=>ae+1,0),k=Iw(),A=e.data!==null,D=e.selected.size,I=k.filter(ae=>e.selected.has(ae.id)&&Yf(ae)).length,M=e.batchProgress;x.useEffect(()=>{qi()},[]),x.useLayoutEffect(()=>{if(!x9(()=>R())){const ae=window.setTimeout(()=>E(oe=>oe+1),50);return()=>window.clearTimeout(ae)}R()},[C]),x.useLayoutEffect(()=>{g9()}),x.useEffect(()=>()=>{b9()},[]);function O(ae){return ae.port===null||ae.port===void 0?"wait":ae.lastTest?.at?ae.lastTest.success?"ok":"fail":"none"}const _=g.trim().toLowerCase(),L=w9(k,t);function z(ae){return j==="all"?!0:j==="manual"||j==="clash"||j==="subscription"?Qa(ae)===j:j===c2?!!ae.orphan:ae.source==="subscription"&&!ae.orphan&&ae.providerId===j}function U(ae){return!(y!=="all"&&Qa(ae)!==y||!z(ae)||S!=="all"&&O(ae)!==S||_&&![ae.name,jh(ae),ae.host,ae.protocol,String(ae.port??"")].join(" ").toLowerCase().includes(_))}function B(ae){const oe=ae??"all";w(oe),b(oe==="all"?"all":oe==="manual"||oe==="clash"?oe:"subscription")}function Q(ae){b(ae),w("all")}const W=k.filter(U),Z=W.map(ae=>ae.id),Y=Z.length>0&&Z.every(ae=>e.selected.has(ae)),q=Z.some(ae=>e.selected.has(ae))&&!Y,G=o2(),$=[];for(const ae of i2())$.push(...W.filter(oe=>Qa(oe)===ae.key));const F=Vh(W.length,"proxies"),X=F.paged?F.slice($):$,re=new Map;for(const ae of W)re.set(Qa(ae),(re.get(Qa(ae))??0)+1);x.useEffect(()=>{F.goto(1)},[_,y,j,S]);function P(ae){const oe=ae.lastTest;if(!oe||!oe.at)return s.jsx("span",{className:"text-subtle",children:l("未测试")});const ee=Rw(oe.durationMs);return s.jsxs("div",{className:"flex flex-col gap-0.5 leading-[1.5] min-w-0",children:[s.jsxs("span",{className:oe.success?"text-success":"text-destructive",children:[oe.success?l("✅ {ip}",{ip:oe.ip||l("连接成功")}):l("❌ 连接失败"),ee?` ${ee}`:"",s.jsxs("span",{className:"text-[11px] text-subtle",children:[" ",qM(oe.at)]})]}),oe.success?null:s.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-[11px] text-subtle",title:String(oe.error||l("连接失败")),children:String(oe.error||l("连接失败"))})]})}function V(ae){const oe=ae.usedBy||[],ee=[];return ae.protocol&&ee.push(ae.protocol),oe.length&&ee.push(s.jsx("span",{className:"text-warn",title:oe.map(de=>String(de.name||de.id||"")).join(l("、")),children:l("{n} 个账号在用",{n:oe.length})})),ee.length?s.jsx("span",{className:"text-[11px] text-subtle",children:ee.map((de,K)=>s.jsxs(x.Fragment,{children:[K?" · ":"",de]},K))}):null}function J(ae){if(ae.resolveError)return s.jsx("span",{className:"text-destructive",title:ae.resolveError,children:l("解析失败")});if(Ew(ae)){const ee=Ou()?.installed===!1;return s.jsx("span",{className:"text-subtle",title:l(ee?"代理内核未安装(在「订阅管理」里下载内核后,节点会自动分配监听端口)":"还没有监听端口(点「测试」会自动补建并等它就绪;或在账号里引用它,保存后自动补建)"),children:jh(ae)||l("未分配端口")})}const oe=jh(ae);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:oe||void 0,children:oe||"—"}),oe?s.jsx(se,{variant:"ghost",size:"icon-xs",className:"copy-btn flex-none","data-copy":oe,title:l("复制地址"),children:"⧉"}):null]})}function ie(ae,oe,ee,de){const K=ee||e.batchBusy;switch(ae){case"pick":return s.jsx(ea,{checked:de,title:l("勾选后可批量操作"),"aria-label":l("勾选「{name}」",{name:oe.name||l("未命名")}),onCheckedChange:be=>IK(oe.id,be)});case"name":return s.jsxs("div",{className:"flex flex-col gap-0.5 leading-[1.5] min-w-0",children:[s.jsx("b",{children:oe.name||l("未命名")}),V(oe)]});case"addr":return J(oe);case"state":{const be=Yf(oe),ne=Eg(oe);return s.jsx(Rs,{checked:oe.enabled,disabled:K||be,"aria-label":l("启用「{name}」",{name:oe.name||l("未命名")}),title:be?ne:void 0,onCheckedChange:ce=>{BK(oe,ce)}})}case"test":return P(oe);case"act":{const be=Mw(oe);Yf(oe);const ne=Eg(oe),ce=e.testing===oe.id;return s.jsxs("div",{className:"row-actions",children:[s.jsx(se,{size:"sm",variant:"ghost",disabled:K||e.testing!==null,onClick:()=>{zK(oe)},children:l(ce?"测试中…":"测试")}),oe.source!=="clash"&&oe.source!=="subscription"?s.jsxs(s.Fragment,{children:[s.jsx(se,{size:"sm",variant:"ghost",disabled:K,onClick:()=>o({item:oe}),children:l("编辑")}),s.jsx(se,{size:"sm",variant:"destructive",disabled:K,onClick:()=>{KM(oe)},children:l("删除")})]}):null,be?s.jsx(se,{size:"sm",variant:"destructive",disabled:K,title:ne,onClick:()=>{KM(oe)},children:l("删除")}):null]})}default:return null}}function me(ae){const oe=e.pending.has(ae.id),ee=DK(ae.id);return s.jsx("tr",{className:Ue(ae.enabled?"":"off",ee&&"bg-primary-soft"),"data-id":ae.id,children:G.map(de=>s.jsx("td",{className:`ta-${de.align}`,children:ie(de.key,ae,oe,ee)},de.key))},ae.id)}function he(){if(!k.length)return s.jsx("tr",{children:s.jsx("td",{colSpan:G.length,className:"empty",children:l(A?"还没有代理。点右上角「+ 新增代理」手填一个,点「同步 Clash Verge」把 Clash 的出口导进来,或在「订阅管理」里导入订阅节点。":"加载中…")})});if(!W.length)return s.jsx("tr",{children:s.jsx("td",{colSpan:G.length,className:"empty",children:_?l("没有匹配「{kw}」的出口",{kw:g.trim()}):l("没有匹配当前筛选的出口")})});const ae=[];let oe="";for(const ee of X){const de=Qa(ee);if(de!==oe){oe=de;const K=i2().find(be=>be.key===de);ae.push(s.jsx("tr",{className:"tr-group",children:s.jsxs("td",{colSpan:G.length,children:[s.jsx("span",{className:"prov-tag",children:K?.label??de}),l("{n} 个",{n:re.get(de)??0}),K?.note?s.jsxs("span",{className:"font-normal",children:[" · ",K.note]}):null]})},`group:${de}:${ae.length}`))}ae.push(me(ee))}return s.jsx(s.Fragment,{children:ae})}return s.jsx(s.Fragment,{children:s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:l("代理池")}),s.jsx("span",{className:"panel-sub",children:A?l("{n} 个出口",{n:k.length}):l("加载中…")}),s.jsx("span",{className:"text-[11px] text-subtle",children:l("订阅与 Clash 的出口自动镜像进来")}),s.jsxs("div",{className:"head-actions",children:[s.jsx(se,{variant:"outline",disabled:e.batchBusy,onClick:()=>d(!0),children:l("设置")}),s.jsx(se,{variant:"outline",disabled:e.batchBusy,onClick:()=>p(!0),children:t.length?l("订阅管理({n})",{n:t.length}):l("订阅管理")}),s.jsx(se,{variant:"outline",disabled:e.syncing||e.batchBusy,onClick:()=>{LK()},children:e.syncing?l("同步中…"):l("同步 Clash Verge")}),s.jsx(se,{variant:"outline",disabled:e.loading||e.batchBusy,onClick:()=>{Xf(),qi()},children:e.loading?l("刷新中…"):l("刷新")}),s.jsx(se,{variant:"default",disabled:e.batchBusy,onClick:()=>o({item:null}),children:l("+ 新增代理")})]})]}),s.jsx("div",{className:"px-3 pt-3",children:s.jsx(n2,{showPortRange:!0})}),D>0?s.jsxs("div",{className:"batch-bar active",children:[s.jsxs("span",{className:"batch-count",children:[l("已选")," ",s.jsx("b",{children:D})," ",l("个 · 共")," ",s.jsx("b",{children:W.length})," ",l("个")]}),I?s.jsx("span",{className:"batch-hidden",children:l("其中 {n} 条是同步来的只读条目(Clash / 订阅):可参与批量测试,删除会跳过",{n:I})}):null,s.jsxs("div",{className:"batch-actions",children:[s.jsx(se,{variant:"outline",disabled:e.batchBusy,onClick:()=>{HK()},children:M?l("测试中 {done}/{total}",{done:M.done,total:M.total}):l("批量测试")}),s.jsx(se,{variant:"destructive",disabled:e.batchBusy,onClick:()=>{UK()},children:l("批量删除")}),s.jsx(se,{variant:"outline",disabled:e.batchBusy,onClick:()=>_K(),children:l("取消选择")})]})]}):s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5 border-b border-border px-4 py-[10px]",children:[s.jsxs(ji,{className:"w-[clamp(150px,22vw,220px)]",children:[s.jsx(Si,{type:"search",value:g,"aria-label":l("搜索节点"),placeholder:l("搜索名称 / 地址 / 端口"),onChange:ae=>v(ae.currentTarget.value)}),s.jsx(wi,{align:"inline-start","aria-hidden":"true",children:s.jsx(S9,{})})]}),s.jsxs(ct,{value:j,onValueChange:B,children:[s.jsx(dt,{className:"w-[clamp(150px,18vw,210px)]","aria-label":l("按提供方筛选"),children:s.jsx(ut,{children:L.find(ae=>ae.value===j)?.label??l("全部提供方")})}),s.jsx(ft,{children:L.map(ae=>s.jsx(Ye,{value:ae.value,children:s.jsxs("span",{className:"flex w-full items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate"+(ae.count?"":" text-subtle"),children:ae.label}),s.jsx("span",{className:"flex-none text-[11px] text-subtle",children:ae.count})]})},ae.value))})]}),s.jsx(Gn,{options:y9(k),value:y,onValueChange:Q,"aria-label":l("按来源筛选")}),s.jsx(Gn,{options:j9(k),value:S,onValueChange:N,"aria-label":l("按状态筛选")}),s.jsx("span",{className:"ml-auto text-[11px] text-subtle",children:l("显示 {n} / 共 {total} 个出口",{n:W.length,total:k.length})})]}),s.jsx("div",{className:"models-table-wrap",children:s.jsxs("table",{className:"models-table proxies-table",children:[s.jsx("colgroup",{children:G.map(ae=>s.jsx("col",{"data-col":ae.key,className:h9[ae.key]||void 0},ae.key))}),s.jsx("thead",{children:s.jsx("tr",{children:G.map(ae=>s.jsx("th",{"data-col":ae.key,className:`ta-${ae.align}`,children:ae.key==="pick"?s.jsx(ea,{checked:Y,indeterminate:q,disabled:!Z.length,title:l("全选当前筛选出的出口"),"aria-label":l("全选当前筛选出的出口"),onCheckedChange:oe=>PK(Z,oe)}):ae.label},ae.key))})}),s.jsx("tbody",{children:he()})]})}),s.jsx(Di,{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?l("未检测到 Clash Verge:{reason}",{reason:e.data.clash.error}):l("未检测到 Clash Verge")}):null,e.error?s.jsx("span",{className:"text-destructive",children:l("读取失败:{reason}",{reason:e.error})}):null]}),total:W.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}),r?s.jsx(GK,{item:r.item,onClose:()=>o(null)}):null,c?s.jsx(KK,{onClose:()=>d(!1)}):null,f?s.jsx(f9,{onClose:()=>p(!1)}):null]})})}function Qa(e){return e.source==="clash"?"clash":e.source==="subscription"?"subscription":"manual"}function i2(){return[{key:"manual",label:l("手动"),note:l("本页可编辑、可删除")},{key:"clash",label:"Clash Verge",note:l("只读:在 Clash Verge 里改")},{key:"subscription",label:l("订阅"),note:l("只读:在「订阅管理」里改")}]}function y9(e){const t=r=>e.filter(o=>Qa(o)===r).length;return[{value:"all",label:l("全部"),count:e.length},{value:"manual",label:l("手动"),count:t("manual")},{value:"clash",label:"Clash",count:t("clash")},{value:"subscription",label:l("订阅"),count:t("subscription")}]}function j9(e){const t=o=>o.port===null||o.port===void 0?"wait":o.lastTest?.at?o.lastTest.success?"ok":"fail":"none",r=o=>e.filter(c=>t(c)===o).length;return[{value:"all",label:l("全部状态"),count:e.length},{value:"ok",label:l("可用"),count:r("ok")},{value:"fail",label:l("失败"),count:r("fail")},{value:"wait",label:l("未就绪"),count:r("wait")}]}const c2="__orphan";function w9(e,t){const r=e.filter(d=>Qa(d)==="subscription"),o=t.map(d=>({value:d.id,label:d.name||d.id,count:r.filter(f=>!f.orphan&&f.providerId===d.id).length})).sort((d,f)=>f.count-d.count||d.label.localeCompare(f.label)),c=r.filter(d=>d.orphan).length;return[{value:"all",label:l("全部提供方"),count:e.length},{value:"manual",label:l("手动"),count:e.filter(d=>Qa(d)==="manual").length},{value:"clash",label:"Clash Verge",count:e.filter(d=>Qa(d)==="clash").length},{value:"subscription",label:l("全部订阅"),count:r.length},...o,...c?[{value:c2,label:l("已移除的订阅"),count:c}]:[]]}function S9(){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 Xf(),await qi()},visibleColumns:()=>o2().map(e=>({key:e.key}))};const u2='.page[data-page="proxies"]';function d2(){const e=document.querySelector(u2);!e||e.dataset.mounted==="1"||(e.dataset.mounted="1",e.replaceChildren(),jn.createRoot(e).render(s.jsx(v9,{})),Us().wbApp?.currentPage==="proxies"&&(Xf(),qi()))}document.querySelector(u2)?d2():document.addEventListener("DOMContentLoaded",d2,{once:!0});const Dg=["today","7","30","month","all","custom"],zw="7",Bw="custom",f2="workbuddy-desktop-report-range",p2="workbuddy-desktop-report-custom-range",m2={today:l("今天"),7:l("近 7 天"),30:l("近 30 天"),month:l("本月"),all:l("全部"),custom:l("自定义区间")},N9={today:l("今天"),7:l("7 天"),30:l("30 天"),month:l("本月"),all:l("全部"),custom:l("自定义")};function C9(){try{const e=localStorage.getItem(f2);return e!==null&&Dg.includes(e)?e:zw}catch{return zw}}function Hw(e){const t=r=>String(r).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function k9(){const e=new Date;return{start:Hw(new Date(e.getFullYear(),e.getMonth(),e.getDate()-6)),end:Hw(e)}}const Ig=/^\d{4}-\d{2}-\d{2}$/;function T9(){try{const e=localStorage.getItem(p2);if(e){const t=JSON.parse(e),r=typeof t?.start=="string"?t.start:"",o=typeof t?.end=="string"?t.end:"";if(Ig.test(r)&&Ig.test(o)&&r<=o)return{start:r,end:o}}}catch{}return k9()}function E9(e){try{localStorage.setItem(p2,JSON.stringify(e))}catch{}}const R9=[[0,l("一")],[2,l("三")],[4,l("五")]],h2=400;function Ki(e){const t=Uw();return t.formatInt?t.formatInt(e):(Number(e)||0).toLocaleString("zh-CN")}function Uw(){return window.wbUnits||{}}function Wn(e){const t=Uw();return t.formatTokens?t.formatTokens(e):String(Number(e)||0)}function g2(e,t){const r=Uw();return r.formatAxis?r.formatAxis(e,t):String(e)}function Yi(e){return`${((Number(e)||0)*100).toFixed(1)}%`}function Pt(e){return Math.round(e*10)/10}function Vw(e){return[...e].reduce((t,r)=>t+(/[\u2e80-\u9fff]/.test(r)?9.7:5.4),0)}function Pg(e){const[t,r,o]=String(e||"").split("-").map(Number);return new Date(t||1970,(r||1)-1,o||1)}const A9=[l("日"),l("一"),l("二"),l("三"),l("四"),l("五"),l("六")];function _g(e){const t=Pg(e);return l("{m}月{d}日 周{wd}",{m:t.getMonth()+1,d:t.getDate(),wd:A9[t.getDay()]})}function x2(e){const t=String(e||"").slice(11,13);return t?`${t}:00`:"—"}const O9=8;function b2(e,t){const r=(Array.isArray(e)?e:[]).map(d=>({name:String(d?.label??d?.model??"").trim()||l("未知模型"),tokens:Number(d?.tokens)||0})).filter(d=>d.tokens>0);if(!r.length)return[];const o=r.slice(0,O9),c=o.map(d=>`${t?`[${t(d.name)}]`:""}${l("{model}:{tokens} tokens",{model:d.name,tokens:Wn(d.tokens)})}`);return r.length>o.length&&c.push(l("…还有 {n} 个模型",{n:r.length-o.length})),c}function v2(e,t){return[_g(e.date),l("总 Token:{tokens}({n} 次请求)",{tokens:Wn(e.tokens),n:Ki(e.requests)}),...b2(e.models,t)].join(` -`)}function M9(e,t){return[`${_g(String(e.hour).slice(0,10))} ${x2(e.hour)}`,l("命中率 {rate}(命中 {hit} / 输入 {input})",{rate:Yi(e.rate),hit:Wn(e.hitTokens),input:Wn(e.inputTokens)}),l("总 Token:{tokens}",{tokens:Wn(e.totalTokens)}),...b2(e.models,t)].join(` -`)}const D9=[1,1.5,2,2.5,3,4,5,6,8,10];function I9(e){if(!(e>0))return 1;const t=10**Math.floor(Math.log10(e)),r=e/t;return(D9.find(c=>c>=r-1e-9)??10)*t}function $w(e){return I9(e/4)*4}function P9(e,t,r){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:l("总请求数"),value:Ki(d),sub:m2[t]||"",mono:!1},{key:"successful",label:l("成功请求数"),value:Ki(f),sub:l("成功率 {rate}",{rate:p}),mono:!1},{key:"tokens",label:l("总 Token"),value:Wn(o.tokens),sub:l("输入 + 输出"),mono:!1},{key:"activeDays",label:l("活跃天数"),value:Ki(o.activeDays),sub:l("区间共 {n} 天",{n:r}),mono:!1},{key:"streak",label:l("当前连续天数"),value:Ki(o.streak),sub:l("含今天在内往前数"),mono:!1}];return g.push(c?{key:"topModel",label:l("Top 模型"),value:String(c.model??""),sub:l("{tokens} tokens · 占 {pct}",{tokens:Wn(c.tokens),pct:Yi(c.percentage)}),mono:!0}:{key:"topModel",label:l("Top 模型"),value:"—",sub:l("所选范围内还没有模型用量"),mono:!1}),g}function y2(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 r=t.reduce((c,d)=>c+d.tokens,0),o=c=>r?c/r*100:0;return[...t].sort((c,d)=>d.tokens-c.tokens).map((c,d)=>{const f=o(c.tokens),p=Wn(c.tokens),g=c.label||c.id||l("未知"),v=c.id?l("{name}({id})",{name:g,id:c.id}):g;return{key:`${d}-${c.id||g}`,id:c.id,name:g,full:v,tip:l("{name}:{tokens} tokens · 占 {pct}%",{name:v,tokens:p,pct:f.toFixed(1)}),tokensText:p,percentText:`${f.toFixed(1)}%`,barWidth:`${f.toFixed(1)}%`}})}function j2(e){return`${Wn(e.reduce((t,r)=>t+(Number(r?.totalTokens??r?.tokens)||0),0))} tokens`}const Lg=["#f73b00","#f7bb07","#4aaa4d","#1872cb","#3444a3","#13c2c2","#722ed1","#eb2f96","#a0d911","#34d399","#d946ef","#ff85c0","#b37feb","#9d174d","#ffa39e","#69b1ff"],_9={size:220,inner:.62,outer:.88,padAngle:2};function L9(e,t,r,o,c,d){const f=R=>(R-90)*Math.PI/180,p=(R,k)=>[Pt(e+R*Math.cos(f(k))),Pt(t+R*Math.sin(f(k)))],g=d-c;if(g>=359.999){const[R,k]=p(r,0),[A,D]=p(r,180),[I,M]=p(o,0),[O,_]=p(o,180);return`M ${R} ${k} A ${r} ${r} 0 1 1 ${A} ${D} A ${r} ${r} 0 1 1 ${R} ${k} Z M ${I} ${M} A ${o} ${o} 0 1 0 ${O} ${_} A ${o} ${o} 0 1 0 ${I} ${M} Z`}const[v,y]=p(r,c),[b,j]=p(r,d),[w,S]=p(o,d),[N,C]=p(o,c),E=g>180?1:0;return`M ${v} ${y} A ${r} ${r} 0 ${E} 1 ${b} ${j} L ${w} ${S} A ${o} ${o} 0 ${E} 0 ${N} ${C} Z`}const z9="#9aa0a6";function w2(e){const t=new Map;for(const r of Array.isArray(e)?e:[]){const o=String(r?.label??r?.model??r?.id??"").trim();!o||t.has(o)||(Number(r?.totalTokens??r?.tokens)||0)>0&&t.set(o,Lg[t.size%Lg.length])}return t}function S2(e,t){const r=(Array.isArray(e)?e:[]).map(C=>({label:String(C?.label??C?.model??C?.id??"").trim()||t,tokens:Number(C?.totalTokens??C?.tokens)||0,requests:Number(C?.requests)||0})).filter(C=>C.tokens>0);if(!r.length)return null;const o=r.reduce((C,E)=>C+E.tokens,0);if(!o)return null;const c=w2(e),{size:d,inner:f,outer:p,padAngle:g}=_9,v=d/2,y=d/2,b=d/2*p,j=d/2*f;let w=0;const S=[],N=[];return r.forEach((C,E)=>{const R=C.tokens/o,k=R*360,A=r.length>1?Math.min(g/2,k/4):0,D=w+A,I=w+k-A;w+=k;const M=c.get(C.label)??Lg[E%Lg.length];let O=null;if(R>=.03){const _=(D+I)/2,L=j+(b-j)*.6,z=(_-90)*Math.PI/180;O={x:Pt(v+L*Math.cos(z)),y:Pt(y+L*Math.sin(z)),text:`${Math.round(R*100)}%`}}I>D&&S.push({key:`${E}-${C.label}`,d:L9(v,y,b,j,D,I),fill:M,evenOdd:k>=359.999,label:O,tip:`${C.label} · ${Wn(C.tokens)} tokens · ${Yi(R)}`}),N.push({key:`${E}-${C.label}`,fill:M,name:C.label,tokensText:Wn(C.tokens),percentText:Yi(R),tip:l("{name} · {tokens} tokens · {n} 次请求 · {pct}",{name:C.label,tokens:Wn(C.tokens),n:Ki(C.requests),pct:Yi(R)})})}),{size:d,slices:S,legend:N,totalText:Wn(o)}}const B9=[1,1.25,1.5,2,2.5,3,4,5,6,8,10];function H9(e){if(!(e>0))return 1;const t=10**Math.floor(Math.log10(e)),r=e/t;let o=1;for(const c of B9)c<=r+1e-9&&(o=c);return o*t}function U9(e){const t=Number(e)||0;if(t<=0)return[0,1,2,3,1/0];const r=Math.max(1,H9(t/4));return[0,r,r*2,r*3,1/0]}function V9(e,t){if(e===0)return"0";const r=t[e-1],o=t[e];return Number.isFinite(o)?r===0?`≤${Wn(o)}`:`${Wn(r)}–${Wn(o)}`:`>${Wn(r)}`}function N2(e){const t=Array.isArray(e)?e:[];return U9(t.reduce((r,o)=>Math.max(r,Number(o?.tokens)||0),0))}function $9(e,t){const r=Array.isArray(e)?e:[];if(!r.length)return null;const o=(Pg(r[0].date).getDay()+6)%7,c=new Array(o).fill(null).concat(r),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,C=Math.max(w,Math.round(t)),E=N2(r),R=O=>E.findIndex(_=>Number(O)<=_),k=[];for(let O=0;O({key:_,x:S+p-6,y:Pt(b+O*j+y/2),text:_})),D=[];let I=-1,M=-9;for(let O=0;O({level:t,text:V9(t,e)}))}function q9(e){const t=e||{};return[["last10m",l("近 10 分钟")],["last1h",l("近 1 小时")],["last24h",l("近 24 小时")],["last7d",l("近 7 天")]].map(([o,c])=>{const d=t[o]||{},f=Number(d.inputTokens)||0;return{key:o,label:c,value:f?Yi(d.rate):"—",sub:l("命中 {hit} / 输入 {input}",{hit:Wn(d.hitTokens),input:Wn(f)})}})}function G9(e,t,r){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(Y=>Number(Y.rate)||0),v=o.map(Y=>Number(Y.totalTokens)||0),y=Math.max(1,$w(Math.max(...g))),b=Math.max(...v),j=$w(b),w=b>0,S=Y=>d.left+(o.length>1?f*Y/(o.length-1):f/2),N=Y=>d.top+p-p*Y/y,C=Y=>d.top+p-p*Y/j,E=[],R=[],k=[];for(let Y=0;Y<=4;Y+=1){const q=y*Y/4,G=Pt(N(q)),$=q*100;E.push({key:`g${Y}`,y:G}),R.push({key:`r${Y}`,x:d.left-8,y:G,anchor:"end",text:`${Number.isInteger($)?$:$.toFixed(1)}%`}),w&&k.push({key:`t${Y}`,x:Pt(d.left+f+8),y:G,anchor:"start",text:g2(j*Y/4,j)})}const A=o.length===1?4.5:2.5,D=(Y,q)=>({points:Y.map((G,$)=>`${Pt(S($))},${Pt(q(G))}`).join(" "),dots:Y.map((G,$)=>({key:`d${$}`,cx:Pt(S($)),cy:Pt(q(G))}))}),I=[],M=(Y,q,G,$)=>{const F=Vw(G),X=$==="middle"?Y-F/2:$==="end"?Y-F:Y,re={left:X,right:X+F,top:q-8.5,bottom:q+2.5};return I.some(P=>re.leftP.left-2&&re.topP.top-1)?null:(I.push(re),{key:`${G}-${Y}-${q}`,x:Pt(Y),y:Pt(q),text:G,anchor:$})},O=(Y,q)=>{const G=Vw(q)/2;return Y-Gd.left+f+6?"end":"middle"},_=[];w&&o.forEach((Y,q)=>{if(!(Number(Y.totalTokens)>0))return;const G=C(v[q]),$=G-12>=d.top-10,F=Wn(v[q]),X=M(S(q),$?G-12:G+13,F,O(S(q),F));X&&_.push({...X,key:`tl${q}`})});const L=[];o.forEach((Y,q)=>{if(!((Number(Y.inputTokens)||0)+(Number(Y.hitTokens)||0)>0))return;const $=N(g[q]),F=$+15<=d.top+p+8,X=Yi(g[q]),re=M(S(q),F?$+13:$-7,X,O(S(q),X));re&&L.push({...re,key:`rl${q}`})});const z=o.length>1?f/(o.length-1):f,U=d.left,B=d.left+f,Q=o.length<=h2?o.map((Y,q)=>{const G=Math.max(U,S(q)-z/2),$=Math.min(B,S(q)+z/2);return{key:`h${q}`,x:Pt(G),width:Pt($-G),tip:M9(Y,r)}}):null,W=Math.max(1,Math.ceil(o.length/8)),Z=[];for(let Y=0;Y=o.length;Z.push({key:`x${Y}`,x:Pt(S(Y)),y:c-8,anchor:Y===0?"start":q?"end":"middle",text:x2(o[Y].hour)})}return{width:t,height:c,plotLeft:U,plotW:f,plotH:p,plotTop:d.top,grid:E,rateTicks:R,tokenTicks:k,rateLine:D(g,N),tokenLine:w?D(v,C):null,dotR:A,rateLabels:L,tokenLabels:_,hourTicks:Z,hits:Q}}function K9(e,t,r){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=c-d.top-d.bottom,g=o.map(B=>Number(B.tokens)||0),v=Math.max(...g),y=$w(v),b=f/o.length,j=Math.max(1,Math.min(28,b*.68)),w=d.top+p,S=B=>d.top+p-p*B/y,N=o.length<=h2,C=v<=0,E=[],R=[];if(!C)for(let B=0;B<=4;B+=1){const Q=y*B/4,W=Pt(S(Q));E.push({key:`g${B}`,x1:d.left,y:W,x2:Pt(d.left+f)}),R.push({key:`v${B}`,x:d.left-8,y:W,anchor:"end",text:g2(Q,y)})}const k=[];o.forEach((B,Q)=>{const W=Number(B.tokens)||0;if(W<=0)return;const Z=S(W);k.push({key:String(B.date??Q),x:Pt(d.left+b*Q+(b-j)/2),y:Pt(Z),width:Pt(j),height:Pt(Math.max(1,w-Z)),rx:j>4?2:1,tip:v2(B),nativeTip:!N})});const A=o.map(B=>Number(B.tokens)>0?Wn(B.tokens):""),D=Math.max(0,...A.map(Vw)),I=A.every(B=>!B)||D+4<=b,M=new Set;I||o.map((B,Q)=>({index:Q,value:Number(B.tokens)||0})).filter(B=>B.value>0).sort((B,Q)=>Q.value-B.value).slice(0,8).forEach(B=>M.add(B.index));const O=[];o.forEach((B,Q)=>{if(!A[Q]||!I&&!M.has(Q))return;const W=S(Number(B.tokens)||0)-6,Z=W-9({key:`h${Q}`,x:Pt(d.left+b*Q),width:Pt(b),tip:v2(B,r)})):null,L=Math.max(1,Math.ceil(o.length/6)),z=[];for(let B=0;B{const Q=o.length===1,W=!Q&&B===o.length-1,Z=Pg(o[B].date);return{key:`d${B}`,x:Q?d.left+f/2:W?d.left+f:Pt(d.left+b*B+b/2),y:c-8,anchor:Q?"middle":W?"end":B===0?"start":"middle",text:`${Z.getMonth()+1}/${Z.getDate()}`}});return{width:t,height:c,plotLeft:d.left,plotW:f,plotH:p,plotTop:d.top,grid:E,valueTicks:R,bars:k,barLabels:O,dateTicks:U,hits:_,blank:C}}function Xi(){return window}const C2=1e3,Y9=Dg.map(e=>({value:e,label:N9[e]})),X9=l("所选范围内每个账号各消耗了多少 Token,按 Token 用量从多到少排。账号是比提供商更细的一维:同一家可以挂多个账号,转发时按优先级在候选链上依次尝试,所以这里反映的是「具体哪个登录态在出力」。百分比按本区间的总 Token 数算(这一块只看用量,请求次数与成功率在概览卡片里)。「未知账号」是指那批请求没有账号身份:走默认登录态转发(未配置账号列表)时会这样;这一维上线前写出的旧聚合行也没有账号明细,但它们会在升级导入旧数据时按明细自动补算回来 —— 只有明细已被手动清理掉的那几天补不回来,仍留在「未知账号」里,那是确实无从恢复的部分。"),Q9=l("所选范围内每个提供商各消耗了多少 Token,按 Token 用量从多到少排。同一个模型名可能有多家都能提供,网关按设置页「转发路由」的优先级依次尝试,所以占比也反映了实际落到谁身上。百分比按本区间的总 Token 数算(这一块只看用量,请求次数与成功率在概览卡片里)。「未知」是指那批请求没记下承载它的提供商 —— 主要是记录提供商这个功能上线之前的旧明细,其次是请求在选定上游之前就失败了(请求体非法、模型不存在、没有可用账号)。这一维与账号那一维不同:旧明细里根本没有「哪家承载」的信息(早期版本只有单一上游,但那是配置事实而非逐条记录),所以无法回算,旧数据会一直留在「未知」里;此后新产生的请求都会记上具体的提供商。"),Z9=l("所选范围内每个模型各消耗了多少 Token,按用量从多到少排,扇区角度即占比。中心是这一维的合计(等于概览里的总 Token),右侧每行给出该模型的 Token 用量与百分比。扇区内的百分比只在 ≥3% 时标出,更小的会挤成一团 —— 完整读数在右侧列表与悬停气泡里。颜色按用量排名分配:最大的那段是红色,依次往后;同一份报表里换个维度看,配色口径不变。"),W9=l("所选范围内每个提供商各消耗了多少 Token,按用量从多到少排,扇区角度即占比。同一个模型名可能有多家都能提供,网关按设置页「转发路由」的优先级依次尝试,所以占比也反映了实际落到谁身上。中心是这一维的合计(等于概览里的总 Token),右侧每行给出该提供商的 Token 用量与百分比。「未知」是指那批请求没记下承载它的提供商 —— 主要是记录提供商这个功能上线之前的旧明细,其次是请求在选定上游之前就失败了。"),J9=l("命中率 = 缓存读取 Token / 输入 Token(promptTokens)。窗口越短越贴近「此刻」:上游把缓存读取与输入分开上报时,该比值合法地可能超过 100%,此处不夹取值、如实展示。"),eY=l("每天的总 Token 用量(输入 + 输出)。柱顶标出当天的读数;区间很长、柱子挤到放不下时只标最高的那几天,其余悬停柱子即可读到。");let zg=C2,Bg=!0,Fw=!1,qw=!1,Gw=0,Ro=null,Qi=null,Hg=null;function Zi(e,t="empty"){return s.jsx("div",{className:t,style:{padding:"14px 0"},children:e})}function Ug({text:e}){return s.jsx("span",{className:"tip-q","data-tip":e})}function tY({accountId:e}){const t=(Xi().wbApp?.getState?.()?.accounts?.accounts||[]).find(f=>f?.id===e),r=typeof t?.provider=="string"?t.provider:"";if(!r)return null;const o=Xi().wbProviders?.labelOf?.(r)||r,c=t&&Xi().wbAccountsModel?.editionSuffix?.(t)||"",d=c?`${o} ${c}`:o;return s.jsx("span",{className:`pbadge p-${r}`,title:l("提供商:{text}",{text:d}),children:d})}function nY({summary:e,range:t}){const r=Array.isArray(e.dailyTrend)?e.dailyTrend:[];return s.jsx(s.Fragment,{children:P9(e.overview,t,r.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 k2({panelId:e,listId:t,labelId:r,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(Ug,{text:c}),s.jsx("span",{className:"panel-sub",id:r,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(tY,{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)):Zi(g)})})]})}function T2({panelId:e,listId:t,title:r,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:r}),s.jsx(Ug,{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:l("总 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))})]}):Zi(f)})})]})}function sY({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":l("近 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 E2({line:e,cls:t,radius:r}){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},o.key))]})}function Kw({items:e,cls:t}){return s.jsx(s.Fragment,{children:e.map(r=>s.jsx("text",{className:`chart-label ${t}`,x:r.x,y:r.y,textAnchor:r.anchor,children:r.text},r.key))})}function rY({view:e}){const{width:t,height:r,plotLeft:o,plotW:c,plotTop:d,plotH:f}=e;return s.jsxs(s.Fragment,{children:[s.jsxs("svg",{className:"report-svg",width:t,height:r,viewBox:`0 0 ${t} ${r}`,role:"img","aria-label":l("近 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(E2,{line:e.tokenLine,cls:"tokens",radius:e.dotR}):null,s.jsx(E2,{line:e.rateLine,cls:"rate",radius:e.dotR}),s.jsx(Kw,{items:e.tokenLabels,cls:"tokens"}),s.jsx(Kw,{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:r,viewBox:`0 0 ${t} ${r}`,"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 aY({view:e}){const{width:t,height:r,plotLeft:o,plotW:c,plotTop:d,plotH:f}=e;return s.jsxs(s.Fragment,{children:[s.jsxs("svg",{className:"report-svg",width:t,height:r,viewBox:`0 0 ${t} ${r}`,role:"img","aria-label":l("按天 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(Kw,{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:l("所选范围内暂无请求")}):null]}),e.hits?s.jsx("svg",{className:"report-svg chart-hit-layer",width:t,height:r,viewBox:`0 0 ${t} ${r}`,"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 lY=680;function Yw(){const e=x.useRef(null),[t,r]=x.useState(0);return x.useLayoutEffect(()=>{const o=e.current;if(!o)return;let c=o.clientWidth;if(c&&r(c),typeof ResizeObserver!="function")return;const d=new ResizeObserver(()=>{const f=o.clientWidth;!f||f===c||(c=f,r(f))});return d.observe(o),()=>d.disconnect()},[]),[e,t||lY]}async function R2(){if(!Fw)try{const e=await Xi().workbuddyDesktop?.getScheduledTasks(),t=(e?.tasks||[]).find(r=>r.id==="reportAutoRefresh");Xw(t||null),Fw=Array.isArray(e?.tasks)}catch(e){console.warn("读取报表自动刷新间隔失败,按默认 1 秒:",e instanceof Error?e.message:e),Xw(null)}}function Xw(e){Fw=!0;const t=Number(e?.interval);!!e&&typeof e=="object"&&Number.isFinite(t)&&t>0&&(e.unit==="seconds"||e.unit==="minutes")?(Bg=e.enabled!==!1,zg=e.unit==="minutes"?t*6e4:t*1e3):(Bg=!0,zg=C2),Qi?.applyAutoConfig(zg,Bg)}const oY={summary:null,error:null};function iY(){const[e,t]=x.useState(oY),[r,o]=x.useState(C9),[c,d]=x.useState(T9),[f,p]=x.useState(()=>({ms:zg,enabled:Bg})),[,g]=x.useState(0),v=x.useRef(r),y=x.useRef(c),b=x.useCallback(F=>{t(F)},[]),j=x.useCallback(async(F={})=>{R2();const X=++Gw,re=v.current,P=re===Bw?y.current:void 0;try{const V=Xi().workbuddyDesktop;if(!V)throw new Error("后端桥不可用");const J=await V.getStatsSummary(re,P);if(X!==Gw)return Ro;if(!J||typeof J!="object")throw new Error("后端未返回报表数据");return Ro=J,b({summary:J,error:null}),Ro}catch(V){if(X!==Gw)return Ro;const J=V instanceof Error?V.message:"";return Ro=null,F.silent||console.warn("读取报表数据失败:",J),b({summary:null,error:J||l("未知错误")}),null}},[b]),w=x.useCallback(F=>{F!==void 0&&(Ro=F||null,F&&b({summary:F,error:null}))},[b]),S=x.useCallback(F=>{const X=Dg.includes(F)?F:zw;if(X!==v.current){v.current=X,o(X);try{localStorage.setItem(f2,X)}catch{}j()}},[j]),N=x.useCallback(F=>{const X={...y.current,...F};if(!Ig.test(X.start)||!Ig.test(X.end))return;const re=X.start<=X.end?X:F.start?{start:X.start,end:X.start}:{start:X.end,end:X.end};y.current=re,d(re),E9(re),v.current===Bw&&j()},[j]);x.useEffect(()=>{if(Qi={load:j,render:w,applyAutoConfig:(F,X)=>p({ms:F,enabled:X})},Hg){const F=Hg;Hg=null,w(F.data)}return Xi().wbApp?.currentPage==="overview"&&j({silent:!0}),()=>{Qi=null}},[j,w]),x.useEffect(()=>{if(!f.enabled||f.ms<=0)return;const F=window.setInterval(()=>{document.hidden||Xi().wbApp?.currentPage!=="overview"||qw||(qw=!0,j({silent:!0}).finally(()=>{qw=!1}))},f.ms);return()=>{window.clearInterval(F)}},[f,j]),x.useEffect(()=>{const F=()=>g(X=>X+1);return window.addEventListener("wb-units-changed",F),()=>window.removeEventListener("wb-units-changed",F)},[]);const C=Yw(),E=Yw(),R=Yw(),{summary:k,error:A}=e,D=k&&Dg.includes(k.range??"")?k.range:r,I=k&&Array.isArray(k.heatmap)?k.heatmap:[],M=k&&Array.isArray(k.cacheTrend24h)?k.cacheTrend24h:[],O=k&&Array.isArray(k.dailyTrend)?k.dailyTrend:[],_=k&&Array.isArray(k.providers)?k.providers:null,L=k&&Array.isArray(k.accounts)?k.accounts:null,z=k&&Array.isArray(k.models)?k.models:null,U=A?Zi(l("读取报表失败:{error}",{error:A}),"empty report-error"):null,B=Zi(l("正在加载…")),Q=U??B,W=x.useMemo(()=>w2(z||[]),[z]),Z=x.useCallback(F=>W.get(F)||z9,[W]),Y=k?$9(I,C[1]):null,q=k?G9(M,E[1],Z):null,G=k?K9(O,R[1],Z):null,$=Hw(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:l("统计概览")}),s.jsx("span",{className:"panel-sub",id:"report-range-label",children:m2[D]||""}),s.jsxs("div",{className:"head-actions",children:[s.jsx(Gn,{options:Y9,value:r,onValueChange:S,"aria-label":l("报表时间范围")}),r===Bw?s.jsxs("span",{className:"report-date-range",children:[s.jsx(Ke,{type:"date",className:"report-date-input w-[132px]",value:c.start,max:c.end||$,"aria-label":l("开始日期"),title:l("起始日期(含当天)"),onChange:F=>N({start:F.target.value})}),s.jsx("span",{className:"report-date-sep","aria-hidden":"true",children:"~"}),s.jsx(Ke,{type:"date",className:"report-date-input w-[132px]",value:c.end,min:c.start||void 0,max:$,"aria-label":l("结束日期"),title:l("结束日期(含当天)"),onChange:F=>N({end:F.target.value})})]}):null]})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"field-grid",id:"report-overview",children:k?s.jsx(nY,{summary:k,range:D}):Q})})]}),s.jsxs("div",{className:"report-rank-grid",children:[L?s.jsx(k2,{panelId:"report-accounts-panel",listId:"report-accounts",labelId:"report-accounts-label",title:l("Top 账号"),tip:X9,rows:y2(L)||[],totalText:j2(L),withBadge:!0,emptyText:l("所选范围内还没有账号用量")}):null,_?s.jsx(k2,{panelId:"report-providers-panel",listId:"report-providers",labelId:"report-providers-label",title:l("Top 提供商"),tip:Q9,rows:y2(_)||[],totalText:j2(_),withBadge:!1,emptyText:l("所选范围内还没有请求记录")}):null]}),s.jsxs("div",{className:"report-donut-grid",children:[z?s.jsx(T2,{panelId:"report-models-panel",listId:"report-models-donut",title:l("模型用量"),tip:Z9,ariaLabel:l("模型用量占比"),view:S2(z,l("未知模型")),emptyText:l("所选范围内还没有模型用量")}):null,_?s.jsx(T2,{panelId:"report-providers-pie-panel",listId:"report-providers-donut",title:l("提供商用"),tip:W9,ariaLabel:l("提供商用占比"),view:S2(_,l("未知")),emptyText:l("所选范围内还没有提供商用量")}):null]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:l("活跃热力图")}),s.jsx("span",{className:"panel-sub",children:l("近 365 天,按天 Token 用量着色(档位按本窗口峰值自动定)")})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"heat-wrap",id:"report-heatmap",ref:C[0],children:k?Y?s.jsx(sY,{view:Y}):Zi(l("暂无热力图数据")):Q})}),s.jsxs("div",{className:"panel-foot",children:[s.jsx("span",{className:"heat-scale-label",children:l("Token")}),s.jsx("span",{className:"heat-legend",id:"report-heat-legend",children:k?F9(N2(I)).map(F=>s.jsxs("span",{className:"heat-legend-item",children:[s.jsx("span",{className:`l${F.level}`}),F.text]},F.level)):null}),s.jsx("div",{className:"spacer"}),s.jsx("span",{children:l("方格为本地自然日,无请求显示为空槽")})]})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:l("缓存命中率")}),s.jsx(Ug,{text:J9})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"field-grid",id:"report-cache-rates",children:k?q9(k.cacheRates).map(F=>s.jsxs("div",{className:"field rate",children:[s.jsx("div",{className:"label",children:F.label}),s.jsxs("div",{className:"value big",children:[F.value,s.jsx("div",{className:"sub",children:F.sub})]})]},F.key)):Q})})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:l("近 24 小时缓存命中率趋势")}),s.jsx("span",{className:"panel-sub",children:l("按本地整点,无请求的整点不标注")})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"chart-wrap",id:"report-cache-trend",ref:E[0],children:k?q?s.jsx(rY,{view:q}):Zi(l("暂无缓存趋势数据")):Q})}),s.jsxs("div",{className:"panel-foot",children:[s.jsxs("span",{className:"chart-legend",children:[s.jsx("span",{className:"swatch rate"}),l("缓存命中率"),s.jsx("span",{className:"axis-hint",children:l("左轴")})]}),s.jsxs("span",{className:"chart-legend",children:[s.jsx("span",{className:"swatch tokens"}),l("总 Token"),s.jsx("span",{className:"axis-hint",children:l("右轴")})]}),s.jsx("div",{className:"spacer"}),s.jsx("span",{children:l("无请求的整点按 0% 计,但不写读数")})]})]}),s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:l("按天 Token 趋势")}),s.jsx(Ug,{text:eY}),s.jsx("span",{className:"panel-sub",id:"report-trend-label",children:k?`${k.startDate||"—"} ~ ${k.endDate||"—"}`:"—"})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"chart-wrap tall",id:"report-daily-trend",ref:R[0],children:k?G?s.jsx(aY,{view:G}):Zi(l("暂无趋势数据")):Q})})]})]})}async function cY(e={}){return Qi?Qi.load(e):Ro}function uY(e){if(e!==void 0){if(!Qi){Hg={data:e??null};return}Qi.render(e)}}function dY(){return Ro}window.wbReport={load:cY,render:uY,lastSummary:dY,applyAutoRefresh:Xw};const A2='.page[data-page="overview"]';let O2=!1;function M2(){if(O2)return;const e=document.querySelector(A2);e&&(O2=!0,e.replaceChildren(),jn.createRoot(e).render(s.jsx(iY,{})))}document.querySelector(A2)?M2():document.addEventListener("DOMContentLoaded",M2,{once:!0}),R2();const Qw={all:{title:l("全部删除"),desc:l("删除日志记录本身。当前有筛选时只删命中的条目,按天聚合报表不受影响;无筛选时清空全部并重置报表。此方式无法恢复。")},raw:{title:l("仅清空报文原文"),desc:l("保留统计行与报表,只抹掉请求 / 响应正文。清理后详情弹窗的「预览对话」将无原文可看,统计数字分毫不动。")}},fY=["all","raw"],pY=3e3;function Rl(){return window}let Zf=!1;function Wf(e,t){Rl().wbApp?.toast?.(e,t)}function mY(e){const t=Math.max(0,Number(e)||0);if(t<1024)return`${Math.round(t)} B`;const r=t/1024;if(r<1024)return`${r.toFixed(1)} KB`;const o=r/1024;return o<1024?`${o.toFixed(1)} MB`:`${(o/1024).toFixed(2)} GB`}function Zw(){const e=Rl().wbRequestsPanel?.clearParams?.();return typeof e=="string"?e:""}function D2(e){return{all:Number(e?.all)||0,raw:Number(e?.raw)||0,dbBytes:Number(e?.dbBytes)||0,vacuumRunning:e?.vacuumRunning===!0}}function Ww(e){return e instanceof Error?e.message:String(e)}function I2(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}function hY({onClose:e}){const[t,r]=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=>{Zf=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)},[]),C=x.useCallback(async()=>{const I=Rl().workbuddyDesktop;if(!I)return;let M;try{M=await I.getStatsClearPreview(Zw())}catch{return}if(!b.current)return;const O=D2(M);N(O),!O.vacuumRunning&&(S(),f(""),Wf(l("✅ 压缩完成")),Rl().wbRequestsPanel?.load?.({silent:!0}))},[N,S]),E=x.useCallback(()=>{j.current===null&&(g(!0),j.current=window.setInterval(()=>{C()},pY))},[C]);async function R(){c({status:"loading"});try{const I=Rl().workbuddyDesktop;if(!I)throw new Error(l("后端桥不可用"));const M=await I.getStatsClearPreview(Zw());if(!b.current)return;const O=D2(M);N(O),O.vacuumRunning&&E()}catch(I){if(!b.current)return;c({status:"failed"}),f(l("预览读取失败:{error}",{error:Ww(I)}))}}x.useEffect(()=>(b.current=!0,R(),()=>{b.current=!1,S(),Zf=!1}),[]);async function k(){const I=Rl().workbuddyDesktop;if(I){g(!0);try{await I.compactStatsDb(),f(l("压缩已在后台开始,完成后会自动提示")),E()}catch(M){const O=Ww(M);if(/409|正在进行/.test(O)){Wf(l("压缩已在进行中")),f(l("压缩已在进行中,接上它的进度等待完成")),E();return}g(!1),f(l("压缩失败:{message}",{message:O})),Wf(l("压缩失败:{message}",{message:O}),"err")}}}async function A(){if(Zf)return;const I=Rl().workbuddyDesktop,M=Rl().wbConfirm?.ask;if(!I||!M)return;const O=Qw[t].title,_=Zw(),L=_.length>0,z=o.status==="ready"?t==="raw"?o.raw:o.all:0;if(await M({title:l("清理请求日志"),html:L?l("确定按当前筛选执行「{label}」?将处理 {count} 条,此操作无法恢复。",{label:I2(O),count:z}):l("确定对全部请求日志执行「{label}」?将处理 {count} 条,此操作无法恢复。",{label:I2(O),count:z}),okText:l(t==="raw"?"抹掉原文":"删除"),okClass:"danger"})){w(!0);try{const B=L?`mode=${t}&${_}`:`mode=${t}&all=1`,Q=await I.clearStatsRequests(B),W=Number(Q?.deleted)||0;Wf(t==="raw"?l("已抹掉 {count} 条报文原文",{count:W}):l("已删除 {count} 条",{count:W})),w(!1),e(),Rl().wbRequestsPanel?.notifyCleared?.()}catch(B){const Q=Ww(B);f(l("清理失败:{message}",{message:Q})),Wf(l("清理失败:{message}",{message:Q}),"err"),w(!1)}}}const D=o.status==="ready"?l("将删除 {count} 条日志 · 其中 {raw} 条仍带报文原文 · 数据库占用 {db}",{count:o.all,raw:o.raw,db:mY(o.dbBytes)}):o.status==="failed"?l("预览读取失败"):l("正在统计…");return s.jsx(Kt,{open:!0,onOpenChange:(I,M)=>{if(!I){if(Zf){M.cancel();return}e()}},children:s.jsxs(Yt,{children:[s.jsx(Ft,{children:s.jsx($t,{children:l("清理请求日志")})}),s.jsxs(Ht,{children:[s.jsx(ch,{"aria-label":l("清理方式"),value:t,onValueChange:I=>r(I==="raw"?"raw":"all"),children:fY.map(I=>{const M=t===I;return s.jsxs("label",{"data-checked":M?"":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(Mi,{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:Qw[I].title}),s.jsx("span",{className:"text-[11.5px] leading-[1.55] text-subtle",children:Qw[I].desc})]},I)})}),s.jsx("p",{className:"text-[11.5px] text-muted-foreground",children:D})]}),s.jsxs(sn,{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:()=>{k()},disabled:p,title:l(p?"压缩正在后台执行,完成后自动恢复":"回收已删除数据占用的磁盘空间(checkpoint + VACUUM,后台执行)"),children:l(p?"压缩中…":"压缩数据库")}),s.jsx(se,{variant:"outline",onClick:e,disabled:v,children:l("取消")}),s.jsx(se,{variant:"destructive",onClick:()=>{A()},disabled:v,children:l(v?"清理中…":"执行清理")})]})]})})}let Jf=null,Mu=null;function P2(){Jf&&(Jf.unmount(),Jf=null),Mu&&(Mu.remove(),Mu=null)}function gY(){Zf||P2()}function xY(){P2(),Mu=document.createElement("div"),document.body.append(Mu),Jf=jn.createRoot(Mu),Jf.render(s.jsx(hY,{onClose:gY}))}window.wbRequestClearModal={open:xY};const _2=[{value:"detail",label:l("请求详情")},{value:"preview",label:l("预览对话")},{value:"raw",label:l("原始报文")}],bY="detail",L2="border-b border-hairline px-2.5 py-[7px] align-top",Ao="border border-hairline px-2 py-1 align-top",vY="border border-hairline bg-surface-2 px-2 py-1 text-[11.5px] tracking-normal",Vg="hover:[&>td]:bg-transparent";function Du(){return window}function Jw(){const e=Du().workbuddyDesktop;if(!e)throw new Error(l("后端桥不可用"));return e}let e0=0;function yY(e){if(!e)return"—";const t=new Date(e),r=o=>String(o).padStart(2,"0");return`${t.getFullYear()}-${r(t.getMonth()+1)}-${r(t.getDate())} ${r(t.getHours())}:${r(t.getMinutes())}:${r(t.getSeconds())}`}function z2(e){const t=Math.round(Number(e)||0);if(t<1e3)return`${t}ms`;const r=Math.floor(t/1e3);if(r>=60)return l("{m}分{s}秒",{m:Math.floor(r/60),s:r%60});const o=t%1e3;return o>0?l("{s}秒{ms}ms",{s:r,ms:o}):l("{n}秒",{n:r})}function jY(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"-":z2(t)}const wY=l("生成速度:输出 token ÷ 流式段用时(总用时 − 首响);流式段不足总用时一半时按总用时计");function SY(e){const t=Number(e.completionTokens)||0,r=Number(e.durationMs)||0;if(t<=0||r<=0)return"";const o=Number(e.firstResponseMs),c=Number.isFinite(o)&&o>0&&o=500&&c*2>=r,f=t/((d?c:r)/1e3);return`${f>=100?Math.round(f):f.toFixed(1)} tok/s`}function $g(e){return Du().wbUnits?.formatTokens?.(e)??(Number(e)||0).toLocaleString("zh-CN")}function NY(e){const t=Math.max(0,Date.now()-(Number(e)||0));return l("{n}秒",{n:Math.max(1,Math.floor(t/1e3))})}function CY(e){const t=Number(e.status)||0;return t>=200&&t<300&&!e.error}function Fg(e){return(Number(e?.status)||0)===0&&!e?.error}function B2(e){const t=String(e.provider??"").trim();return String(e.providerLabel??"").trim()||(t?Du().wbProviders?.labelOf?.(t)||t:"")}function ep(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 n0(e){return e instanceof Error?e.message:String(e)}const H2=[{label:l("请求头"),pick:e=>t0(e.requestHeaders)},{label:l("请求体"),pick:e=>t0(e.requestBody)},{label:l("响应头"),pick:e=>t0(e.responseHeaders)},{label:l("响应体"),pick:e=>e.responseBody?String(e.responseBody):""}];function qg({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(Fd,{className:"size-3.5"}):null,e]})}function ia({label:e,children:t}){return s.jsxs(yl,{className:Vg,children:[s.jsx("th",{scope:"row",className:`w-[76px] whitespace-nowrap text-left text-[12.5px] font-semibold text-muted-foreground ${L2}`,children:e}),s.jsx(vn,{className:L2,children:t})]})}function kY({row:e}){if(Fg(e)){const c=Du().wbRequestPhase;if(!c?.badgeHtml)return s.jsxs(ze,{variant:"info",shape:"tag",title:l("请求正在转发中,用时列显示的是已用时"),children:[s.jsx(Lv,{className:"req-live-dot"}),l("进行中")]});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,r=CY(e),o=!r&&t>=200&&t<300?l("HTTP {status},但响应体阶段出错",{status:t}):"";return s.jsx(ze,{variant:r?"success":"destructive",shape:"tag",title:o||void 0,children:t||l("失败")})}function TY({row:e}){const t=String(e.clientModel??"").trim(),r=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||!r||r.toLowerCase()===t.toLowerCase())return s.jsx(s.Fragment,{children:f(o,d||c)||"—"});const p=f(r,d),g=f(t,c);return s.jsxs("span",{className:"flex flex-col gap-0.5",children:[s.jsxs("span",{title:l("转发到上游的模型:{model}",{model:p}),children:["⬆️ ",p]}),s.jsxs("span",{className:"text-muted-foreground",title:l("下游请求的模型:{model}",{model:g}),children:["⬇️ ",g]})]})}function EY(e){const t=Number(e?.status),r=e?.status!==null&&e?.status!==void 0&&Number.isFinite(t),o=e?.error?String(e.error):"";if(o){const c=r?l("失败({status}):{error}",{status:String(t),error:o}):l("失败:{error}",{error:o});return s.jsx("span",{className:"break-words text-destructive",children:c})}return r?s.jsx("span",{className:"text-success",children:l("成功({status})",{status:String(t)})}):s.jsx("span",{className:"text-muted-foreground",children:l("无结果记录")})}function RY({row:e}){const t=Array.isArray(e.attemptDetails)?e.attemptDetails:[];if(!t.length)return s.jsx(s.Fragment,{children:"-"});const r=Number(e.attempts)||1;return s.jsxs(yy,{className:"text-[11.5px]",children:[s.jsx(LT,{children:s.jsx(yl,{className:Vg,children:[l("轮次"),l("提供商"),l("账号"),l("结果"),l("体积"),l("内部重试"),l("提示")].map(o=>s.jsx(zT,{className:vY,children:o},o))})}),s.jsxs(jy,{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?l(",{n}秒后重试",{n:Math.round(j/1e3)}):l(",{n}毫秒后重试",{n:Math.round(j)}):"";return`${String(b?.reason||l("未知原因"))}${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?l("实际发给上游 {bytes} 字节",{bytes:g.toLocaleString()}):void 0;return s.jsxs(yl,{className:Vg,children:[s.jsx(vn,{className:Ao,children:c+1}),s.jsx(vn,{className:Ao,children:B2(o)||(o?.provider?String(o.provider):l("未知"))}),s.jsx(vn,{className:Ao,children:o?.account?String(o.account):"—"}),s.jsx(vn,{className:Ao,children:EY(o)}),s.jsx(vn,{className:`${Ao} whitespace-nowrap`,title:y,children:v}),s.jsx(vn,{className:`${Ao} whitespace-nowrap`,title:f||void 0,children:d.length?l("↻ {n} 次",{n:d.length}):"-"}),s.jsx(vn,{className:Ao,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:[l("被跳过:"),p.map(v=>String(v.name||v.id||"")).join("、")]}):null,g?s.jsx("div",{className:"mt-1",children:l("最终承载:{picked}",{picked:g})}):null]})}function OY({row:e}){if(!e)return s.jsx(qg,{text:l("列表数据已刷新,请重试(关闭后重新打开这条详情)")});const t=String(e.accountName??"").trim(),r=SY(e);return s.jsx(yy,{className:"text-[12.5px] text-subtle [&_tr:last-child>td]:border-b-0 [&_tr:last-child>th]:border-b-0",children:s.jsxs(jy,{children:[s.jsx(ia,{label:l("时间"),children:yY(e.ts)}),s.jsx(ia,{label:l("状态"),children:s.jsx(kY,{row:e})}),s.jsx(ia,{label:l("耗时"),children:Fg(e)?s.jsxs(s.Fragment,{children:[NY(e.ts),s.jsx("span",{className:"text-[11.5px] text-muted-foreground",children:l("(请求仍在转发中)")})]}):l("{duration} / 首帧 {first}",{duration:z2(e.durationMs),first:jY(e.firstResponseMs)})}),s.jsx(ia,{label:l("重试次数"),children:String(Number(e.attempts)||1)}),s.jsx(ia,{label:l("模型"),children:s.jsx(TY,{row:e})}),s.jsxs(ia,{label:l("提供商"),children:[B2(e)||"—",t?s.jsx("span",{className:"text-[11.5px] text-muted-foreground",children:l("(账号:{account})",{account:t})}):null]}),s.jsxs(ia,{label:l("令牌"),children:[l("输入 {input} · 输出 {output} · 总计 {total} · 缓存读 {cache}",{input:$g(e.promptTokens),output:$g(e.completionTokens),total:$g(e.totalTokens),cache:$g(e.cacheReadTokens)}),r?s.jsxs("span",{title:wY,children:[" · ",r]}):null]}),e.isTest?s.jsx(ia,{label:l("来源"),children:s.jsx(ze,{variant:"brand",shape:"tag",title:l("模型管理页操作列那颗「测试」发起的请求:与真实请求同一条转发链路,但不计入报表统计"),children:l("模型测试")})}):null,s.jsx(ia,{label:l("错误"),children:e.error?s.jsx("span",{className:"text-destructive",children:String(e.error)}):"—"}),s.jsx(ia,{label:l("尝试明细"),children:s.jsx(RY,{row:e})}),e.route?s.jsx(ia,{label:l("路由回放"),children:s.jsx(AY,{row:e})}):null,s.jsx(ia,{label:l("敏感词"),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 MY({state:e}){if(!e)return s.jsx(qg,{text:l("正在读取…"),loading:!0});const t=e==="gone"?null:e.body,r=t&&Du().wbConversationPreview?.render?.(t.requestBody,t.responseBody)||"";return r?s.jsxs("div",{children:[e!=="gone"&&e.truncated?s.jsx("div",{className:"mb-2 text-[11.5px] text-warning",children:l("正文超过单条上限,可能已被截断")}):null,s.jsx("div",{dangerouslySetInnerHTML:{__html:r}})]}):s.jsx(qg,{text:l("无报文原文(未开启「调试模式」,或已被清理)")})}function DY({data:e}){const t=e.status===null||e.status===void 0?"-":String(e.status),r=[e.url?`URL: ${e.url}`:"",e.provider?l("提供商: {provider}",{provider:String(e.provider)}):"",l("上游状态码: {status}",{status:t})].filter(Boolean);return s.jsxs("div",{className:"flex flex-col gap-4",children:[r.length?s.jsx("div",{className:"border-b border-hairline pb-2.5 text-xs leading-[1.7] break-all text-subtle",children:r.map((o,c)=>s.jsx("div",{children:o},c))}):null,H2.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(qg,{text:l("这条请求没有保存这一段报文")})]},o.label)})]})}function IY({id:e,row:t,token:r,onClose:o}){const[c,d]=x.useState(bY),[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),C=x.useRef({detail:0,preview:0,raw:0}),E=x.useCallback(()=>!S.current||r!==e0,[r]);async function R(){try{const O=await Jw().getStatsRequestRaw(e);if(E())return;const _=ep(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("读取原始正文失败(预览对话显示空态):",n0(O))}}async function k(){try{const O=await Jw().getDebugTraffic(e);if(E())return;const _=ep(O)?O:{};if(!H2.some(L=>(L.pick(_)||"").trim())){v("gone");return}v({data:_}),b(_.truncated?l("报文超过单条上限,请求体 / 响应体已按上限截断"):l("内容按原样保存,请求头中的凭据字段已替换为 [redacted]"))}catch(O){if(E())return;v("gone"),b(l("在设置 → 通用里开启「调试模式」后,新发生的请求才会保存报文")),console.warn("读取调试报文失败(原始报文标签隐藏):",n0(O))}}x.useEffect(()=>(S.current=!0,R(),k(),()=>{S.current=!1}),[]),x.useLayoutEffect(()=>{const O=N.current;O&&(O.scrollTop=C.current[c])},[c]);function A(O){if(O==="raw"&&!ep(g)||O===c)return;const _=N.current;_&&(C.current[c]=_.scrollTop),d(O)}async function D(){if(!e||!Fg(t))return;const O=Du().wbConfirm?.ask;if(!(!O||!await O({title:l("终止请求"),html:l("确定终止这条正在转发的请求?
上游连接会立即断开,明细将记为「请求已被手动终止」。"),okText:l("终止"),okClass:"danger"}))){w("pending");try{if(await Jw().terminateStatsRequest(e),!S.current)return;w("accepted"),b(l("已受理终止:上游连接已断开,列表稍后刷新为「请求已被手动终止」"))}catch(L){if(!S.current)return;w("idle"),b(l("终止失败:{error}",{error:n0(L)}))}}}const I=ep(g),M=x.useMemo(()=>I?_2:_2.filter(O=>O.value!=="raw"),[I]);return s.jsx(Kt,{open:!0,onOpenChange:O=>{O||o()},children:s.jsxs(Yt,{className:"w-[min(920px,calc(100vw-48px))]",children:[s.jsx(Ft,{children:s.jsx($t,{children:l("请求详情")})}),s.jsxs(Ht,{ref:N,className:"gap-3",children:[s.jsx(Gn,{options:M,value:c,onValueChange:A,"aria-label":l("详情内容"),className:"self-start"}),s.jsx("section",{hidden:c!=="detail",children:s.jsx(OY,{row:t})}),s.jsx("section",{hidden:c!=="preview",children:s.jsx(MY,{state:f})}),I?s.jsx("section",{hidden:c!=="raw",children:s.jsx(DY,{data:g.data})}):null]}),s.jsxs(sn,{children:[s.jsx("span",{className:"min-w-0 text-[11.5px] text-muted-foreground",children:y}),s.jsx("div",{className:"mr-auto"}),Fg(t)?s.jsx(se,{variant:"destructive",disabled:j!=="idle",onClick:()=>{D()},title:l("断开上游连接,明细记为「请求已被手动终止」"),children:l("终止请求")}):null,s.jsx(se,{variant:"outline",onClick:o,children:l("关闭")})]})]})})}let tp=null,Iu=null;function U2(){tp&&(tp.unmount(),tp=null),Iu&&(Iu.remove(),Iu=null)}function V2(){e0+=1,U2()}function PY(e,t){const r=String(e??"").trim();if(!r)return;U2();const o=++e0;Iu=document.createElement("div"),document.body.append(Iu),tp=jn.createRoot(Iu),tp.render(s.jsx(IY,{id:r,row:ep(t)?t:null,token:o,onClose:V2}))}window.wbRequestDetail={open:PY,close:V2};const _Y=150,LY=80,Wi=8,Gg=8,zY=520,BY=220,HY=1.1,UY=900,s0=12,r0="req-hover-panel",VY=["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(" "),np="rh-row rh-dim min-w-0 break-words text-muted-foreground",$Y="rh-row min-w-0 break-words";function FY(){return window}function a0(e){return typeof e=="object"&&e!==null?e:null}const $2=e=>Array.isArray(e?.attemptDetails)?e.attemptDetails:[],F2=e=>Array.isArray(e?.retries)?e.retries:[],qY=e=>Array.isArray(e?.sensitiveHits)?e.sensitiveHits:[];function l0(e){const t=String(e??"").trim();return t?FY().wbProviders?.labelOf?.(t)||t:""}function GY(e){const t=a0(e);return(Number(t?.attempts)||1)>1?!0:$2(t).some(r=>F2(r).length>0||!!r?.notice)}function q2(e){return e.dataset.reqHover==="sensitive"?"sensitive":"chain"}function KY({details:e}){if(e.length<2)return null;const t=e.map(r=>l0(r.provider)||l("未知"));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:l("切换路径:")}),s.jsx("span",{className:"rh-chain-v font-semibold text-foreground",children:t.join(" → ")})]})}function YY({item:e}){const t=F2(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:l("↻ 重试 {n} 次",{n:t.length})}),t.map((r,o)=>{const c=String(r?.reason??"").trim(),d=Number(r?.status),f=r?.status!==null&&r?.status!==void 0&&Number.isFinite(d),p=Number(r?.delayMs),g=Number.isFinite(p)&&p>0?p>=1e3?l(",{n}秒后重试",{n:Math.round(p/1e3)}):l(",{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||l("未知原因")}),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 XY({item:e,index:t,inFlight:r}){const o=l0(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:$Y,children:[s.jsx("span",{className:"rh-no mr-1 text-muted-foreground",children:l("尝试 {n} ·",{n:t+1})}),s.jsx("span",{className:"rh-who mr-1 font-semibold text-foreground",children:o||l("未知")}),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?l("失败({status}):{error}",{status:String(d),error:p}):l("失败:{error}",{error:p})}):f?s.jsx("span",{className:"rh-ok font-medium text-success",children:l("成功({status})",{status:String(d)})}):r?s.jsx("span",{className:"rh-dim text-muted-foreground",children:l("进行中…")}):s.jsx("span",{className:"rh-dim text-muted-foreground",children:l("无结果记录")})]}),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(YY,{item:e})]})}function QY({entry:e}){const t=Number(e.attempts)||1,r=$2(e);if(!r.length){const c=l0(e.provider),d=c?l("共 {n} 次尝试,最终由 {provider} 承载",{n:t,provider:c}):l("共 {n} 次尝试",{n:t});return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:np,children:d}),s.jsx("div",{className:np,children:l("这条记录的尝试明细未采集(该字段上线前的旧数据,或请求在转发前就失败)")})]})}const o=(Number(e.status)||0)===0&&!e.error;return s.jsxs(s.Fragment,{children:[s.jsx(KY,{details:r}),r.map((c,d)=>s.jsx(XY,{item:c,index:d,inFlight:o&&d===r.length-1},d)),r.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(r?.word??"")}),s.jsx("span",{className:"rh-hit-c text-muted-foreground tabular-nums whitespace-nowrap",children:`× ${String(Number(r?.count)||0)}`})]},o)),t.length>s0?s.jsx("div",{className:np,children:l("另有 {n} 个词命中",{n:t.length-s0})}):null]}):s.jsx("div",{className:np,children:l("这条记录命中了敏感词,但没有留下命中明细")})}function WY({kind:e,entry:t,panelRef:r}){return s.jsx("div",{ref:r,id:r0,role:"tooltip","data-kind":e,className:VY,children:e==="sensitive"?s.jsx(ZY,{entry:t}):s.jsx(QY,{entry:t})})}let Sn=null,Oo=0,sp=0,rp=null,Kg=null,o0=null,i0=null,Ji=null,ec=null,ap=null,G2="chain";function c0(){window.clearTimeout(Oo),window.clearTimeout(sp),Oo=0,sp=0,rp=null}function JY(){const e=ap?.current,t=Sn;if(!e||!t)return;const r=t.getBoundingClientRect(),o=window.innerWidth-Wi*2;e.style.maxWidth="none",e.style.width="max-content";const c=e.offsetWidth,d=G2==="sensitive",p=Math.max(d?BY:zY,c)*(d?HY:1),g=Math.min(p,o,UY);e.style.maxWidth=`${g}px`,e.style.width=d?`${g}px`:"auto";const v=e.offsetWidth,y=e.offsetHeight,b=window.innerHeight-r.bottom-Gg-Wi,j=r.top-Gg-Wi,w=bb,S=r.left+r.width/2,N=Math.max(Wi,Math.min(S-v/2,window.innerWidth-Wi-v)),C=w?r.top-Gg-y:r.bottom+Gg;e.style.left=`${Math.round(N)}px`,e.style.top=`${Math.round(Math.max(Wi,Math.min(C,window.innerHeight-Wi-y)))}px`}function K2(e){if(!Sn)return;const t=e.target;t instanceof Node&&(t===Sn||Sn.contains(t)||Ta())}function Y2(){Ta()}function X2(){Ta()}let Yg=!1;function eX(){Yg||(Yg=!0,document.addEventListener("click",K2,!0),window.addEventListener("scroll",Y2,!0),window.addEventListener("resize",X2))}function tX(){Yg&&(Yg=!1,document.removeEventListener("click",K2,!0),window.removeEventListener("scroll",Y2,!0),window.removeEventListener("resize",X2))}function nX(){tX(),ec&&(ec.unmount(),ec=null),Ji&&(Ji.remove(),Ji=null),ap=null}function Q2(e,t){G2=e,(!Ji||!ec||!ap)&&(Ji=document.createElement("div"),document.body.append(Ji),ap=x.createRef(),ec=jn.createRoot(Ji));const r=ec,o=ap;ys.flushSync(()=>{r.render(s.jsx(WY,{kind:e,entry:t,panelRef:o}))}),eX(),JY()}function Z2(e){if(!e.isConnected)return;const t=a0(o0?.(e));t&&(c0(),Sn&&Sn!==e&&Ta(),Sn=e,Q2(q2(e),t),e.classList.add("active"),e.setAttribute("aria-describedby",r0))}function Ta(){c0(),Sn&&(Sn.classList.remove("active"),Sn.removeAttribute("aria-describedby"),Sn=null),nX()}function sX(){if(!Sn)return;const e=String(Sn.dataset.reqHover||""),t=String(Sn.dataset.reqId||"");i0=!!(e&&t)&&Sn.matches(":hover")&&!sp?{action:"move",kind:e,key:t}:{action:"close"}}function rX(){const e=i0;if(i0=null,!e||!Sn)return;if(e.action==="close"){Ta();return}const t=Kg?aX(Kg,e.kind,e.key):null,r=t?a0(o0?.(t)):null;if(!t||!r){Ta();return}t!==Sn&&(Sn.classList.remove("active"),Sn.removeAttribute("aria-describedby"),Sn=t,Q2(q2(t),r),t.classList.add("active"),t.setAttribute("aria-describedby",r0))}function aX(e,t,r){for(const o of e.querySelectorAll("[data-req-hover]"))if(String(o.dataset.reqHover||"")===t&&String(o.dataset.reqId||"")===r)return o;return null}function Xg(e){const t=e.target;return t instanceof Element?t.closest("[data-req-hover]"):null}function lX(e){const t=Xg(e);if(!t||!Kg?.contains(t)||(c0(),Sn===t&&ec))return;const r=Sn?0:_Y;Sn&&Ta(),rp=t,Oo=window.setTimeout(()=>{Oo=0,rp=null,Z2(t)},r)}function oX(e){const t=Xg(e);if(t){if(rp===t){window.clearTimeout(Oo),Oo=0,rp=null;return}Sn===t&&(window.clearTimeout(Oo),Oo=0,sp=window.setTimeout(()=>{sp=0,Sn===t&&Ta()},LY))}}function iX(e){const t=Xg(e);t&&Z2(t)}function cX(e){const t=Xg(e);t&&Sn===t&&Ta()}function uX(e){e.key!=="Escape"||!Sn||Ta()}function dX(e){const t=e?.host;t&&(Kg=t,o0=e?.entryOf??null,t.addEventListener("pointerover",lX),t.addEventListener("pointerout",oX),t.addEventListener("focusin",iX),t.addEventListener("focusout",cX),t.addEventListener("keydown",uX))}window.wbRequestHover={bind:dX,close:Ta,hasProcessFacts:GY,beforeListRedraw:sX,afterListRedraw:rX};function js(){return window}function u0(e){return e instanceof Error?e.message:String(e)}function Qg(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}const Zg={connecting:{label:l("连接中"),cls:"phase-connecting"},waiting:{label:l("等待响应"),cls:"phase-waiting"},streaming:{label:l("响应中"),cls:"phase-streaming"},retrying:{label:l("重试中"),cls:"phase-retrying"},queued:{label:l("排队中"),cls:"phase-queued"}},W2=l("进行中"),fX="running",J2={connecting:l("请求已受理,正在选路、取凭证、建立上游连接"),waiting:l("上游请求已发出,正在等第一个字节到达(模型的思考时间也在这段)"),streaming:l("首帧已到,上游内容正在下发"),retrying:l("本轮尝试失败,正在退避等待或切换到下一个账号"),queued:l("上游模型繁忙,请求已排进上游队列;网关正按上游建议的时长等待后重发(不是登录态或额度问题)"),"":l("请求正在转发中,用时列显示的是已用时")};function d0(e){const t=String(e?.phase??"").trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Zg,t)?t:""}function eD(e){const t=d0(e);return t?Zg[t].label:W2}function tD(e){if(e==null||e==="")return"";const t=Number(e);if(!Number.isFinite(t)||t<0)return"";const r=Math.max(1,Math.floor(t/1e3));return r<60?l("{n}秒",{n:r}):l("{m}分{s}秒",{m:Math.floor(r/60),s:r%60})}function pX(e){const t=e?.phaseElapsedMs;if(t!=null&&t!==""){const c=Number(t);if(Number.isFinite(c)&&c>=0)return c}const r=Number(e?.phaseStartedAt);if(!Number.isFinite(r)||r<=0)return null;const o=Date.now()-r;return Number.isFinite(o)?Math.max(0,o):null}function mX(e){const t=d0(e),r=t?Zg[t].label:W2,o=t?Zg[t].cls:fX,c=J2[t]||J2[""];return`${Qg(r)}`}function hX(e){const t=tD(pX(e));if(!t)return"";const r=eD(e),o=l("进入「{phase}」阶段已持续 {time}",{phase:r,time:t});return`${Qg(t)}`}const f0=[{key:"time",label:l("时间"),sel:".req-time",track:"92px"},{key:"target",label:l("提供商 / 账号"),sel:".req-target",track:"minmax(0, 1.1fr)"},{key:"retry",label:l("重试"),sel:".req-retry",track:"52px"},{key:"status",label:l("状态"),sel:".req-status",track:"96px"},{key:"model",label:l("模型"),sel:".req-model",track:"minmax(0, 1.3fr)"},{key:"client",label:l("客户端"),sel:".req-client",track:"110px"},{key:"dur",label:l("用时"),sel:".req-dur",track:"96px",align:"right"},{key:"usage",label:l("用量"),sel:".req-usage",track:"minmax(0, 1.6fr)"},{key:"error",label:l("错误"),sel:".req-error-cell",track:"minmax(0, 1.2fr)"},{key:"detail",label:l("详情"),sel:".req-detail",track:"60px",align:"right"}],nD=1e3,gX=zh;function sD(e){return typeof e=="number"&&e>0?e:lu}const rD="workbuddy-desktop-logs-requests-range",aD="workbuddy-desktop-requests-filters",xX=3e4,p0=["today","7","30","month","all"],m0="all",bX={today:l("今天"),7:l("近 7 天"),30:l("近 30 天"),month:l("本月"),all:l("全部")},vX={today:l("今天"),7:l("7 天"),30:l("30 天"),month:l("本月"),all:l("全部")},yX=p0.map(e=>({value:e,label:vX[e]})),lD=[{value:"",label:l("全部状态")},{value:"ok",label:l("成功")},{value:"error",label:l("失败")}],jX=l("全部状态"),oD=l("全部提供商"),iD=l("全部模型"),Wg={status:"",provider:"",model:""};function Jg(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function wX(e){const t=new Date;switch(e){case"today":return Jg(t);case"7":return Jg(new Date(t.getFullYear(),t.getMonth(),t.getDate()-6));case"30":return Jg(new Date(t.getFullYear(),t.getMonth(),t.getDate()-29));case"month":return Jg(new Date(t.getFullYear(),t.getMonth(),1));default:return null}}const Xt={filters:{...Wg},range:SX(),runningOnly:!1,offset:0,size:sD(Hh("requests",zh))};let ex={...Wg},h0=!1,cD=!1,g0=[],tx=nD,nx=!0,x0=!1,b0=!1,uD=0,v0=0,y0=null,dD=!1,Pu=null;function SX(){try{const e=localStorage.getItem(rD);return e!==null&&p0.includes(e)?e:m0}catch{return m0}}function NX(e){try{localStorage.setItem(rD,e)}catch{}}function fD(){const e=js().wbFilterMemory;return e?(h0=!0,ex=e.load(aD,{...Wg}),Xt.filters={...ex},{...ex}):{...Wg}}function CX(e){ex={...e},js().wbFilterMemory?.save(aD,{status:e.status||"",provider:e.provider||"",model:e.model||""})}function pD(){const e=new URLSearchParams,t=wX(Xt.range);t!==null&&e.set("start",String(t));const r=Xt.runningOnly?"running":Xt.filters.status;return r&&e.set("status",r),Xt.filters.provider&&e.set("provider",Xt.filters.provider),Xt.filters.model&&e.set("model",Xt.filters.model),e}function kX(){const e=pD();return e.set("offset",String(Xt.offset)),e.set("limit",String(Xt.size)),e.toString()}function j0(e){const t=Math.round(Number(e)||0);if(t<1e3)return`${t}ms`;const r=Math.floor(t/1e3);if(r>=60)return l("{m}分{s}秒",{m:Math.floor(r/60),s:r%60});const o=t%1e3;return o>0?l("{s}秒{ms}ms",{s:r,ms:o}):l("{n}秒",{n:r})}const TX=l("生成速度:输出 token ÷ 流式段用时(总用时 − 首响);流式段不足总用时一半时按总用时计"),EX=500;function RX(e){const t=Number(e.completionTokens)||0,r=Number(e.durationMs)||0;if(t<=0||r<=0)return"";const o=Number(e.firstResponseMs),c=Number.isFinite(o)&&o>0&&o=EX&&c*2>=r,f=t/((d?c:r)/1e3);return`${f>=100?Math.round(f):f.toFixed(1)} tok/s`}function AX(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"-":j0(t)}function sx(e){return js().wbUnits?.formatTokens?.(e)??(Number(e)||0).toLocaleString("zh-CN")}function OX(e){const t=Math.max(0,Date.now()-(Number(e)||0));return l("{n}秒",{n:Math.max(1,Math.floor(t/1e3))})}function MX(e){const t=Number(e.promptTokens)||0;return t<=0?"-":`${((Number(e.cacheReadTokens)||0)/t*100).toFixed(2)}%`}function w0(e){const t=Number(e.status)||0;return t>=200&&t<300&&!e.error}function lp(e){return(Number(e?.status)||0)===0&&!e?.error}const mD=e=>String(e?.id||e?.ts||"");function DX(e){return(Array.isArray(e?.attemptDetails)?e.attemptDetails:[]).reduce((r,o)=>{const c=o?.retries;return r+(Array.isArray(c)?c.length:0)},0)}function hD(e){return js().wbProviders?.labelOf?.(e)||e}function IX(e){const t=new Set;return e.map((r,o)=>{const c=mD(r)||`i${o}`;let d=c,f=1;for(;t.has(d);)d=`${c}#${f++}`;return t.add(d),d})}async function gD(){if(!(Date.now()-v0({value:String(o?.id||""),label:String(o?.label||o?.id||"")})).filter(o=>o.value),r=(Array.isArray(e?.models)?e.models:[]).map(o=>String(o||"")).filter(Boolean);Pu?.setFilterOptions(t,r)}catch(e){console.warn("读取请求日志筛选清单失败,筛选项退化为「全部」:",u0(e))}}}async function PX(){if(!x0)try{const e=await js().workbuddyDesktop?.getScheduledTasks(),t=(e?.tasks||[]).find(r=>r.id==="requestsAutoRefresh");S0(t||null),x0=Array.isArray(e?.tasks)}catch(e){console.warn("读取请求日志自动刷新间隔失败,按默认 1 秒:",u0(e)),S0(null)}}function S0(e){x0=!0;const t=Number(e?.interval),r=e?.unit;!!e&&typeof e=="object"&&Number.isFinite(t)&&t>0&&(r==="seconds"||r==="minutes")?(nx=e.enabled!==!1,tx=r==="minutes"?t*6e4:t*1e3):(nx=!0,tx=nD),Pu?.setAuto({ms:tx,enabled:nx})}function _X(){if(dD)return;const e=js().wbColSettings;e&&(dD=!0,y0=e.register({id:"requests",label:l("请求日志表"),columns:f0.map(({key:t,label:r,align:o})=>({key:t,label:r,align:o})),mount:()=>document.querySelector('.page[data-page="requests"] .panel-head .head-actions'),onChange:()=>{ys.flushSync(()=>Pu?.repaint()),js().wbTableColumns?.repaint?.("requests")}}))}function N0(){return(y0?y0.apply(f0):f0).map(t=>({...t,align:t.align||"left"}))}const LX={entries:[],total:0,matched:0,running:0,loaded:!1,error:""};function zX(e){return e.loaded?e.total?l("没有符合筛选条件的请求"):l("暂无请求日志,网关还没有转发过请求"):l("正在加载请求日志…")}function BX(e){const t=Number(e.firstResponseMs);return!Number.isFinite(t)||t<=0?null:s.jsx("span",{className:"req-dur-line sub",title:l("首响:上游首帧到达的耗时(请求仍在转发中)"),children:l("首响 {time}",{time:j0(t)})})}function HX(e,t){const{align:r,key:o}=t,c=t.sel.slice(1)+(o==="dur"?" req-num":""),d=`${c} ta-${r}`;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?hD(f):"");return s.jsxs("span",{className:d,children:[g?s.jsx("span",{className:"req-provider",title:f&&f!==g?l("{name}({id})",{name:g,id:f}):g,children:g}):s.jsx("span",{className:"req-provider is-empty",title:l("这条明细没有记录提供商(旧数据或请求未走到转发)"),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:l("请求在任何账号接手之前就失败了"),children:"—"})]},o)}case"retry":{const f=Number(e.attempts)||1,p=mD(e),g=[];if(e.isTest&&g.push(s.jsx(ze,{variant:"brand",shape:"tag",title:l("这条明细是一次模型测试(人工发起):走的是真实转发链路,但不计入报表统计"),children:l("测试")},"test")),js().wbRequestHover?.hasProcessFacts?.(e)??f>1){const y=f>1?f:DX(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?l("重试 {n}",{n:y}):l("重试")},"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":l("命中了敏感词"),children:l("敏")},"sensitive")),g.length?s.jsx("span",{className:d,children:g},o):s.jsx("span",{className:`req-none ta-${r}`,children:"-"},o)}case"status":{if(lp(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:l("请求正在转发中,用时列显示的是已用时"),children:[s.jsx(Lv,{className:"req-live-dot","aria-hidden":"true"}),l("进行中")]})})},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=w0(e),g=!p&&f>=200&&f<300?l("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||l("失败")})},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:l("转发到上游的模型:{model}",{model:j}),children:["⬆️ ",j]}),s.jsxs("span",{className:"req-model-line sub",title:l("下游请求的模型:{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:l("这条明细没有记录来源客户端(旧数据、模型测试,或请求未带 User-Agent)"),children:"—"},o);const p=f==="other"?l("其它"):f;return s.jsx("span",{className:d,title:f==="other"?l("识别到 User-Agent,但不属于已知的客户端类型:{ua}",{ua:f}):l("来源客户端:{client}",{client:p}),children:p},o)}case"dur":return lp(e)?s.jsxs("span",{className:d,children:[s.jsx("span",{className:"req-dur-line",title:l("已用时(请求仍在转发中)"),children:OX(e.ts)}),BX(e)]},o):s.jsxs("span",{className:d,children:[s.jsx("span",{className:"req-dur-line",children:j0(e.durationMs)}),s.jsx("span",{className:"req-dur-line sub",title:l("首响:上游首帧到达的耗时"),children:l("首响 {time}",{time:AX(e.firstResponseMs)})})]},o);case"usage":{if(lp(e))return s.jsx("span",{className:d},o);if(!w0(e))return s.jsxs("span",{className:d,title:l("失败请求不记录用量"),children:[s.jsx("span",{className:"req-usage-line",children:"in: - / out: - / all: -"}),s.jsx("span",{className:"req-usage-line sub",children:l("缓存读取: - / 命中率: -")})]},o);const f=`in: ${sx(e.promptTokens)} / out: ${sx(e.completionTokens)} / all: ${sx(e.totalTokens)}`,p=l("缓存读取: {cache} / 命中率: {rate}",{cache:sx(e.cacheReadTokens),rate:MX(e)}),g=RX(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:TX,children:[" · ",g]}):null]})]},o)}case"error":return lp(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-${r}`,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:l("查看该请求的上游原始报文"),onClick:()=>{js().wbRequestDetail?.open?.(f,e)},children:l("详情")})},o):s.jsx("span",{className:`req-none ${c} ta-${r}`,children:"-"},o)}default:return null}}function UX(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 VX(){const[e,t]=x.useState(LX),[r,o]=x.useState(()=>fD()),[c,d]=x.useState(()=>Xt.range),[f,p]=x.useState(!1),[g,v]=x.useState(0),[y,b]=x.useState(()=>Xt.size),[j,w]=x.useState(()=>({ms:tx,enabled:nx})),[S,N]=x.useState([]),[C,E]=x.useState([]),[,R]=x.useState(0),k=x.useRef(null),A=x.useRef(null),D=x.useRef(!1),I=x.useCallback(ee=>(Xt.filters={...Xt.filters,...ee},o({...Xt.filters}),Xt.filters),[]),M=x.useCallback(ee=>{Xt.range=ee,d(ee)},[]),O=x.useCallback(ee=>{Xt.offset=ee,v(ee)},[]),_=x.useCallback(ee=>{Xt.runningOnly=ee,p(ee)},[]),L=x.useCallback(()=>{h0||!js().wbFilterMemory||(h0=!0,!cD&&I(fD()))},[I]),z=x.useCallback((ee,de)=>{js().wbRequestHover?.beforeListRedraw?.(),de&&(g0=de),D.current=!0,t(ee)},[]),U=x.useCallback(ee=>{js().wbRequestHover?.beforeListRedraw?.(),D.current=!0,t(de=>({...de,error:ee}))},[]),B=x.useCallback(async(ee={})=>{const{silent:de=!1,resetPage:K=!1}=ee;K&&O(0),PX(),L(),de||gD();const be=++uD;try{const ne=js().workbuddyDesktop;if(!ne)throw new Error(l("后端桥不可用"));const ce=await ne.getStatsRequests(kX());if(be!==uD)return;const we={entries:Array.isArray(ce?.entries)?ce.entries:[],total:Number(ce?.total)||0,matched:Number(ce?.matched)||0,running:Number(ce?.running)||0,loaded:!0,error:""},Ee=Math.max(0,(Math.ceil(we.matched/Xt.size)-1)*Xt.size);if(Xt.offset>Ee)return O(Ee),B({silent:de});K&&(A.current=0),z(we,we.entries)}catch(ne){de||(console.warn("读取请求日志失败:",u0(ne)),U(l("读取请求日志失败,详见控制台")))}},[O,z,U,L]);x.useEffect(()=>(Pu={load:B,setAuto:ee=>w(ee),setFilterOptions:(ee,de)=>{N(ee),E(de)},repaint:()=>R(ee=>ee+1)},js().wbRequestHover?.bind?.({host:k.current,entryOf:ee=>{const de=ee?.dataset?.reqId||"";return de&&(g0.find(K=>String(K?.id||"")===de)||g0.find(K=>String(K?.ts||"")===de))||null}}),B({silent:!0}),gD(),()=>{Pu=null}),[B]),x.useLayoutEffect(()=>{_X(),R(ee=>ee+1)},[]);const Q=e.error||!e.entries.length?"":N0().map(ee=>ee.key).join("|");x.useLayoutEffect(()=>{Q&&js().wbTableColumns?.repaint?.("requests")},[Q]),x.useEffect(()=>{if(!j.enabled||j.ms<=0)return;const ee=window.setInterval(()=>{document.hidden||js().wbApp?.currentPage!=="requests"||b0||(b0=!0,B({silent:!0}).finally(()=>{b0=!1}))},j.ms);return()=>{window.clearInterval(ee)}},[j,B]),x.useLayoutEffect(()=>{D.current&&(D.current=!1,js().wbRequestHover?.afterListRedraw?.());const ee=A.current;if(ee===null)return;A.current=null;const de=k.current;de&&(de.scrollTop=ee)});function W(ee){const de=Math.max(1,Math.ceil(e.matched/Xt.size)),be=(Math.min(Math.max(1,ee),de)-1)*Xt.size;be!==Xt.offset&&(O(be),A.current=0,B())}function Z(ee){const de=sD(ee);if(de===Xt.size)return;Xt.size=de,b(de),Uh("requests",de);const K=Xt.offset+1;O(Math.max(0,Math.floor((K-1)/de)*de)),A.current=0,B()}function Y(ee){cD=!0,CX(I(ee)),B({resetPage:!0})}function q(ee){const de=p0.includes(ee)?ee:m0;de!==Xt.range&&(M(de),NX(de),B({resetPage:!0}))}function G(ee){ee!==Xt.runningOnly&&(_(ee),B({resetPage:!0}))}const $=N0(),F=Math.max(1,Math.ceil(e.matched/Xt.size)),X=Math.min(F,Math.floor(g/Xt.size)+1),re=e.matched?g+1:0,P=e.matched?g+e.entries.length:0,V=e.error?"—":e.matched===e.total?l("{n} 条",{n:e.total}):l("{matched} / {total} 条",{matched:e.matched,total:e.total}),J=!f&&e.running>0?l(" · {n} 进行中",{n:e.running}):"",ie=[bX[c]||l("全部")];f?ie.push(l("只看进行中")):r.status==="ok"?ie.push(l("只看成功")):r.status==="error"&&ie.push(l("只看失败")),r.provider&&ie.push(hD(r.provider)),r.model&&ie.push(r.model);const me=x.useMemo(()=>!r.provider||S.some(ee=>ee.value===r.provider)?S:[{value:r.provider,label:r.provider},...S],[r.provider,S]),he=x.useMemo(()=>!r.model||C.includes(r.model)?C:[r.model,...C],[r.model,C]),ae=IX(e.entries),oe=e.entries.map((ee,de)=>s.jsx("div",{className:`req-row${lp(ee)?" running":w0(ee)?"":" failed"}`,children:$.map(K=>HX(ee,K))},ae[de]));return s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:l("请求日志列表")}),s.jsx(ze,{id:"req-badge",variant:"outline","data-tone":"",children:V+J}),s.jsx("span",{className:"panel-sub",children:l("按时间倒序,全量保留")}),s.jsx("div",{className:"head-actions",children:s.jsx(se,{id:"btn-req-clear",variant:"destructive",onClick:()=>{js().wbRequestClearModal?.open?.()},children:l("清理")})})]}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"log-filters",children:[s.jsx(Gn,{options:yX,value:c,onValueChange:q,"aria-label":l("请求日志时间范围"),className:"shrink-0"}),s.jsxs(ct,{value:r.status,disabled:f,onValueChange:ee=>Y({status:String(ee??"")}),children:[s.jsx(dt,{id:"req-status",className:"min-w-[120px]",title:l(f?"「仅看进行中」开启时,状态固定为进行中":"按请求结果筛选"),"aria-label":l("按请求结果筛选"),children:s.jsx(ut,{children:lD.find(ee=>ee.value===r.status)?.label??jX})}),s.jsx(ft,{children:lD.map(ee=>s.jsx(Ye,{value:ee.value,children:ee.label},ee.value))})]}),s.jsxs(ct,{value:r.provider,onValueChange:ee=>Y({provider:String(ee??"")}),children:[s.jsx(dt,{id:"req-provider",className:"min-w-[120px]",title:l("按提供商筛选(只列日志里出现过的)"),"aria-label":l("按提供商筛选"),children:s.jsx(ut,{children:r.provider?me.find(ee=>ee.value===r.provider)?.label||r.provider:oD})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"",children:oD}),me.map(ee=>s.jsx(Ye,{value:ee.value,children:ee.label},ee.value))]})]}),s.jsxs(ct,{value:r.model,onValueChange:ee=>Y({model:String(ee??"")}),children:[s.jsx(dt,{id:"req-model",className:"min-w-[120px]",title:l("按模型筛选(只列日志里出现过的;精确匹配模型名)"),"aria-label":l("按模型筛选"),children:s.jsx(ut,{children:r.model||iD})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"",children:iD}),he.map(ee=>s.jsx(Ye,{value:ee,children:ee},ee))]})]}),s.jsx(SV,{id:"btn-req-running",variant:"outline",size:"default",pressed:f,onPressedChange:G,title:l("只显示正在转发中的请求(状态列按阶段显示:连接中 / 等待响应 / 响应中 / 重试中,用时列显示已用时)"),children:l("仅看进行中")}),s.jsx("div",{className:"spacer"}),s.jsx("span",{className:"panel-sub",id:"req-summary",children:ie.join(" · ")})]}),s.jsx("div",{className:"log-list",id:"req-list",ref:k,children:e.error?s.jsx("div",{className:"log-empty",children:e.error}):e.entries.length?[UX($),...oe]:s.jsx("div",{className:"log-empty",children:zX(e)})})]}),s.jsx(Di,{total:e.matched,range:{start:re,end:P},page:X,pageCount:F,size:y,sizes:gX,onSizeChange:Z,onPageChange:W,disabled:!e.loaded&&!e.error})]})}async function xD(e={}){await Pu?.load(e)}function $X(){return pD().toString()}function FX(){return v0=0,xD({resetPage:!0})}const bD='.page[data-page="requests"]';let vD=!1;function yD(){if(vD)return;const e=document.querySelector(bD);e&&(vD=!0,e.replaceChildren(),jn.createRoot(e).render(s.jsx(VX,{})))}document.querySelector(bD)?yD():document.addEventListener("DOMContentLoaded",yD,{once:!0}),window.wbRequestsPanel={load:xD,applyAutoRefresh:S0,visibleColumns:N0,clearParams:$X,notifyCleared:FX},window.wbRequestPhase={labelOf:eD,badgeHtml:mX,elapsedLineHtml:hX,elapsedText:tD,phaseOf:d0};function rt(){return window}function Wt(e){return e instanceof Error?e.message:String(e)}function We(e,t){rt().wbApp?.toast?.(e,t)}async function qX(e){try{await rt().workbuddyDesktop?.openReleasePage?.(e)}catch(t){We(`打开链接失败:${Wt(t)}`,"err")}}const rx=[{id:"general",label:"通用",icon:"sliders"},{id:"display",label:"显示",icon:"display"},{id:"gateway",label:"网关",icon:"traffic"},{id:"retry",label:"重试",icon:"refresh"},{id:"timeout",label:"超时",icon:"timer"},{id:"security",label:"安全",icon:"shield"},{id:"data",label:"数据",icon:"database"},{id:"feedback",label:"反馈与需求",icon:"feedback"},{id:"about",label:"更新",icon:"download"}],jD="workbuddy-desktop-settings-cat",GX="workbuddy-desktop-theme",KX="workbuddy-desktop-zoom",wD="wb:theme",SD="wb:zoom",C0=80,ND=130,ax=5,YX=Array.from({length:(ND-C0)/ax+1},(e,t)=>C0+t*ax),XX=[{value:"system",label:"跟随系统"},{value:"light",label:"浅色"},{value:"dark",label:"深色"}];function QX(){try{const e=localStorage.getItem(GX);return e==="light"||e==="dark"?e:"system"}catch{return"system"}}function ZX(){try{const e=localStorage.getItem(KX);if(e===null||e.trim()==="")return 100;const t=Number(e);if(!Number.isFinite(t))return 100;const r=Math.round(t/ax)*ax;return Math.min(ND,Math.max(C0,r))}catch{return 100}}const k0=1,T0=3650,E0=[{key:"logRetentionDays",id:"settings-retention-log",label:"事件日志保留天数",unit:"天",min:k0,max:T0,hint:"登录 / 账号切换 / 429 切换等系统事件,可填 1–3650 天。"},{key:"requestRetentionDays",id:"settings-retention-request",label:"请求日志保留天数",unit:"天",min:k0,max:T0,hint:"「请求日志」页的逐条请求记录,可填 1–3650 天。"},{key:"dailyRetentionDays",id:"settings-retention-daily",label:"按天聚合保留天数",unit:"天",min:k0,max:T0,hint:"报表页的热力图与按天趋势,可填 1–3650 天。"}],CD=[{key:"retryCount",id:"settings-retry-count",label:"同一账号重试次数",unit:"次",min:0,max:10,hint:"在同一个账号上原地重发几次(不含首发;整条请求共用一份,用完后换来的账号只发一次就继续换)。可填 0–10,0 表示失败立即换号。"},{key:"retryCrossProviderCount",id:"settings-retry-cross-provider-count",label:"切换账号重试次数",unit:"次",min:0,max:10,hint:"失败后最多再换几个账号试(填 N = 最多换 N 个,首发那个不算)。换到同一家名下另一个账号、或换到另一家,都各算一次;换满仍失败就返回错误。可填 0–10,0 表示失败立即报错。"},{key:"retryIntervalSeconds",id:"settings-retry-interval",label:"重试间隔",unit:"秒",min:0,max:300,hint:"两次重试之间的等待时间,两项共用,可填 0–300 秒。"}],kD=[{key:"connectTimeoutSeconds",id:"settings-timeout-connect",label:"连接中超时",unit:"秒",min:1,max:3600,hint:"建立上游 TCP/TLS 连接或代理隧道的最大等待时间(秒),默认 30 秒,范围 1~3600。"},{key:"headersTimeoutSeconds",id:"settings-timeout-headers",label:"等待响应超时",unit:"秒",min:1,max:3600,hint:"请求发出后等待上游响应头的最大时间(秒),默认 300 秒,范围 1~3600。"},{key:"streamIdleTimeoutSeconds",id:"settings-timeout-stream-idle",label:"流式响应空闲超时",unit:"秒",min:1,max:3600,hint:"流式响应相邻数据之间允许的最大空闲时间(秒),收到新数据后重新计时,默认 300 秒,范围 1~3600。"},{key:"bodyTimeoutSeconds",id:"settings-timeout-body",label:"非流式响应超时",unit:"秒",min:1,max:3600,hint:"读取完整非流式响应体允许的最大时间(秒),默认 300 秒,范围 1~3600。"}],TD=[{key:"queueMaxWaits",id:"settings-queue-max-waits",label:"排队等待次数",unit:"次",min:0,max:10,hint:"上游模型繁忙时会先排队(回一句「建议 N 秒后再来」,Qoder 免费模型就是这样):网关等一会儿再发同一请求,最多等几次。默认 2 次,可填 0–10;填 0 表示不等待,排队直接返回 503 并说明「不是登录态或额度问题」。"},{key:"queueWaitSeconds",id:"settings-queue-wait-seconds",label:"排队等待秒数",unit:"秒",min:0,max:120,hint:"每次等待的时长,默认 0 = 跟随上游建议(实测 9~30 秒,上游没给建议时用 15 秒)。可填 0–120 秒强制一个固定时长。"}],ED="noRetryStatusCodes",R0=100,A0=599,RD=50,Mo=[{value:"passthrough",optionLabel:"透传客户端 system(默认)",toastLabel:"透传客户端 system"},{value:"custom",optionLabel:"替换为网关提示词",toastLabel:"替换为网关提示词"},{value:"append",optionLabel:"追加网关提示词",toastLabel:"追加网关提示词"}];function AD(e,t,r,o){const c=String(e??"").trim();if(!c)return{ok:!1,message:`${o}不能为空(可填 ${t}–${r})`};if(!/^\d+$/.test(c))return{ok:!1,message:`${o}必须是整数`};const d=Number(c);return dr?{ok:!1,message:`${o}必须在 ${t}–${r} 之间(当前填的是 ${c})`}:{ok:!0,value:d}}function WX(e,t){const r={...t};if(e&&typeof e=="object"){const o=e;typeof o.closeToTray=="boolean"&&(r.closeToTray=o.closeToTray),typeof o.autostart=="boolean"&&(r.autostart=o.autostart),typeof o.lanAccess=="boolean"&&(r.lanAccess=o.lanAccess),typeof o.lanPanel=="boolean"&&(r.lanPanel=o.lanPanel),typeof o.lightweightMode=="boolean"&&(r.lightweightMode=o.lightweightMode)}return r}function OD(e,t,r){if(!t||typeof t!="object")return null;const o=t,c={...r||{}};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 JX(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 r=t/1024;return r<1024?`${r.toFixed(1)} MB`:`${(r/1024).toFixed(2)} GB`}function eQ(e){const t=Number(e);return!Number.isFinite(t)||t<0?"—":t.toLocaleString("zh-CN")}const Os={displayTheme:"控制界面的深浅色,与左侧边栏底部的三个主题按钮是同一个设置(改哪一处,另一处立刻跟上)。「跟随系统」会随操作系统当前的浅色 / 深色自动切换,并在系统主题变化时即时跟上;选「浅色」或「深色」则把界面固定在该模式,不再随系统变化。窗口标题栏的深浅色会一并同步,不会出现深色界面配一条浅色标题栏的情况。",displayZoom:"等比放大或缩小整个界面(文字、控件、间距一起变),效果与浏览器按 Ctrl +/- 相同:80%–130%、5% 一档。窗口本身不缩放,变的是页面内容的显示比例,设置立即生效并记住,下次启动直接按这个比例打开。放得越大可视范围越小,窗口较窄或表格较宽时不建议调得太大。",displayLanguage:"界面语言。可选简体中文、繁體中文、English、日本語、한국어、Português (Brasil),或「跟随系统」(按浏览器 / 系统的语言列表自动选)。切换后整页立即刷新;该偏好只存在本机(localStorage),不影响账号、密钥与转发。",tray:"默认关闭窗口不会退出程序,而是把窗口缩到系统托盘,转发继续在后台运行(OpenAI 客户端不受影响);要彻底退出程序,请在托盘图标上右键选「退出」。关掉这个开关后,点关闭按钮即退出程序、转发随之中断。「开机自动启动」开启后,登录系统时会自动启动本程序(通常直接驻留托盘),不需要手动打开。",lightweight:"开启后,关闭窗口不只是隐藏,而是把界面窗口整个销毁:底层的 WebView2 六个常驻进程(约 200MB 内存)随之退出,网关转发、定时签到、余额查询都在后台进程里继续,不受影响;需要界面时点托盘图标重新打开(WebView 冷启动约 1 秒)。注意:界面销毁期间「ZCode 活动套餐」通道的验证码令牌由界面铸造,无法补充 —— 走该通道的请求会以 503 落进请求日志(写明原因),重新打开界面即自动恢复。此开关只在「关闭窗口时最小化到托盘」开启时有意义,最小化窗口不受影响。",lan:"默认网关只监听 127.0.0.1,只有本机能访问。开启后网关改听所有网卡,同一局域网内的设备可以把 API 地址指向本机 IP 一起使用。出于安全考虑,开启前必须先注册一个面板管理员:管理接口从此要求管理员会话或网关 Key,模型额度不会对局域网裸奔;一把启用的网关 Key 都没有时,转发接口也会拒绝服务,直到创建第一把。改动需要重启应用生效。「同时开放网页管理面板」把管理界面也出给局域网(其他设备的浏览器打开本机 IP 即可管理),默认关闭 —— 桌面端的面板仍只由本程序自己出。",units:"控制报表与请求日志里 Token 读数的写法:开启后按中文量级显示(1.2亿 / 8400万),关闭则用 k / M 缩写(与上游文档、接口字段的写法一致)。这只影响显示口径,不改变任何统计与存储的数值。",queue:"只对「排队制」的上游生效(目前是 Qoder 的免费模型):模型繁忙时上游不报错,只回一句「建议 N 秒后再来」(业务码 10605),网关按建议时长等一会儿再发同一请求,等满次数仍排不上才把「排队中」作为错误返回(HTTP 503,文案会说明这不是登录态或额度问题)。等待发生在首个字节之前,吃的是「等待响应超时」那份预算 —— 两项设置一起决定一次请求最多卡多久;排队不会标记账号限额、也不会换账号(换谁都一样在排队)。保存后对下一个请求立即生效,不用重启。",timeouts:"上游请求四个阶段各自的等待上限(秒,1~3600):①「连接中超时」= 建立 TCP/TLS 连接或代理隧道的最大等待,默认 30 秒;②「等待响应超时」= 请求发出后等上游响应头的最大时间,默认 300 秒 —— 网关请求上游恒带 stream,响应头在 SSE 建立时就到达,与模型思考多久无关;③「流式响应空闲超时」= 流式响应相邻两块数据之间允许的最大空闲,收到新数据即重新计时,默认 300 秒 —— 上游长时间不吐数据即判定连接僵死并断开;④「非流式响应超时」= 读完整份非流式响应体的总预算(一次性计时、不重置),默认 300 秒。四项都是「等待上限」,只要数据还在来,正常的流式回答就一直往下传。保存后对下一个请求立即生效,不用重启。",retry:"请求转发到上游失败时(服务器瞬时错误、连接失败,以及 WorkBuddy 的 11-128 敏感词拦截),网关会等一段间隔后再发一次。次数分两档,管的是两件事:①「同一账号重试次数」在同一账号上原地重发几次 —— 一般是提示词被上游拦截、或链路瞬时抖动,等一会儿重发往往就好了;②「切换账号重试次数」这份请求最多再换几个账号试 —— 首发的那个账号不算,每换一个扣一次,不分是不是同一家(换到同一家的下一个账号也算一次),换满还失败就把错误返回给客户端。两项都设为 0 表示失败不重试、直接报错。注意账号级限额(429)不占这里的换号次数 —— 那类失败走「冷却该账号并换下一个账号」的降级,与这里的重试是两条路。另有「指定错误码直接换号」名单(默认 402):命中名单的上游状态码不在同一账号重发,直接按队列换下一个账号继续试(换号也占「切换账号重试次数」),换满仍失败才把错误返回给客户端。",sanitize:"上游用「逐字精确匹配」的方式审核请求体(不是语义审核):客户端注入的固定模板句、计费头字段名、以及某些裸错误码出现在报文里就会整单拦截,返回 400。开启本项后,网关在每次转发前改写这些指纹 —— 表头键值整段删除,承载语义的模板句只换一个词(如 official CLI for Claude → official CLI tool for Claude),对话内容与语义都不受影响。规则集是内置的,不需要也无法维护词表。关掉本项后客户端模板会原样发往上游,可能重新出现模板句被误拦的报错。",clineHeaders:"Cline 上游按请求头判定「调用方是不是 Cline 自家产品」:X-CLIENT-TYPE: cline-sdk 是硬门槛(缺了它免费池模型一律 403),版本号与平台标识让请求更贴近官方客户端的形态。这里列出的是网关默认会发的头:改某一行的值 = 覆盖默认值(也可以新增默认清单之外的自定义头);把值清空保存 = 这个头不发送;在界面删掉被改过的行 = 回落默认值。改完点「保存」,下一个 Cline 请求立即生效。不懂某一行的含义就不要动它 —— 伪装头的价值在「与官方客户端逐字一致」。",cors:"网关面(/v1/*)默认不应答浏览器跨源请求:页面直连会被预检拦下,只报「无法连接 API」。注意来源是 * —— 未配「网关 Key」时任何网页都能借本机网关打上游,故默认关闭;只给自己用的话,让页面与网关同源(本地反代 /v1)更稳妥。面板接口(/api/*)不受影响。",prompt:"客户端(Claude Code / Codex 等 CLI)会在 system 提示词里注入几十句固定模板,上游按逐字匹配审核,命中就整单拦截(HTTP 400)。指纹脱敏能改写实测命中过的那几句,但换一个客户端版本就可能冒出新的。这里可以把 system 整段换成网关自己那份:①「透传」= 不动客户端 system(默认,行为与之前完全一致);②「替换」= 删掉客户端所有 system / developer 消息,换成网关的提示词(客户端项目规范随之消失);③「追加」= 在开头连续 system 块之后插入一条网关提示词,既有消息逐字不动(客户端规范与网关提示词并用)。那份提示词有两个来源:提示词文件(留空用内置默认),或直接在界面上编辑正文 —— 编辑过就以那份正文为准(优先于文件),清空则回到文件 / 内置默认。另外,透传 / 追加模式下撞了内容拦截(多半是指纹误报)时,网关会自动换一段最小中性提示词重试一次,并把「降级期」开到次日 00:00 —— 期间所有请求直接带中性提示词出门,不再先撞一次 400;这里能看见并提前解除它。上面几项是**默认值**:想给某个提供商单独配,用下面的「按提供商」加一行(带「网关自带」的家默认就列在那里)—— 不同的上游对这些内容的接受程度不一样。",debug:"开启后,网关会把每次转发**发给上游的请求**(请求头 + 请求体)与**上游返回的响应**(状态码 + 响应头 + 响应体)完整保存到本地,供请求日志页的「详情」查看。请求头里的 Authorization、Cookie、API Key 等凭据字段一律替换成 [redacted],不会明文落盘;请求体与响应体按原样保存(可能包含你的对话内容)。报文只保留最近 500 条,超出后丢弃最旧的。这是排障用的临时开关,不需要时建议关闭。",io:"导出会把全部账号与自定义提供商定义写入一个 JSON 文件,可以拷到另一台机器上导入后继续使用。导入采用合并策略:同提供商下按业务身份(UID / userId / apiKey 等)去重 —— 已存在的账号只更新凭证,保留本机原有的优先级顺序;新账号追加到转发顺序末尾,不会抢占当前正在使用的账号;自定义提供商定义按 id 合并,本机缺失时自动补建。",retention:"三类数据各自独立计时,超出保留天数的部分会被删除:事件日志是登录、账号切换、429 切换这类系统事件;请求日志是网关每次转发到上游的逐条记录;按天聚合供报表页的热力图与按天趋势使用。把某一档改小(例如 30 天改成 7 天)保存后会立即删除超出的历史数据,此操作不可恢复;改大或保持不变不会删除任何数据。三项的可填范围均为 1–3650 天。",storage:"全部数据(账号、事件日志、请求记录、调试报文、设置)统一保存在配置目录下的 agent2api.db 这一个 SQLite 数据库里。备份时只需拷贝这个文件;更换保存位置请设置环境变量 AGENT2API_PROXY_HOME 后重启程序。"},us={timeouts:"保存后立即生效,不用重启;超时按上游失败处理(计入请求日志的「错误」列,并按「请求重试」的设置决定是否重试)。",queue:"等待期间请求日志的状态列会显示「排队中」阶段,详情弹窗的「内部重试」里能逐次看到等待时长;等待用尽后返回 HTTP 503(不是 401/429:既不会刷新凭证,也不会把账号标成限额)。",retry:"保存后立即生效,不用重启;次数用尽仍失败时,错误原样返回给客户端。",retryCodes:"命中这些上游状态码的失败不在同一账号重发,直接换下一个账号继续试(换号占用「切换账号重试次数」,换满仍失败才把错误原样返回给客户端)。输入 100–599 的状态码后回车添加,点 × 或退格删除;默认 402(积分不足)。清空全部表示任何错误都照常重试。",sanitize:"默认开启。命中明细会记进请求日志的「敏」标签(悬停可看命中了哪几条规则)。本项只改发给上游的副本,客户端看到的响应内容不变。",clineHeaders:"值与默认值相同的行不占覆盖(存的是「改过的键」,不是全量配置);值留空保存表示这个头不发送,删除改过的行表示回落默认值。改完立即生效,不用重启。",cors:"默认关闭。改动立即生效,不用重启;关闭期间的跨源请求会被预检拦下。",debug:"开启后新发生的请求才会被记录(已经过去的请求补不回来)。报文统一存放在本地数据库里,只保留最近 500 条(超出后丢弃最旧的),条数见左侧「数据 → 数据存储」的「调试报文」。",promptMode:"替换 = 客户端 system / developer 消息全部删掉,换成网关的提示词;追加 = 保留客户端内容,只在开头 system 块之后多插一条。两者都只改发给上游的副本,客户端看到的响应不变。",promptFile:"UTF-8 文本文件路径,留空用内置默认提示词(通用编码助手提示词,不含任何会被上游拦截的模板句)。只在「替换 / 追加」模式下生效,透传模式不读它。",promptText:"在这里直接编辑提示词正文:保存后以这份文本为准(优先于上面的提示词文件),清空则回到文件 / 内置默认。改一个字不必再去编辑器里开文件。",promptGatewayText:"上游按「结构」校验身份:三段必须各自成块,所以这里分开编辑三段(不能合成一段)。动态段里的运行值写成占位符,发请求时才替换:{cwd} 工作目录、{platform} 平台、{shell} shell、{os_version} 系统版本、{git} 是否 git 仓库、{provider} 提供方标识、{model} 模型名。清空某一段 = 那一段恢复官方原文。第三段发出时前面会自带一个空行(官方形状)。",prompt:"改完立即生效,不用重启(下一个请求就用新模式)。降级是自动的临时状态,解除后本模式自己的提示词立刻恢复。",promptProviders:"「用哪份提示词」本来是按上游分别决定的事,所以每家可以有自己的模式、提示词文件与正文:不在这里列出的提供商一律沿用上面那份默认设置,「跟随默认」把这一家取消、回到默认。带「网关自带」那一行的家(目前是 ZCode 两家)默认就列在这里 —— 那一段是网关自己装上去的文本,不来自客户端也不来自提示词文件,默认开启、可以关掉,也可以改它的正文(改过的那一段以你的文本为准);关掉后还能不能通过上游校验,取决于上游当下的口径,行内说明了实测依据。「模式 / 提示词文件 / 正文」管的是客户端自己的 system 怎么处理,与那个开关是两件事。",retention:"保存后立即生效:改小保留天数会立刻删除超出的历史数据,且不可恢复。",storageFile:"配置目录下的 agent2api.db(账号、日志、请求记录、调试报文与设置都在里面)。",storageSize:"库主文件的大小(不含运行期间的 WAL 临时文件,退出时已自动并回)。",storage:"数据统一保存在配置目录下的 agent2api.db;如需更换位置,请设置环境变量 AGENT2API_PROXY_HOME 后重启程序。",captcha:"开启后,登录页在浏览器后台自动完成验证(对真人无感),而脚本每次尝试都要先算一道题 —— 暴力破解与抢注的成本显著上升。仅影响面板的登录 / 注册,与 API 客户端的 API Key 无关。",panelLogin:"当前浏览器以管理员身份登录着本面板。「退出登录」会撤销这台设备的登录会话(30 天内的自动续期一并失效),需要重新输入账号密码;其他已登录的设备不受影响。"},un={appLoading:"—",appUnavailable:"主进程未返回启动设置,请更新桌面端后重试",appTrayOn:"关闭窗口时程序不退出,转发继续在后台运行;退出请用托盘菜单",appTrayOff:"关闭窗口即退出程序,后台转发随之中断",appLightOn:"轻量模式已开启:关窗即销毁界面进程(释放约 200MB 内存),网关在后台继续;界面销毁期间 ZCode 活动套餐通道不可用,相关请求会在请求日志里注明原因",unitsOn:"当前显示为「1.2亿 / 8400万」这类中文量级。",unitsOff:"当前显示为「1.20M / 8.4k」这类英文缩写。",debugUnavailable:"未能读取调试模式设置,请稍后重试",debugOn:"正在保存上游原始报文:",debugOff:"未开启,转发时不保存任何原始报文。",sanitizeUnavailable:"未能读取指纹脱敏设置,请稍后重试",sanitizeOn:"正在剥离出站请求里的审核指纹:表头键值整段删除,模板句最小改写。",sanitizeOff:"未开启,客户端 system 模板会原样发往上游,可能被内容审核误拦(400)。",corsUnavailable:"未能读取网关跨域访问设置,请稍后重试",corsOn:"正在应答跨源请求:浏览器跨域请求可直连 /v1/*。",corsOff:"未开启,浏览器跨域无法直连网关。",promptUnavailable:"未能读取系统提示词设置,请稍后重试",degradeUntilFallback:"次日 00:00",themeSystem:"当前跟随操作系统的深浅色设置,系统切换时界面会自动跟上。",themeLight:"当前固定为浅色模式,不随系统变化。",themeDark:"当前固定为深色模式,不随系统变化。",zoomWeb:"网页端的界面缩放由浏览器自己控制(Ctrl + / Ctrl -,或浏览器菜单里的缩放),此项不可调。",zoomDefault:"当前按 100% 显示(默认比例)。",languageHint:"界面语言只保存在本机(localStorage)。切换后整页立即刷新,不影响账号、密钥与转发。"},tQ=[{value:"order",label:l("顺序优先"),tip:l("排第 1 的接走所有请求,直到它不能答(限流 / 故障 / 额度尽)才轮到下一位 —— 就是「从上往下」的现状行为。")},{value:"rotate",label:l("负载均衡"),tip:l("每条请求轮换到下一个可用账号;新会话交给当前最闲的那位。适合想把手里的号摊开用、不让某一个一直扛。")},{value:"provider",label:l("家内轮询"),tip:l("家之间仍按优先级,只有同一家内部轮流用各账号 —— 想优先用某几家、又不愿把某一家的某个账号焊死时用它。")}],nQ=[{value:"auto",label:l("自动"),tip:l("同一会话在 5 分钟内尽量跟住同一个账号;停了 5 分钟再发就算新会话。多数场景用它 —— 多轮对话少换号,也不至于把账号焊死。")},{value:"session",label:l("会话内"),tip:l("同一会话在 6 小时内跟住同一个账号;适合一坐几个小时的长会话,上游的上下文缓存能吃到更多。")},{value:"turn",label:l("每轮"),tip:l("每条请求都重新按策略选路 —— 行为与「关闭」一致,仅保留会话识别的记录。")},{value:"off",label:l("关闭"),tip:l("不做会话识别,每条请求都重新按策略选路。")}],sQ=[{key:"zcodeCaptchaPoolTarget",id:"settings-captcha-pool-target",label:l("库存目标"),unit:l("个"),min:1,max:10,hint:l("ZCode 活动套餐通道每条请求都要消耗一个当次铸造的人机验证令牌(一次性,2 分钟过期),库存低于该值时界面自动补铸到它。默认 3 个。调大能吸收突发并发,但用不掉的令牌 2 分钟就过期作废,烧的是上游风控配额。可填 1–10。")},{key:"zcodeCaptchaPoolPollMs",id:"settings-captcha-pool-poll-ms",label:l("轮询间隔"),unit:l("毫秒"),min:1e3,max:3e4,hint:l("铸造守卫每隔多久看一次库存(毫秒)。只影响发现缺货的反应速度 —— 库存够用时轮询不会铸造任何令牌。默认 2500 毫秒,可填 1000–30000。")},{key:"zcodeCaptchaPoolMaxPerRound",id:"settings-captcha-pool-max-per-round",label:l("单轮铸造上限"),unit:l("个"),min:1,max:5,hint:l("发现缺货时一轮最多铸几个(连铸之间固定隔 500 毫秒)。默认 1 个:SDK 同一实例连铸容易互相干扰。调大补货更快,但单轮连铸越多越容易触发上游风控。可填 1–5。")}];function MD(){return rt().workbuddyDesktop?.platform==="web"}let mt={...{category:rx[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:MD()};const O0=new Set;function rQ(e){return O0.add(e),()=>{O0.delete(e)}}function aQ(){return mt}function lQ(){return x.useSyncExternalStore(rQ,aQ)}function nt(e){mt={...mt,...e};for(const t of O0)t()}function Ea(e){nt({app:{...mt.app,...e}})}function Do(){nt({})}let rs=null;function tr(e){rs=e,nt({busy:e})}function Vs(){rs=null,nt({busy:null})}function M0(e){const t=rx.some(r=>r.id===e)?String(e):rx[0].id;nt({category:t,scrollReset:mt.scrollReset+1})}function oQ(e){M0(e);try{localStorage.setItem(jD,e)}catch{}}function DD(){let e=null;try{e=localStorage.getItem(jD)}catch{e=null}M0(e)}function ID(){nt({unitsChinese:rt().wbUnits?.isChinese?.()!==!1})}function iQ(e){rt().wbUnits?.setChinese?.(e),ID(),We(l(e?"✅ 已改用本地量级词(万 / 亿式)":"✅ 已改用 k / M 缩写"))}function D0(e){if(e===void 0)return;if(!e||typeof e!="object"){Ea({status:"unavailable"});return}const t=e;Ea({status:"ready",closeToTray:t.closeToTray===!0,autostart:t.autostart===!0,lanAccess:t.lanAccess===!0,lanPanel:t.lanPanel===!0,lightweightMode:t.lightweightMode===!0})}async function PD(){try{D0(await rt().workbuddyDesktop?.getAppSettings())}catch(e){console.warn("读取应用设置失败:",Wt(e)),D0(null)}}async function cQ(){const e=rt().workbuddyDesktop;if(e?.localIp){try{Ea({lanIp:await e.localIp()||null})}catch{}try{const t=Number((await e.getBackendStatus?.())?.port)||0;t&&Ea({port:t})}catch{}try{const t=(await e.panelAdminStatus?.())?.registered===!0;Ea({adminRegistered:t})}catch{}}}async function I0(e,t){if(rs){Do();return}const r=mt.app,o={closeToTray:e==="tray"?t:r.closeToTray,autostart:e==="autostart"?t:r.autostart,lanAccess:r.lanAccess,lanPanel:r.lanPanel,lightweightMode:e==="lightweight"?t:r.lightweightMode};tr("app"),Ea(o);const c=l(e==="autostart"?"开机自动启动":e==="lightweight"?"轻量模式":"关闭窗口时最小化到托盘");try{const d=rt().workbuddyDesktop;if(!d)throw new Error(l("主进程桥不可用"));const f=await d.saveAppSettings(o);Ea({status:"ready",...WX(f,o)}),We(l("✅ 已更新「{label}」",{label:c}))}catch(d){Ea(r),We(l("保存失败:{message}",{message:Wt(d)}),"err")}finally{Vs()}}function uQ(e){if(rs){Do();return}nt({lanConfirm:{mode:e?"enable":"disable",panel:mt.app.lanPanel}})}function dQ(e){if(rs){Do();return}nt({lanConfirm:{mode:"panel",panel:e}})}function P0(e){const t=mt.lanConfirm;if(nt({lanConfirm:null}),!(!t||!e)){if(t.mode==="disable"){lx(!1,!1);return}if(t.mode==="panel"){lx(!0,t.panel);return}fQ()}}async function fQ(){const e=rt().workbuddyDesktop;if(!e?.panelAdminStatus){We(l("当前环境不支持局域网访问设置"),"err");return}tr("lan");let t;try{t=(await e.panelAdminStatus())?.registered===!0}catch(r){Vs(),We(l("查询管理员状态失败:{message}",{message:Wt(r)}),"err");return}if(Vs(),Ea({adminRegistered:t}),t){await lx(!0,mt.app.lanPanel);return}nt({lanRegister:{busy:!1,error:""}})}async function pQ(e,t){if(rs)return;const r=rt().workbuddyDesktop;if(!r?.panelRegister)return;const o=e.trim();if(!o||o.length>64){nt({lanRegister:{busy:!1,error:l("请填写管理员账号(64 字符以内)")}});return}if(t.length<8){nt({lanRegister:{busy:!1,error:l("密码至少 8 位")}});return}nt({lanRegister:{busy:!0,error:""}});try{if(await r.panelRegister(o,t),mt.lanRegister===null)return;nt({lanRegister:null}),Ea({adminRegistered:!0}),await lx(!0,mt.app.lanPanel)}catch(c){nt({lanRegister:{busy:!1,error:Wt(c)}})}}function _D(){nt({lanRegister:null})}async function lx(e,t){if(rs)return;const r=rt().workbuddyDesktop;if(!r?.changeLanAccess){We(l("当前环境不支持局域网访问设置"),"err");return}tr("lan"),Ea({lanAccess:e,lanPanel:t});try{(await r.changeLanAccess(e,t))?.createdKey&&We(l("✅ 已自动创建网关 Key「默认」(可在「网关 Key」页查看)")),We(l("✅ 设置已保存,应用正在重启…"))}catch(o){We(l("保存失败:{message}",{message:Wt(o)}),"err"),await PD()}finally{Vs()}}async function mQ(){if(!rs){nt({ioFailure:null}),tr("export");try{const e=await rt().workbuddyDesktop?.exportAccounts();if(e?.canceled){We(l("已取消导出"));return}const t=Number(e?.count)||0,r=Number(e?.customProviders)||0;if(!t&&!r){We(l("没有可导出的账号"),"err");return}const o=r?l("、{n} 个自定义提供商",{n:r}):"",c=e?.file?l(" 到 {file}",{file:e.file}):"";We(l("✅ 已导出 {count} 个账号{note}{file}",{count:t,note:o,file:c}))}catch(e){We(l("操作失败:{message}",{message:Wt(e)}),"err")}finally{Vs()}}}async function hQ(){if(!rs){nt({ioFailure:null}),tr("import");try{const e=await rt().workbuddyDesktop?.importAccounts();if(e?.canceled){We(l("已取消导入"));return}const t=Number(e?.added)||0,r=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(l("跳过 {n} 个",{n:o})),c&&v.push(l("失败 {n} 个",{n:c}));const y=v.length?l(",{items}",{items:v.join(l("、"))}):"",b=p||g?l(",自定义提供商新增 {added} 个、更新 {updated} 个",{added:p,updated:g}):"",j=l("新增 {added} 个、更新 {updated} 个{suffix}{note}",{added:t,updated:r,suffix:y,note:b});if(c){We(l("导入完成:{summary}",{summary:j}),"err");const w=d.slice(0,3).map(S=>{const N=S?.customProvider?l("自定义提供商 {id}",{id:S?.id||l("(无 id)")}):S?.id??l("未知账号"),C=S?.message??l("未知原因");return l("{label}({message})",{label:N,message:C})}).join(l(";"));nt({ioFailure:{failed:c,detail:w,more:d.length>3}})}else We(l("✅ 导入完成:{summary}",{summary:j}));(t||r||p||g)&&await rt().wbApp?.refresh?.()}catch(e){We(l("操作失败:{message}",{message:Wt(e)}),"err")}finally{Vs()}}}function ox(e){if(e===void 0)return;const t=OD(E0,e,mt.retention.values);nt({retention:{status:t===null?"unavailable":"ready",values:t}})}async function ix(){try{ox(await rt().workbuddyDesktop?.getRetention())}catch(e){console.warn("读取数据保留设置失败:",Wt(e)),ox(null)}}let cx=null;function ux(e){const t=cx;cx=null,nt({retentionConfirm:null}),t?.(e)}function gQ(e){return new Promise(t=>{cx&&ux(!1),cx=t,nt({retentionConfirm:{head:e}})})}function xQ(e,t,r){return t===null?l("没能读到「{label}」的当前值,改为 {days} 天可能会删除超出的历史数据。",{label:e.label,days:r}):l("「{label}」将从 {previous} 天改为 {days} 天。",{label:e.label,previous:t,days:r})}async function bQ(e,t){if(rs||mt.retentionConfirm)return;const r=AD(t,e.min,e.max,l("天数"));if(!r.ok){We(r.message,"err");return}const o=mt.retention.values?.[e.key],c=typeof o=="number"&&Number.isInteger(o)?o:null;if(c!==null&&r.value===c)return;const d=c===null||r.valueNumber.isInteger(d?.[f.key]))){const f=d?.[e.key]??t;We(r?l("✅ 已保留 {days} 天,超出部分已清理",{days:f}):l("✅ 已保留 {days} 天",{days:f}));return}await ix(),We(r?l("✅ 已保留 {days} 天,超出部分已清理",{days:t}):l("✅ 已保留 {days} 天",{days:t}))}catch(c){We(l("保存失败:{message}",{message:Wt(c)}),"err"),await ix()}finally{Vs()}}function op(e,t){if(t===void 0)return;const r=OD(e.fields,t,e.read().values);e.write({status:r===null?"unavailable":"ready",values:r}),e.syncExtras?.(r===null?null:t)}async function _u(e){try{op(e,await e.get())}catch(t){console.warn(`${e.consoleLabel}失败:`,Wt(t)),op(e,null)}}async function _0(e,t,r){if(rs)return;const o=AD(r,t.min,t.max,t.label);if(!o.ok){We(o.message,"err");return}const c=e.read().values?.[t.key];if(Number.isInteger(c)&&o.value===c)return;tr(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});op(e,f);const p=e.read().values?.[t.key],g=Number.isInteger(p)?p:o.value;We(l("✅ 已保存:{label} {value}",{label:t.label,value:String(g)}))}catch(f){We(l("保存失败:{message}",{message:Wt(f)}),"err"),await _u(e)}finally{Vs()}}const LD={scope:"queue",fields:TD,consoleLabel:"读取排队等待设置",get:()=>rt().workbuddyDesktop?.getQueue(),save:e=>rt().workbuddyDesktop?.saveQueue(e),read:()=>mt.queue,write:e=>nt({queue:e})};async function zD(){await _u(LD)}async function yQ(e,t){await _0(LD,e,t)}const jQ={scope:"captchaPool",fields:sQ,consoleLabel:"读取验证码令牌池设置",get:()=>rt().workbuddyDesktop?.getCaptchaPool(),save:e=>rt().workbuddyDesktop?.saveCaptchaPool(e),read:()=>mt.captchaPool,write:e=>nt({captchaPool:e})};async function wQ(){await _u(jQ)}const BD="routingStrategy",HD="routingSticky",SQ="routingFailoverBackoff",NQ="routingSink",CQ="routingBreakerEnabled",kQ={[BD]:new Set(tQ.map(e=>e.value)),[HD]:new Set(nQ.map(e=>e.value))};function TQ(e){const t=e&&typeof e=="object"?e:{},r=(c,d)=>{const f=t[c];return typeof f=="string"&&kQ[c].has(f)?f:d},o=(c,d)=>{const f=t[c];return typeof f=="boolean"?f:d};return{strategy:r(BD,"order"),sticky:r(HD,"auto"),failoverBackoff:o(SQ,!0),sink:o(NQ,!0),breakerEnabled:o(CQ,!1)}}async function EQ(){try{const e=await rt().workbuddyDesktop?.getRoutingConfig();if(e===void 0){nt({routing:{...mt.routing,status:"unavailable"}});return}nt({routing:{status:"ready",...TQ(e)}})}catch(e){console.warn("读取路由设置失败:",Wt(e)),nt({routing:{...mt.routing,status:"unavailable"}})}}const ip={scope:"retry",fields:CD,consoleLabel:"读取请求重试设置",get:()=>rt().workbuddyDesktop?.getRetry(),save:e=>rt().workbuddyDesktop?.saveRetry(e),read:()=>mt.retry,write:e=>nt({retry:e}),syncExtras:e=>{if(e===null){nt({retryCodes:null});return}const t=e[ED];if(!Array.isArray(t))return;nt({retryCodes:t.filter(o=>typeof o=="number"&&Number.isInteger(o)&&o>=R0&&o<=A0)})}};function RQ(e){op(ip,e)}async function UD(){await _u(ip)}async function AQ(e,t){await _0(ip,e,t)}async function L0(e){if(!rs){nt({retryCodes:e}),tr("codes");try{const t=await rt().workbuddyDesktop?.saveRetry({[ED]:e});op(ip,t),We(l("✅ 已保存:指定错误码直接换号"))}catch(t){We(l("保存失败:{message}",{message:Wt(t)}),"err"),await _u(ip)}finally{Vs()}}}async function OQ(e){const t=mt.retryCodes;if(t===null)return;const r=String(e??"").trim();if(!r)return;if(!/^\d+$/.test(r)||Number(r)A0){We(l("状态码必须是 {min}–{max} 的整数(收到: {text})",{min:R0,max:A0,text:r}),"err");return}const o=Number(r);if(t.includes(o)){We(l("状态码 {code} 已在名单里",{code:o}));return}if(t.length>=RD){We(l("名单最多 {max} 个状态码",{max:RD}),"err");return}await L0([...t,o])}async function MQ(e){const t=mt.retryCodes;!t||!t.includes(e)||await L0(t.filter(r=>r!==e))}async function DQ(){const e=mt.retryCodes;e?.length&&await L0(e.slice(0,-1))}const VD={scope:"timeouts",fields:kD,consoleLabel:"读取请求超时设置",get:()=>rt().workbuddyDesktop?.getTimeouts(),save:e=>rt().workbuddyDesktop?.saveTimeouts(e),read:()=>mt.timeouts,write:e=>nt({timeouts:e})};async function $D(){await _u(VD)}async function IQ(e,t){await _0(VD,e,t)}function dx(e){if(e===void 0)return;if(!e||typeof e!="object"){nt({debug:{status:"unavailable",on:!1,count:null,limit:null}});return}const t=e,r=Number(t.count),o=Number(t.limit);nt({debug:{status:"ready",on:t.debugMode===!0,count:Number.isInteger(r)?r:null,limit:Number.isInteger(o)?o:null}})}async function z0(){try{dx(await rt().workbuddyDesktop?.getDebug())}catch(e){console.warn("读取调试模式设置失败:",Wt(e)),dx(null)}}async function PQ(e){if(rs){Do();return}tr("debug"),nt({debug:{...mt.debug,on:e}});try{const t=await rt().workbuddyDesktop?.saveDebug(e);dx(t),We(l(e?"✅ 调试模式已开启":"✅ 调试模式已关闭"))}catch(t){We(l("保存失败:{message}",{message:Wt(t)}),"err"),await z0()}finally{Vs()}}function fx(e){if(e===void 0)return;if(!e||typeof e!="object"){nt({sanitize:{status:"unavailable",on:!1}});return}nt({sanitize:{status:"ready",on:e.sanitizeBlacklistFingerprints===!0}})}async function B0(){try{fx(await rt().workbuddyDesktop?.getSanitize())}catch(e){console.warn("读取出站指纹脱敏设置失败:",Wt(e)),fx(null)}}async function _Q(e){if(rs){Do();return}tr("sanitize"),nt({sanitize:{status:"ready",on:e}});try{const t=await rt().workbuddyDesktop?.saveSanitize(e);fx(t),We(l(e?"✅ 出站指纹脱敏已开启":"已关闭出站指纹脱敏"))}catch(t){We(l("保存失败:{message}",{message:Wt(t)}),"err"),await B0()}finally{Vs()}}function H0(e){if(!e||typeof e!="object")return{};const t={};for(const[r,o]of Object.entries(e))typeof o=="string"&&(t[r]=o);return t}function U0(e){if(e===void 0)return;if(!e||typeof e!="object"){nt({clineHeaders:{status:"unavailable",defaults:{},overrides:{},effective:{}}});return}const t=e;nt({clineHeaders:{status:"ready",defaults:H0(t.defaults),overrides:H0(t.overrides),effective:H0(t.effective)}})}async function V0(){try{U0(await rt().workbuddyDesktop?.getClineHeaders())}catch(e){console.warn("读取 Cline 伪装头失败:",Wt(e)),U0(null)}}async function LQ(){await V0(),We(l("Cline 伪装头已刷新"))}async function FD(e){if(rs){Do();return}tr("clineHeaders");try{const t=await rt().workbuddyDesktop?.saveClineHeaders(e);U0(t),We(l("✅ Cline 伪装头已保存"))}catch(t){We(l("保存失败:{message}",{message:Wt(t)}),"err"),await V0()}finally{Vs()}}function $0(e){if(e===void 0)return;if(!e||typeof e!="object"){nt({cors:{status:"unavailable",on:!1}});return}nt({cors:{status:"ready",on:e.corsEnabled===!0}})}async function F0(){try{$0(await rt().workbuddyDesktop?.getCors())}catch(e){console.warn("读取网关跨域访问设置失败:",Wt(e)),$0(null)}}async function zQ(e){if(rs){Do();return}tr("cors"),nt({cors:{status:"ready",on:e}});try{const t=await rt().workbuddyDesktop?.saveCors(e);$0(t),We(l(e?"网关跨域访问已开启":"已关闭网关跨域访问"))}catch(t){We(l("保存失败:{message}",{message:Wt(t)}),"err"),await F0()}finally{Vs()}}async function qD(){try{const e=await rt().workbuddyDesktop?.getCaptchaSetting();nt({captcha:{available:!0,enabled:e?.captchaEnabled===!0}})}catch(e){nt({captcha:{available:!1,enabled:!1}}),console.warn("读取机器人校验设置失败:",Wt(e))}}async function BQ(e){if(rs){Do();return}tr("captcha"),nt({captcha:{...mt.captcha,enabled:e}});try{const t=await rt().workbuddyDesktop?.saveCaptchaSetting(e);nt({captcha:{available:!0,enabled:t?.captchaEnabled===!0}}),We(l(e?"✅ 机器人校验已开启":"⚠️ 机器人校验已关闭"))}catch(t){We(l("保存失败:{message}",{message:Wt(t)}),"err"),await qD()}finally{Vs()}}function HQ(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 UQ(){try{const e=await rt().workbuddyDesktop?.getModelsDev?.();nt({modelsDev:HQ(e)})}catch(e){nt({modelsDev:{...mt.modelsDev,status:"unavailable"}}),console.warn("读取 models.dev 元数据设置失败:",Wt(e))}}function Lu(e){if(e===void 0)return;if(!e||typeof e!="object"){nt({prompt:{...mt.prompt,status:"unavailable"}});return}const t=e,r=FQ(t.promptGateway);nt({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:VQ(t.promptProviders,r),gateway:r,gatewayText:qQ(t.promptGatewayText),options:$Q(t.promptProviderOptions)}})}function VQ(e,t){return!e||typeof e!="object"?[]:Object.entries(e).filter(([r,o])=>!!r&&!!o&&typeof o=="object").map(([r,o])=>{const c=o;return{id:r,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[r]??!0,configured:!0}}).sort((r,o)=>r.id.localeCompare(o.id))}function $Q(e){return Array.isArray(e)?e.filter(t=>!!t&&typeof t=="object"&&String(t.id||"")).map(t=>{const r=t;return{id:String(r.id),label:String(r.label||r.id),gatewayNote:String(r.gatewayNote||""),gatewayChars:Number(r.gatewayChars)||0,gatewayBlocks:GQ(r.gatewayBlocks)}}):[]}function FQ(e){if(!e||typeof e!="object")return{};const t={};for(const[r,o]of Object.entries(e)){const c=String(r||"").trim();!c||typeof o!="boolean"||(t[c]=o)}return t}function qQ(e){if(!e||typeof e!="object")return{};const t={};for(const[r,o]of Object.entries(e)){const c=String(r||"").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 GQ(e){if(!e||typeof e!="object")return null;const t=e,r={identity:String(t.identity||""),stable:String(t.stable||""),dynamic:String(t.dynamic||"")};return!r.identity.trim()&&!r.stable.trim()&&!r.dynamic.trim()?null:r}async function tc(){try{Lu(await rt().workbuddyDesktop?.getPrompt())}catch(e){console.warn("读取系统提示词设置失败:",Wt(e)),Lu(null)}}async function cp(e,t){if(rs)return await tc(),!1;tr("prompt");try{const r=await rt().workbuddyDesktop?.savePrompt(t);return Lu(r),We(l("✅ 已保存:{label}",{label:e})),!0}catch(r){return We(l("保存失败:{message}",{message:Wt(r)}),"err"),await tc(),!1}finally{Vs()}}async function KQ(e){const t=Mo.find(r=>r.value===e);await cp(l("模式改为「{mode}」",{mode:t?.toastLabel??e}),{promptMode:e})}async function YQ(e){await cp(e.trim()?l("提示词文件已更新"):l("已改回内置默认提示词"),{promptFile:e})}async function XQ(e){const t=!e.trim();return cp(l(t?"已清掉界面编辑的提示词(回落文件 / 内置默认)":"提示词正文已更新"),{promptText:t?"":e})}function Io(e,t){return e.options.find(r=>r.id===t)?.label||t}function nc(e){const t=e==null?"":String(e).trim();return t&&mt.prompt.options.some(r=>r.id===t)?t:""}async function up(e,t,r){return cp(e,{promptProviders:{[t]:r}})}function px(e,t){const r=!t.configured;return{promptMode:t.mode,promptFile:t.file,promptText:r&&e.source==="inline"?e.text:""}}async function QQ(e){const t=nc(e);if(!t)return;const r=mt.prompt;await up(l("已为「{label}」单独配置提示词",{label:Io(r,t)}),t,px(r,{mode:r.mode,file:r.file,text:r.text,source:r.source,lines:r.lines,fileError:r.fileError,gateway:r.gateway[t]??!0,configured:!1}))}async function ZQ(e,t){const r=nc(e.id);if(!r||!Mo.some(c=>c.value===t))return;const o=Mo.find(c=>c.value===t);await up(l("「{label}」的模式改为「{mode}」",{label:Io(mt.prompt,r),mode:o?.toastLabel??t}),r,{...px(mt.prompt,e),promptMode:t})}async function WQ(e,t){const r=nc(e.id);r&&await up(t.trim()?l("「{label}」的提示词文件已更新",{label:Io(mt.prompt,r)}):l("「{label}」改用内置默认提示词",{label:Io(mt.prompt,r)}),r,{...px(mt.prompt,e),promptFile:t})}async function JQ(e,t){const r=nc(e.id);if(!r)return!1;const o=!t.trim(),c=Io(mt.prompt,r);return up(o?l("已清掉「{label}」界面编辑的正文",{label:c}):l("「{label}」的提示词正文已更新",{label:c}),r,{...px(mt.prompt,e),promptText:o?"":t})}async function eZ(e){const t=nc(e);t&&await up(l("已取消「{label}」的单独配置",{label:Io(mt.prompt,t)}),t,null)}async function tZ(e,t){const r=nc(e);if(!r)return;const o=Io(mt.prompt,r);if(rs){await tc();return}tr("prompt");try{const c=await rt().workbuddyDesktop?.savePrompt({promptGateway:{[r]:t}});Lu(c),We(t?l("✅ 已为「{label}」装上网关自带提示词",{label:o}):l("已关闭「{label}」的网关自带提示词:能否通过上游校验取决于上游当前口径",{label:o}),t?"ok":"err")}catch(c){We(l("保存失败:{message}",{message:Wt(c)}),"err"),await tc()}finally{Vs()}}async function nZ(e,t){const r=nc(e);if(!r)return!1;const o=Io(mt.prompt,r),c=!t||!(t.identity.trim()||t.stable.trim()||t.dynamic.trim());return cp(c?l("「{label}」的网关自带提示词已改回官方原文",{label:o}):l("「{label}」的网关自带提示词正文已更新",{label:o}),{promptGatewayText:{[r]:c?null:t}})}async function sZ(){if(!rs){tr("prompt");try{const e=await rt().workbuddyDesktop?.savePrompt({clearDegrade:!0});Lu(e),We(l("✅ 已解除内容拦截降级"))}catch(e){We(l("解除失败:{message}",{message:Wt(e)}),"err"),await tc()}finally{Vs()}}}function dp(e){const t=Number(e);return Number.isFinite(t)?t:null}function q0(e){if(e===void 0)return;const t=e&&typeof e=="object"?e.database:null;if(!t||typeof t!="object"){nt({storage:{...mt.storage,status:"unavailable"}});return}const r=t;nt({storage:{status:"ready",available:r.available!==!1,file:String(r.file||""),bytes:Number(r.bytes)||0,accounts:dp(r.accounts),logs:dp(r.logs),requests:dp(r.requests),dailyDays:dp(r.dailyDays),debug:dp(r.debug)}})}async function GD(){try{q0(await rt().workbuddyDesktop?.getStorage())}catch(e){console.warn("读取数据存储概况失败:",Wt(e)),q0(null)}}async function rZ(){try{return await rt().workbuddyDesktop?.panelLogout(),window.location.href="/login",!0}catch(e){return We(l("退出失败:{message}",{message:Wt(e)}),"err"),!1}}async function KD(){DD(),ID(),nt({panelLogin:MD()}),await Promise.all([PD(),cQ(),ix(),UD(),$D(),zD(),wQ(),EQ(),z0(),B0(),V0(),F0(),tc(),GD(),qD(),UQ(),rt().wbUpdatePanel?.load?.()])}async function aZ(){await ix(),We(l("保留天数已刷新"))}async function lZ(){await UD(),We(l("重试设置已刷新"))}async function oZ(){await $D(),We(l("超时设置已刷新"))}async function iZ(){await zD(),We(l("排队等待设置已刷新"))}async function cZ(){await z0(),We(l("调试模式设置已刷新"))}async function uZ(){await B0(),We(l("指纹脱敏设置已刷新"))}async function dZ(){await F0(),We(l("网关跨域访问设置已刷新"))}async function fZ(){await tc(),We(l("系统提示词设置已刷新"))}async function pZ(){await GD(),We(l("存储概况已刷新"))}const mx=[{key:"identity",label:l("第一段(身份句)"),short:l("第一段"),hint:l("官方原文只有一句:声明自己是 ZCode。")},{key:"stable",label:l("第二段(稳定段)"),short:l("第二段"),hint:l("工具用法与环境说明那一大段。")},{key:"dynamic",label:l("第三段(动态段)"),short:l("第三段"),hint:l("沟通方式 / 上下文管理 + Environment 段。")}];function mZ(e){return l(e==="inline"?"界面里编辑的正文":e==="file"?"提示词文件":e==="builtin"?"内置默认提示词":"(未生效)")}function YD({title:e,text:t,source:r,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(Kt,{open:!0,onOpenChange:S=>{S||b||f()},children:s.jsxs(Yt,{className:"w-[min(880px,calc(100vw-48px))]",children:[s.jsx(Ft,{children:s.jsx($t,{children:e})}),s.jsxs(Ht,{children:[s.jsxs(zn,{children:[s.jsx("h3",{children:l("保存后以这里的文本为准")}),s.jsxs("p",{children:[l("这一份就是「替换 / 追加」模式下网关要发的 system 正文。"),r==="none"?l("当前是透传模式:存下来也不会发出,切成「替换 / 追加」之后才生效。"):l("当前生效的正文来自{source}{file}。保存后这一份会盖过提示词文件与内置默认{note}。",{source:mZ(r),file:o.trim()&&r!=="inline"?l("(文件:{path})",{path:o.trim()}):"",note:r!=="inline"&&o.trim()?l(",文件里后续的改动在清空这里之前不再生效"):""}),l("想回到原来那份,把这里清空再保存即可(不会删掉你配的文件路径)。")]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(tt,{htmlFor:"settings-prompt-body",children:l("提示词正文")}),s.jsx($d,{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()?l("{lines} 行、{chars} 字符(按当前草稿计)",{lines:p.split(` -`).length,chars:p.length}):l("空 = 不要这一份,回落提示词文件 / 内置默认提示词。")})]})]}),s.jsxs(sn,{children:[s.jsx(se,{variant:"outline",className:"mr-auto",disabled:b||r!=="inline",onClick:()=>{w("")},children:l("清除这里的正文")}),s.jsx(se,{variant:"outline",disabled:b,onClick:f,children:l("取消")}),s.jsx(se,{variant:"default",disabled:b||!j,onClick:()=>{w(p)},children:l(v?"保存中…":"保存")})]})]})})}function hZ({prompt:e,locked:t,busy:r}){const[o,c]=x.useState(!1);return s.jsxs(s.Fragment,{children:[s.jsx(se,{id:"btn-prompt-edit-body",variant:"outline",disabled:t||r,onClick:()=>c(!0),children:l("编辑正文")}),o?s.jsx(YD,{title:l("编辑提示词正文 · 全局"),text:e.text,source:e.source,file:e.file,disabled:r,save:XQ,onClose:()=>c(!1)}):null]})}function gZ({item:e,label:t,locked:r,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:r||o,onClick:()=>d(!0),children:l("编辑正文")}),c?s.jsx(YD,{title:l("编辑提示词正文 · {label}",{label:t}),text:e.text,source:e.source,file:e.file,disabled:o,save:f=>JQ(e,f),onClose:()=>d(!1)}):null]})}function xZ({id:e,title:t,official:r,over:o,enabled:c,disabled:d,onClose:f}){const[p,g]=x.useState(()=>({identity:o?.identity?.trim()?o.identity:r.identity,stable:o?.stable?.trim()?o.stable:r.stable,dynamic:o?.dynamic?.trim()?o.dynamic:r.dynamic})),[v,y]=x.useState(!1),b=v||d,j=mx.some(N=>p[N.key]!==r[N.key]),w=mx.filter(N=>o?.[N.key]?.trim()).map(N=>N.label);async function S(N){y(!0);try{await nZ(e,N)&&f()}finally{y(!1)}}return s.jsx(Kt,{open:!0,onOpenChange:N=>{N||b||f()},children:s.jsxs(Yt,{className:"w-[min(880px,calc(100vw-48px))]",children:[s.jsx(Ft,{children:s.jsx($t,{children:t})}),s.jsxs(Ht,{children:[s.jsxs(zn,{children:[s.jsx("h3",{children:l("三段各自成块,所以分开编辑")}),s.jsxs("p",{children:[l("上游按"),s.jsx("strong",{children:l("结构")}),l("校验身份:这三段必须各自成块排在最前(实测:三段并成一段会被回 405 / 3012)。因此这里按段编辑,不能合成一段。改过的段以你的文本为准,没改的段继续用官方原文;清空某一段 = 那一段恢复官方原文。"),w.length?l("当前已改过:{edited}。",{edited:w.join(l("、"))}):l("当前三段都是官方原文。"),c?"":l("注意:这一家的「网关自带」开关现在是关的,改过的正文要等开关打开才生效。")]}),s.jsx("p",{children:us.promptGatewayText})]}),mx.map(N=>s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs(tt,{htmlFor:`settings-prompt-block-${e}-${N.key}`,children:[N.label,s.jsx("span",{className:"ml-2 font-normal text-subtle",children:p[N.key]===r[N.key]?l("(官方原文)"):l("(已改)")})]}),s.jsx($d,{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:C=>{const E=C.currentTarget.value;g(R=>({...R,[N.key]:E}))}}),s.jsx("div",{className:"hint",children:N.hint})]},N.key))]}),s.jsxs(sn,{children:[s.jsx(se,{variant:"outline",className:"mr-auto",disabled:b||!w.length,onClick:()=>{S(null)},children:l("恢复官方原文")}),s.jsx(se,{variant:"outline",disabled:b,onClick:f,children:l("取消")}),s.jsx(se,{variant:"default",disabled:b||!j,onClick:()=>{S(p)},children:l(v?"保存中…":"保存")})]})]})})}function bZ({item:e,option:t,over:r,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:l("编辑正文")}),d?s.jsx(xZ,{id:e.id,title:l("编辑网关自带提示词 · {label}",{label:t.label}),official:p,over:r,enabled:e.gateway,disabled:c,onClose:()=>f(!1)}):null]}):null}function vZ(e){return e?mx.filter(t=>(e[t.key]||"").trim()).map(t=>t.short).join(l("、")):""}function yZ(e,t){return rt().wbIcons?.icon?.(e,t)||""}function Dn({tone:e,children:t}){const r=e==="ok"?"success":e==="bad"?"destructive":"outline";return s.jsx(ze,{variant:r,children:t})}function ds({title:e,tip:t,badge:r,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,r,o?s.jsx("div",{className:"head-actions",children:o}):null]})}function Ra({id:e,label:t,checked:r,disabled:o,tip:c,onCheckedChange:d}){return s.jsxs("label",{className:"switch",children:[s.jsx(Rs,{id:e,checked:r,disabled:o,onCheckedChange:f=>d(f)}),s.jsx("span",{children:t}),c?s.jsx("span",{className:"tip-q","data-tip":c}):null]})}function hx({field:e,value:t,disabled:r,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(Ke,{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:r||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 gx(e){return e.status==="ready"?s.jsx(Dn,{tone:"ok",children:"已生效"}):e.status==="unavailable"?s.jsx(Dn,{tone:"bad",children:"不可用"}):s.jsx(Dn,{tone:"idle",children:"检测中…"})}function Za({id:e,onClick:t}){return s.jsx(se,{id:e,variant:"outline",onClick:t,children:"刷新"})}function jZ(e){const{lanAccess:t,lanPanel:r,lanIp:o,port:c}=e.app;return t?`已开启:其他设备把 API 地址指向 ${`http://${o||"<本机IP>"}${c?`:${c}`:""}`}/v1${r?";网页管理面板已一并开放(浏览器打开同一地址)":""}。`:"未开启:网关只监听 127.0.0.1,仅本机可以访问。"}function wZ({snap:e}){const t=e.app,r=t.status==="unavailable"?un.appUnavailable:t.status==="loading"?un.appLoading:t.closeToTray?t.lightweightMode?un.appLightOn:un.appTrayOn:un.appTrayOff;return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"启动与托盘",tip:Os.tray,badge:t.status==="ready"?s.jsx(Dn,{tone:"ok",children:"已应用"}):t.status==="unavailable"?s.jsx(Dn,{tone:"bad",children:"不可用"}):s.jsx(Dn,{tone:"idle",children:"检测中…"})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"settings-switches",children:[s.jsx(Ra,{id:"settings-close-to-tray",label:"关闭窗口时最小化到托盘",checked:t.closeToTray,disabled:e.busy==="app",onCheckedChange:o=>{I0("tray",o)}}),s.jsx(Ra,{id:"settings-lightweight",label:"轻量模式(关窗释放界面内存)",tip:Os.lightweight,checked:t.lightweightMode,disabled:e.busy==="app"||!t.closeToTray,onCheckedChange:o=>{I0("lightweight",o)}}),s.jsx(Ra,{id:"settings-autostart",label:"开机自动启动",checked:t.autostart,disabled:e.busy==="app",onCheckedChange:o=>{I0("autostart",o)}})]}),s.jsx("div",{className:"settings-state",children:r})]})]}),!e.panelLogin&&s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"局域网访问",tip:Os.lan}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"settings-switches",children:[s.jsx(Ra,{id:"settings-lan-access",label:"允许局域网内的设备访问网关",checked:e.app.lanAccess,disabled:e.busy==="lan",onCheckedChange:uQ}),s.jsx(Ra,{id:"settings-lan-panel",label:"同时开放网页管理面板",checked:e.app.lanPanel,disabled:e.busy==="lan"||!e.app.lanAccess,onCheckedChange:dQ})]}),s.jsx("div",{className:"settings-state",children:jZ(e)})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"计量单位",tip:Os.units}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"settings-switches",children:s.jsx(Ra,{id:"settings-chinese-units",label:"使用中文单位(亿 / 万)",checked:e.unitsChinese,onCheckedChange:iQ})}),s.jsx("div",{className:"settings-state",children:e.unitsChinese?un.unitsOn:un.unitsOff})]})]})]})}function SZ(e){return e==="light"?un.themeLight:e==="dark"?un.themeDark:un.themeSystem}function NZ(){const[e,t]=x.useState(QX),[r,o]=x.useState(ZX),c=rt().workbuddyDesktop?.platform==="web";x.useEffect(()=>{const f=g=>t(String(g.detail||"system")),p=g=>o(Number(g.detail)||100);return window.addEventListener(wD,f),window.addEventListener(SD,p),()=>{window.removeEventListener(wD,f),window.removeEventListener(SD,p)}},[]);const d=r===100?"100%(默认)":`${r}%`;return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"显示模式",tip:Os.displayTheme}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{children:s.jsx(Gn,{"aria-label":"显示模式",options:XX,value:e,onValueChange:f=>rt().wbApp?.applyTheme?.(f)})}),s.jsx("div",{className:"settings-state",children:SZ(e)})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"界面缩放",tip:Os.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:"缩放比例"}),s.jsx("span",{className:"prompt-input",children:s.jsxs(ct,{value:String(r),onValueChange:f=>rt().wbApp?.applyZoom?.(Number(f)),children:[s.jsx(dt,{id:"settings-zoom",className:"w-[140px]",disabled:c,"aria-label":"界面缩放比例",children:s.jsx(ut,{children:d})}),s.jsx(ft,{children:YX.map(f=>s.jsx(Ye,{value:String(f),children:f===100?"100%(默认)":`${f}%`},f))})]})}),s.jsx("div",{className:"hint",children:"放大或缩小整个界面(文字与控件一起变),效果与浏览器 Ctrl +/- 相同: 共 11 档,立即生效并记住。"})]})}),s.jsx("div",{className:"settings-state",children:c?un.zoomWeb:r===100?un.zoomDefault:`当前按 ${r}% 显示。`})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"语言设置",tip:Os.displayLanguage}),s.jsxs("div",{className:"panel-body",children:[s.jsx(CZ,{}),s.jsx("div",{className:"settings-state",children:un.languageHint})]})]})]})}function CZ(){const e=window.wbI18n,t=e?.rawLocale?.()??"auto",r=e?.LOCALES??[],o=c=>c==="auto"?l("跟随系统"):r.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:l("界面语言")}),s.jsx("span",{className:"prompt-input",children:s.jsxs(ct,{value:t,onValueChange:c=>{c&&e?.setLocale(c)},children:[s.jsx(dt,{id:"settings-language",className:"w-[200px]","aria-label":l("界面语言"),children:s.jsx(ut,{children:o(t)})}),s.jsxs(ft,{children:[s.jsx(Ye,{value:"auto",children:l("跟随系统")}),r.map(c=>s.jsx(Ye,{value:c.code,children:c.label},c.code))]})]})})]})})}function kZ({codes:e,status:t,busy:r}){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:"指定错误码直接换号"}),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:`删除 ${p}`,"aria-label":`删除状态码 ${p}`,onClick:g=>{g.stopPropagation(),MQ(p)},children:"✕"})]},p)),s.jsx(Ke,{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?"—":"输入状态码,回车添加",inputMode:"numeric",autoComplete:"off",value:o,disabled:f||r,onChange:p=>c(p.target.value),onKeyDown:p=>{if(p.key==="Enter"){p.preventDefault(),OQ(o),c("");return}p.key==="Backspace"&&!o&&DQ()}})]})}),s.jsx("div",{className:"hint",children:us.retryCodes})]})}function TZ({prompt:e,locked:t,busy:r}){const[o,c]=x.useState(null);async function d(){const f=o;if(f!==null)try{await YQ(f)}finally{c(null)}}return s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"settings-prompt-file",children:"提示词文件"}),s.jsx("span",{className:"prompt-input",children:s.jsx(Ke,{id:"settings-prompt-file",type:"text",placeholder:"留空 = 用内置默认提示词",value:o!==null?o:e.file,disabled:t||r,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:us.promptFile})]})}function EZ(e){if(e.status==="loading")return un.appLoading;if(e.status==="unavailable")return un.promptUnavailable;const t=XD(e.source),r=[];return e.mode==="passthrough"?r.push("客户端 system 原样出站(只靠指纹脱敏改写模板句)。"):r.push(`${e.mode==="custom"?"替换":"追加"}生效:上游收到的 system 来自${t}${e.lines?`(${e.lines} 行)`:""}。`),e.fileError&&r.push(`⚠️ ${e.fileError}`),r.join("")}function XD(e){return e==="inline"?"界面里编辑的正文":e==="file"?"提示词文件":e==="builtin"?"内置默认提示词":""}function RZ(e){return`已自动切换到最小中性提示词(撞了上游内容拦截,多半是 system 指纹误报),到 ${e.degradeUntilText||un.degradeUntilFallback} 自动解除。期间本模式自己的提示词不会发出;把提示词改好后可以立即解除。`}function AZ({item:e,label:t,locked:r,busy:o}){const[c,d]=x.useState(null);async function f(){const p=c;if(p!==null)try{p!==e.file&&await WQ(e,p)}finally{d(null)}}return s.jsx("span",{className:"prompt-input",children:s.jsx(Ke,{id:`settings-prompt-file-${e.id}`,type:"text",placeholder:"留空 = 用内置默认提示词","aria-label":`${t} 提示词文件`,value:c!==null?c:e.file,disabled:r||o,onChange:p=>d(p.target.value),onFocus:()=>d(e.file),onBlur:()=>{f()},onKeyDown:p=>{p.key==="Enter"&&p.currentTarget.blur()}})})}function OZ(e,t){if(!t)return`未单独配置:模式、提示词文件与正文都跟随上面的全局配置(当前「${Mo.find(o=>o.value===e.mode)?.toastLabel??e.mode}」)。`;if(e.mode==="passthrough")return"客户端 system 原样出站。";const r=`${e.mode==="custom"?"替换":"追加"}生效:上游收到的 system 来自${XD(e.source)}${e.lines?`(${e.lines} 行)`:""}。`;return e.fileError?`${r} ⚠️ ${e.fileError}`:r}function MZ({item:e,option:t,over:r,locked:o,busy:c}){const d=e.gateway,f=t.gatewayChars,p=f?`约 ${f.toLocaleString("zh-CN")} 字符`:"一段内置装配",g=vZ(r);return s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{className:"prompt-gateway-label",children:"网关自带"}),s.jsxs("span",{className:"prompt-input",children:[s.jsx(Ra,{id:`settings-prompt-gateway-${e.id}`,label:`装上${p}的官方身份提示词`,checked:d,disabled:o||c,onCheckedChange:v=>{tZ(e.id,v)}}),s.jsx(bZ,{item:e,option:t,over:r,locked:o,busy:c})]}),s.jsxs("div",{className:d?"hint":"hint prompt-gateway-off",children:[d?t.gatewayNote:`已关闭。${t.gatewayNote}`,g?` 正文已改:${g}(其余段用官方原文)。`:""]})]})}function DZ({prompt:e,locked:t,busy:r}){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=Mo.find(R=>R.value===w.mode)?.optionLabel??w.mode,C=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(ct,{value:w.mode,onValueChange:R=>{R!=null&&String(R)&&ZQ(w,String(R))},children:[s.jsx(dt,{id:`settings-prompt-mode-${w.id}`,className:"w-[240px]",disabled:t||r,"aria-label":`${S} 的提示词模式`,children:s.jsx(ut,{children:N})}),s.jsx(ft,{children:Mo.map(R=>s.jsx(Ye,{value:R.value,children:R.optionLabel},R.value))})]}),s.jsx(AZ,{item:w,label:S,locked:t,busy:r}),s.jsx(gZ,{item:w,label:S,locked:t,busy:r}),w.configured?s.jsx(se,{variant:"outline",disabled:t||r,onClick:()=>{eZ(w.id)},children:"跟随默认"}):null]}),s.jsx("div",{className:"hint",children:OZ(w,w.configured)})]}),E&&C?s.jsx(MZ,{item:w,option:E,over:e.gatewayText[w.id],locked:t,busy:r}):null]},w.id)}),s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"settings-prompt-provider-add",children:"添加提供商"}),s.jsx("span",{className:"prompt-input",children:s.jsxs(ct,{value:g,onValueChange:w=>{v("");const S=w==null?"":String(w);S&&QQ(S)},children:[s.jsx(dt,{id:"settings-prompt-provider-add",className:"w-[240px]",disabled:t||r||p.length===0,"aria-label":"添加要单独配置的提供商",children:s.jsx(ut,{children:g?y(g):p.length?"添加提供商…":"全部已配置"})}),s.jsx(ft,{children:p.map(w=>s.jsx(Ye,{value:w.id,children:w.label},w.id))})]})}),s.jsx("div",{className:"hint",children:us.promptProviders})]})]})}function IZ({snap:e}){const t=e.prompt,r=t.status!=="ready",o=e.busy==="prompt",c=Mo.find(d=>d.value===t.mode)?.optionLabel??t.mode;return s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"系统提示词",tip:Os.prompt,badge:t.status==="ready"?s.jsx(Dn,{tone:"ok",children:t.mode==="passthrough"?"透传":"已接管"}):t.status==="unavailable"?s.jsx(Dn,{tone:"bad",children:"不可用"}):s.jsx(Dn,{tone:"idle",children:"检测中…"}),actions:s.jsx(Za,{id:"btn-prompt-refresh",onClick:()=>{fZ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"retention-list",children:[s.jsxs("div",{className:"prompt-group",children:["全局配置",s.jsx("span",{className:"note",children:"所有未单独配置的提供商都用这一份"})]}),s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"settings-prompt-mode",children:"模式"}),s.jsx("span",{className:"prompt-input",children:s.jsxs(ct,{value:t.mode,onValueChange:d=>{d!=null&&String(d)&&KQ(String(d))},children:[s.jsx(dt,{id:"settings-prompt-mode",className:"w-[240px]",disabled:r||o,"aria-label":"系统提示词模式",children:s.jsx(ut,{children:c})}),s.jsx(ft,{children:Mo.map(d=>s.jsx(Ye,{value:d.value,children:d.optionLabel},d.value))})]})}),s.jsx("div",{className:"hint",children:us.promptMode})]}),s.jsx(TZ,{prompt:t,locked:r,busy:o}),s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"btn-prompt-edit-body",children:"提示词正文"}),s.jsx("span",{className:"prompt-input",children:s.jsx(hZ,{prompt:t,locked:r,busy:o})}),s.jsxs("div",{className:"hint",children:[us.promptText,t.source==="inline"?`(当前生效的就是这一份,${t.lines} 行)`:t.text.trim()?`(已存一份正文,${t.lines} 行;切成「替换 / 追加」后生效)`:""]})]}),s.jsxs("div",{className:"prompt-group",children:["按提供商配置",s.jsx("span",{className:"note",children:"只列单独配置过的家,其余沿用上面的全局配置"})]}),s.jsx(DZ,{prompt:t,locked:r,busy:o}),t.status==="ready"&&t.degradeActive?s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{children:"内容拦截降级"}),s.jsx("span",{className:"prompt-input",children:s.jsx(se,{id:"btn-prompt-clear-degrade",variant:"outline",disabled:o,onClick:()=>{sZ()},children:"立即解除"})}),s.jsx("div",{className:"hint",children:RZ(t)})]}):null]}),s.jsx("div",{className:"settings-state",children:EZ(t)}),s.jsx("div",{className:"hint retention-note",children:us.prompt})]})]})}function PZ(e){if(e.status==="loading")return un.appLoading;if(e.status==="unavailable")return un.debugUnavailable;const t=e.count!==null&&e.limit!==null?`已保存 ${e.count} / ${e.limit} 条报文(超出后丢弃最旧的)。`:"";return e.on?`${un.debugOn}${t}凭据类请求头已脱敏。`:un.debugOff}function _Z({snap:e}){return s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"请求超时",tip:Os.timeouts,badge:gx(e.timeouts),actions:s.jsx(Za,{id:"btn-timeouts-refresh",onClick:()=>{oZ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"retention-list",children:kD.map(t=>s.jsx(hx,{field:t,value:e.timeouts.values?.[t.key]??null,disabled:e.busy==="timeouts",onCommit:r=>IQ(t,r)},t.key))}),s.jsx("div",{className:"hint retention-note",children:us.timeouts})]})]})}function LZ({snap:e}){return s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"请求重试",tip:Os.retry,badge:gx(e.retry),actions:s.jsx(Za,{id:"btn-retry-refresh",onClick:()=>{lZ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"retention-list",children:[CD.map(t=>s.jsx(hx,{field:t,value:e.retry.values?.[t.key]??null,disabled:e.busy==="retry",onCommit:r=>AQ(t,r)},t.key)),s.jsx(kZ,{codes:e.retryCodes,status:e.retry.status,busy:e.busy==="codes"||e.busy==="retry"})]}),s.jsx("div",{className:"hint retention-note",children:us.retry})]})]})}function zZ({snap:e}){return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"排队等待",tip:Os.queue,badge:gx(e.queue),actions:s.jsx(Za,{id:"btn-queue-refresh",onClick:()=>{iZ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"retention-list",children:TD.map(t=>s.jsx(hx,{field:t,value:e.queue.values?.[t.key]??null,disabled:e.busy==="queue",onCommit:r=>yQ(t,r)},t.key))}),s.jsx("div",{className:"hint retention-note",children:us.queue})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"指纹脱敏",tip:Os.sanitize,badge:e.sanitize.status==="ready"?s.jsx(Dn,{tone:"ok",children:"已生效"}):e.sanitize.status==="unavailable"?s.jsx(Dn,{tone:"bad",children:"不可用"}):s.jsx(Dn,{tone:"idle",children:"检测中…"}),actions:s.jsx(Za,{id:"btn-sanitize-refresh",onClick:()=>{uZ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"settings-switches",children:s.jsx(Ra,{id:"settings-sanitize",label:"剥离上游审核黑名单指纹(改写请求体里的模板句与表头)",checked:e.sanitize.on,disabled:e.sanitize.status!=="ready"||e.busy==="sanitize",onCheckedChange:t=>{_Q(t)}})}),s.jsx("div",{className:"settings-state",children:e.sanitize.status==="loading"?un.appLoading:e.sanitize.status==="unavailable"?un.sanitizeUnavailable:e.sanitize.on?un.sanitizeOn:un.sanitizeOff}),s.jsx("div",{className:"hint retention-note",children:us.sanitize})]})]}),s.jsx(HZ,{snap:e}),s.jsx(IZ,{snap:e}),s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"调试模式",tip:Os.debug,badge:e.debug.status==="ready"?s.jsx(Dn,{tone:"ok",children:"已生效"}):e.debug.status==="unavailable"?s.jsx(Dn,{tone:"bad",children:"不可用"}):s.jsx(Dn,{tone:"idle",children:"检测中…"}),actions:s.jsx(Za,{id:"btn-debug-refresh",onClick:()=>{cZ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"settings-switches",children:s.jsx(Ra,{id:"settings-debug-mode",label:"保存上游原始报文(请求头、请求体、响应头、响应体)",checked:e.debug.on,disabled:e.debug.status!=="ready"||e.busy==="debug",onCheckedChange:t=>{PQ(t)}})}),s.jsx("div",{className:"settings-state",children:PZ(e.debug)}),s.jsx("div",{className:"hint retention-note",children:us.debug})]})]})]})}function QD(e){const t=Object.entries(e.defaults).map(([r,o])=>({key:r,value:r in e.overrides?e.overrides[r]:o,isDefault:!0}));for(const[r,o]of Object.entries(e.overrides))r in e.defaults||t.push({key:r,value:o,isDefault:!1});return t}function BZ(e,t){const r=Object.keys(e);return r.length!==Object.keys(t).length?!1:r.every(o=>e[o]===t[o])}function HZ({snap:e}){const t=e.clineHeaders,[r,o]=x.useState(()=>QD(t));x.useEffect(()=>{o(QD(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 r){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&&!BZ(p(),t.overrides);return s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"Cline 伪装头",tip:Os.clineHeaders,badge:t.status==="ready"?s.jsx(Dn,{tone:"ok",children:"已生效"}):t.status==="unavailable"?s.jsx(Dn,{tone:"bad",children:"不可用"}):s.jsx(Dn,{tone:"idle",children:"检测中…"}),actions:s.jsx(Za,{id:"btn-cline-headers-refresh",onClick:()=>{LQ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"retention-list",children:[d?r.map((v,y)=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ke,{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(Ke,{className:"flex-1 font-mono text-[13px]",value:v.value,disabled:c,placeholder:v.isDefault?"值(留空 = 不发送)":"值",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?"还原":"删除"})]},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:"添加自定义头"}),s.jsx("div",{className:"flex-1"}),s.jsx(se,{variant:"ghost",disabled:c||!d||Object.keys(t.overrides).length===0,onClick:()=>{FD({})},children:"恢复默认"}),s.jsx(se,{disabled:c||!d||!g,onClick:()=>{FD(p())},children:"保存"})]})]}),s.jsx("div",{className:"settings-state",children:t.status==="loading"?un.appLoading:t.status==="unavailable"?"未能读取 Cline 伪装头设置,请稍后重试":g?"有未保存的修改":`${Object.keys(t.effective).length} 个头将随每个 Cline 请求发送`+(Object.keys(t.overrides).length>0?`(${Object.keys(t.overrides).length} 项被覆盖)`:"(全部为默认值)")}),s.jsx("div",{className:"hint retention-note",children:us.clineHeaders})]})]})}function UZ({snap:e}){const[t,r]=x.useState(!1);async function o(){r(!0),await rZ()||r(!1)}return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"网关跨域访问(CORS)",tip:Os.cors,badge:e.cors.status==="ready"?e.cors.on?s.jsx(Dn,{tone:"bad",children:"已开启"}):s.jsx(Dn,{tone:"ok",children:"已关闭"}):e.cors.status==="unavailable"?s.jsx(Dn,{tone:"bad",children:"不可用"}):s.jsx(Dn,{tone:"idle",children:"检测中…"}),actions:s.jsx(Za,{id:"btn-cors-refresh",onClick:()=>{dZ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"settings-switches",children:s.jsx(Ra,{id:"settings-cors",label:"允许浏览器里的页面跨来源调用网关(/v1/*)",checked:e.cors.on,disabled:e.cors.status!=="ready"||e.busy==="cors",onCheckedChange:c=>{zQ(c)}})}),s.jsx("div",{className:"settings-state",children:e.cors.status==="loading"?un.appLoading:e.cors.status==="unavailable"?un.corsUnavailable:e.cors.on?un.corsOn:un.corsOff}),s.jsx("div",{className:"hint retention-note",children:us.cors})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"机器人校验"}),s.jsxs("div",{className:"panel-body",children:[s.jsx(Ra,{id:"settings-captcha",label:"登录 / 注册需要通过 ALTCHA 人机验证(工作量证明)",checked:e.captcha.enabled,disabled:!e.captcha.available||e.busy==="captcha",onCheckedChange:c=>{BQ(c)}}),s.jsx("div",{className:"hint",children:us.captcha})]})]}),e.panelLogin?s.jsxs("section",{className:"panel",id:"panel-login-section",children:[s.jsx(ds,{title:"面板登录"}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"hint",children:us.panelLogin}),s.jsx("div",{className:"mt-2.5",children:s.jsx(se,{id:"btn-panel-logout",variant:"outline",disabled:t,onClick:()=>{o()},children:"退出登录"})})]})]}):null]})}function fp({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 VZ(e){return e.status==="loading"?s.jsx(Dn,{tone:"idle",children:"检测中…"}):e.status==="unavailable"?s.jsx(Dn,{tone:"bad",children:"不可用"}):s.jsx(Dn,{tone:e.available?"ok":"bad",children:e.available?"已生效":"数据库不可用"})}function $Z({snap:e}){const t=e.busy,r=e.storage,o=r.status==="ready",c=o&&r.available,d=o&&r.file?r.file:"—",f=p=>c&&p!==null?eQ(p):"—";return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"账号导入 / 导出",tip:Os.io,actions:s.jsxs(s.Fragment,{children:[s.jsx(se,{id:"btn-settings-export",variant:"outline",disabled:t==="export",onClick:()=>{mQ()},children:t==="export"?"导出中…":"导出账号"}),s.jsx(se,{id:"btn-settings-import",variant:"default",disabled:t==="import",onClick:()=>{hQ()},children:t==="import"?"导入中…":"导入账号"})]})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"danger-zone",children:[s.jsx("strong",{children:"导出文件内含 accessToken / refreshToken / apiKey 等凭证与自定义提供商定义"}),",可直接用于登录。请妥善保管,不要外传或上传到公共位置。"]}),e.ioFailure?s.jsx("div",{className:"io-result",children:s.jsxs("span",{className:"text-destructive",children:["失败 ",e.ioFailure.failed," 个:",e.ioFailure.detail,e.ioFailure.more?" 等":""]})}):null]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"数据保留",tip:Os.retention,badge:gx(e.retention),actions:s.jsx(Za,{id:"btn-retention-refresh",onClick:()=>{aZ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"retention-list",children:E0.map(p=>s.jsx(hx,{field:p,value:e.retention.values?.[p.key]??null,disabled:e.busy==="retention",onCommit:g=>bQ(p,g)},p.key))}),s.jsx("div",{className:"hint retention-note",children:us.retention})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"数据存储",tip:Os.storage,badge:VZ(r),actions:s.jsx(Za,{id:"btn-storage-refresh",onClick:()=>{pZ()}})}),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:"数据库文件"}),s.jsx("span",{className:"storage-line",children:s.jsx("span",{className:"storage-path",id:"storage-db-path",title:d,children:d})}),s.jsx("div",{className:"hint",children:us.storageFile})]}),s.jsxs("div",{className:"retention-row",children:[s.jsx("label",{htmlFor:"storage-db-size",children:"占用大小"}),s.jsx("span",{className:"storage-line",children:s.jsx("span",{className:"storage-path",id:"storage-db-size",children:c?JX(r.bytes):"—"})}),s.jsx("div",{className:"hint",children:us.storageSize})]})]}),s.jsxs("div",{className:"retention-list storage-counts",children:[s.jsx(fp,{label:"账号",value:f(r.accounts)}),s.jsx(fp,{label:"事件日志",value:f(r.logs)}),s.jsx(fp,{label:"请求记录",value:f(r.requests)}),s.jsx(fp,{label:"报表天数",value:f(r.dailyDays)}),s.jsx(fp,{label:"调试报文",value:f(r.debug)})]}),s.jsx("div",{className:"hint retention-note",children:us.storage})]})]})]})}const FZ=[{title:"问题反馈",desc:"遇到 Bug、报错或异常行为",cta:"去反馈",url:"https://github.com/aimod-cc/agent2api/issues/new?template=bug_report.yml"},{title:"功能建议",desc:"想要的新功能或改进想法",cta:"提建议",url:"https://github.com/aimod-cc/agent2api/issues/new?template=feature_request.yml"},{title:"请求提供商 / 模型支持",desc:"希望接入新的提供商或模型",cta:"去申请",url:"https://github.com/aimod-cc/agent2api/issues/new?template=provider_request.yml"}];function qZ(){return s.jsxs("section",{className:"panel",children:[s.jsx(ds,{title:"反馈与需求"}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"hint",children:"点下面的入口会用系统默认浏览器打开 GitHub 的对应表单(需要 GitHub 账号, 模板已预设好,填完直接提交即可)。"}),s.jsx("div",{className:"mt-3 flex flex-col gap-2",children:FZ.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:()=>{qX(e.url)},children:e.cta})]},e.url))})]})]})}function GZ({confirm:e}){const t=x.useRef(null);return s.jsx(Kt,{open:e!==null,onOpenChange:r=>{r||ux(!1)},children:s.jsxs(Yt,{className:"w-[min(440px,calc(100vw-48px))]",initialFocus:t,children:[s.jsx(Ft,{children:s.jsx($t,{children:"确认缩短保留天数"})}),s.jsx(Ht,{children:s.jsxs("div",{className:"danger-zone",children:[e?.head,s.jsx("br",{}),s.jsx("strong",{children:"超出的历史数据会被立即删除,且不可恢复。"}),"确定继续?"]})}),s.jsxs(sn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{ref:t,variant:"outline",onClick:()=>ux(!1),children:"取消"}),s.jsx(se,{variant:"destructive",onClick:()=>ux(!0),children:"继续并清理"})]})]})})}const G0={enable:{title:"开启局域网访问",body:()=>s.jsxs(s.Fragment,{children:["为了安全,开启前需要先注册一个",s.jsx("b",{children:"面板管理员账号"}),"(已注册过会跳过这一步,直接生效)。",s.jsx("br",{}),"开启后网关将监听所有网卡,同一局域网内的设备即可把 API 地址指向本机 IP 一起使用;管理接口从此要求 管理员会话或网关 Key,转发接口在没有一把启用的 Key 时也会拒绝服务(届时会自动创建一把名为「默认」的 Key)。",s.jsx("br",{}),s.jsx("strong",{children:"保存后应用将重启以生效。"}),"确定继续?"]}),label:"继续"},disable:{title:"关闭局域网访问",body:()=>s.jsxs(s.Fragment,{children:["关闭后网关回到只监听 127.0.0.1,局域网内的设备将无法继续访问;已配置的网关 Key 与账号都不受影响。",s.jsx("br",{}),s.jsx("strong",{children:"保存后应用将重启以生效。"}),"确定继续?"]}),label:"关闭并重启"},panel:{title:"变更网页管理面板",body:e=>e?s.jsxs(s.Fragment,{children:["开放后,局域网内其他设备的浏览器打开本机 IP 即可进入管理面板(需管理员账号登录)。",s.jsx("br",{}),s.jsx("strong",{children:"保存后应用将重启以生效。"}),"确定继续?"]}):s.jsxs(s.Fragment,{children:["关闭后,管理界面不再从局域网提供,只有本机的桌面程序可以管理;已开启的 API 转发不受影响。",s.jsx("br",{}),s.jsx("strong",{children:"保存后应用将重启以生效。"}),"确定继续?"]}),label:"保存并重启"}};function KZ({confirm:e,register:t}){const r=x.useRef(null),o=x.useRef(null),c=x.useRef(null),d=e!==null||t!==null,f=()=>{t!==null?_D():P0(!1)},p=()=>{pQ(o.current?.value??"",c.current?.value??"")};return s.jsx(Kt,{open:d,onOpenChange:g=>{g||f()},children:s.jsx(Yt,{className:"w-[min(480px,calc(100vw-48px))]",initialFocus:r,children:t!==null?s.jsxs(s.Fragment,{children:[s.jsx(Ft,{children:s.jsx($t,{children:"注册管理员账号"})}),s.jsxs(Ht,{children:[s.jsx("div",{children:"局域网开放后,管理接口要求登录。请设置管理员账号与密码,注册完成会直接继续开启流程。"}),s.jsxs("form",{onSubmit:g=>{g.preventDefault(),t.busy||p()},children:[s.jsx(tt,{htmlFor:"lan-admin-name",className:"mt-3.5 mb-[5px] block text-[12.5px]",children:"账号"}),s.jsx(Ke,{ref:o,id:"lan-admin-name",autoComplete:"username",placeholder:"管理员账号",disabled:t.busy}),s.jsx(tt,{htmlFor:"lan-admin-password",className:"mt-3.5 mb-[5px] block text-[12.5px]",children:"密码"}),s.jsx(Ke,{ref:c,id:"lan-admin-password",type:"password",autoComplete:"new-password",placeholder:"至少 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(sn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{ref:r,variant:"outline",onClick:_D,disabled:t.busy,children:"取消"}),s.jsx(se,{onClick:p,disabled:t.busy,children:t.busy?"正在注册…":"注册并开启"})]})]}):s.jsxs(s.Fragment,{children:[s.jsx(Ft,{children:s.jsx($t,{children:e?G0[e.mode].title:""})}),s.jsx(Ht,{children:s.jsx("div",{children:e?G0[e.mode].body(e.panel):null})}),s.jsxs(sn,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{ref:r,variant:"outline",onClick:()=>P0(!1),children:"取消"}),s.jsx(se,{onClick:()=>P0(!0),children:e?G0[e.mode].label:"继续"})]})]})})})}function YZ(){const e=lQ(),t=x.useRef(null);x.useEffect(()=>{const o=t.current;o&&(o.scrollTop=0)},[e.scrollReset]);const r=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:rx.map(o=>s.jsxs("button",{type:"button",className:e.category===o.id?"settings-nav-item active":"settings-nav-item","data-cat":o.id,onClick:()=>oQ(o.id),children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:yZ(o.icon,17)}}),o.label]},o.id))}),s.jsxs("div",{className:"settings-panes",ref:t,children:[s.jsx("div",{className:r("general"),"data-cat":"general",children:s.jsx(wZ,{snap:e})}),s.jsx("div",{className:r("display"),"data-cat":"display",children:s.jsx(NZ,{})}),s.jsx("div",{className:r("gateway"),"data-cat":"gateway",children:s.jsx(zZ,{snap:e})}),s.jsx("div",{className:r("retry"),"data-cat":"retry",children:s.jsx(LZ,{snap:e})}),s.jsx("div",{className:r("timeout"),"data-cat":"timeout",children:s.jsx(_Z,{snap:e})}),s.jsx("div",{className:r("security"),"data-cat":"security",children:s.jsx(UZ,{snap:e})}),s.jsx("div",{className:r("data"),"data-cat":"data",children:s.jsx($Z,{snap:e})}),s.jsx("div",{className:r("feedback"),"data-cat":"feedback",children:s.jsx(qZ,{})}),s.jsx("div",{className:r("about"),"data-cat":"about"})]}),s.jsx(GZ,{confirm:e.retentionConfirm}),s.jsx(KZ,{confirm:e.lanConfirm,register:e.lanRegister})]})}const ZD='.page[data-page="settings"]';let K0=null;function WD(){if(K0)return;const e=document.querySelector(ZD);e&&(e.replaceChildren(),K0=jn.createRoot(e),ys.flushSync(()=>{K0?.render(s.jsx(YZ,{}))}))}DD(),document.querySelector(ZD)?WD():document.addEventListener("DOMContentLoaded",WD,{once:!0}),window.wbSettingsPanel={load:KD,render:D0,renderRetention:ox,renderRetry:RQ,renderDebug:dx,renderSanitize:fx,renderPrompt:Lu,renderStorage:q0,showCategory:M0},rt().wbApp?.currentPage==="settings"&&KD();const JD="agent2api-col-config:",Y0=[{value:"left",label:l("左")},{value:"center",label:l("中")},{value:"right",label:l("右")}],XZ=e=>Y0.some(t=>t.value===e),QZ=Y0.map(e=>`ta-${e.value}`),eI="colset-dragging",tI="open";let X0=null;const nI="grid grid-cols-[18px_minmax(78px,1fr)_44px_minmax(106px,auto)] items-center gap-2";function sI(){return window}const xx=new Map;function Q0(e){return e.columns.map(t=>({key:t.key,visible:t.visible!==!1,align:t.align||"left"}))}function ZZ(e,t){const r=Array.isArray(t),o=!r&&t&&typeof t=="object"?t:null,c=r?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(Q0(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,C=XZ(b.align)?b.align:null;g.push({key:j,visible:b.visible!==!1,align:C&&C!==N?C:S})}for(const y of e.columns)v.has(y.key)||WZ(g,e,{...p.get(y.key)});return g}function WZ(e,t,r){const o=t.columns.findIndex(c=>c.key===r.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,r);return}}e.unshift(r)}function JZ(e){try{const t=localStorage.getItem(JD+e.id);return ZZ(e,t?JSON.parse(t):[])}catch{return Q0(e)}}function eW(e){try{const t={};for(const r of e.columns)t[r.key]=r.align||"left";localStorage.setItem(JD+e.id,JSON.stringify({v:2,defaults:t,items:e.config}))}catch{}}const tW=e=>xx.get(e)?.config||null,nW=(e,t)=>e.columns.find(r=>r.key===t)?.label||t;function rI(e,t){const r=xx.get(e);if(!r)return t;const o=new Map(t.map(c=>[c.key,c]));return r.config.filter(c=>c.visible&&o.has(c.key)).map(c=>({...o.get(c.key),align:c.align}))}function pp(e,{silent:t=!1}={}){eW(e),t||e.onChange?.(e.config),Al&&Al.id===e.id&&Al.repaint()}let Al=null;function bx(){if(!Al)return;const e=Al;Al=null,e.destroy()}function sW(e,t){bx();const r=document.createElement("div");document.body.append(r);const o=jn.createRoot(r),c={current:null};Al={id:e.id,spec:e,repaint:()=>c.current?.(),destroy:()=>{o.unmount(),r.remove()}},o.render(s.jsx(iW,{spec:e,anchor:t,repaintRef:c,onClose:bx}))}function rW(e,t){Al&&Al.id===e.id?bx():sW(e,t)}function aW(e,t,r){const o=[...e],[c]=o.splice(t,1);return o.splice(r,0,c),o}function lW(e,t,r,o){const c=document.elementFromPoint(e,t)?.closest?.("[data-col-key]");if(!c||!r||!r.contains(c))return"";const d=c.getAttribute("data-col-key")||"";return o.some(f=>f.key===d)?d:""}const oW=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 iW({spec:e,anchor:t,repaintRef:r,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(()=>(r.current=y,()=>{r.current=null}),[y,r]),x.useEffect(()=>(c.classList.add(tI),c.setAttribute("aria-expanded","true"),()=>{c.classList.remove(tI),c.setAttribute("aria-expanded","false")}),[c]),x.useEffect(()=>{const N=()=>{const C=c.getBoundingClientRect();(!c.isConnected||!C.width||C.bottom<=0||C.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(),pp(e))},[e]);function b(N,C){const E=e.config.find(R=>R.key===N);E&&(!C&&e.config.filter(R=>R.visible).length<=1||(E.visible=C,pp(e)))}function j(N,C){const E=e.config.find(R=>R.key===N);!E||E.align===C||(E.align=C,pp(e))}function w(){e.config=Q0(e),pp(e)}function S(N,C){C.preventDefault(),g.current?.teardown(),p(N),document.body.classList.add(eI);const E=d.current;function R(){window.removeEventListener("pointermove",k),window.removeEventListener("pointerup",A),document.body.classList.remove(eI),g.current=null,p(null)}function k(D){const I=lW(D.clientX,D.clientY,E,e.config);if(!I||I===N)return;const M=e.config.findIndex(_=>_.key===N),O=e.config.findIndex(_=>_.key===I);M<0||O<0||(e.config=aW(e.config,M,O),y())}function A(){R(),pp(e)}g.current={teardown:R},window.addEventListener("pointermove",k),window.addEventListener("pointerup",A)}return s.jsx(rf,{open:!0,modal:!1,onOpenChange:(N,C)=>{N||(C?.reason==="outside-press"&&(X0=C.event??null),o())},children:s.jsxs(af,{anchor:c,side:"bottom",align:"end",sideOffset:6,collisionPadding:8,className:"w-[336px]","aria-label":l("{name}的列设置",{name:e.label||e.id}),children:[s.jsxs("div",{className:Ue(nI,"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:l("列")}),s.jsx("span",{className:"text-center",children:l("显示")}),s.jsx("span",{className:"text-center",children:l("对齐")})]}),s.jsx("div",{ref:d,className:"min-h-0 flex-1 overflow-y-auto px-3 py-1",children:e.config.map(N=>{const C=nW(e,N.key),E=f===N.key;return s.jsxs("div",{"data-col-key":N.key,className:Ue(nI,"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:l("按住拖动调整列顺序"),onPointerDown:R=>S(N.key,R),children:oW}),s.jsx("span",{className:"min-w-0 truncate text-xs text-foreground",title:C,children:C}),s.jsx(Rs,{className:"justify-self-center",checked:N.visible,onCheckedChange:R=>b(N.key,R),"aria-label":l("显示「{label}」列",{label:C}),title:N.visible?l("这一列正在显示"):l("这一列已隐藏")}),s.jsx(Gn,{className:"w-full justify-center",options:Y0,value:N.align,onValueChange:R=>j(N.key,R),"aria-label":l("「{label}」列的对齐",{label:C})})]},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:l("拖动 ⋮⋮ 调整顺序")}),s.jsx(se,{variant:"outline",size:"sm",onClick:w,children:l("恢复默认")})]})]})})}function cW(e,t){e&&(e.classList.remove(...QZ),e.classList.add(`ta-${t}`))}const aI=new Map;function uW(e,t){const r=aI.get(e);if(r&&r.table===t&&r.row.isConnected)return r;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 aI.set(e,d),d}function dW(e,t,r){const o=xx.get(e);if(!o||!t)return;const c=uW(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||r?.has(v.key)){y.remove(),b?.remove();continue}cW(y,v.align),d.appendChild(y),b&&f&&f.appendChild(b)}sI().wbTableColumns?.repaint?.(e)}function fW(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=l("调整「{name}」的列:显示 / 隐藏、顺序、对齐",{name:e.label||e.id}),t.innerHTML=`${sI().wbIcons?.icon?.("settings",14)||""}${l("列设置")}`,t.setAttribute("aria-haspopup","dialog"),t.setAttribute("aria-expanded","false"),t.addEventListener("click",r=>{if(X0===r){X0=null;return}rW(e,t)}),t}function pW(e){return(typeof e.mount=="function"?e.mount():e.mount?document.querySelector(e.mount):null)||null}function mW(e){const t={...e,config:JZ(e)};xx.set(e.id,t);const r=pW(e),o=fW(t);return r&&(e.buttonPlacement==="last"?r.appendChild(o):r.insertBefore(o,r.firstChild)),{apply:c=>rI(e.id,c),config:()=>t.config}}window.wbColSettings={register:mW,apply:rI,configOf:tW,syncStaticHead:dW,close:bx};function Wa(){return window}const hW=new Set(["updateCheck"]);function lI(e){return(Array.isArray(e?.tasks)?e.tasks:[]).filter(r=>!hW.has(r.id))}const gW=2e4,oI=1,xW=" · ";function zu(e,t){Wa().wbApp?.toast?.(e,t)}function vx(e){return e instanceof Error?e.message:String(e)}function iI(e){return l(e==="seconds"?"秒":"分钟")}function cI(e){const t=Number(e)||0;return t?new Date(t).toLocaleTimeString("zh-CN",{hour12:!1}):""}function uI(e){const t=Number(e)||0;if(!t)return"";const r=t-Date.now();if(r<=0)return l("即将执行");const o=Math.round(r/1e3);if(o<60)return l("{n} 秒后",{n:o});const c=Math.round(o/60);if(c<60)return l("{n} 分钟后",{n:c});const d=Math.round(c/60);return d<24?l("{n} 小时后",{n:d}):l("{n} 天后",{n:Math.round(d/24)})}function bW(e){const t=e.runner==="backend",r=[];if(e.lastRunAt){const o=cI(e.lastRunAt);r.push(e.lastResult?l("上次执行 {time}({result})",{time:o,result:e.lastResult}):l("上次执行 {time}",{time:o}))}else r.push(l(t?"还没有执行记录":"由页面按间隔自动刷新"));return t&&e.enabled&&e.nextRunAt&&r.push(l("下次执行 {time}({relative})",{time:cI(e.nextRunAt),relative:uI(e.nextRunAt)})),t&&e.retryAt&&e.retryAt>Date.now()&&r.push(l("冷却中,{relative}重试",{relative:uI(e.retryAt)})),r.join(xW)}function vW(e,t){const r=String(t??"").trim(),o=iI(e.unit);if(!r)return{ok:!1,message:l("间隔不能为空(可填 {min}–{max} {unit})",{min:e.min,max:e.max,unit:o})};if(!/^\d+$/.test(r))return{ok:!1,message:l("间隔必须是整数")};const c=Number(r);return ce.max?{ok:!1,message:l("间隔必须在 {min}–{max} {unit} 之间(当前填的是 {value})",{min:e.min,max:e.max,unit:o,value:r})}:{ok:!0,value:c}}function yW(e){const t=Wa();e.id==="logsAutoRefresh"?t.wbLogsPanel?.applyAutoRefresh?.(e):e.id==="requestsAutoRefresh"?t.wbRequestsPanel?.applyAutoRefresh?.(e):e.id==="reportAutoRefresh"&&t.wbReport?.applyAutoRefresh?.(e)}let sc=!1,yx=null,Z0=!1;async function dI(){if(!yx){Z0=!0;return}await yx()}function jW(){const[e,t]=x.useState([]),[r,o]=x.useState(!1),[c,d]=x.useState(null),[f,p]=x.useState({});function g(I){p(M=>{if(!(I in M))return M;const O={...M};return delete O[I],O})}const v=x.useCallback(async()=>{const I=Wa().workbuddyDesktop;try{if(!I)throw new Error(l("后端桥不可用"));const M=await I.getScheduledTasks();t(lI(M)),o(!0)}catch(M){console.warn("读取定时任务失败:",vx(M)),t([]),o(!0)}},[]),y=x.useCallback(async()=>{if(sc||document.hidden||Wa().wbApp?.currentPage!=="tasks")return;const I=Wa().workbuddyDesktop;if(I)try{const M=await I.getScheduledTasks();t(lI(M))}catch(M){console.warn("同步定时任务状态失败:",vx(M))}},[]);x.useEffect(()=>{const I=window.setInterval(()=>{y()},gW);return()=>{window.clearInterval(I)}},[y]),x.useEffect(()=>{Wa().wbApp?.renderTopbarStatus?.()},[e,r]),x.useEffect(()=>(yx=v,Z0&&(Z0=!1,v()),()=>{yx=null}),[v]);async function b(I,M,O){if(sc)return;const _=Wa().workbuddyDesktop;if(_){sc=!0;try{const L=await _.saveScheduledTask(I,M);t(z=>z.map(U=>U.id===I?L:U)),yW(L),zu(l("✅ 已更新「{label}」",{label:O}))}catch(L){zu(l("保存失败:{reason}",{reason:vx(L)}),"err"),await v()}finally{sc=!1}}}async function j(I,M){const O=vW(I,M);if(!O.ok){zu(O.message,"err"),g(I.id);return}if(O.value===I.interval){g(I.id);return}await b(I.id,{interval:O.value},l("{name}间隔",{name:l(I.label)})),g(I.id)}async function w(I){if(sc)return;const M=Wa().workbuddyDesktop;if(M){sc=!0,d(I.id);try{const O=await M.runScheduledTask(I.id);if(O?.task){const _=O.task;t(L=>L.map(z=>z.id===I.id?_:z))}zu(l("✅ {task}:{summary}",{task:l(I.label),summary:O?.summary||l("已执行")})),I.id==="credentialMaintenance"&&await Wa().wbApp?.refresh?.()}catch(O){zu(l("执行失败:{reason}",{reason:vx(O)}),"err"),await v()}finally{sc=!1,d(null)}}}function S(I){const M=iI(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(Rs,{checked:I.enabled===!0,onCheckedChange:_=>{b(I.id,{enabled:_},l("{name}开关",{name:l(I.label)}))}}),s.jsx("span",{className:"task-name",children:l(I.label)})]}),s.jsx("span",{className:"tip-q","data-tip":l(I.description)}),s.jsx(ze,{className:"task-badge",variant:I.enabled?"success":"outline",children:I.enabled?l("已开启"):l("已关闭")}),I.running?s.jsx(ze,{className:"task-badge",variant:"warning",children:l("执行中…")}):null]}),s.jsx("div",{className:"task-state",children:bW(I)})]}),s.jsxs("div",{className:"task-actions",children:[s.jsxs("span",{className:"task-interval",children:[s.jsx("span",{className:"task-interval-label",children:l("每")}),s.jsx(Ke,{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:l("可填 {min}–{max} {unit}(默认 {def} {unit})",{min:I.min,max:I.max,unit:M,def:I.defaultInterval}),onChange:_=>{const L=_.currentTarget.value;p(z=>({...z,[I.id]:L}))},onBlur:_=>{j(I,_.currentTarget.value)},onKeyDown:_=>{_.key==="Enter"&&_.currentTarget.blur()}}),s.jsx("span",{className:"task-interval-unit",children:M})]}),I.canRun===!0?s.jsx(se,{size:"sm",variant:"outline",disabled:O||I.running===!0,onClick:()=>{w(I)},children:l(O?"执行中…":"立即执行")}):null]})]},I.id)}const N=e.length===0,C=e.filter(I=>I.enabled).length,E=N?r?l("不可用"):"—":l("{enabled} / {total} 个已开启",{enabled:C,total:e.length}),R=N?r?"destructive":"outline":C?"success":"outline",k=R==="destructive"?"bad":R==="success"?"ok":"",A=e.map(I=>S(I)),D=A.slice(oI);return s.jsxs("section",{className:"panel",children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:l("任务清单")}),s.jsx(ze,{id:"tasks-badge",variant:R,"data-tone":k,children:E}),s.jsx("span",{className:"panel-sub",children:l("状态每 20 秒自动同步")}),s.jsx("div",{className:"head-actions",children:s.jsx(se,{variant:"outline",onClick:()=>{v().then(()=>zu(l("定时任务已刷新")))},children:l("刷新")})})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"task-list",children:N?s.jsx("div",{className:"log-empty",children:l(r?"没有可显示的定时任务。后端未返回任务清单,请确认网关正在运行。":"正在加载定时任务…")}):s.jsxs(s.Fragment,{children:[A.slice(0,oI),D.length?s.jsx("div",{className:"task-grid",children:D}):null]})})}),s.jsxs("div",{className:"panel-foot",children:[s.jsxs("span",{children:[l("任务配置保存在 "),s.jsx("code",{children:"~/.agent2api/config.json"}),l(" 的 "),s.jsx("code",{children:"scheduledTasks"}),l(" 字段")]}),s.jsx("span",{children:l("改动立即生效,不需要重启程序")})]})]})}const fI='.page[data-page="tasks"]';let pI=!1;function mI(){if(pI)return;const e=document.querySelector(fI);e&&(pI=!0,e.replaceChildren(),jn.createRoot(e).render(s.jsx(jW,{})))}document.querySelector(fI)?mI():document.addEventListener("DOMContentLoaded",mI,{once:!0}),window.wbTasksPanel={load:dI},Wa().wbApp?.currentPage==="tasks"&&dI();const hI="workbuddy-desktop-update-skip";function wW(){try{return localStorage.getItem(hI)||""}catch{return""}}function SW(e){try{localStorage.setItem(hI,e)}catch{}}let gI="";function jx(e,t){if(!e||e.hasUpdate!==!0||e.pendingRestart===!0)return;const r=String(e.latestVersion||"").trim();r&&An().wbApp?.currentPage!=="settings"&&(r===wW()||r===gI||(gI=r,xI(),Bu=document.createElement("div"),document.body.append(Bu),mp=jn.createRoot(Bu),mp.render(s.jsx(NW,{info:e,onGoUpdate:t,onClose:xI}))))}function NW({info:e,onGoUpdate:t,onClose:r}){const o=String(e.latestVersion||""),c=String(e.notes||"").trim(),d=c?ZM(c):"";function f(){SW(o),r()}function p(){r();const g=An();g.wbApp?.showPage?.("settings"),g.wbSettingsPanel?.showCategory?.("about"),t(e)}return s.jsx(Kt,{open:!0,onOpenChange:g=>{g||r()},children:s.jsxs(Yt,{children:[s.jsx(Ft,{children:s.jsx($t,{children:l("检测到更新")})}),s.jsxs(Ht,{children:[s.jsxs("p",{className:"text-[12.5px] leading-[1.6] text-subtle",children:[l("新版本 "),s.jsx("strong",{className:"text-foreground",children:o}),l(" 已发布(当前 {current}),更新日志如下:",{current:e.currentVersion||l("未知")})]}),s.jsx("div",{className:"max-h-[46vh] overflow-y-auto overscroll-contain pr-1.5",onClick:WM,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:l("这个版本没有填写发布说明。")})})})]}),s.jsxs(sn,{children:[s.jsx(se,{variant:"outline",size:"sm",onClick:f,children:l("跳过此次更新")}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:r,children:l("取消")}),s.jsx(se,{variant:"default",onClick:p,children:l("去更新")})]})]})})}let mp=null,Bu=null;function xI(){mp&&(mp.unmount(),mp=null),Bu&&(Bu.remove(),Bu=null)}const bI="updateCheck",Hu=1,wx=1440,CW="https://github.com/settings/tokens/new?description="+encodeURIComponent("Agent2API 更新检查");function kW(e){return e?e.error?{badge:s.jsx(ze,{shape:"tag",variant:"destructive",title:e.error,children:l("无法解密")}),hint:l("重新粘贴保存一次即可自愈")}:e.filled&&e.origin==="stored"?{badge:s.jsx(ze,{shape:"tag",variant:"success",children:l("已填写")}),hint:l("已加密存储在本地,不显示具体值;粘贴新令牌可覆盖")}:e.filled?{badge:s.jsx(ze,{shape:"tag",variant:"secondary",children:l("环境变量")}),hint:l("已配置 GITHUB_TOKEN 环境变量,界面保存的令牌优先于它")}:{badge:s.jsx(ze,{shape:"tag",variant:"outline",children:l("未填写")}),hint:l("填写后检查限额 60 → 5000 次/小时(创建令牌无需勾选任何权限)")}:{badge:s.jsx(ze,{shape:"tag",variant:"outline",children:l("读取中")}),hint:""}}function TW({open:e,onClose:t}){const[r,o]=x.useState(JM),[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),C=e2(r);x.useEffect(()=>{e&&(p(""),XK().then(o),(async()=>{try{d(await An().workbuddyDesktop?.getUpdateToken()??null)}catch{}})(),(async()=>{try{const L=((await An().workbuddyDesktop?.getScheduledTasks?.())?.tasks??[]).find(B=>B.id===bI),z=L?.enabled===!0,U=Math.max(Hu,Math.round(Number(L?.interval)||0));b({enabled:z,interval:U}),w(String(U))}catch{}})())},[e]);async function E(_){if(!S){N(!0);try{const L=await An().workbuddyDesktop?.saveScheduledTask?.(bI,_),z=L?.enabled===!0,U=Math.max(Hu,Math.round(Number(L?.interval)||0));b({enabled:z,interval:U}),w(String(U)),er(l("✅ 自动检查更新已保存"))}catch(L){er(l("保存失败:{error}",{error:Dr(L)}),"err")}finally{N(!1)}}}async function R(){const _=Math.round(Number(j));if(!Number.isFinite(_)||_wx){er(l("检查间隔必须是 {min} ~ {max} 分钟",{min:Hu,max:wx}),"err");return}y&&_===y.interval||await E({interval:_})}async function k(_){const L=await QK(_);L&&o(z=>({...z,proxyChoice:L.choice}))}async function A(){const _=f.trim();if(!_){er(l("请先粘贴 GitHub 令牌"),"err");return}v(!0);try{const L=await An().workbuddyDesktop?.setUpdateToken({token:_});d(L??null),p(""),L?.saved===!1?er(l("令牌已生效,但写入磁盘失败(重启后会丢失)"),"err"):er(l("✅ GitHub 令牌已保存(加密存储,界面不再显示)"))}catch(L){er(l("保存失败:{error}",{error:Dr(L)}),"err")}finally{v(!1)}}async function D(){v(!0);try{const _=await An().workbuddyDesktop?.setUpdateToken({token:null});d(_??null),er(l("✅ 已清除界面保存的 GitHub 令牌(环境变量若配置过则继续生效)"))}catch(_){er(l("清除失败:{error}",{error:Dr(_)}),"err")}finally{v(!1)}}const I=kW(c),M=!!c?.error||c?.origin==="stored",O=c?.filled&&c?.origin!=="env"?l("已填写(粘贴新令牌可覆盖)"):l("粘贴 GitHub 令牌(ghp_… / github_pat_…)");return s.jsx(Kt,{open:e,onOpenChange:_=>{_||t()},children:s.jsxs(Yt,{className:"w-[min(460px,calc(100vw-48px))]",children:[s.jsx(Ft,{children:s.jsx($t,{children:l("更新设置")})}),s.jsxs(Ht,{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:l("自动检查更新")}),s.jsx(Rs,{checked:y?.enabled===!0,disabled:S||!y,onCheckedChange:_=>{E({enabled:_===!0})},"aria-label":l("自动检查更新")})]}),s.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[s.jsx(Ke,{type:"number",min:Hu,max:wx,step:1,className:"w-[110px]",disabled:S||!y||y.enabled!==!0,value:j,onChange:_=>w(_.currentTarget.value),onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),R())},"aria-label":l("检查间隔(分钟)")}),s.jsx("span",{className:"text-[12px] text-subtle",children:l("分钟({min} ~ {max})",{min:Hu,max:wx})}),s.jsx(se,{variant:"outline",size:"sm",disabled:S||!y||Math.round(Number(j))===y.interval,onClick:()=>{R()},children:l("保存")})]}),s.jsx("div",{className:"mt-1.5 text-[12px] text-subtle",children:l("到点自动向 GitHub 查询新版本,查到就走「检测到更新」弹窗;关闭后「检查更新」按钮仍可手动触发")})]}),s.jsx("div",{className:"h-px bg-hairline"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[13px] font-semibold text-foreground",children:l("出网代理")}),s.jsx("div",{className:"mt-1.5",children:s.jsxs(ct,{value:C.current,onValueChange:_=>{k(String(_))},children:[s.jsx(dt,{className:Ue("w-full",C.broken&&"border-destructive-bd"),title:C.title,"aria-label":l("更新出网代理"),children:s.jsx(ut,{className:"min-w-0 truncate",children:C.selected?.label||l("直连")})}),s.jsx(ft,{children:C.items.map(_=>s.jsx(Ye,{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:l("GitHub 令牌")}),s.jsx(se,{variant:"outline",size:"xs",title:l("在默认浏览器中打开 GitHub 的令牌创建页(备注已预设,无需勾选任何权限,直接点 Generate token)"),onClick:()=>{QM(CW)},children:l("打开 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(Ke,{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:l("保存")}),M?s.jsx(se,{variant:"outline",size:"sm",disabled:g,onClick:()=>{D()},children:l("清除")}):null]})]})]})]})})}function EW({open:e,onClose:t}){return s.jsx(Kt,{open:e,onOpenChange:r=>{r||t()},children:s.jsxs(Yt,{className:"w-[min(320px,calc(100vw-48px))]",children:[s.jsx(Ft,{children:s.jsx($t,{children:l("加入 QQ 群")})}),s.jsxs(Ht,{className:"items-center gap-3 text-center",children:[s.jsx("img",{className:"qq-qr",src:YK,alt:l("QQ 群二维码")}),s.jsxs("div",{className:"qq-no",children:[s.jsx("span",{className:"k",children:l("群号")}),s.jsx("code",{children:Rg}),s.jsx(se,{type:"button",size:"sm",variant:"ghost","data-copy":Rg,children:l("复制")})]}),s.jsx("p",{className:"qq-hint",children:l("用手机 QQ 扫上面的二维码,或在 QQ 里搜索群号加入。")})]})]})})}const RW=1e3,vI=8,AW=10,OW=1e3,MW={"":"outline",ok:"success",warn:"warning",bad:"destructive"},DW={info:null,checkedAt:0,repository:"",badgeText:l("未检查"),badgeTone:"",stateText:l("点击「检查更新」查询最新发布版本。"),stateError:!1,percent:0,phase:"idle",readyPath:"",checking:!1,actionBusy:!1,restartSeconds:0};function Ol(e){return String(e).padStart(2,"0")}function IW(e){const t=new Date(String(e??""));return!e||Number.isNaN(t.getTime())?"":`${t.getFullYear()}-${Ol(t.getMonth()+1)}-${Ol(t.getDate())} ${Ol(t.getHours())}:${Ol(t.getMinutes())}`}function yI(e){const t=new Date(e);if(!e||Number.isNaN(t.getTime()))return"";const r=new Date,o=t.getFullYear()===r.getFullYear()&&t.getMonth()===r.getMonth()&&t.getDate()===r.getDate(),c=`${Ol(t.getHours())}:${Ol(t.getMinutes())}:${Ol(t.getSeconds())}`;return o?c:`${Ol(t.getMonth()+1)}-${Ol(t.getDate())} ${c}`}function Sx(e){return e?.installerKind?e.installerKind==="dmg":/Mac|iPhone|iPad/.test(navigator.userAgent||"")}function Aa(e){return e?.selfUpdate===!0}function jI(e){return e?Aa(e)?e.serverAsset??null:e.asset??null:null}function PW(e){return Aa(e)?l("正在下载服务端更新包…(下载完成后由面板完成替换,重启容器内的服务后生效)"):Sx(e)?l("正在下载安装包…(下载完成后会挂载磁盘映像,把应用拖进「应用程序」即可完成安装)"):l("正在下载安装包…(下载完成后启动安装程序需要管理员权限,会弹出 UAC 确认框)")}function wI(e,t){return Aa(e)?l("更新包已就绪:{name}。点「安装并重启」后,面板会校验并替换容器内的程序与界面文件,然后重启服务(页面会自动刷新)。",{name:t}):Sx(e)?l("安装包已就绪:{name}。点击「打开安装包」后会挂载磁盘映像,把应用拖进「应用程序」即可完成安装。",{name:t}):l("安装包已就绪:{name}。点击「安装并重启」后需要管理员权限,会弹出 UAC 确认框。",{name:t})}function _W(e){return Aa(e)?l("安装并重启"):Sx(e)?l("打开安装包"):l("安装并重启")}let ca=DW;const W0=new Set;function J0(){return ca}function LW(e){return W0.add(e),()=>{W0.delete(e)}}function In(e){ca={...ca,...e};for(const t of W0)t()}let yr=!1,eS=null,Nx=null;function Uu(){Nx!==null&&(window.clearInterval(Nx),Nx=null)}function ws(e,t=""){In({badgeText:e,badgeTone:t})}function Nn(e,t=!1){In({stateText:e,stateError:t})}function Cx(){const{info:e,checkedAt:t}=ca;if(!e)return;const r=t?l("(检查于 {time})",{time:yI(t)}):"";if(e.pendingRestart===!0){ws(l("待重启"),"warn"),Nn(l("更新已应用到容器内,重启服务后生效。{at}",{at:r}));return}if(e.hasUpdate===!0){if(ws(l("有新版本"),"warn"),Aa(e)&&!e.serverAsset){Nn(l("发现新版本 {latest}(当前 {current}),但该版本没有提供容器内更新包;请在宿主机执行 docker compose pull && docker compose up -d 升级。{at}",{latest:String(e.latestVersion||""),current:String(e.currentVersion||""),at:r}));return}Nn(l("发现新版本 {latest}(当前 {current})。{at}",{latest:String(e.latestVersion||""),current:String(e.currentVersion||""),at:r}))}else e.hasUpdate===!1?(ws(l("已是最新"),"ok"),Nn(l("当前已是最新版本({current})。{at}",{current:String(e.currentVersion||""),at:r}))):(ws(l("无法比较"),"warn"),Nn(e.latestVersion?l("最新发布版本为 {latest},但当前版本号「{current}」无法解析,未做新旧判断。{at}",{latest:e.latestVersion,current:e.currentVersion||l("未知"),at:r}):l("仓库暂无发布版本。{at}",{at:r})))}function SI(e){!e||e.checked===!1||(In({info:e,checkedAt:Number(e.checkedAt)||0}),e.repository&&tS(e.repository),ca.phase==="idle"&&Cx())}function tS(e){const t=String(e||"").trim();/^[\w.-]+\/[\w.-]+$/.test(t)&&In({repository:t})}function nS(e){if(!e)return!1;if(e.active){const t=Math.max(0,Math.min(100,Number(e.percent)||0)),r=(Number(e.received)||0)/1024/1024,o=(Number(e.total)||0)/1024/1024;return In({phase:"downloading",percent:t}),ws(l("下载中"),"warn"),Nn(l("正在下载 {name}:{percent}%({received} / {total} MB)",{name:e.filename||l("安装包"),percent:t,received:r.toFixed(1),total:o.toFixed(1)})),!0}if(Uu(),In({percent:0}),e.error)return ws(l("下载失败"),"bad"),Nn(l("下载失败:{error}",{error:e.error}),!0),In({phase:"failed"}),!0;if(e.canceled)return ws(l("已取消"),"warn"),Nn(Aa(ca.info)?l("下载已取消,可重新点击「下载并更新」。"):l("下载已取消,可重新点击「下载并安装」。")),In({phase:"idle"}),!0;if(e.done&&e.path){const t=e.path,r=e.filename||t;return ws(l("可安装"),"ok"),In({phase:"ready",readyPath:t}),Aa(ca.info)?(Nn(wI(ca.info,r)),!0):(t!==eS?(eS=t,Nn(Sx(ca.info)?l("安装包已下载完成,正在挂载磁盘映像…"):l("安装包已下载完成,正在启动安装程序(需要管理员权限,会弹出 UAC 确认框)…")),CI(t)):Nn(wI(ca.info,r)),!0)}return!1}async function zW(){try{const e=await An().workbuddyDesktop?.updateProgress();if(!e){Uu();return}nS(e)}catch(e){Uu(),Nn(l("读取下载进度失败:{error}",{error:Dr(e)}),!0)}}function NI(){Uu(),Nx=window.setInterval(()=>{zW()},RW)}async function CI(e){const t=An().workbuddyDesktop;if(t)try{const o=(await t.runInstaller(e,!0))?.restart!==!1;Nn(l(o?"安装程序已启动,本程序将退出以便完成覆盖安装。安装程序需要管理员权限,会弹出 UAC 确认框,请选择「是」。":"安装包已挂载,请在弹出的窗口里把应用拖进「应用程序」完成安装。安装完成后重新打开本程序即可。"))}catch(r){ws(l("启动失败"),"bad"),Nn(l("启动安装程序失败:{error}",{error:Dr(r)}),!0)}}async function BW(){const e=An().workbuddyDesktop;if(e?.installUpdate)try{ws(l("安装中"),"warn"),Nn(l("正在校验并替换容器内的程序与界面文件…"));const t=await e.installUpdate(),r=String(t?.version||"").trim();Nn(r?l("已替换为 {version},正在重启服务…",{version:r}):l("替换完成,正在重启服务…")),await e.restartService?.().catch(()=>{}),sS(r)}catch(t){ws(l("安装失败"),"bad"),Nn(l("安装失败:{error}",{error:Dr(t)}),!0)}}async function HW(){const e=An().workbuddyDesktop;if(!(!e?.rollbackUpdate||yr)){yr=!0,In({actionBusy:!0});try{ws(l("回滚中"),"warn"),Nn(l("正在回滚到上一版本…")),await e.rollbackUpdate(),Nn(l("已还原上一版本,正在重启服务…")),await e.restartService?.().catch(()=>{}),sS("")}catch(t){ws(l("回滚失败"),"bad"),Nn(l("回滚失败:{error}",{error:Dr(t)}),!0)}finally{yr=!1,In({actionBusy:!1})}}}function sS(e){Uu(),In({phase:"restarting",restartSeconds:vI,readyPath:""}),ws(l("重启中"),"warn");let t=vI;const r=()=>{if(Nn(e?l("{version} 已就位,服务正在重启,页面会在恢复后自动刷新…({seconds}s)",{version:e,seconds:Math.max(0,t)}):l("服务正在重启,页面会在恢复后自动刷新…({seconds}s)",{seconds:Math.max(0,t)})),t<=0){window.clearInterval(o),UW();return}t-=1,In({restartSeconds:t})},o=window.setInterval(r,1e3);r()}async function UW(){for(let e=0;e{window.setTimeout(t,OW)})}window.location.reload()}async function kI(){if(yr)return null;yr=!0,In({checking:!0}),ws(l("检查中"),"warn"),Nn(l("正在查询 GitHub 上的最新发布版本…"));let e=null;try{const t=An().workbuddyDesktop;if(!t)throw new Error(l("后端桥不可用"));e=await t.checkUpdate()??null,In({info:e,checkedAt:Number(e?.checkedAt)||Date.now()}),e?.repository&&tS(e.repository),Cx()}catch(t){e=null,In({info:null,checkedAt:0}),ws(l("检查失败"),"bad"),Nn(l("检查更新失败:{error}",{error:Dr(t)}),!0)}finally{yr=!1,In({checking:!1})}return An().wbApp?.updateUpdateBadge?.(e),jx(e,hp),e}async function TI(){let e=null;try{e=await An().workbuddyDesktop?.getUpdateStatus()??null}catch{}if(e&&e.checked!==!1){SI(e),An().wbApp?.updateUpdateBadge?.(e),jx(e,hp);return}ca.info||(ws(l("未检查")),Nn(l("点击「检查更新」查询 GitHub 上的最新发布版本。")))}async function rS(){if(yr)return;const e=J0();if(e.info?.pendingRestart===!0&&e.phase!=="downloading"){yr=!0,In({actionBusy:!0});try{await An().workbuddyDesktop?.restartService?.().catch(()=>{}),sS("")}finally{yr=!1,In({actionBusy:!1})}return}if(e.phase!=="downloading"&&e.readyPath){yr=!0,In({actionBusy:!0});try{Aa(e.info)?await BW():await CI(e.readyPath)}finally{yr=!1,In({actionBusy:!1})}return}if(e.phase==="downloading"){try{await An().workbuddyDesktop?.cancelUpdate(),Nn(l("正在取消下载…"))}catch(r){er(l("取消失败:{error}",{error:Dr(r)}),"err")}return}const t=jI(e.info);if(!t?.url){er(Aa(e.info)?l("这一版没有提供容器内更新包"):l("没有可下载的安装包"),"err");return}if(RI(e)){yr=!0,In({actionBusy:!0});try{await An().workbuddyDesktop?.downloadUpdate({url:t.url,name:t.name}),eS=null,In({phase:"downloading",readyPath:"",percent:0}),ws(l("下载中"),"warn"),Nn(PW(e.info)),NI()}catch(r){ws(l("下载失败"),"bad"),Nn(l("下载失败:{error}",{error:Dr(r)}),!0)}finally{yr=!1,In({actionBusy:!1})}}}async function EI(){Cx(),await TI();try{const e=await An().workbuddyDesktop?.updateProgress();if(e?.active){nS(e),NI();return}if(e?.done&&e.path){nS(e);return}}catch{}}async function hp(e){if(e?.pendingRestart===!0){await rS();return}e?.hasUpdate===!0&&(In({info:e,checkedAt:Number(e.checkedAt)||ca.checkedAt}),e.repository&&tS(e.repository),Cx(),An().wbApp?.updateUpdateBadge?.(e),jx(e,hp)),await EI();const t=J0();if(!(t.phase==="downloading"||t.readyPath)&&t.info?.hasUpdate)for(let r=0;r<3;r+=1){if(yr){await new Promise(o=>{window.setTimeout(o,400)});continue}await rS();return}}function RI(e){return e.phase==="restarting"?null:e.info?.pendingRestart===!0&&e.phase==="idle"?{label:l("立即重启"),disabled:e.actionBusy}:!(e.info?.hasUpdate===!0&&!!jI(e.info)?.url)&&e.phase!=="downloading"&&e.phase!=="ready"?null:{label:e.phase==="downloading"?l("取消下载"):e.phase==="failed"?l("重试下载"):e.phase==="ready"?_W(e.info):Aa(e.info)?l("下载并更新"):l("下载并安装"),disabled:e.actionBusy}}function VW(e,t){const r=e.info,o=String(r?.notes||"").trim();if(!o)return s.jsx("div",{className:"update-log-hint",children:l(r?"这个版本没有填写发布说明。":"点击「检查更新」后,这里会显示最新版本的更新说明。")});const c=ZM(o),d=XM(r?.pageUrl),f=IW(r?.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(r?.latestVersion||l("最新版本"))}),r?.prerelease===!0?s.jsx(ze,{shape:"tag",variant:"warning",children:l("预发布")}):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:l("这个版本没有填写发布说明。")})}),s.jsxs("div",{className:"rel-foot",children:[d?s.jsx("a",{href:d,"data-external":d,target:"_blank",rel:"noopener",children:l("在 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:l("群号:{group}",{group:Rg}),onClick:t,children:l("加入 QQ 群")})]})]})]})}function $W(){const e=x.useSyncExternalStore(LW,J0),t=RI(e),[r,o]=x.useState(!1),[c,d]=x.useState(!1);x.useEffect(()=>()=>{Uu()},[]);const f=e.repository?`https://github.com/${e.repository}`:"",p=e.repository?`https://github.com/${e.repository.split("/")[0]}`:"",g=Aa(e.info),v=g&&e.info?.backupAvailable===!0&&e.phase!=="downloading"&&e.phase!=="ready"&&e.phase!=="restarting",y=e.info?.latestVersion?e.info.prerelease?l("{version}(预发布)",{version:e.info.latestVersion}):e.info.latestVersion:"—",b=String(e.info?.latestVersion||"").trim(),j=b?`${b}${e.checkedAt?l(" · 检查于 {time}",{time:yI(e.checkedAt)}):""}`:"";return s.jsxs("section",{className:"panel",onClick:WM,children:[s.jsxs("div",{className:"panel-head",children:[s.jsx("h2",{children:l("软件更新")}),s.jsx("span",{className:"tip-q","data-tip":l(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:MW[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:l("出网线路与 GitHub 令牌设置"),onClick:()=>o(!0),children:l("更新设置")}),s.jsx(se,{id:"btn-update-check",variant:"outline",disabled:e.checking||e.phase==="restarting",onClick:()=>{kI()},children:e.checking?l("检查中…"):l("检查更新")}),v?s.jsx(se,{id:"btn-update-rollback",variant:"outline",disabled:e.actionBusy,title:l("把容器内的程序与界面文件还原到更新前的版本,并重启服务"),onClick:()=>{HW()},children:l("回滚到上一版本")}):null,t?s.jsx(se,{id:"btn-update-download",variant:"default",disabled:t.disabled,onClick:()=>{rS()},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:l("当前版本")}),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:l("最新版本")}),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(qd,{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:l("关于作者")}),s.jsxs("span",{children:[l("本工具由")," ",s.jsx("a",{id:"update-author-link",href:p,"data-external":p,target:"_blank",rel:"noopener",children:e.repository.split("/")[0]})," ",l("个人开发并开源维护,免费使用、不带广告,也不会收集你的账号数据。如果它帮到了你,欢迎到项目仓库点个 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:l("在浏览器中打开项目仓库,点 Star 支持作者"),children:l("收藏项目")})})]}):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:l("更新日志")}),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:VW(e,()=>d(!0))})]})]}),r?s.jsx(TW,{open:!0,onClose:()=>o(!1)}):null,c?s.jsx(EW,{open:!0,onClose:()=>d(!1)}):null]})}const AI='.settings-pane[data-cat="about"]';let aS=null;function OI(){if(aS)return;const e=document.querySelector(AI);e&&(e.replaceChildren(),aS=jn.createRoot(e),aS.render(s.jsx($W,{})))}document.querySelector(AI)?OI():document.addEventListener("DOMContentLoaded",OI,{once:!0}),window.wbUpdatePanel={load:EI,check:kI,syncFromCache:TI,openAndDownload:hp,applyStatus:SI,showUpdateModal:e=>jx(e,hp)};const FW="zcode.z.ai/billing",qW={active:"success",pending:"warning",expired:"ghost",unknown:"outline"};function GW(e){const t=String(e||"").trim().toLowerCase();return t==="daily"?l("每日"):t==="weekly"?l("每周"):t==="monthly"?l("每月"):""}function KW(e){const t=Number(e);if(!Number.isFinite(t)||t<=0)return"";const r=window.wbUnits;return r?.formatTokens?r.formatTokens(t):String(t)}function rc(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"":Pe().wbApp?.formatTime?.(t*1e3)||new Date(t*1e3).toLocaleString()}function YW(e){const t=KW(e.grantUnits),r=String(e.unitType||"").trim(),o=t?[t,r].filter(Boolean).join(" "):"",c=GW(e.period),d=[String(e.showName||"").trim(),o].filter(Boolean).join(" ");return d?c?l("{body}({period})",{body:d,period:c}):d:""}function MI(e){return(e.entitlements||[]).map(YW).filter(Boolean).join(l("、"))}function XW(e){const t=rc(e.startsAt),r=rc(e.endsAt);return t&&r?`${t} → ${r}`:r?l("到期 {time}",{time:r}):t?l("开始 {time}",{time:t}):""}function QW(e){const t=new Date(e*1e3);if(Number.isNaN(t.getTime()))return"";const r=`${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?l("今天 {time}",{time:r}):c===1?l("明天 {time}",{time:r}):rc(e)}function ZW(e){const t=[],r=Number(e.pendingUntil);if(Number.isFinite(r)&&r>0){const c=QW(r);c&&t.push(l("待生效 {time}",{time:c}))}const o=rc(e.endsAt);if(o&&t.push(l("到期 {time}",{time:o})),t.length===0){const c=rc(e.startsAt);c&&t.push(l("开始 {time}",{time:c}))}return t.join(" · ")}function WW({options:e,onClose:t}){const r=e.id,[,o]=x.useState(0);x.useEffect(()=>uR(()=>o(M=>M+1)),[]);const[c,d]=x.useState([]),[f,p]=x.useState({status:"loading"}),[g,v]=x.useState(""),y=Ca(r),b=String(y?.name||e.name||r),j=Th(y),w=[...new Set([...j,...c])],S=y?.claimPlans&&typeof y.claimPlans=="object"&&!Array.isArray(y.claimPlans)?y.claimPlans:{},N=y?Ka(y):void 0,C=N&&typeof N=="object"&&!Array.isArray(N)?N:null,E=C&&Array.isArray(C.plans)?C.plans:[],R=w.filter(M=>M&&!E.some(O=>String(O.planId||"")===M)),k=Qs().usageInflight.has(r),A=Pe().wbZcodeClaim,D=x.useCallback(async()=>{if(!A?.preview){p({status:"error",message:l("当前环境不支持领取(桥接方法缺失)")});return}p({status:"loading"});try{const M=await A.preview(r);p({status:"ready",result:M||{}})}catch(M){p({status:"error",message:pt(M)})}},[A,r]);x.useEffect(()=>{D();const M=Ca(r);M&&Ka(M)===void 0&&Ph(r)},[r,D]);async function I(M){if(!(!A?.claim||g)){v(M);try{const O=await A.claim(r,M);if(O?.ok||O?.failure==="already_claimed"){const _=O.planId||M;_&&d(L=>L.includes(_)?L:[...L,_]),Ph(r),Pe().wbApp?.refresh?.(),D()}}finally{v("")}}}return s.jsx(Kt,{open:!0,onOpenChange:(M,O)=>{if(!M){if(g){O.cancel();return}t()}},children:s.jsxs(Yt,{className:"w-[min(560px,calc(100vw-48px))]",children:[s.jsx(Ft,{children:s.jsx($t,{children:l("ZCode 套餐明细 — {name}",{name:b})})}),s.jsxs(Ht,{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:[l("可领取的套餐"),s.jsx(ze,{variant:"outline",shape:"tag",children:l("官方限时活动")})]}),f.status==="loading"?s.jsxs("div",{className:"flex items-center gap-2 py-2 text-[12.5px] text-muted-foreground",children:[s.jsx(Fd,{className:"size-3"}),l("正在探测可领取的套餐…")]}):f.status==="error"?s.jsxs("div",{className:"py-1 text-[12.5px] text-destructive",children:[l("探测失败:{message}",{message:f.message}),s.jsx(se,{variant:"outline",size:"xs",className:"ml-2",onClick:()=>{D()},children:l("重试")})]}):f.result.deployed?(f.result.plans||[]).length===0?s.jsx("p",{className:"py-1 text-[12.5px] text-muted-foreground",children:l("当前没有可领取的套餐(活动期内每天发一份,明天可再领)")}):s.jsx("ul",{className:"m-0 list-none p-0",children:(f.result.plans||[]).map(M=>{const O=String(M.planId||""),_=w.includes(O),L=MI(M),z=XW(M);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:M.name||O||l("套餐")}),_?s.jsx(ze,{variant:"success",shape:"tag",children:l("今日已领")}):null]}),z?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:z}):null,L?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:L}):null,M.description?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:M.description}):null]}),s.jsx(se,{variant:"outline",size:"xs",className:"flex-none",title:_?l("这一份今天已经领过了(重复领取上游会回「已领取过」)"):void 0,disabled:g!=="",onClick:()=>{I(O)},children:l(g===O?"领取中…":_?"再领一次":"领取")})]},O||M.name)})}):s.jsx("p",{className:"py-1 text-[12.5px] text-muted-foreground",children:l("当前没有可领取的套餐(活动尚未开始)")}),s.jsx("p",{className:"mt-1.5 text-[11.5px] text-muted-foreground",children:l("活动期内每天发一份新套餐;同一份当天重复领取会提示「已领取过」,次日可再领。领取要走一次人机验证(滑块)。")}),f.status==="ready"&&f.result.activationError?s.jsx("p",{className:"text-[11.5px] text-muted-foreground",children:l("(激活事件补报失败,可能影响领取资格:{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:[l("我的套餐"),Array.isArray(C?.wallets)&&C.wallets.length>0&&C.availableView?s.jsx(ze,{variant:"outline",shape:"tag",children:String(C.walletsFrom||"")==="monitor"?String(C.availableView):l("可用 {value}",{value:String(C.availableView)})}):null,s.jsx("div",{className:"ml-auto",children:s.jsx(se,{variant:"outline",size:"xs",disabled:k,title:l("重新读取该账号的余额与套餐(走余额查询那条链)"),onClick:()=>{Ph(r)},children:l(k?"查询中…":"查询余额")})})]}),E.length>0?s.jsx("ul",{className:"m-0 list-none p-0",children:E.map(M=>{const O=String(M.planId||""),_=String(M.state||"unknown"),L=MI(M),z=ZW(M),U=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:M.name||O||l("套餐")}),s.jsx(ze,{variant:qW[_]||"outline",shape:"tag",children:WE(_)})]}),z?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:z}):null,L?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:L}):null]}),U>0?s.jsx("span",{className:"flex-none text-[11.5px] text-muted-foreground",children:l("本地领取于 {time}",{time:rc(U/1e3)})}):null]},O||M.name)})}):s.jsx("p",{className:"py-1 text-[12.5px] text-muted-foreground",children:N===void 0?l("还没有余额读数(已自动查询一次,稍候;也可以点右上角「查询余额」重读)"):C&&C.source&&C.source!==FW?l("这个账号的余额走窗口限额通道(只配了编码套餐 API Key):只有每 N 小时的剩余比例,读不到套餐清单"):l("读数里没有套餐清单(免费账号、或套餐的上游状态还没刷新;可点右上角「查询余额」重读)")}),R.length>0?s.jsx("p",{className:"mt-1.5 text-[11.5px] text-muted-foreground",children:l("本地台账里今天还领过这些,但上面的读数里还没有:{plans}(读数刷新可能有延迟)",{plans:R.map(M=>{const O=Number(S[M])||0,_=O>0?rc(O/1e3):"";return _?l("{plan}({time} 领取)",{plan:M,time:_}):M}).join(l("、"))})}):null]})]}),s.jsxs(sn,{children:[s.jsx("span",{className:"min-w-0 text-[11.5px] text-muted-foreground",children:w.length>0?l("今天(北京时间)已领取 {n} 份:{plans}",{n:w.length,plans:w.join(l("、"))}):l("今天还没有领过:上面「可领取的套餐」里逐份点「领取」即可")}),s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:l("关闭")})]})]})})}let gp=null,Vu=null;function DI(){gp&&(gp.unmount(),gp=null),Vu&&(Vu.remove(),Vu=null)}function JW(e){e?.id&&(DI(),Vu=document.createElement("div"),document.body.append(Vu),gp=jn.createRoot(Vu),gp.render(s.jsx(WW,{options:e,onClose:DI})))}window.wbZcodePlans={open:JW};const II="w-auto flex-auto";function PI({onInput:e,domRef:t,icon:r,className:o,inputClassName:c,...d}){const f=g=>{t.current=g},p=g=>{e?.(g.currentTarget.value)};return r?s.jsxs(ji,{className:Ue(II,o),children:[s.jsx(Si,{ref:f,className:c,onInput:p,...d}),s.jsx(wi,{"aria-hidden":"true",children:r})]}):s.jsx(Ke,{ref:f,className:Ue(II,c),onInput:p,...d})}function eJ(e,t){const r=jn.createRoot(e),o={current:null};return r.render(s.jsx(PI,{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(){r.unmount()}}}const tJ=[["id","id"],["type","type"],["name","name"],["title","title"],["placeholder","placeholder"],["min","min"],["max","max"],["step","step"],["autocomplete","autoComplete"]];function nJ(e){const t={defaultValue:e.value||void 0,inputClassName:e.className||void 0};for(const[f,p]of tJ){const g=e.getAttribute(f);g!=null&&(t[p]=g)}const r=e.getAttribute("maxlength");r!=null&&(t.maxLength=Number(r));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 _I(e){if(e.dataset.islandUpgraded)return;e.dataset.islandUpgraded="1";const t=nJ(e),r=e.parentElement?.classList.contains("input-affix")?e.parentElement:null;let o;r?(r.className=r.className.replace(/\binput-affix\b/,"").trim(),r.style.display="flex",r.style.alignItems="center",o=r):(o=document.createElement("span"),o.style.display="contents",e.replaceWith(o));const c={current:null},d=jn.createRoot(o);ys.flushSync(()=>{d.render(s.jsx(PI,{...t,domRef:c}))})}function LI(e=document){if(e instanceof HTMLInputElement&&e.matches("[data-island-input]")){_I(e);return}e.querySelectorAll("input[data-island-input]").forEach(_I)}function sJ(){LI();const e=new MutationObserver(t=>{for(const r of t)for(const o of r.addedNodes)o instanceof Element&&LI(o)});return e.observe(document.body,{childList:!0,subtree:!0}),e}function rJ(e,t){const r=jn.createRoot(e);let o={options:t.options,value:t.value,ariaLabel:t.ariaLabel,className:t.className};const c=()=>{r.render(s.jsx(Gn,{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(){r.unmount()}}}window.wbSegmented={mount:rJ},window.wbInput={mount:eJ},sJ()})(); +`)})}function b8(e){if(e===void 0)return{text:r("未查询"),kind:"muted",title:r("尚未查询该账号的余额")};if(e===null)return{text:r("查询中…"),kind:"muted",title:r("正在查询")};const t=au(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?"∞":br(a.totalLeft);return{text:r("可用 {total}",{total:o}),kind:"ok",title:r("总剩余 {total} · 套餐 {plan} · 奖励 {bonus}",{total:o,plan:br(a.planLeft),bonus:br(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):br(j?.balance)}`).join(" · "),f=yA(a.subscription),p=[];if(c.length===0&&Array.isArray(a.plans)&&a.plans.length>0){const j=jA(a);p.push(j&&wA(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:br(g.balance),unit:String(g.unit||o)}):r("可用 {value} {unit}",{value:br(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 jA(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 v8(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 wA(e){const t=Array.isArray(e.entitlements)?e.entitlements:[];for(const a of t){const o=aa(a?.totalUnits);if(o===null||o<=0)continue;const c=aa(a?.usedUnits),d=aa(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 y8(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=aa(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:br(y),total:br(b)}):r("剩 {remaining}",{remaining:br(y)}),tone:y<=0?"muted":N!==null&&N<20?"warn":"ok",percent:N,over:!1,title:S?void 0:r("上游未给总量,画不出剩余比例")});continue}if(w!==null||aa(g.allowanceTokens)!==null){const S=aa(g.usedTokens)??0,N=aa(g.allowanceTokens),k=N!==null&&N>1,E=k&&S>N,R=g.unlimited===!0,C=k?Math.max(0,Math.min(100,(1-S/N)*100)):null,A=R?r("无上限 · 已用 {used}",{used:vo(S)}):k?r("剩 {remaining} / {total}",{remaining:vo(Math.max(0,N-S)),total:vo(N)}):S>0?r("已用 {used}",{used:vo(S)}):r("未使用");d.push({name:j8(v),view:A,tone:E?"bad":!k&&!R?"muted":C!==null&&C<20?"warn":"ok",percent:C,over:E,title:[j,R?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:aa(t.available),unit:o,plan:aF(f.planName),free:lR(f.planName),resetDate:String(f.resetDate||""),missing:p,benefitAbsent:t.benefitAbsent===!0}}function S8(e){const t=Cl(e);let a=null;for(const b of Q6(e)){if(b.enabled===!1)continue;const j=of(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=Uy(o),p=d?"":` · ${Ch(f.remainingMs,f.daily)}`,g=f.daily?r("今日已用"):r("周期 Token"),v=o.reset==="daily"?r("今天(本地 0 点重置)"):r("{period}窗口",{period:JE(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:Ch(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:Nl(c.used)})," ","/ ",Nl(o.threshold),p]})}function N8({account:e}){if(!Ca(e))return s.jsx("span",{className:"muted",title:r("该提供商没有余额查询"),children:"—"});const t=Ya(e),a=b8(t),o=kh(e,t)?s.jsx(ze,{variant:"warning",shape:"tag",title:r("余额低于限制器的阈值,转发时会跳过该账号(余额回升自动恢复)"),children:r("余额不足 · 已跳过")}):Hy(e,Cl(e))?s.jsx(ze,{variant:"warning",shape:"tag",title:r("本周期 Token 消耗达到限制器的上限,转发时会跳过该账号(窗口重置自动恢复)"),children:r("Token 限额 · 已跳过")}):null,c=S8(e),d=a.kind==="ok"||a.kind==="warn"?g8(t):[],f=d.length?s.jsx(ze,{variant:"warning",shape:"tag",title:x8(d),children:r("待生效 {n} 份",{n:d.length})}):null,p=a.kind==="ok"||a.kind==="warn"?U6(t):[],g=aR(e)&&p.length?{rows:p,subscriptionLine:h8(t),kind:a.kind,title:a.title}:null;if(rF(e)){const j=a.kind==="ok"||a.kind==="warn"?w8(t):null;return j?s.jsx(k8,{summary:a,detail:j,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 v=a.kind==="ok"||a.kind==="warn"?y8(t):null;if(!v)return s.jsxs("span",{className:"usage-sum-wrap",children:[g?s.jsx(FE,{variant:"sum",...g,children:a.text}):s.jsx("span",{className:`usage-sum ${a.kind}`,title:a.title,children:a.text}),o,f,c]});const y=s.jsxs(s.Fragment,{children:[v.percent!==null?s.jsx(qd,{value:v.percent,className:"usage-pool-bar"}):null,s.jsx("span",{className:`usage-pool-view ${a.kind}`,children:v.text})]});return s.jsxs("span",{className:"usage-pool",title:a.title,children:[v.planName?s.jsx("span",{className:"usage-pool-name",children:v.planName}):null,g?s.jsx(FE,{variant:"pool",...g,children:y}):s.jsx("span",{className:"usage-pool-line",children:y}),o,f,c]})}function k8({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(rf,{open:c,onOpenChange:d,children:[s.jsxs(wh,{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(af,{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(C8,{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:[br(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.jsxs("span",{className:"usage-flat-line",title:p.title,children:[s.jsxs("span",{className:"usage-flat-head",children:[s.jsx("span",{className:"usage-flat-name",children:p.name}),s.jsx("span",{className:`usage-flat-view ${p.tone}`,children:p.view})]}),p.percent!==null?s.jsx("span",{className:`usage-flat-track${p.over?" over":""}`,children:s.jsx("i",{style:{width:`${p.percent}%`},"aria-label":r("剩余 {percent}%",{percent:Math.round(p.percent)})})}):null]},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 C8({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 T8({account:e,namesHidden:t}){const a=Nh(e),o=lr(On(e)),c=ru(e)||r("未命名账号"),d=String(e.email||"").trim(),f=String(e.nickname||"").trim(),p=String(e.name||"").trim(),g=w=>t?kF(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)}):"",cf(e)?r("桌面端实时登录态(凭证每次从客户端登录态文件读取)"):"",e.updatedAt?r("更新于 {time}",{time:Us(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(nU,{delay:0,children:s.jsxs(Ri,{children:[s.jsx(Ai,{render:s.jsx("div",{className:"acct-name"}),children:s.jsx("span",{className:"name",children:g(c)})}),s.jsxs(Oi,{children:[s.jsx(sU,{}),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 E8({account:e}){const t=e.proxy,a=t?.config?.source||t?.source,o=t?.label||r(a==="custom"?"自定义代理":"已设置"),c=t?.error,d=EF(),f=Array.isArray(d)?d:[];let p="";a==="pool"&&t?.config?.proxyId?p=`${Ka}${t.config.proxyId}`:t&&(p=zh);const g=[{value:"",label:r("直连")}];for(const b of f)g.push({value:`${Ka}${b.id}`,label:lf(b)});if(d===null?g.push({value:"__hint_pool__",label:r("正在读取代理列表…"),disabled:!0}):f.length||g.push({value:"__hint_pool__",label:RF()?r("代理列表读取失败(重试中)"):r("还没有代理(去「网络代理」页添加)"),disabled:!0}),p===zh){const b=a==="clash"?r("Clash 出口:"):a==="custom"?r("自定义:"):"";g.push({value:zh,label:`${b}${o}${c?r("(不可用)"):""}`})}else a==="pool"&&!f.some(b=>`${Ka}${b.id}`===p)&&g.push({value:p,label:`${o}${c?r("(不可用)"):""}`});g.push({value:VR,label:r("自定义代理…")});const v=c?r("代理不可用:{error}(转发时会回退直连);选「自定义代理…」去修改",{error:c}):a==="clash"||a==="custom"?r("当前:{label}(未经过代理池 —— 可在「网络代理」页把出口同步进池后来这里改选)",{label:o}):r("当前:{label};选项来自「网络代理」页;「自定义代理…」打开完整设置",{label:t?o:r("直连")}),y=g.find(b=>b.value===p);return s.jsxs(ut,{value:p,onValueChange:b=>{BF(e.id,String(b),p)},children:[s.jsx(ft,{className:Ve("w-full",c&&"border-destructive-bd"),title:v,"aria-label":r("出网代理"),children:s.jsx(dt,{children:y?.label||r("直连")})}),s.jsx(pt,{children:g.map(b=>s.jsx(Xe,{value:b.value,disabled:b.disabled,children:b.label},b.value))})]})}function R8({account:e,atFront:t}){const[a,o]=x.useState(!1),c=Ca(e),d=nR(e);return s.jsxs("div",{className:"acct-actions",children:[d?s.jsx(se,{variant:"outline",size:"xs",title:nF(e)?sF(e):r("查看可领取的套餐与名下已有的套餐(每天一期,领取需过一次人机验证)"),onClick:()=>FR(e.id),children:r("领套餐")}):null,c?s.jsx(se,{variant:"outline",size:"xs",disabled:a,title:r("查询该账号剩余余额(读数显示在余额列)"),onClick:()=>{o(!0),LF(e.id).finally(()=>o(!1))},children:r("余额")}):null,s.jsx(se,{variant:"outline",size:"xs",title:r("备注名 / 启用 / 代理"),onClick:()=>Ph(e.id),children:r("设置")}),s.jsx(A8,{account:e,atFront:t})]})}function A8({account:e,atFront:t}){const[a,o]=x.useState(!1),c=or(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(rf,{open:a,onOpenChange:o,children:[s.jsx(wh,{render:s.jsx(se,{variant:"outline",size:"xs",title:r("更多操作")}),children:"⋯"}),s.jsx(af,{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),BR(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),Ph(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:cf(e)?r("删除这条账号记录(不会影响客户端自己的登录态;之后可再点「导入桌面端登录态」加回来)"):void 0,onClick:()=>{o(!1),Pe().wbApp?.runAccountAction?.("remove",e.id)},children:r("删除账号")})]})})]})}function O8({account:e,onClose:t,onClear:a}){const o=qy(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:ru(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=Yy(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===Ky?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 M8({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(O8,{account:e,onClose:()=>NR(e.id,"limits",!1),onClear:c=>o(e.id,c)})})}):null}function D8({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(ta,{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(I8,{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 I8({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:()=>NF(),dangerouslySetInnerHTML:{__html:Qh(e?"eyeOff":"eye",13)}})}const SA="dragging",yf=["drop-before","drop-after"];let Xa=null;function NA(e){e.querySelectorAll(`.${yf[0]}, .${yf[1]}`).forEach(t=>{t.classList.remove(...yf)})}function P8(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 kA(e,t){for(let a=0;aa!==e.item);NA(e.container),t.length&&(e.index>=t.length?t[t.length-1].classList.add(yf[1]):t[e.index].classList.add(yf[0]))}function CA(e){if(!Xa)return;if(e.buttons===0){Zh(!1);return}const t=Xa.items.filter(o=>o!==Xa.item),a=kA(t,e.clientY);a!==Xa.index&&(Xa.index=a,_8(Xa))}function Zh(e){const t=Xa;t&&(Xa=null,window.removeEventListener("pointermove",CA),window.removeEventListener("pointerup",TA),window.removeEventListener("pointercancel",EA),window.removeEventListener("keydown",RA),document.body.classList.remove("queue-dragging"),t.item.classList.remove(SA),NA(t.container),e&&(t.kind==="group"?gj?.onDrop({kind:"group",provider:t.provider,index:t.index}):gj?.onDrop({kind:"row",provider:t.provider,accountId:t.accountId,index:t.index})))}function TA(){Zh(!0)}function EA(){Zh(!1)}function RA(e){e.key==="Escape"&&Zh(!1)}let gj=null;function L8(e,t){gj=t,e&&e.dataset.queueDragBound!=="1"&&(e.dataset.queueDragBound="1",e.addEventListener("pointerdown",a=>{if(a.button!==0||Xa)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=P8(f,p);if(y.length<2)return;const b=y.filter(j=>j!==f);Xa={kind:p,provider:g,accountId:v,item:f,container:f.parentElement||e,items:y,index:kA(b,a.clientY)},f.classList.add(SA),document.body.classList.add("queue-dragging"),window.addEventListener("pointermove",CA),window.addEventListener("pointerup",TA),window.addEventListener("pointercancel",EA),window.addEventListener("keydown",RA)}))}let Wh=null,AA=!1,xj=0,Jh=null,OA="";function MA(){return Wh?Wh.apply(rj):rj}function DA(){window.wbAccountsView?.render?.()}function z8(){const e=MA(),t=`${Jh?"T":"F"}|${e.map(o=>`${o.key}:${o.align}`).join("|")}`;if(t===OA)return;OA=t,Pe().wbColSettings?.syncStaticHead("accounts",Jh);const a=[...Jh?.querySelectorAll("thead th")||[]];a.forEach((o,c)=>{const d=o.querySelector(".col-grip");d&&(d.style.display=c===a.length-1?"none":"")})}function B8(){const e=x.useSyncExternalStore(gR,Zs),t=x.useRef(null),[,a]=x.useReducer(U=>U+1,0),o=!!Qy(),c=kl(),{groups:d,allGroups:f}=pF(Ya,Cl),p=mF(Ya,Cl),g=[{value:"all",label:r("全部({n})",{n:c.length})}].concat(xR().map(U=>({value:U.id,label:r("{label}({count})",{label:U.label,count:U.count})}))),v=d.flatMap(U=>U.accounts),y=hF(),b=MA(),j=$h(v.length,"accounts",{defaultSize:"all"}),w=j.paged?j.slice(v):v,S=Oh()||j.paged,N=Oh()?r("清除筛选"):r("把每页调回「全部」");x.useEffect(()=>{AF()}),x.useEffect(()=>{bF()},[e.version]),x.useLayoutEffect(()=>{if(!AA){if(!Pe().wbColSettings?.register){window.clearTimeout(xj),xj=window.setTimeout(()=>k(U=>U+1),50);return}AA=!0,Wh=Pe().wbColSettings?.register({id:"accounts",label:r("账号表"),columns:rj.map(U=>({key:U.key,label:U.label,align:U.align,legacyAlign:U.legacyAlign})),mount:()=>document.querySelector("#batch-bar .batch-actions"),onChange:DA})||null,Wh&&a();return}z8()});const[,k]=x.useState(0);x.useEffect(()=>()=>window.clearTimeout(xj),[]),x.useEffect(()=>{j$(t.current,DA)},[]);const E=v.map(U=>U.id),R=E.length>0&&E.every(U=>e.selected.has(U)),C=E.some(U=>e.selected.has(U)),A=[...e.selected].filter(U=>!E.includes(U)).length,D=e.selected.size>0,I=f.length>0&&f.every(U=>e.collapsed.has(U.provider)),M=new Map;for(const U of d)M.set(U.provider,w.filter(B=>On(B)===U.provider).map(B=>B.id));const O=x.useRef({displayed:d,all:f,renderedRows:M});x.useEffect(()=>{O.current={displayed:d,all:f,renderedRows:M}});const _=x.useRef({locked:!1,lockReason:"",onDrop:U=>{}}),L=x.useCallback(U=>{const{displayed:B,all:Q}=O.current;if(U.kind==="group"){const J=Q.findIndex(K=>K.provider===U.provider);if(J<0)return;const ie=Q[J],me=Q.filter((K,be)=>be!==J),he=U.indexK.provider===he),oe=he===null||ae<0?me.length:ae;if(oe===J)return;const de=[...me.slice(0,oe),ie,...me.slice(oe)].flatMap(K=>K.members.map(be=>be.id));HR(de,r("{name} 移到第 {rank} 顺位",{name:ie.label,rank:oe+1}));return}const W=Q.find(J=>J.provider===U.provider);if(!W)return;const Z=W.members.findIndex(J=>J.id===U.accountId);if(Z<0)return;const Y=W.members[Z],q=W.members.filter((J,ie)=>ie!==Z),G=O.current.renderedRows.get(U.provider)||[],F=U.indexJ.id===F),X=F===null||$<0?q.length:$;if(X===Z)return;const re=[...q.slice(0,X),Y,...q.slice(X)],V=Q.map(J=>J.provider===U.provider?{...J,members:re}:J).flatMap(J=>J.members.map(ie=>ie.id));HR(V,r("{name} 移到 {group} 组内第 {rank} 位",{name:String(Y.name||Y.id),group:W.label,rank:X+1}))},[]);x.useEffect(()=>{_.current={locked:S,lockReason:N,onDrop:L}}),x.useEffect(()=>{L8(t.current,{isLocked:()=>_.current.locked,onLockedAttempt:()=>He(r("当前视图不能调整组顺位:{reason} 之后再拖动",{reason:_.current.lockReason}),"err"),onDrop:U=>_.current.onDrop(U)})},[]);function z(U,B,Q){switch(U){case"pick":return s.jsx(ta,{checked:Q.picked,"data-pick":B.id,title:r("勾选后可批量操作"),"aria-label":r("勾选后可批量操作"),onCheckedChange:W=>jF(B.id,W)});case"order":return s.jsx(i8,{account:B,rank:Q.rank});case"account":return s.jsx(T8,{account:B,namesHidden:e.namesHidden});case"proxy":return s.jsx(E8,{account:B});case"connections":return s.jsx(m8,{account:B});case"status":return s.jsx(d8,{account:B});case"limits":return s.jsx(f8,{account:B,open:Q.limitsOpen});case"expiry":return s.jsx(p8,{account:B});case"usage":return s.jsx(N8,{account:B});case"actions":return s.jsx(R8,{account:B,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(ut,{value:e.filter.provider,onValueChange:U=>xF(String(U)),children:[s.jsx(ft,{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(dt,{children:g.find(U=>U.value===e.filter.provider)?.label||r("全部")})}),s.jsx(pt,{children:g.map(U=>s.jsx(Xe,{value:U.value,children:U.label},U.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(Ye,{className:"acct-search",type:"search",value:e.filter.q,placeholder:r("账号名 / 邮箱 / 备注"),"aria-label":r("搜索账号"),onChange:U=>gF(U.currentTarget.value)})]}),s.jsx("div",{className:"divider"}),s.jsxs("div",{className:"group",children:[s.jsx("span",{className:"label",children:r("状态")}),s.jsx(Pn,{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:U=>bR("enabled",U),"aria-label":r("启用状态")})]}),s.jsxs("div",{className:"group",children:[s.jsx("span",{className:"label",children:r("限额")}),s.jsx(Pn,{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:U=>bR("limit",U),"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:()=>vF(f.map(U=>U.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(Ca),title:r("查询全部账号的余额(含已禁用账号 —— 禁用只表示不参与转发)"),onClick:()=>{LR()},children:e.usageBusy?r("查询中…"):r("查询余额")})]})]}),s.jsxs("div",{className:Ve("batch-bar",D&&"active"),id:"batch-bar",children:[s.jsxs("label",{className:"batch-select-all",children:[s.jsx(ta,{id:"batch-select-all",checked:R,indeterminate:!R&&C,disabled:!E.length,"aria-label":r("全选当前筛选结果"),onCheckedChange:U=>wR(E,U)}),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,Oh()?s.jsx(se,{id:"btn-clear-filter",variant:"ghost",size:"xs",title:r("清空搜索与三个筛选档位,回到全部账号"),onClick:()=>vR(),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:!D,onClick:()=>Wy([...e.selected],"enable"),children:r("批量操作")}),s.jsx(se,{id:"btn-batch-clear",variant:"outline",disabled:!D,onClick:()=>wF(),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:H8,style:{minWidth:`${v$(b.map(U=>U.key))}px`},children:[s.jsx(U8,{}),s.jsx(D8,{namesHidden:e.namesHidden,allPicked:R,somePicked:C,disabled:!E.length,onToggleAll:U=>wR(E,U)}),d.map(U=>{const B=e.collapsed.has(U.provider),Q=w.filter(W=>On(W)===U.provider);return s.jsxs("tbody",{className:"acct-group","data-provider":U.provider,children:[s.jsx(u8,{group:U,collapsed:B,colSpan:b.length}),B?null:Q.map(W=>{const Z=U.members.findIndex(q=>q.id===W.id)+1,Y=HF(W,y,Z>0?Z:1);return s.jsxs(x.Fragment,{children:[s.jsx("tr",{className:Ve("acct-row",!or(W)&&"disabled",Y.picked&&"selected"),"data-id":W.id,"data-provider":U.provider,"data-desktop":cf(W)?"1":void 0,children:b.map(q=>s.jsx("td",{className:`cell-${q.key} ta-${q.align}`,children:z(q.key,W,Y)},q.key))}),s.jsx(M8,{account:W,colSpan:b.length,limitsOpen:SR(W.id,"limits"),onClear:(q,G)=>{zF(q,G)}})]},W.id)})]},U.provider)})]}):s.jsxs("div",{className:"empty",children:[r("当前筛选条件下没有账号"),Oh()?s.jsx("button",{type:"button",className:"link-btn",onClick:()=>vR(),children:r("清除筛选")}):null]}):s.jsx("div",{className:"empty",children:r("暂无账号,请点击右上角「添加账号」")}):s.jsxs("div",{className:"empty",children:[s.jsx("span",{className:"spinner"}),r("正在加载…")]})}),s.jsx(Di,{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(d$,{})]})}function H8(e){Jh=e}function U8(){const e=b$(),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 IA='.page[data-page="accounts"]';let bj=null;function PA(){if(bj)return;const e=document.querySelector(IA);e&&(e.replaceChildren(),bj=wn.createRoot(e),Ns.flushSync(()=>{bj.render(s.jsx(B8,{}))}))}VF(),DF(),document.querySelector(IA)?PA():document.addEventListener("DOMContentLoaded",PA,{once:!0});const V8=64,F8=100,$8=r("OpenAI 兼容填到 /v1;Anthropic 填根地址"),q8=r("Anthropic 协议填根地址,不要带 /v1"),G8="https://open.bigmodel.cn/api/paas/v4",K8="https://api.anthropic.com",Y8=[{value:"chat_completions",label:"OpenAI - Chat Completions"},{value:"responses",label:"OpenAI - Responses"},{value:"anthropic",label:"Anthropic - Messages"}],uu="custom-protocol-select",du="custom-name-input",fu="custom-baseurl-input",jf="custom-apikey-input",wf="custom-noauth-check",pu="custom-existing-select",Sf="custom-existing-apikey-input",eg="custom-existing-noauth-check",Nf="custom-existing-name-input",X8="custom-create-button",Q8="custom-existing-button",Z8="custom-existing-remove";let vj=!1;const _A=()=>Ct().wbProviders?.PROTOCOL_OPTIONS||Y8,LA=()=>Ct().wbProviders?.customList?.()||[];async function yj(e,t){if(!vj){vj=!0,e(!0);try{await t()}finally{vj=!1,e(!1)}}}async function zA(e){Ct().wbAddAccountModal?.close?.(),Ct().wbProviders?.refreshCustom?.(),await Ct().wbApp?.refresh?.(),Ws(e)}function tg(e,t){Ii(e,t?"1":"")}function ng(e){return ra(e)==="1"}function BA({checked:e,note:t,onChange:a}){return s.jsxs("div",{className:"add-field",children:[s.jsx(st,{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(ta,{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 W8({mode:e,providerHint:t,presetKey:a,showToken:o,version:c}){const d=_A(),[f,p]=x.useState(()=>ra(uu)||d[0].value),[g,v]=x.useState(""),[y,b]=x.useState(()=>ra(pu)),[j,w]=x.useState(()=>ng(wf)),[S,N]=x.useState(()=>ng(eg)),k=x.useMemo(()=>LA(),[c]),R=(t&&k.some(M=>M.id===t)?t:"")||(k.some(M=>M.id===y)?y:k[0]?.id||""),C=k.find(M=>M.id===R)?.name||r("该提供商");x.useEffect(()=>{Ii(pu,R)},[R]),x.useEffect(()=>{if(e!=="create"||!a)return;const M=Ct().wbPresetProviders?.presetOf?.(a);if(!M)return;Ii(du,M.name||""),Ii(fu,M.baseUrl||""),M.protocol&&(p(M.protocol),Ii(uu,M.protocol));const O=M.account?.noAuth===!0;w(O),tg(wf,O),v(M.hint||"")},[e,a,t,o]);const A=f==="anthropic",D=g||(A?q8:$8),I=(M,O)=>_=>{O(_),tg(M,_)};return s.jsxs(s.Fragment,{children:[s.jsxs(Hn,{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(st,{htmlFor:du,children:[r("名称"),s.jsx("i",{className:"req","aria-hidden":"true",children:"*"})]}),s.jsx(Ye,{id:du,type:"text",maxLength:V8,"aria-required":"true",placeholder:r("如:智谱 GLM"),...El(du)}),s.jsx("span",{className:"hint",children:r("1~64 个字符,账号列表里按它分组显示")})]}),s.jsxs("div",{className:"add-field",children:[s.jsx(st,{htmlFor:uu,children:r("协议")}),s.jsxs(ut,{value:f,onValueChange:M=>{const O=String(M);p(O),Ii(uu,O),v("")},children:[s.jsx(ft,{id:uu,className:"col-start-2 row-start-1 w-full",children:s.jsx(dt,{children:d.find(M=>M.value===f)?.label||f})}),s.jsx(pt,{children:d.map(M=>s.jsx(Xe,{value:M.value,children:M.label},M.value))})]})]}),s.jsxs("div",{className:"add-field",children:[s.jsxs(st,{htmlFor:fu,children:["Base URL",s.jsx("i",{className:"req","aria-hidden":"true",children:"*"})]}),s.jsx(Ye,{id:fu,type:"text","aria-required":"true",placeholder:A?K8:G8,...El(fu)}),s.jsx("span",{className:"hint",id:"custom-baseurl-hint",children:D})]}),s.jsxs("div",{className:"add-field",children:[s.jsx(st,{htmlFor:jf,children:"API Key"}),s.jsx(Ye,{id:jf,type:"password",autoComplete:"new-password",placeholder:"sk-…",disabled:j,...El(jf)}),s.jsx("span",{className:"hint",children:r(j?"不需要 Key:转发与拉取模型都不发送鉴权头":"上游不要鉴权时留空,并勾选下面一项(留空又不勾会被当成未配置凭证)")})]}),s.jsx(BA,{checked:j,note:r(j?"已声明无需鉴权:账号会被正常选路,出网时不带任何鉴权头":"本地 Ollama、OpenCode Zen 免费档这类上游要勾上,否则账号不可用"),onChange:I(wf,w)})]})]}),s.jsxs(Hn,{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:C}),r(" 同一家可以放多把 key,按优先级轮换。")]})]}),s.jsxs("div",{className:"add-form",children:[s.jsxs("div",{className:"add-field",children:[s.jsx(st,{htmlFor:pu,children:r("提供商")}),s.jsxs(ut,{value:R,onValueChange:M=>b(String(M)),children:[s.jsx(ft,{id:pu,className:"col-start-2 row-start-1 w-full",children:s.jsx(dt,{children:C})}),s.jsx(pt,{children:k.map(M=>s.jsx(Xe,{value:M.id,children:M.name||M.id},M.id))})]})]}),s.jsxs("div",{className:"add-field",children:[s.jsx(st,{htmlFor:Sf,children:"API Key"}),s.jsx(Ye,{id:Sf,type:"password",autoComplete:"new-password",placeholder:"sk-…",disabled:S,...El(Sf)}),s.jsx("span",{className:"hint",children:r(S?"不需要 Key:转发与拉取模型都不发送鉴权头":"上游不要鉴权时留空,并勾选下面一项(留空又不勾会被当成未配置凭证)")})]}),s.jsx(BA,{checked:S,note:r(S?"已声明无需鉴权:账号会被正常选路,出网时不带任何鉴权头":"同一家可以混着放:有 Key 的账号与无鉴权账号各按各的规则走"),onChange:I(eg,N)}),s.jsxs("div",{className:"add-field",children:[s.jsx(st,{htmlFor:Nf,children:r("备注名")}),s.jsx(Ye,{id:Nf,type:"text",maxLength:F8,placeholder:r("可选"),...El(Nf)}),s.jsx("span",{className:"hint",children:r("留空则用提供商名称")})]})]})]})]})}function HA(e,t){const a=qh(t);Ws(r("添加失败:{reason}",{reason:a}),"err"),e.setHint(a)}async function J8(e){const t=ra(du),a=ra(uu)||_A()[0].value,o=ra(fu),c=ra(jf),d=ng(wf);if(!t){Ws(r("请填写名称"),"err");return}if(!o){Ws(r("请填写 Base URL"),"err");return}await yj(e.setBusy,async()=>{const f={name:t,protocol:a,baseUrl:o},p=e.presetKey?Ct().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),d?f.noAuth=!0:c&&(f.apiKey=c),e.setHint("");try{const v=await Ct().wbProviders?.customRequest?.("POST","/api/custom-providers",f);cj([du,fu,jf]),tg(wf,!1);const y=v?.provider?.name||t;await zA(r("✅ 已创建自定义提供商「{name}」并添加账号",{name:y}))}catch(v){HA(e,v)}})}async function eq(e){const t=ra(pu);if(!t){Ws(r("请先选择一个自定义提供商"),"err");return}const a=ra(Sf),o=ng(eg),c=ra(Nf);await yj(e.setBusy,async()=>{const d={provider:t};o?d.noAuth=!0:a&&(d.apiKey=a),c&&(d.name=c),e.setHint("");try{const f=await Ct().wbProviders?.customRequest?.("POST","/api/accounts",d);cj([Sf,Nf]),tg(eg,!1);const p=f?.account?.name||LA().find(g=>g.id===t)?.name||"";await zA(r("✅ {label}账号已添加{name}",{label:"",name:p?`:${p}`:""}))}catch(f){HA(e,f)}})}async function tq(){const e=ra(pu);if(!e){Ws(r("请先选择一个自定义提供商"),"err");return}const t=Ct().wbCustomProvidersUi?.remove;if(typeof t!="function"){Ws(r("删除功能不可用(脚本未就绪)"),"err");return}await yj(()=>{},async()=>{await t(e)&&Ct().wbAddAccountModal?.close?.()})}function nq({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:Z8,variant:"destructive",title:r("级联删除名下全部账号,不可恢复"),onClick:()=>{tq()},children:r("删除此提供商")}):null,s.jsx(se,{id:X8,hidden:e!=="create",disabled:a,onClick:()=>{J8(f)},children:r(a&&e==="create"?"提交中…":"创建并添加账号")}),s.jsx(se,{id:Q8,hidden:e!=="existing",disabled:a,onClick:()=>{eq(f)},children:r(a&&e==="existing"?"提交中…":"添加账号")})]})]})}const jj={step:"pick",accountType:pj,search:"",provider:_i,providerHint:"",presetKey:"",showToken:0},UA=()=>Ct().wbProviders?.customList?.()||[];function sq({onClose:e,onReady:t}){const[a,o]=x.useState(jj),[c,d]=x.useState(0),f=x.useCallback(()=>d(C=>C+1),[]),p=x.useCallback(()=>{o(jj);const C=Ct().wbProviders;(C?.all?.()||[]).length||C?.load?.().then(f),C?.refreshCustom?.().then(f)},[f]),g=x.useCallback(()=>{p(),o({...jj,step:"form",provider:cu})},[p]);x.useEffect(()=>(t({reset:p,openNewCustomForm:g}),()=>t(null)),[t,p,g]),x.useEffect(()=>{Ct().wbWebLogin?.refresh?.()},[]),x.useEffect(()=>{Ct().wbProviders?.refreshCustom?.().then(f)},[f]),x.useEffect(()=>{a.step!=="form"||a.provider!==cu||Ct().wbProviders?.refreshCustom?.().then(f)},[a.step,a.provider,a.showToken,f]);const v=H$(a.provider),y=a.provider===cu,b=a.provider===_i||y||!!v,j=a.providerHint?"existing":"create",w=a.providerHint?UA().find(C=>C.id===a.providerHint)?.name||"":a.presetKey&&Ct().wbPresetProviders?.presetOf?.(a.presetKey)?.name||"",S=a.provider===_i?uj:Ct().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};C===hj?o(D=>({...D,...A,provider:cu,providerHint:"",presetKey:""})):C.startsWith(vf)?o(D=>({...D,...A,provider:cu,providerHint:"",presetKey:C.slice(vf.length)})):UA().some(D=>D.id===C)?o(D=>({...D,...A,provider:cu,providerHint:C,presetKey:""})):o(D=>({...D,...A,provider:C,providerHint:"",presetKey:""}))}const E=()=>o(C=>({...C,step:"pick"})),R=a.accountType===J$;return s.jsx(Kt,{open:!0,onOpenChange:C=>{C||e()},children:s.jsxs(Yt,{className:"w-[min(880px,calc(100vw-48px))]",children:[s.jsx($t,{children:s.jsx(Ft,{children:r("添加账号")})}),s.jsx(_t,{children:s.jsx(o8,{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:R,importPanel:void 0})}),null,s.jsx(Kt,{open:a.step==="form",onOpenChange:C=>{C||E()},children:s.jsxs(Yt,{keepMounted:!0,overlayForceRender:!0,className:"w-[min(620px,calc(100vw-48px))]",children:[s.jsx($t,{children:s.jsx(Ft,{children:N})}),s.jsxs(_t,{children:[s.jsx(W$,{active:a.provider===_i}),pA.map(C=>s.jsx(Z$,{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(W8,{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(Hn,{children:[s.jsx("h3",{children:r("该提供商账号添加功能即将上线")}),s.jsx("p",{children:r("「{name}」的账号添加功能还在开发中,敬请期待。",{name:S})})]})})]}),y?s.jsx(en,{children:s.jsx(nq,{mode:j,presetKey:a.presetKey})}):null]})})]})})}let yo=null,mu=null,Li=null,sg=null;function rq(){yo&&(yo.unmount(),yo=null),mu&&(mu.remove(),mu=null),Li=null}function VA(){mu=document.createElement("div"),document.body.append(mu),yo=wn.createRoot(mu),yo.render(s.jsx(sq,{onClose:FA,onReady:e=>{if(Li=e,!e)return;const t=sg;sg=null,t?.()}}))}function FA(){Ct().wbWebLogin?.cancelIfActive?.(""),Ct().wbAutoclawOauth?.cancel?.(),rq()}function wj(){if(yo){Li?.reset();return}sg=()=>Li?.reset(),VA()}function aq(){if(yo){Li?.openNewCustomForm();return}sg=()=>Li?.openNewCustomForm(),VA()}for(const e of["btn-add-account","btn-add-account-2"])document.getElementById(e)?.addEventListener("click",wj);const $A=window;$A.wbAddAccountModal={open:wj,close:FA},$A.wbAccountAddForms={syncAddProvider:()=>{yo?Li?.reset():wj()},openNewCustomForm:aq};function Rr(){return Pe().workbuddyDesktop??{}}function qA(){return window}const GA="workbuddy-desktop-checkin-tab",lq=["center","schedule","records"];function oq(){try{const e=localStorage.getItem(GA);return lq.includes(e)?e:"center"}catch{return"center"}}function KA(e){if(e!==ms.tab){try{localStorage.setItem(GA,e)}catch{}Js({tab:e})}}async function rg(e){KA(e),ms.loaded||await Rl()}let ms={version:0,tab:oq(),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 Sj=new Set;function iq(){for(const e of Sj)e()}function Js(e){ms={...ms,...e,version:ms.version+1},iq()}function ir(){return ms}function YA(e){return Sj.add(e),()=>Sj.delete(e)}function cq(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 Nj(e){return(Array.isArray(e)?e:[]).map(cq).filter(a=>a!==null)}function is(e){return Number(e)||0}async function Rl(){try{const e=await Rr().getCheckinCenter?.();if(!e)throw new Error(r("后端未返回签到中心数据"));Js({snapshot:e,loaded:!0,loadError:"",autoTimeDraft:null,keepaliveDraft:null}),uq(e.extras?.onboarding??[])}catch(e){Js({loaded:!0,loadError:mt(e)})}}function uq(e){for(const t of e){const a=t.settled;if(!a||typeof a!="object")continue;const o=ms.onboarding.get(t.id);if(o?.status==="loaded"&&o.unclaimed>0)continue;const c=Nj(a.tasks),d=is(a.at);jo(t.id,{status:"loaded",error:void 0,checkedAt:void 0,settled:!0,settledAt:d>0?d:void 0,tasks:c,unclaimed:0,earned:is(a.earned),total:is(a.total)})}}function XA(e){const t=new Set(ms.expanded);t.has(e)?t.delete(e):t.add(e),Js({expanded:t})}function kj(e){const t=`onb:${e}`,a=new Set(ms.expanded);a.has(t)?a.delete(t):a.add(t),Js({expanded:a})}function QA(e){return ms.expanded.has(`onb:${e}`)}async function dq(){if(!ms.runningAll){Js({runningAll:!0});try{const e=await Rr().runAutoCheckinNow?.();if(e){const t=is(e.succeeded),a=is(e.active),o=is(e.total),c=is(e.failedCount),d=a>0?r(",日活保活 {n} 个",{n:a}):"";c>0?He(r("签到完成:{succeeded}/{total} 成功{active},{failed} 个失败",{succeeded:t,total:o,active:d,failed:c}),"err"):He(r("✅ 签到完成:{succeeded}/{total} 个账号成功领取{active}",{succeeded:t,total:o,active:d})),qA().wbAccountsView?.refreshUsageAfterCheckin?.(null)}}catch(e){He(r("签到失败:{error}",{error:mt(e)}),"err")}finally{Js({runningAll:!1}),await Rl(),ZA(ir().snapshot?.extras.onboarding??[]),Pe().wbApp?.refresh?.()}}}async function ag(e,t="checkin"){const a=`${e}:${t}`;if(ms.signing.has(a))return;const o=new Set(ms.signing);o.add(a),Js({signing:o});try{let c;t==="checkin"?c=(await Rr().checkinAllAccounts?.(e))?.results?.[0]:c=await Rr().runCheckinActivity?.(e,t)??void 0;const d=c?.claim,f=c?.activity,p=f?.report?.succeeded===!0;c?.error?He(r("签到失败:{error}",{error:String(c.error)}),"err"):t==="keepalive"?f?.pokeSucceeded===!0||p?He(r("✅ {message}",{message:d?.msg||r("活跃保活完成")})):He(d?.msg||r("活跃保活失败"),"err"):d?.success===!0?He(r("✅ {message}",{message:d.msg||r("签到成功")})):d?.alreadyCompleted===!0?He(d?.msg||r("今日已领取"),"err"):p?He(r("✅ {message}",{message:d?.msg||r("活跃上报完成,但活动未开启")})):f?.pokeSucceeded===!0?He(r("✅ {message}",{message:d?.msg||r("活跃保活完成,但活动未开启")})):He(d?.msg||r("未领取"),"err"),qA().wbAccountsView?.refreshUsageAfterCheckin?.(e)}catch(c){He(r("签到失败:{error}",{error:mt(c)}),"err")}finally{const c=new Set(ir().signing);c.delete(a),Js({signing:c}),await Rl();const d=(ir().snapshot?.extras.onboarding??[]).filter(f=>f.id===e);ZA(d),Pe().wbApp?.refresh?.()}}function lg(e){Js({keepaliveDraft:e.map(t=>t.trim()).filter(Boolean)})}async function fq(e){const t=e.map(a=>a.trim()).filter(Boolean);if(!ir().keepaliveSaving){Js({keepaliveSaving:!0});try{const a=await Rr().saveCheckinKeepalive?.(t);if(a){const o=ir().snapshot;Js({snapshot:o&&{...o,keepalive:a},keepaliveDraft:null}),He(r("已保存:保活模型链"))}}catch(a){He(r("保存失败:{error}",{error:mt(a)}),"err")}finally{Js({keepaliveSaving:!1})}}}async function ZA(e){for(const t of e)pq(t.id)||await Cj(t.id);for(const t of e){const a=ir().onboarding.get(t.id);a?.status!=="loaded"||a.claiming||a.settled||(t.provider==="officeace"||a.unclaimed>0)&&await WA(t.id)}}function pq(e){return ms.onboarding.get(e)?.settled===!0}function hu(e){return ms.onboarding.get(e)??{status:"idle",tasks:[],unclaimed:0,earned:0,total:0,claiming:!1}}function jo(e,t){const a=new Map(ms.onboarding);a.set(e,{...hu(e),...t}),Js({onboarding:a})}async function Cj(e,t){const a=hu(e);if(!(a.status==="loading"||a.claiming)){jo(e,{status:"loading",error:void 0,settled:!1});try{const o=await Rr().getOnboardingTasks?.(e,t?.refresh===!0),c=Nj(o?.tasks),d=o?.settled===!0;jo(e,{status:"loaded",checkedAt:Date.now(),tasks:c,unclaimed:c.filter(f=>!f.done&&!f.blocked).length,earned:is(o?.earned),total:is(o?.total),settled:d,settledAt:d&&is(o?.settledAt)||void 0}),t?.expand===!0&&c.length>0&&!QA(e)&&kj(e)}catch(o){jo(e,{status:"error",error:mt(o),settled:!1})}}}async function WA(e){const t=hu(e);if(!(t.claiming||t.status!=="loaded")){jo(e,{claiming:!0});try{jo(e,{tasks:hu(e).tasks.map(b=>b.done?b:{...b,claiming:!0,error:void 0})});const a=await Rr().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=Nj(a?.tasks),f=(d.length?d:hu(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;jo(e,{claiming:!1,checkedAt:Date.now(),tasks:f,unclaimed:f.filter(b=>!b.done&&!b.blocked).length,earned:is(a?.earned),total:is(a?.total),settled:g,settledAt:g&&is(a?.settledAt)||void 0});const v=f.filter(b=>b.error&&!b.done).length,y=typeof a?.message=="string"?a.message.trim():"";v?He(r("新手福利有 {n} 项领取失败,可重试",{n:v}),"err"):y?He(y,"ok"):p&&He(r("✅ 新手福利领取完成,累计 {n} 积分",{n:is(a?.earned)}))}catch(a){const o=mt(a);jo(e,{claiming:!1,tasks:hu(e).tasks.map(c=>({...c,claiming:!1,error:c.done?void 0:o}))}),He(r("领取失败:{error}",{error:o}),"err")}finally{await Rl()}}}function JA(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:is(o.current),target:is(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 eO(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:is(o.credit),energy:is(o.energy)}:null}).filter(a=>a!==null)}function zi(e){return ms.growth.get(e)??{status:"idle",energy:null,streak:null,tasks:[],travel:null,school:null,running:!1,runningSchool:!1,runningTravel:!1}}function Ar(e,t){const a=new Map(ms.growth);a.set(e,{...zi(e),...t}),Js({growth:a})}function mq(e){return ms.expanded.has(`growth:${e}`)}function tO(e){const t=`growth:${e}`,a=new Set(ms.expanded);a.has(t)?a.delete(t):a.add(t),Js({expanded:a})}async function og(e){const t=zi(e);if(!(t.status==="loading"||t.running)){Ar(e,{status:"loading",error:void 0});try{const a=await Rr().getGrowthStatus?.(e),o=a?.tasks??{},c=a?.travel??null,d=a?.school??null;Ar(e,{status:"loaded",checkedAt:Date.now(),energy:a?.energy===null||a?.energy===void 0?null:is(a.energy),streak:a?.streak===null||a?.streak===void 0?null:is(a.streak),tasks:JA(o.tasks),travel:c,school:d?{...d,tasks:JA(d.tasks)}:null,error:typeof o.error=="string"?o.error:void 0})}catch(a){Ar(e,{status:"error",error:mt(a)})}}}async function nO(e,t){const a=zi(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){He(r("没有需要执行的任务"));return}Ar(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 Rr().runGrowthTask?.(e,g.code,t),y=eO([v])[0];y&&(Ar(e,{results:[...zi(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,Ar(e,{results:[...zi(e).results??[],{code:g.code,outcome:"failed",message:mt(v),credit:0,energy:0}]})}Ar(e,{running:!1}),p>0?He(r("成长任务完成({done} 项成功、{failed} 项失败),积分 +{credit} 能量 +{energy}",{done:f,failed:p,credit:c,energy:d}),"err"):He(r("✅ 成长任务执行完成:积分 +{credit} 能量 +{energy}",{credit:c,energy:d})),await og(e)}async function hq(e,t){if(!zi(e).runningSchool){Ar(e,{runningSchool:!0,error:void 0});try{const o=await Rr().runGrowthSchool?.(e,t),c=eO(o?.results),d=o?.lottery??null;Ar(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:is(d.drawn)})):void 0,checkedAt:Date.now()}),He(d?r("开学季执行完成:{message}",{message:String(d.message??"")}):r("✅ 开学季任务执行完成")),await og(e)}catch(o){Ar(e,{runningSchool:!1,error:mt(o)}),He(r("开学季执行失败:{error}",{error:mt(o)}),"err")}}}async function gq(e){if(!zi(e).runningTravel){Ar(e,{runningTravel:!0,error:void 0});try{const a=await Rr().runGrowthTravel?.(e),o=String(a?.message??""),c=String(a?.outcome??"");Ar(e,{runningTravel:!1,checkedAt:Date.now()}),c==="failed"?He(r("猫猫旅行失败:{message}",{message:o}),"err"):He(r("猫猫旅行:{message}",{message:o})),await og(e)}catch(a){Ar(e,{runningTravel:!1,error:mt(a)}),He(r("猫猫旅行失败:{error}",{error:mt(a)}),"err")}}}function xq(e){return e.totalCount?e.doneCount>=e.totalCount?"done":e.doneCount>0?"part":"todo":"none"}function bq(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 wo={version:0,data:null,loaded:!1,loadError:"",saving:!1,runningId:null,editingId:null};const Tj=new Set;function vq(){for(const e of Tj)e()}function Or(e){wo={...wo,...e,version:wo.version+1},vq()}function sO(){return wo}function yq(e){return Tj.add(e),()=>Tj.delete(e)}function gu(){return Pe().workbuddyDesktop??{}}async function rO(){try{const e=await gu().getCheckinSchedules?.();if(!e)throw new Error(r("后端未返回定时签到数据"));Or({data:e,loaded:!0,loadError:""})}catch(e){Or({loaded:!0,loadError:mt(e)})}}function ig(e){e&&Or({data:e,loadError:""}),Rl()}async function jq(e){if(!wo.saving){Or({saving:!0});try{const t=await gu().saveAutoCheckin?.({enabled:e});ig(t),He(r(e?"✅ 定时签到已开启":"定时签到已关闭"))}catch(t){He(r("保存失败:{error}",{error:mt(t)}),"err")}finally{Or({saving:!1})}}}async function aO(e){if(!wo.saving){Or({saving:!0});try{const t=await gu().saveCheckinSchedule?.(e);ig(t),Or({editingId:null}),He(r("已保存:定时条目"))}catch(t){He(r("保存失败:{error}",{error:mt(t)}),"err")}finally{Or({saving:!1})}}}async function wq(e,t){await aO({id:e.id,label:e.label??"",enabled:t,time:e.time??"",providers:Array.isArray(e.providers)?e.providers:[]})}async function Sq(e){if(!wo.saving){Or({saving:!0});try{await gu().deleteCheckinSchedule?.(e),ig(await gu().getCheckinSchedules?.()),He(r("已删除定时条目"))}catch(t){He(r("删除失败:{error}",{error:mt(t)}),"err")}finally{Or({saving:!1})}}}async function Nq(e){if(!wo.runningId){Or({runningId:e});try{const t=await gu().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?He(r("签到完成:{succeeded}/{total} 成功{active},{failed} 个失败",{succeeded:o,total:d,active:p,failed:f}),"err"):He(r("✅ 签到完成:{succeeded}/{total} 个账号成功领取{active}",{succeeded:o,total:d,active:p})),ig(t)}}catch(t){He(r("执行失败:{error}",{error:mt(t)}),"err")}finally{Or({runningId:null}),await Rl()}}}function Ej(e){Or({editingId:e})}const kq=r("到点后自动签到勾选提供商的可用账号(WorkBuddy 国内版走每日签到接口,国际版走每日活跃任务:探测活动、领日活奖励、再用免费模型保活;小浣熊走桌面端每日积分链路;AutoClaw 走官方客户端的每日签到任务;Qoder 中国版走活动领取,没被下发活动的账号会得到中性提示;Qoder 国际版要先带设备风控身份(本机 Qoder 客户端 / qodercli 的 UMID 组件生成)才能看到「每日 100 Credits」活动,缺组件时会得到明确的说明而不是报错;Trae 领 SOLO 的每日签到积分(按自然日 0 点重置),上游没对该账号开活动、或凭据里没有设备号时得到的是「未领取 + 具体原因」而不是报错;Loomy 每天替账号打一次首次登录积分;KukuAI 领「免费领积分」的每日任务;CodeArts 领当日的运营福利(领取 → 确认 → 回读核实,自动执行受每天 6 次 / 间隔 10 分钟的写请求限流);OfficeAce 果办一次领当天全部奖励(每日签到 + 新人礼))。错过时点开机后会自动补签,不会因为当时没开机而漏掉。各家签到接口都是幂等的,重复执行不会重复领取。");function Cq(){const[e,t]=x.useState(sO());return x.useEffect(()=>yq(()=>t(sO())),[]),e}function Tq(){const[e,t]=x.useState(ir());return x.useEffect(()=>YA(()=>t(ir())),[]),e}function lO(e,t){const a=Array.isArray(e.providers)?e.providers:[];return t.filter(o=>a.includes(o.id)).map(o=>o.label)}function Eq(e,t){const a=lO(e,t);return a.length?t.length>0&&a.length>=t.length?r("全部 {n} 家",{n:t.length}):a.join(r("、")):r("未勾选提供商")}function Rq(e,t){const a=lO(e,t);return a.length?a.join(r("、")):r("未勾选提供商")}function Aq(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?Us(t.at):"—"}${t.reason?` · ${t.reason}`:""} —— ${o.join(r(" · "))}`}function oO({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 aO({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(Ye,{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(Ye,{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(ta,{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:()=>Ej(null),children:r("取消")}),s.jsx(se,{size:"sm",variant:"default",disabled:!y||t.saving,onClick:()=>{w()},children:t.saving?r("保存中…"):r("保存")})]})]})}function Oq({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(oO,{entry:null,store:e})]})}function Mq({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 Sq(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(ps,{checked:e.enabled===!0,disabled:t.saving,onCheckedChange:g=>{wq(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:Rq(e,a),children:r("每天 {time} · {scope}",{time:e.time??"—",scope:Eq(e,a)})}),s.jsx("div",{className:"ck-prov-desc",children:r("上次执行:{line}",{line:Aq(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:Us(f)}):"—"}),s.jsx(se,{size:"sm",variant:"ghost",disabled:c||t.runningId!==null,onClick:()=>{Nq(e.id)},children:r(c?"执行中…":"立即执行")}),s.jsx(se,{size:"sm",variant:"ghost",onClick:()=>Ej(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(oO,{entry:e,store:t}):null]})}function Dq(e,t){return e.length===t.length&&e.every((a,o)=>a===t[o])}let kf=null;function Iq(e,t){for(let a=0;ag!==t.row),d=Iq(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 Cf(){const e=kf;kf=null,window.removeEventListener("pointermove",iO),window.removeEventListener("pointerup",Cf),window.removeEventListener("pointercancel",Cf),document.body.classList.remove("ck-chain-dragging"),e?.row.classList.remove("dragging")}function Pq(e,t,a,o){if(e.button!==0||kf||a.length<2)return;const c=e.currentTarget.closest(".ck-chain-row");c&&(e.preventDefault(),kf={list:[...a],from:t,row:c,onChange:o},c.classList.add("dragging"),document.body.classList.add("ck-chain-dragging"),window.addEventListener("pointermove",iO),window.addEventListener("pointerup",Cf),window.addEventListener("pointercancel",Cf))}function _q({models:e,defaultModels:t,dirty:a,saving:o}){const[c,d]=x.useState(""),f=()=>{const p=c.trim();if(p){if(e.includes(p)){He(r("清单里已经有「{name}」",{name:p}),"err");return}lg([...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:()=>{fq(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:()=>lg([...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=>Pq(v,g,e,lg),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:()=>lg(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(Ye,{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 Lq(){const e=Cq(),t=Tq();if(x.useEffect(()=>{rO()},[]),!e.loaded)return s.jsxs("div",{className:"ck-loading",children:[s.jsx($d,{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&&!Dq(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:()=>{rO()},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":kq}),s.jsx("span",{className:"panel-sub",children:r("每条条目各有时刻与范围 · 各自当天去重 · 错过时点开机自动补签")}),s.jsx(se,{size:"sm",variant:"outline",className:"ml-auto flex-none",disabled:e.saving,onClick:()=>Ej(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(ps,{checked:o,disabled:e.saving,onCheckedChange:b=>{jq(b===!0)}}),s.jsx("span",{className:"text-subtle text-xs",children:r(o?"开着:启用的条目按各自时刻执行":"关着:所有条目都不执行")})]})]})}),s.jsxs("div",{children:[e.editingId==="new"?s.jsx(Oq,{store:e}):null,c.map(b=>s.jsx(Mq,{entry:b,store:e},b.id)),c.length===0?s.jsx("div",{className:"ck-empty",children:r("还没有定时条目 —— 点「添加条目」建一条,或到「签到中心」手动签到。")}):null]})]}),s.jsx(_q,{models:v,defaultModels:p,dirty:y,saving:t.keepaliveSaving})]})}const cg="checkin-records",cO=["today","7","30","month","all"],xu="all",zq=[{value:"today",label:r("今天")},{value:"7",label:r("7 天")},{value:"30",label:r("30 天")},{value:"month",label:r("本月")},{value:"all",label:r("全部")}],uO="workbuddy-desktop-checkin-records-range";function ug(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function dO(e){const t=new Date;switch(e){case"today":return ug(t);case"7":return ug(new Date(t.getFullYear(),t.getMonth(),t.getDate()-6));case"30":return ug(new Date(t.getFullYear(),t.getMonth(),t.getDate()-29));case"month":return ug(new Date(t.getFullYear(),t.getMonth(),1));default:return null}}function Bq(){try{const e=localStorage.getItem(uO);return e!==null&&cO.includes(e)?e:xu}catch{return xu}}function fO(e){try{localStorage.setItem(uO,e)}catch{}}function pO(e){return typeof e=="number"&&e>0?e:lu}const Rj={success:{label:"成功领取",variant:"success"},already:{label:"今日已领",variant:"brand"},pending:{label:"等待窗口",variant:"warning"},failed:{label:"失败",variant:"destructive"}},Hq={schedule:"定时",startup:"补签",manual:"手动",single:"单签",activity:"活动"},Aj=[{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 Oj=null;function mO(){return Oj?Oj.apply([...Aj]):Aj.map(e=>({...e,align:e.align??"left"}))}function hO(){window.wbTableColumns?.repaint?.(cg)}function gO(e){return(ir().snapshot?.auto?.providerOptions??[]).find(a=>a.id===e)?.label??e}function Uq(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?Us(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?gO(e.provider):"—"},t.key);case"source":return s.jsxs("td",{className:a,children:[s.jsx("span",{className:"ck-record-source",children:Hq[e.source??""]??e.source??"—"}),e.reason?s.jsx("span",{className:"ck-record-reason",children:e.reason}):null]},t.key);case"outcome":{const o=Rj[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 Vq(){const[e,t]=x.useState([]),[a,o]=x.useState(0),[c,d]=x.useState(1),[f,p]=x.useState(()=>Bq()),[g,v]=x.useState(()=>pO(Vh(cg,Hh))),[y,b]=x.useState({outcome:"",provider:"",keyword:""}),[j,w]=x.useState(""),[S,N]=x.useState(!1),[k,E]=x.useState(""),[R,C]=x.useState(0),A=x.useRef(null),D=x.useRef(0),[,I]=x.useReducer(G=>G+1,0),M=ir().snapshot?.auto?.providerOptions??[],O=mO(),_=Math.max(1,Math.ceil(a/g)),L=Math.min(c,_),z=y.outcome!==""||y.provider!==""||y.keyword!==""||f!==xu,U=a?{start:(L-1)*g+1,end:Math.min(a,L*g)}:null,B=x.useCallback(async G=>{const F=D.current+1;D.current=F,N(!0),E("");try{const X=await Pe().workbuddyDesktop?.getCheckinRecords?.({limit:G.size,offset:(G.page-1)*G.size,outcome:G.filters.outcome,provider:G.filters.provider,keyword:G.filters.keyword,start:dO(G.range)});if(F!==D.current)return;t(Array.isArray(X?.records)?X.records:[]),o(Number(X?.total)||0)}catch($){if(F!==D.current)return;E($ instanceof Error?$.message:String($))}finally{F===D.current&&N(!1)}},[]);x.useEffect(()=>{B({page:c,size:g,range:f,filters:y})},[B,c,g,f,y]),x.useEffect(()=>{c>_&&d(_)},[c,_]),x.useLayoutEffect(()=>{const G=Pe().wbColSettings;if(!G?.register){const F=window.setTimeout(()=>C($=>$+1),50);return()=>window.clearTimeout(F)}Oj=G.register({id:cg,label:r("签到记录表"),columns:Aj.map(F=>({key:F.key,label:F.label,align:F.align??"left"})),mount:()=>A.current,onChange:()=>{Ns.flushSync(()=>I()),hO()}}),I()},[R]),x.useLayoutEffect(()=>{hO()}),x.useEffect(()=>()=>{Pe().wbColSettings?.close()},[]);const Q=G=>{b(G),d(1)},W=G=>{const F=cO.includes(G)?G:xu;F!==f&&(fO(F),p(F),d(1))},Z=G=>{v(pO(G)),Fh(cg,G),d(1)},Y=()=>{w(""),fO(xu),p(xu),Q({outcome:"",provider:"",keyword:""})},q=async()=>{const G=Pe().wbConfirm?.ask;if(!G)return;const F=r(z?"确定清空当前筛选出的签到记录?清空后无法恢复。":"确定清空全部签到记录?清空后无法恢复。");if(await G({title:r("清空签到记录"),html:F,okText:r("清空"),okClass:"danger"}))try{await Pe().workbuddyDesktop?.clearCheckinRecords?.(z?{outcome:y.outcome,provider:y.provider,keyword:y.keyword,start:dO(f)}:{all:"1"}),xO("签到记录已清空"),await B({page:1,size:g,range:f,filters:y}),d(1)}catch($){xO(r("清空失败:{error}",{error:$ instanceof Error?$.message:String($)}),"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:()=>{B({page:c,size:g,range:f,filters:y})},children:r(S?"刷新中…":"刷新")}),s.jsx(se,{size:"sm",variant:"ghost",className:"text-destructive",onClick:()=>{q()},children:r("清空")})]})]}),s.jsxs("div",{className:"ck-records-filters",children:[s.jsx(Pn,{options:zq,value:f,onValueChange:W,"aria-label":r("签到记录时间范围"),className:"shrink-0"}),s.jsxs(ut,{value:y.outcome,onValueChange:G=>Q({...y,outcome:G??""}),children:[s.jsx(ft,{className:"w-[128px] shrink-0","aria-label":r("按结果筛选"),children:s.jsx(dt,{children:y.outcome?Rj[y.outcome]?.label??y.outcome:r("全部结果")})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"",children:r("全部结果")}),Object.entries(Rj).map(([G,F])=>s.jsx(Xe,{value:G,children:F.label},G))]})]}),s.jsxs(ut,{value:y.provider,onValueChange:G=>Q({...y,provider:G??""}),children:[s.jsx(ft,{className:"w-[148px] shrink-0","aria-label":r("按提供商筛选"),children:s.jsx(dt,{children:y.provider?gO(y.provider):r("全部提供商")})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"",children:r("全部提供商")}),M.map(G=>s.jsx(Xe,{value:G.id,children:G.label},G.id))]})]}),s.jsx("div",{className:"spacer"}),s.jsx(Ye,{type:"search",className:"ck-records-search w-[200px] basis-[200px] min-w-[150px] grow-0 shrink",placeholder:r("搜账号 / 收益 / 错误 / 触发原因"),value:j,onChange:G=>w(G.currentTarget.value),onBlur:()=>{j!==y.keyword&&Q({...y,keyword:j.trim()})},onKeyDown:G=>{G.key==="Enter"&&G.currentTarget.blur(),G.key==="Escape"&&(w(y.keyword),G.currentTarget.blur())}}),z?s.jsx(se,{size:"sm",variant:"ghost",onClick:Y,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:()=>{B({page:c,size:g,range:f,filters:y})},children:r("重试")})]}):null,e.length===0&&!S?s.jsx("div",{className:"ck-empty",children:r(z?"没有符合筛选条件的签到记录":"还没有签到记录 —— 手动签到或等定时条目执行后,明细会出现在这里。")}):s.jsx("div",{className:"ck-records-scroll",children:s.jsxs("table",{className:"ck-table ck-records-table",children:[s.jsx("colgroup",{children:O.map(G=>s.jsx("col",{"data-col":G.key,className:`ck-col-${G.key}`},G.key))}),s.jsx("thead",{children:s.jsx("tr",{children:O.map(G=>s.jsx("th",{"data-col":G.key,className:`ck-col-${G.key} ta-${G.align}`,children:G.label},G.key))})}),s.jsx("tbody",{children:e.map(G=>s.jsx("tr",{children:O.map(F=>Uq(G,F))},G.rowId))})]})}),s.jsx(Di,{total:a,range:U,page:L,pageCount:_,size:g,sizes:Hh,onSizeChange:Z,onPageChange:d,disabled:S})]})}function xO(e,t){Pe().wbApp?.toast?.(e,t)}window.wbCheckinRecords={visibleColumns:()=>mO().map(e=>({key:e.key}))};const bO={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("每日福利 · 领取 → 确认 → 回读核实 · 按北京时间自然日重置")},Fq=[{value:"center",label:r("签到中心")},{value:"schedule",label:r("定时签到")},{value:"records",label:r("签到记录")}];function $q(e){return e==="raccoon"?"小浣熊":e==="loomy"?"Loomy":e==="codearts"?"CodeArts":e==="officeace"?"OfficeAce 果办":e}function qq(){const[e,t]=x.useState(ir());return x.useEffect(()=>YA(()=>t(ir())),[]),e}function Gq({group:e}){const t=xq(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 Tf({id:e,label:t}){const a=Xh[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 Kq({group:e}){const t=ir().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?Us(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:()=>{ag(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:()=>{ag(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:()=>{ag(o.id,"full")},children:a(o.id,"full")?r("执行中…"):r("保活+领取")})]}):s.jsx(se,{size:"sm",variant:"ghost",disabled:a(o.id,"checkin"),onClick:()=>{ag(o.id)},children:a(o.id,"checkin")?r("签到中…"):o.checkedInToday?r("重签"):r("签到")})})]},o.id)})})]})}function Yq({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&&XA(e.id),onKeyDown:o=>{a&&(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),XA(e.id))},role:a?"button":void 0,tabIndex:a?0:-1,"aria-expanded":a?t:void 0,children:[s.jsx(Tf,{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:bO[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(Gq,{group:e}),a?s.jsx("span",{className:"ck-chev","aria-hidden":!0,children:"›"}):null]})]}),e.id==="qoder-intl"?s.jsx(vO,{}):null,t?s.jsx("div",{className:"ck-prov-detail",children:s.jsx(Kq,{group:e})}):null]})}function vO(){const[e,t]=x.useState(null),a=x.useCallback(async()=>{try{t(await Rr().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 Rr().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 Xq({row:e}){const t=e.provider??"loomy",a=ir().onboarding.get(e.id),o=a?.tasks??[],c=a?.unclaimed??0,d=a?.status==="loaded"&&o.length>0,f=d&&QA(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?()=>kj(e.id):void 0,onKeyDown:p=>{d&&(p.key==="Enter"||p.key===" ")&&(p.preventDefault(),kj(e.id))},role:d?"button":void 0,tabIndex:d?0:-1,"aria-expanded":d?f:void 0,children:[s.jsx(Tf,{id:t,label:$q(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:Us(a.settledAt)})}`:a?.checkedAt?` · ${r("查询于 {time}",{time:Us(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:()=>{Cj(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:()=>{WA(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 Qq({row:e}){const t=Rh({claimPlans:e.claimPlans}),a=t.length>0;return s.jsxs("div",{className:"ck-welfare-row",children:[s.jsx(Tf,{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:Us(e.claimAt)}):r("限时体验套餐(start-plan),活动期内每天一份 · 领取需滑块验证码")})]}),s.jsx("div",{className:"ck-prov-right",children:s.jsx(se,{size:"sm",variant:"outline",onClick:()=>FR(e.id,e.name),children:r(a?"套餐明细":"去领取")})})]})}function Zq({row:e}){const t=ir().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&&mq(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?()=>tO(e.id):void 0,onKeyDown:b=>{d&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),tO(e.id))},role:d?"button":void 0,tabIndex:d?0:-1,"aria-expanded":d?f:void 0,children:[s.jsx(Tf,{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:Us(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:()=>{og(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:()=>{nO(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:()=>{nO(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:()=>{gq(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:()=>{hq(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 Wq({group:e}){return s.jsxs("div",{className:"ck-prov-row",children:[s.jsxs("div",{className:"ck-prov-main",style:{cursor:"default"},children:[s.jsx(Tf,{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:bO[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(vO,{}):null]})}function Jq({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=bq(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(qd,{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:()=>{rg("schedule")},role:"button",tabIndex:0,onKeyDown:N=>{N.key==="Enter"&&rg("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:Us(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:()=>{rg("records")},role:"button",tabIndex:0,onKeyDown:N=>{N.key==="Enter"&&rg("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:()=>{dq()},children:e.runningAll||d?.running===!0?r("签到中…"):r("立即全部签到")})]}),s.jsxs("div",{children:[(c?.providers??[]).map(N=>N.totalCount>0?s.jsx(Yq,{group:N,expanded:e.expanded.has(N.id)},N.id):s.jsx(Wq,{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"||Cj(N.id)},children:r("全部查询")}):null]}),p.length?s.jsx("div",{children:p.map(N=>s.jsx(Xq,{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(Qq,{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(Zq,{row:N},N.id))}):s.jsx("div",{className:"ck-empty",children:r("没有支持成长任务的账号(需要 WorkBuddy 国内版)。")})]})]})]})}function eG(){const e=qq(),t=e.snapshot;if(x.useEffect(()=>{Rl()},[]),x.useEffect(()=>{window.wbApp?.renderTopbarStatus?.()},[e.version]),!e.loaded)return s.jsxs("div",{className:"ck-loading",children:[s.jsx($d,{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:()=>{Rl()},children:r("重试")})]}):null,s.jsxs("div",{className:"ck-tabs",children:[s.jsx(Pn,{options:Fq,value:e.tab,onValueChange:c=>KA(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(Jq,{store:e}):null,e.tab==="schedule"?s.jsx(Lq,{}):null,e.tab==="records"?s.jsx(Vq,{}):null]})}const yO='.page[data-page="checkin"]';let jO=!1;function wO(){if(jO)return;const e=document.querySelector(yO);e&&(jO=!0,e.replaceChildren(),wn.createRoot(e).render(s.jsx(eG,{})))}const SO=()=>Rl();window.wbCheckinPanel={load:SO},document.querySelector(yO)?wO():document.addEventListener("DOMContentLoaded",wO,{once:!0}),Pe().wbApp?.currentPage==="checkin"&&SO();function tG(e){return String(e??"").replace(/&/g,"&").replace(//g,">").replace(/"/g,""")}function nG({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(CU,{open:!0,onOpenChange:y=>{y||t(!1)},children:s.jsxs(AU,{initialFocus:v,showCloseButton:!0,children:[s.jsx(OU,{className:"pr-10",children:s.jsx(EU,{children:a})}),s.jsx(MU,{children:s.jsx(IU,{tone:p==="danger-zone"?"danger":"neutral",dangerouslySetInnerHTML:{__html:o||tG(c).replace(/\n/g,"
")}})}),s.jsxs(DU,{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 Ef=null,bu=null,dg=null;function sG(){Ef&&(Ef.unmount(),Ef=null),bu&&(bu.remove(),bu=null)}function NO(e){const t=dg;dg=null,sG(),t?.(e)}function rG(e={}){return new Promise(t=>{dg&&NO(!1),dg=t,bu=document.createElement("div"),document.body.append(bu),Ef=wn.createRoot(bu),Ef.render(s.jsx(nG,{options:e,onSettle:NO}))})}window.wbConfirm={ask:rG};const aG=r("Base URL 填进客户端的「API 地址 / Base URL」栏;对话协议按客户端支持的类型三选一(Chat Completions / Responses / Anthropic Messages),三者共用同一套模型与账号池,可随时切换;鉴权用「网关 Key」页里任一启用 Key。");function Rf({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 lG(){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":aG})]}),s.jsxs("div",{className:"ep-list",children:[s.jsx(Rf,{id:"api-base",name:"Base URL",note:r("填进客户端的「API 地址 / Base URL」")}),s.jsx("div",{className:"ep-group",children:r("对话协议(按客户端支持的类型选一行)")}),s.jsx(Rf,{id:"api-chat",name:"OpenAI Chat Completions",note:r("多数 OpenAI 兼容客户端的默认协议")}),s.jsx(Rf,{id:"api-responses",name:"OpenAI Responses",note:r("OpenAI 新协议(Codex、新版 SDK)")}),s.jsx(Rf,{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(Rf,{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 kO='.page[data-page="docs"]';let CO=!1;function TO(){if(CO)return;const e=document.querySelector(kO);e&&(CO=!0,e.replaceChildren(),wn.createRoot(e).render(s.jsx(lG,{})))}document.querySelector(kO)?TO():document.addEventListener("DOMContentLoaded",TO,{once:!0});function la(){return window}function Mj(e){return e instanceof Error?e.message:String(e)}function Af(e,t){la().wbApp?.toast?.(e,t)}function oG(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}const Dj=[{key:"name",label:r("名称")},{key:"key",label:"Key"},{key:"time",label:r("创建时间")},{key:"state",label:r("启用")},{key:"act",label:r("操作"),align:"right"}],iG={name:"cell-name",key:"cell-key",time:"cell-time",state:"cell-state state",act:"cell-act r"},EO='.page[data-page="keys"]';let fg=null,Ij=null;function RO(){return fg?fg.apply([...Dj]):Dj.map(e=>({...e,align:e.align??"left"}))}function AO(){la().wbColSettings?.syncStaticHead?.("keys",document.querySelector("table.keys-table"))}function cG(){if(fg)return;const e=la().wbColSettings?.register({id:"keys",label:r("网关 Key 表"),columns:Dj,mount:()=>document.querySelector('.page[data-page="keys"] .panel-head .head-actions'),onChange:()=>{AO(),Ij?.()}});e&&(fg=e,AO())}function uG(e){return Array.isArray(e?.keys)?e.keys:[]}function dG(e){return Array.isArray(e?.providers)?e.providers:[]}function fG(e){const t=e?.modelsByProvider;return t&&typeof t=="object"?t:{}}function Pj(e){return la().wbProviders?.labelOf?.(e)||e}function pG(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 MO(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 xG({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(()=>OO(e?.allowedProviders)),[R,C]=x.useState(()=>OO(e?.allowedModels)),A=x.useMemo(()=>t.map(z=>({value:String(z.id),label:r(String(z.label??z.id))})),[t]),D=x.useMemo(()=>MO(k,A),[k,A]),I=x.useMemo(()=>pG(a,D,R),[a,D,R]),M=x.useMemo(()=>MO(R,I),[R,I]),O=I.length?r("没有匹配的选项"):D.length?r("这几家当前没有可用模型(账号未登录或清单为空)"):r("请先在上面选择可用提供商");function _(){N.current=!1,S(!1)}async function L(){if(!N.current){N.current=!0,S(!0),j(r("保存中…"));try{const z=la().workbuddyDesktop;if(!z)throw new Error(r("后端桥不可用"));if(d){const Q=await z.updateKey(d,{allowedProviders:D,allowedModels:M});_(),c(Q),o(),Af(r("✅ 可用范围已保存"));return}const U=v.trim();if(U&&U.length<8){j(r("Key 至少需要 8 个字符"));return}const B=await z.createKey({name:p.trim(),key:U||void 0,allowedProviders:D,allowedModels:M});_(),c(B,B?.created?.id),o(),Af(r("✅ Key 已创建,记得复制给客户端"))}catch(z){j(r("保存失败:{reason}",{reason:Mj(z)}))}finally{_()}}}return s.jsx(Kt,{open:!0,onOpenChange:(z,U)=>{if(!z){if(N.current){U.cancel();return}o()}},children:s.jsxs(Yt,{children:[s.jsx($t,{children:s.jsx(Ft,{children:f?r("可用范围 · {name}",{name:e?.name||r("未命名")}):r("新建 API Key")})}),s.jsxs(_t,{children:[s.jsxs(Hn,{children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(st,{htmlFor:"key-name",className:"text-[12.5px] whitespace-nowrap text-subtle",children:r("名称")}),s.jsx(Ye,{id:"key-name",type:"text",maxLength:60,placeholder:r("例如 Cursor / 公司电脑"),autoComplete:"off",value:p,disabled:f,onChange:z=>g(z.currentTarget.value)})]}),!f&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(st,{htmlFor:"key-value",className:"text-[12.5px] whitespace-nowrap text-subtle",children:"Key"}),s.jsx(Ye,{id:"key-value",type:"text",placeholder:r("留空自动生成;手填至少 8 个字符"),autoComplete:"off",spellCheck:!1,value:v,onChange:z=>y(z.currentTarget.value),onKeyDown:z=>{z.key==="Enter"&&L()}})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(st,{className:"text-[12.5px] whitespace-nowrap text-subtle",children:r("可用提供商")}),s.jsx(_y,{value:D,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(st,{className:"text-[12.5px] whitespace-nowrap text-subtle",children:r("可用模型")}),s.jsx(_y,{value:M,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:gG(D,M)})]}),s.jsx("div",{className:"min-h-[18px] text-[11.5px] text-muted-foreground",children:b})]}),s.jsxs(en,{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 pg=null;async function bG(){await pg?.load()}function vG(){pg?.render()}function yG(){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=la().workbuddyDesktop;if(!L)throw new Error(r("后端桥不可用"));b(await L.getKeys()??null)}catch(L){Af(r("读取 Key 列表失败:{reason}",{reason:Mj(L)}),"err")}finally{y.current=!1}}},[b]);async function S(L,z,U){if(!v.current.has(L)){v.current.add(L),d(new Set(v.current));try{j(await z()),U&&Af(U)}catch(B){Af(r("操作失败:{reason}",{reason:Mj(B)}),"err")}finally{v.current.delete(L),d(new Set(v.current))}}}function N(L){o(z=>{const U=new Set(z);return U.has(L)?U.delete(L):U.add(L),U})}async function k(L){const z=la().workbuddyDesktop,U=la().wbConfirm?.ask;if(!z||!U)return;const B=oG(L.name||L.masked||L.id);await U({title:r("删除网关 Key"),html:r("确定删除 Key「{name}」?使用它的客户端会立刻无法访问。",{name:B}),okText:r("删除"),okClass:"danger"})&&S(L.id,()=>z.deleteKey(L.id),r("Key 已删除"))}function E(L,z){const U=la().workbuddyDesktop;U&&S(L.id,()=>U.updateKey(L.id,{enabled:z}),r(z?"Key 已启用":"Key 已停用"))}x.useLayoutEffect(()=>(pg={load:w,render:()=>g(L=>L+1)},Ij=()=>g(L=>L+1),cG(),g(L=>L+1),()=>{pg=null,Ij=null}),[w]),x.useEffect(()=>{la().wbApp?.currentPage==="keys"&&w()},[w]),x.useEffect(()=>{la().wbApp?.renderTopbarStatus?.()},[e]);const R=uG(e),C=$h(R.length,"keys"),A=C.paged?C.slice(R):R,D=RO(),I=e?.authRequired===!0,M=A.filter(L=>L.enabled).length,O=I?r("已启用鉴权 · {n} 把 Key 生效",{n:M}):r("未启用鉴权");function _(L,z,U){switch(L){case"name":return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"mid",children:s.jsx("span",{className:"t",children:z.name||r("未命名")})}),s.jsx("div",{className:"mname",title:hG(z),children:mG(z)})]});case"key":{const B=a.has(z.id);return s.jsxs("div",{className:"keycell",children:[s.jsx("code",{className:"kv",children:B?z.key:z.masked}),s.jsx(se,{size:"sm",variant:"ghost",onClick:()=>N(z.id),children:r(B?"隐藏":"显示")}),s.jsx(se,{size:"sm",variant:"ghost","data-copy":z.key,title:r("复制 Key"),children:r("复制")})]})}case"time":return s.jsx("span",{className:"muted",children:z.createdAt?la().wbApp?.formatTime?.(z.createdAt):"—"});case"state":return s.jsx(ps,{checked:z.enabled===!0,disabled:U,"aria-label":r("启用「{name}」",{name:z.name||r("未命名")}),onCheckedChange:B=>E(z,B)});case"act":return s.jsxs("div",{className:"row-actions",children:[s.jsx(se,{size:"sm",variant:"ghost",disabled:U,onClick:()=>p({key:z}),children:r("可用范围")}),s.jsx(se,{size:"sm",variant:"destructive",disabled:U,onClick:()=>{k(z)},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 z=c.has(L.id);return s.jsx("tr",{className:L.enabled?"":"off","data-id":L.id,children:D.map(U=>s.jsx("td",{className:`${iG[U.key]??""} ta-${U.align}`,children:_(U.key,L,z)},U.key))},L.id)}):s.jsx("tr",{children:s.jsx("td",{colSpan:D.length,className:"empty",children:r(e?"还没有 Key,当前不鉴权":"加载中…")})})})]})}),s.jsx(Di,{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:R.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(xG,{target:f.key,providers:dG(e),modelsByProvider:fG(e),onClose:()=>p(null),onSaved:(L,z)=>{z&&o(U=>new Set(U).add(z)),j(L)}}):null]})}let DO=!1;function IO(){if(DO)return;const e=document.querySelector(EO);e&&(DO=!0,e.replaceChildren(),wn.createRoot(e).render(s.jsx(yG,{})))}document.querySelector(EO)?IO():document.addEventListener("DOMContentLoaded",IO,{once:!0}),window.wbKeysPanel={load:bG,render:vG,visibleColumns:RO};const jG="login-app",wG=x.createElement("panel-captcha",{id:"captcha"});function SG(){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(st,{htmlFor:"username",className:"mt-3.5 mb-[5px] text-[12.5px]",children:r("账号")}),s.jsx(Ye,{id:"username",autoComplete:"username",placeholder:r("管理员账号")}),s.jsx(st,{htmlFor:"password",className:"mt-3.5 mb-[5px] text-[12.5px]",children:r("密码")}),s.jsx(Ye,{id:"password",type:"password",autoComplete:"new-password",placeholder:r("至少 8 位")}),wG,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 NG(){const e=document.getElementById(jG);e&&Ns.flushSync(()=>{wn.createRoot(e).render(s.jsx(SG,{}))})}NG();function Mr(){return window}function _j(e){return e instanceof Error?e.message:String(e)}function mg(e,t){Mr().wbApp?.toast?.(e,t)}const PO=1e3,kG=Uh,CG=500,_O="workbuddy-desktop-logs-range",Lj="workbuddy-desktop-logs-filters",TG=300,EG="~/.agent2api/logs.jsonl",zj=["today","7","30","month","all"],Bj="all",RG={today:r("今天"),7:r("7 天"),30:r("30 天"),month:r("本月"),all:r("全部")},AG=zj.map(e=>({value:e,label:RG[e]})),Hj=[{value:"",label:r("全部级别")},{value:"debug",label:r("debug 及以上")},{value:"info",label:r("info 及以上")},{value:"warn",label:r("warn 及以上")},{value:"error",label:r("仅 error")}],OG=r("全部级别"),LO=r("全部分类"),MG={debug:r("调试"),info:r("信息"),warn:r("警告"),error:r("错误")};let hg=PO,gg=!0,Uj=!1,Vj=!1,Fj=!1,$j=null,So=null,qj=null,xg=null,Gj=!1,Kj=!1;const Yj={level:"",category:"",keyword:""};function DG(){const e=Mr().wbFilterMemory;if(!e)return{...Yj};Gj=!0;const t=e.load(Lj,{...Yj});return{level:Hj.some(a=>a.value===t.level)?t.level:"",category:t.category,keyword:t.keyword}}function bg(e){Mr().wbFilterMemory?.save(Lj,{level:e.level||"",category:e.category||"",keyword:e.keyword.trim()||""})}function IG(){try{const e=localStorage.getItem(_O);return e!==null&&zj.includes(e)?e:Bj}catch{return Bj}}function PG(e){try{localStorage.setItem(_O,e)}catch{}}function vg(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function _G(e){const t=new Date;switch(e){case"today":return vg(t);case"7":return vg(new Date(t.getFullYear(),t.getMonth(),t.getDate()-6));case"30":return vg(new Date(t.getFullYear(),t.getMonth(),t.getDate()-29));case"month":return vg(new Date(t.getFullYear(),t.getMonth(),1));default:return null}}function LG(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 zG(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 Xj(e){return Array.isArray(e?.entries)?e.entries:[]}function yg(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 Qj(e,t){return Object.hasOwn(e,t)}function BG(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 zO(e,t){const a=new URLSearchParams,o=e.keyword.trim(),c=_G(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 HG(e,t){const a=zO(e,t);return a.set("limit",String(CG)),a.toString()}function UG(e,t){return zO(e,t).toString()}function VG(e){$j=e||null,Mr().wbApp?.updateLogsBadge?.($j)}async function FG(){if(!Uj)try{const e=await Mr().workbuddyDesktop?.getScheduledTasks(),t=(e?.tasks||[]).find(a=>a.id==="logsAutoRefresh");Zj(t||null),Uj=Array.isArray(e?.tasks)}catch(e){console.warn("读取日志自动刷新间隔失败,按默认 10 秒:",_j(e)),Zj(null)}}function Zj(e){Uj=!0;const t=Number(e?.interval);!!e&&typeof e=="object"&&Number.isFinite(t)&&t>0&&(e.unit==="seconds"||e.unit==="minutes")?(gg=e.enabled!==!1,hg=e.unit==="minutes"?t*6e4:t*1e3):(gg=!0,hg=PO),So?.applyAutoConfig(hg,gg)}async function $G(e={}){await So?.load(e)}function qG(e){if(!So){xg={data:e??null};return}So.render(e)}function GG(){return $j}async function KG(e){if(!So){qj=e;return}await So.showCategory(e)}const YG={entries:[],total:0,matched:0,file:EG,categories:{},loaded:!1};function Wj(e,t){return{entries:Xj(e),total:Number(e?.total)||0,matched:Number(e?.matched)||0,file:e?.file||t.file,categories:Object.keys(t.categories).length?t.categories:BG(e?.categories),loaded:!0}}function XG(e){return e.loaded?e.total?r("没有符合筛选条件的日志"):r("暂无日志"):r("正在加载日志…")}function QG(){const[e,t]=x.useState(YG),[a,o]=x.useState(DG),[c,d]=x.useState(IG),[f,p]=x.useState(1),[g,v]=x.useState(()=>Vh("logs")),[y,b]=x.useState(null),[j,w]=x.useState(()=>({ms:hg,enabled:gg})),S=x.useRef(null),N=x.useRef(null),k=x.useRef(null),E=x.useRef(null),R=x.useRef(a),C=x.useRef(c),A=x.useRef(f),D=x.useRef(g),I=x.useRef(e),M=x.useCallback(ne=>{const ce={...R.current,...ne};return R.current=ce,o(ce),ce},[]),O=x.useCallback(ne=>{C.current=ne,d(ne)},[]),_=x.useCallback(ne=>{A.current=ne,p(ne)},[]),L=x.useCallback(ne=>{D.current=ne,v(ne),Fh("logs",ne)},[]),z=x.useCallback(ne=>{I.current=ne,t(ne)},[]),U=x.useCallback(()=>{if(Gj)return;const ne=Mr().wbFilterMemory;if(!ne||(Gj=!0,Kj))return;const ce=ne.load(Lj,{...Yj});M({level:ce.level,category:ce.category,keyword:ce.keyword})},[M]),B=x.useCallback(async(ne={})=>{const{silent:ce=!1,resetPage:we=!1}=ne;we&&_(1),FG(),U();const Ee=HG(R.current,C.current),ve=A.current;try{const ke=Mr().workbuddyDesktop;if(!ke)throw new Error(r("后端桥不可用"));const[Ce,Se]=await Promise.all([ke.getLogs(Ee),ke.getLogStats()]),ge=we?0:S.current?.scrollTop??0,Te=Wj(Ce,I.current);z(Te),_(yg(A.current,Xj(Ce),D.current)),N.current=A.current===ve?ge:0,VG(Se),Object.keys(Te.categories).length&&R.current.category&&!Qj(Te.categories,R.current.category)&&(bg(M({category:""})),B({resetPage:!0}))}catch(ke){ce||(console.warn("读取运行日志失败:",_j(ke)),z(Wj(null,I.current)),_(yg(A.current,[],D.current)))}},[z,_,U]),Q=x.useCallback(ne=>{ne!==void 0&&(z(Wj(ne,I.current)),_(yg(A.current,Xj(ne),D.current)))},[z,_]),W=x.useCallback(async ne=>{if(Qj(I.current.categories,ne)||await B({silent:!0}),!Qj(I.current.categories,ne))return;const ce=M({category:ne});bg(ce),_(1),await B({resetPage:!0}),Mr().wbApp?.showPage?.("logs",{persist:!0})},[M,_,B]);x.useEffect(()=>{if(So={load:B,render:Q,showCategory:W,applyAutoConfig:(ce,we)=>w({ms:ce,enabled:we})},xg){const ce=xg;xg=null,Q(ce.data)}const ne=qj;return ne!==null?(qj=null,W(ne)):B({silent:!0}),()=>{So=null,k.current!==null&&window.clearTimeout(k.current),k.current=null}},[B,Q,W]),x.useEffect(()=>{if(!j.enabled||j.ms<=0)return;const ne=window.setInterval(()=>{document.hidden||Mr().wbApp?.currentPage!=="logs"||Vj||(Vj=!0,B({silent:!0}).finally(()=>{Vj=!1}))},j.ms);return()=>{window.clearInterval(ne)}},[j,B]),x.useLayoutEffect(()=>{const ne=N.current;if(ne===null)return;N.current=null;const ce=S.current;ce&&(ce.scrollTop=ne)});async function Z(ne,ce,we){if(!Fj){Fj=!0,b({which:ne,label:ce});try{await we()}catch(Ee){mg(r("操作失败:{error}",{error:_j(Ee)}),"err")}finally{Fj=!1,b(null)}}}async function Y(){const ne=UG(R.current,C.current),ce=ne.length>0,we=ce?r("确定清空当前筛选出的 {count} 条日志?清空后无法恢复。",{count:Number(I.current.matched)||0}):r("确定清空全部运行日志?清空后无法恢复。"),Ee=Mr().wbConfirm?.ask;Ee&&await Ee({title:r("清空运行日志"),html:we,okText:r("清空"),okClass:"danger"})&&await Z("clear",r("清空中…"),async()=>{const ve=Mr().workbuddyDesktop;if(!ve)throw new Error(r("后端桥不可用"));await ve.clearLogs(ce?ne:"all=1"),await B({resetPage:!0}),mg(r("运行日志已清空"))})}async function q(){await Z("export",r("导出中…"),async()=>{const ne=Mr().workbuddyDesktop;if(!ne)throw new Error(r("后端桥不可用"));const ce=await ne.exportLogs();if(!(!ce||ce.canceled)){if(ce.count===0){mg(r("暂无日志可导出"),"err");return}mg(r("✅ 已导出 {count} 条日志到 {file}",{count:String(ce.count),file:String(ce.file)}))}})}function G(ne){const ce=yg(ne,I.current.entries,D.current);ce!==A.current&&(_(ce),N.current=0)}function F(ne){if(ne===D.current)return;const ce=I.current.entries.length,we=ce?(A.current-1)*(D.current==="all"?ce:D.current):0;L(ne),_(ne==="all"?1:Math.floor(we/ne)+1),N.current=0}function $(ne){Kj=!0,bg(M(ne)),B({resetPage:!0})}function X(ne){Kj=!0,M({keyword:ne}),k.current!==null&&window.clearTimeout(k.current),k.current=window.setTimeout(()=>{k.current=null,bg(R.current),B({resetPage:!0})},TG)}function re(ne){const ce=zj.includes(ne)?ne:Bj;ce!==C.current&&(O(ce),PG(ce),B({resetPage:!0}))}const P=e.entries,V=g!=="all",J=Math.max(1,V?Math.ceil(P.length/g):1),ie=Math.min(Math.max(1,f),J),me=V?P.slice((ie-1)*g,ie*g):P,he=P.length?V?(ie-1)*g+1:1:0,ae=P.length?V?he+me.length-1:P.length:0,oe=e.categories,ee=e.matched===e.total?r("{n} 条",{n:e.total}):r("{matched} / {total} 条",{matched:e.matched,total:e.total});x.useEffect(()=>{const ne=e.loaded?ee:"—";E.current!==ne&&(E.current=ne,Mr().wbApp?.renderTopbarStatus?.())},[e.loaded,ee]);function de(ne,ce){const we=ne.level||"",Ee=zG(ne);return s.jsxs("div",{className:`log-row ${we}`,children:[s.jsx("span",{className:"log-rail",children:s.jsx("span",{className:`log-dot ${we}`})}),s.jsxs("div",{className:"log-main",children:[s.jsxs("div",{className:"log-line",children:[s.jsx("span",{className:"log-cat",children:oe[ne.category||""]||ne.category}),s.jsx("span",{className:`log-lvl ${we}`,children:MG[we]||ne.level}),s.jsx("span",{className:"msg",children:ne.message})]}),Ee?s.jsx("div",{className:"log-extra-wrap",children:s.jsx("span",{className:"extra",children:Ee})}):null]}),s.jsx("span",{className:"time",children:LG(ne.ts)})]},ne.id??ce)}const K=y?.which==="export",be=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:()=>{q()},children:K?y?.label:r("导出")}),s.jsx(se,{id:"btn-logs-clear",variant:"destructive",disabled:y!==null,onClick:()=>{Y()},children:be?y?.label:r("清空")})]})]}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"log-filters",children:[s.jsx(Pn,{options:AG,value:c,onValueChange:re,"aria-label":r("事件日志时间范围"),className:"shrink-0"}),s.jsxs(ut,{value:a.level,onValueChange:ne=>$({level:String(ne??"")}),children:[s.jsx(ft,{id:"logs-level",className:"min-w-[120px]",title:r("按最低级别筛选"),"aria-label":r("按最低级别筛选"),children:s.jsx(dt,{children:Hj.find(ne=>ne.value===a.level)?.label??OG})}),s.jsx(pt,{children:Hj.map(ne=>s.jsx(Xe,{value:ne.value,children:ne.label},ne.value))})]}),s.jsxs(ut,{value:a.category,onValueChange:ne=>$({category:String(ne??"")}),children:[s.jsx(ft,{id:"logs-category",className:"min-w-[120px]",title:r("按分类筛选"),"aria-label":r("按分类筛选"),children:s.jsx(dt,{children:a.category?oe[a.category]||a.category:LO})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"",children:LO}),Object.entries(oe).map(([ne,ce])=>s.jsx(Xe,{value:ne,children:ce},ne))]})]}),s.jsxs(ji,{className:"w-auto flex-auto",children:[s.jsx(Si,{id:"logs-keyword",type:"search",placeholder:r("搜索消息关键词…"),autoComplete:"off","aria-label":r("搜索消息关键词"),value:a.keyword,onChange:ne=>X(ne.currentTarget.value)}),s.jsx(wi,{"aria-hidden":"true",children:"⌕"})]})]}),s.jsx("div",{className:"log-list",id:"log-list",ref:S,children:me.length?me.map((ne,ce)=>de(ne,ce)):s.jsx("div",{className:"log-empty",children:XG(e)})})]}),s.jsx(Di,{total:P.length,range:V?{start:he,end:ae}:null,page:ie,pageCount:J,size:g,sizes:kG,onSizeChange:F,onPageChange:G})]})}const BO='.page[data-page="logs"]';let HO=!1;function UO(){if(HO)return;const e=document.querySelector(BO);e&&(HO=!0,e.replaceChildren(),wn.createRoot(e).render(s.jsx(QG,{})))}document.querySelector(BO)?UO():document.addEventListener("DOMContentLoaded",UO,{once:!0}),window.wbLogsPanel={load:$G,render:qG,lastStats:GG,applyAutoRefresh:Zj,showCategory:KG};const vu=["maxInputTokens","maxOutputTokens","supportsToolCall","supportsImages","supportsVideo","supportsReasoning"],Of=["maxInputTokens","maxOutputTokens"],VO=["supportsToolCall","supportsImages","supportsVideo","supportsReasoning"],yu={maxInputTokens:r("上下文窗口"),maxOutputTokens:r("最大输出 Token"),supportsToolCall:r("工具调用"),supportsImages:r("图片识别"),supportsVideo:r("视频识别"),supportsReasoning:r("支持思考")};r("工具"),r("图片"),r("视频"),r("思考");const ZG=1e8;function Jj(e){return Of.includes(e)}function ew(e,t){if(Jj(e)){const a=typeof t=="number"?t:Number(t);return!Number.isFinite(a)||a<1||a>ZG?null:Math.trunc(a)}return typeof t=="boolean"?t:null}function FO(e){const t={};if(!e||typeof e!="object")return t;const a=e;for(const o of vu){const c=ew(o,a[o]);c!==null&&(t[o]=c)}return t}function tw(e){return Array.isArray(e)?vu.filter(t=>e.some(a=>a===t)):[]}function nw(e){return FO(e?.capabilities)}function $O(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 Mf(e){const t=Number(e);return!Number.isFinite(t)||t<=0?r("未声明"):Math.round(t).toLocaleString("en-US")}function sw(e){return e===!0?"on":e===!1?"off":"unset"}function WG(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 JG(e,t,a,o=""){const c=yu[e],d=a?r("(已被手动覆盖,弹窗里可恢复继承)"):"",f=e7(o);if(Jj(e))return t==null?r("{label}:上游未声明{suffix}",{label:c,suffix:d}):r("{label}:{value}(对下游声明的精确值){origin}{suffix}",{label:c,value:Mf(t),origin:f,suffix:d});const p=sw(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 ju(e,t){const a=e?.capSources?.[t];return a==="upstream"||a==="modelsdev"||a==="user"?a:""}function e7(e){return e==="modelsdev"?r("(由 models.dev 补齐)"):e==="user"?r("(手动设定)"):""}function t7(e){const t={};for(const a of vu){const o=e[a];Jj(a)?t[a]=ew(a,o.trim()):t[a]=o==="on"?!0:o==="off"?!1:null}return t}function Df(){return window}const qO=e=>String(e??"").trim().toLowerCase(),Vs=(e,t)=>qO(e)===qO(t);function Jn(e){return typeof e=="string"&&e.startsWith("custom-")}function Bi(){return(Df().wbProviders?.customList?.()||[]).filter(e=>Jn(e?.id))}function GO(){return Df().wbProviders?.customList?.()||[]}function No(e){return Bi().find(t=>t.id===e)||null}function n7(e){const t=FO(e),a={};for(const o of vu){const c=t[o];(typeof c=="number"||typeof c=="boolean")&&(a[o]=c)}return Object.keys(a).length?a:void 0}function KO(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=n7(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=>Vs(f.alias,c.id)&&Vs(f.target,c.id));d&&(c.enabled=c.enabled&&d.enabled,c.reasoning=d.reasoning||c.reasoning)}const o=a.filter(c=>!(Vs(c.alias,c.target)&&t.some(d=>Vs(d.id,c.target))));return{models:t,mappings:o}}function YO(e){const t=No(e);if(!t)return null;const a=KO(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=>Vs(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 Hi(e,t){const a=Df().wbProviders;if(!a?.customRequest)throw new Error(r("目录模块未就绪"));const o=No(e);if(!o)throw new Error(r("该自定义提供商已不存在(可能已被删除),请刷新后重试"));const c=KO(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 XO(e,t,a,o={}){const{enabled:c,reasoning:d}=o;await Hi(e,f=>{if(Vs(t,a)){const g=f.models.find(v=>Vs(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=>Vs(g.alias,t)&&Vs(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 QO(e,t,a){await Hi(e,o=>{const c=o.mappings.length;if(o.mappings=o.mappings.filter(d=>!(Vs(d.alias,t)&&Vs(d.target,a))),o.mappings.length===c)throw new Error(r("映射「{alias} → {target}」不存在",{alias:t,target:a}));return null})}async function ZO(e,t){const a=String(t??"").trim();if(!a)throw new Error(r("请填写模型 ID"));await Hi(e,o=>{if(o.models.some(c=>Vs(c.id,a)))throw new Error(r("模型「{name}」已存在(忽略大小写判重)",{name:a}));return o.models.push({id:a,enabled:!0,reasoning:""}),null})}async function s7(e,t){const a=(Array.isArray(t)?t:[]).map(o=>String(o??"").trim()).filter(Boolean);if(!a.length)throw new Error(r("没有选中任何模型"));return Hi(e,o=>{let c=0;for(const d of a)o.models.some(f=>Vs(f.id,d))||(o.models.push({id:d,enabled:!0,reasoning:""}),c++);return c})}async function WO(e,t,a){await Hi(e,o=>{const c=o.models.find(f=>Vs(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 JO(e,t){return Hi(e,a=>{const o=a.mappings.length;a.mappings=a.mappings.filter(d=>!Vs(d.target,t));const c=o-a.mappings.length;return a.models=a.models.filter(d=>!Vs(d.id,t)),{removedMappings:c}})}async function r7(e){const t=Df().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 Hi(e,d=>{let f=0;for(const p of o)d.models.some(g=>Vs(g.id,p))||(d.models.push({id:p,enabled:!0,reasoning:""}),f++);return f});return{total:o.length,added:Number(c)||0}}Df().wbModelsCustom={isCustom:Jn,list:Bi,listSource:GO,record:No,buildView:YO,setBinding:XO,removeMapping:QO,addModel:ZO,addModels:s7,removeModel:JO,setCapabilities:WO,fetchModels:r7};const oa="__custom__",a7=["off","none","minimal","low","medium","high","xhigh","max"];function If(e,t){const a=eM(t);if(a.length)return a;const o=e?.reasoningLevels;return Array.isArray(o)&&o.length?o.filter(c=>typeof c=="string"):[...a7]}function eM(e){const t=e?.reasoningLevels;return Array.isArray(t)?t.filter(a=>typeof a=="string"&&a.trim()!==""):[]}function l7(e,t){const a=t.map(eM).filter(f=>f.length>0);if(!a.length||a.length!==t.length)return If(e);const[o,...c]=a,d=o.filter(f=>c.every(p=>p.includes(f)));return d.length?d:If(e)}function tM(e,t,a){return`${String(e??"").trim().toLowerCase()}${String(t??"").trim().toLowerCase()}${String(a??"").trim().toLowerCase()}`}function o7(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(tM(a.alias,a.target,a.provider),o)}return(a,o,c)=>t.get(tM(a,o,c))||""}function Xt(){return window}function ko(e){return e instanceof Error?e.message:String(e)}function vr(e,t){Xt().wbApp?.toast?.(e,t)}function rw(e){const t=Xt().wbApp?.esc;return t?t(e):String(e??"").replace(/[&<>"']/g,a=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[a]||a)}function i7(e){const t=Xt().formatTime??Xt().wbApp?.formatTime;return String(t?.(e)??"")}const nM=e=>String(e??"").trim().toLowerCase(),Co=(e,t)=>nM(e)===nM(t),sM=8,rM="workbuddy-desktop-models-filters",aw=["all","enabled","disabled","mapped"],c7={all:r("全部"),enabled:r("已启用"),disabled:r("已禁用"),mapped:r("有映射")},u7=aw.map(e=>({value:e,label:c7[e]})),lw=["default","rate-asc","rate-desc"],d7={default:r("默认"),"rate-asc":r("倍率升序"),"rate-desc":r("倍率降序")},f7=lw.map(e=>({value:e,label:d7[e]})),ow=[{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"}],aM=new Set(["rate","source"]),Pf="custom-all",iw={models:[],mappings:[]},lM={provider:"all",state:"all",search:"",sort:"default"};function oM(){const e=Xt().wbFilterMemory;if(!e)return{...lM};const t=e.load(rM,{...lM});return{provider:String(t.provider||"all"),state:aw.includes(t.state)?t.state:"all",search:String(t.search||""),sort:lw.includes(t.sort)?t.sort:"default"}}const jg=oM();let iM=!!Xt().wbFilterMemory,wg=!1,es={provider:jg.provider,stateFilter:jg.state,search:jg.search,sort:jg.sort,data:null,expanded:new Set,pending:new Set,mapping:null,customModel:null,capability:null};const cw=new Set;function _f(){return es}function p7(e){return cw.add(e),()=>{cw.delete(e)}}function Ds(e){const t={...es,...e},a=Ng(t),o=Ng(es)!==a;es=a===t.provider?t:{...t,provider:a},h7(),o&&kg();for(const c of cw)c()}function Sg(e){Xt().wbFilterMemory?.save(rM,e)}function cM(){if(iM||wg||!Xt().wbFilterMemory)return;iM=!0;const e=oM();(e.provider!==es.provider||e.state!==es.stateFilter||e.search!==es.search||e.sort!==es.sort)&&Ds(e)}function Ng(e){const t=e.provider;return t==="all"||t===Pf||Bi().some(a=>a.id===t)||Array.isArray(e.data?.models)&&e.data.models.some(a=>(a.provider||"")===t)||!e.data||!uw()?t:"all"}function wu(){return Ng(es)}function uw(){return!!Xt().wbProviders}function Su(){return wu()===Pf}function uM(){return Su()||Jn(wu())}let Lf=null;function dw(e){const t=No(e);return(!Lf||Lf.id!==e||Lf.record!==t)&&(Lf={id:e,record:t,view:YO(e)||iw}),Lf.view}let zf=null;function m7(){const e=GO();if(zf&&zf.directory===e)return zf.view;const t=[],a=[];for(const o of Bi()){const c=dw(String(o.id||""));t.push(...c.models||[]),a.push(...c.mappings||[])}return zf={directory:e,view:t.length||a.length?{models:t,mappings:a}:iw},zf.view}function fw(){const e=wu();return Jn(e)?dw(e):e===Pf?m7():es.data||iw}function Bf(){const e=fw();return Array.isArray(e.models)?e.models:[]}function dM(){const e=fw();return Array.isArray(e.mappings)?e.mappings:[]}let fM=(e,t,a)=>"";function h7(){fM=o7(dM())}function pw(){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 g7(){const e=new Map;for(const t of Bi()){const a=String(t.id||"");if(!a)continue;const o=dw(a);e.set(a,{label:String(t.name||a),n:(o.models||[]).length})}return e}function x7(){return[...pw().keys()]}function b7(e){const a=(Array.isArray(es.data?.models)?es.data.models:[]).find(o=>o.provider===e);return Number(a?.refreshedAt)||0}function mw(){const e=new Map;for(const t of Bf()){const a=t.provider||"";a&&!e.has(a)&&e.set(a,t.providerLabel||a)}return[...e].map(([t,a])=>({id:t,label:a}))}function pM(e){return e?Bf().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 v7(){const e=[],t=Xt().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 Bi()){const o=String(a.id||"");o&&e.push({id:o,label:String(a.name||o)})}return e.length?e:mw()}let Hf=null,hw=null;function mM(){const e=Hf?Hf.apply(ow):ow;return uM()?e.filter(t=>!aM.has(t.key)):e}function kg(){Xt().wbColSettings?.syncStaticHead("models",hw,uM()?aM:null)}function y7(){if(Hf)return;Hf=Xt().wbColSettings?.register({id:"models",label:r("模型管理表"),columns:ow,mount:()=>document.querySelector('.page[data-page="gateway"] .panel-head .head-actions'),buttonPlacement:"last",onChange:()=>{kg(),Ui()}})||null,Hf&&Ui()}let Cg=0,gw=!1;async function Tg({force:e=!1}={}){if(gw&&!e)return;const t=++Cg;gw=!0,cM();try{const a=await Xt().workbuddyDesktop?.getModelManage();if(t!==Cg)return;Ds({data:a&&Array.isArray(a.models)?a:null})}catch(a){if(t!==Cg)return;Ui(),vr(r("读取模型清单失败:{message}",{message:ko(a)}),"err")}finally{t===Cg&&(gw=!1)}}async function hM(){try{await Xt().wbProviders?.refreshCustom?.()}catch{}await Tg({force:!0})}function Ui(){Ds({})}function Vi(e){const t=e;if(t&&Array.isArray(t.models)){Ds({data:t});return}Ui()}async function Eg(e,t,a,o){if(Jn(e))return XO(e,t,a,o);const c=Xt().workbuddyDesktop;if(!c)throw new Error(r("后端桥不可用"));return c.addModelMapping(t,a,e,o.reasoning,o.enabled)}async function j7(e,t,a){if(Jn(e))return QO(e,t,a);const o=Xt().workbuddyDesktop;if(!o)throw new Error(r("后端桥不可用"));return o.removeModelMapping(t,a,e)}async function w7(e,t){if(Jn(e))return ZO(e,t);const a=Xt().workbuddyDesktop;if(!a)throw new Error(r("后端桥不可用"));return a.addCustomModel(e,t)}async function gM(e,t){if(Jn(e))return JO(e,t);const a=Xt().workbuddyDesktop;if(!a)throw new Error(r("后端桥不可用"));return a.removeCustomModel(e,t)}async function S7(e,t,a){if(Jn(e))return WO(e,t,a);const o=Xt().workbuddyDesktop;if(!o)throw new Error(r("后端桥不可用"));return o.setModelCapabilities(e,t,a)}async function xw(e,t,a){if(!es.pending.has(e)){Ds({pending:new Set(es.pending).add(e)});try{Vi(await t()),a&&vr(a)}catch(o){vr(r("操作失败:{message}",{message:ko(o)}),"err")}finally{const o=new Set(es.pending);o.delete(e),Ds({pending:o})}}}function Uf(e){return Nu(e).some(t=>t.enabled!==!1)}function Nu(e){const t=e.provider||"",a=dM().filter(p=>Co(p.target,e.id)&&(!p.provider||Co(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 Fi=e=>`${e.provider||""}:${e.id}`,bw=(e,t,a)=>`${e}:${t}:${a||""}`;function N7(e){Ds({expanded:new Set(es.expanded).add(e)})}function k7(e){const t=new Set(es.expanded);t.delete(e),Ds({expanded:t})}function C7(e){const t=aw.includes(e)?e:"all";t!==es.stateFilter&&(wg=!0,Ds({stateFilter:t}),Sg({state:t}))}function T7(e){const t=lw.includes(e)?e:"default";t!==es.sort&&(wg=!0,Ds({sort:t}),Sg({sort:t}))}function E7(e){wg=!0,Ds({search:e}),Sg({search:e})}function Vf(e){Ds({provider:String(e??"").trim()||"all"}),Sg({provider:es.provider}),kg()}async function R7(e){const t=Xt().wbCustomProvidersUi;if(!t?.remove){vr(r("删除入口未就绪,请重试或重启应用"),"err");return}await t.remove(e)&&await Tg({force:!0})}function A7(){Xt().wbAccountAddForms?.openNewCustomForm?.()}function xM(e){Ds({mapping:e})}function O7(){Ds({mapping:null})}function M7(){const e=wu(),t=Jn(e);Ds({customModel:{provider:t||e!=="all"&&e!==Pf?e:"",locked:t}})}function D7(){Ds({customModel:null})}function bM(e,t){Ds({capability:{provider:e,id:t}})}function I7(){Ds({capability:null})}function vM(e,t){return Bf().find(a=>(a.provider||"")===e&&Co(a.id,t))||null}function vw(e){if(Jn(e)){const t=No(e)?.name;return typeof t=="string"&&t||e}return Xt().wbProviders?.labelOf?.(e)||e}function yM(){const e=wu(),t=Jn(e),a=t?No(e)?.name||e:r("内置提供商");Xt().wbModelsFetchModal?.open({providerId:e===Pf?"":e,custom:t,name:a,onDone:()=>Ui(),onRefreshed:()=>{Tg({force:!0})}})}window.wbModelsPanel={render:Ui,load:Tg,refreshAll:hM,refreshModels:yM,visibleColumns:mM,selectProvider:Vf,builtinProviders:x7,providerRefreshedAt:b7};function yw(e,t,a){return fM(e,t,a)}function P7(e){hw=e}function _7(){const e=hw;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 L7=e=>[{value:"inherit",label:e},{value:"on",label:r("支持")},{value:"off",label:r("不支持")}];function z7(e){const t=sw(e);return r(t==="on"?"支持":t==="off"?"不支持":"未声明")}function jM(e,t,a,o,c=""){const d=t!=null,f=Of.includes(e)?Mf(t):z7(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 B7(e,t,a){return a?vu.filter(o=>{const c=e[o];return c!=null}):t}function H7(e,t){const a={};for(const o of vu){const c=t.includes(o),d=e[o];Of.includes(o)?a[o]=c&&typeof d=="number"?String(d):"":a[o]=c?d===!0?"on":"off":"inherit"}return a}function U7({context:e,onClose:t}){const a=Jn(e.provider),o=vM(e.provider,e.id),c=WG(o),d=nw(o),f=B7(d,tw(o?.capOverrides),a),[p,g]=x.useState(()=>H7(d,f)),[v,y]=x.useState(""),[b,j]=x.useState(!1);if(!o)return s.jsx(Kt,{open:!0,onOpenChange:D=>{D||t()},children:s.jsxs(Yt,{children:[s.jsx($t,{children:s.jsx(Ft,{children:r("模型能力")})}),s.jsx(_t,{children:s.jsx("p",{className:"text-sm leading-[1.7] text-subtle",children:r("这一行已不在当前清单里(模型被移除、或目录刷新后上游不再提供它)。关闭后刷新列表再试。")})}),s.jsxs(en,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("关闭")})]})]})});const w=o.id,S=o.providerLabel||vw(e.provider),N=r(a?"未声明":"继承上游"),k=r(a?"清除":"恢复继承");function E(D){const I=d[D];return R(D)?"":a?r("未填写"):typeof I=="number"?r("继承上游 {value}",{value:Mf(I)}):r("上游未声明")}function R(D){return f.includes(D)}function C(D,I){g(M=>({...M,[D]:I}))}async function A(){if(!b){for(const D of Of){const I=p[D].trim();if(I&&ew(D,I)===null){y(r("{label}要填 1 ~ 1 亿之间的整数(留空 = {inherit})",{label:yu[D],inherit:N}));return}}j(!0),y(r("保存中…"));try{Vi(await S7(e.provider,e.id,t7(p))),t(),vr(r("✅ 已保存 {id} 的能力位({provider})",{id:w,provider:S}))}catch(D){y(r("保存失败:{message}",{message:ko(D)})),j(!1)}}}return s.jsx(Kt,{open:!0,onOpenChange:(D,I)=>{if(!D){if(b){I.cancel();return}t()}},children:s.jsxs(Yt,{children:[s.jsx($t,{children:s.jsx(Ft,{children:r("模型能力")})}),s.jsxs(_t,{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})]}),Of.map(D=>s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-[7px]",children:[s.jsx(st,{htmlFor:`cap-${D}`,children:yu[D]}),R(D)?s.jsx(se,{variant:"ghost",size:"2xs",disabled:b,title:r(a?"清除这一项(回到未声明)":"清除覆盖,回到上游声明值"),onClick:()=>C(D,""),children:k}):null]}),s.jsx(Ye,{id:`cap-${D}`,inputMode:"numeric",autoComplete:"off",spellCheck:!1,placeholder:E(D),disabled:b,value:p[D],onChange:I=>C(D,I.currentTarget.value),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),A())}}),s.jsx("p",{className:"text-xs leading-[1.6] text-subtle",children:jM(D,d[D]??null,R(D),a,ju(o,D))})]},D)),VO.map(D=>s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(st,{children:yu[D]}),s.jsx(Pn,{options:L7(N),value:p[D],"aria-label":yu[D],className:"self-start",onValueChange:I=>C(D,String(I))}),s.jsx("p",{className:"text-xs leading-[1.6] text-subtle",children:jM(D,d[D]??null,R(D),a,ju(o,D))})]},D)),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(en,{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 Ff(){return window}const V7="你好",wM=4e3,F7=[{value:"chat_completions",label:"OpenAI - Chat Completions"},{value:"responses",label:"OpenAI - Responses"},{value:"anthropic",label:"Anthropic - Messages"}],$7={chat_completions:"Chat Completions",responses:"Responses",anthropic:"Anthropic Messages"},q7="direct",G7={remote:r("远程目录"),builtin:r("内置清单"),manual:r("手动登记")},K7=[{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 SM(){return Ff().wbApp?.getState?.()?.accounts?.accounts||[]}function NM(e){return SM().filter(t=>(t.provider||nu)===e&&t.available!==!1&&t.enabled!==!1).sort(Th)}function kM(e){const t=String(e.email||"").trim();return t&&lr(e.provider).emailAsName?t:ru(e)||t||r("未命名账号")}function Y7(){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 jw(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 X7(e,t){return NM(e).length?"":r("该提供商没有可用账号(要在账号页启用一个、且凭证完整),一行都发不出去")}function CM({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 Q7({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 Z7(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 TM(e){if(e.transport||!e.result||e.result.error)return!1;const t=Number(e.result.status)||0;return t>=200&&t<300}function W7({target:e,onClose:t}){const a=e.provider,o=vM(a,e.id),c=NM(a),d=Gy(SM()),[f,p]=x.useState(""),[g,v]=x.useState(V7),[y,b]=x.useState("chat_completions"),[j,w]=x.useState(""),[S,N]=x.useState(null),[k,E]=x.useState(""),[R,C]=x.useState(""),[A,D]=x.useState(!0),[I,M]=x.useState(()=>{const K=c.find(be=>!uf(be,e.id))||c[0];return K?[K.id]:[]}),[O,_]=x.useState([]),[L,z]=x.useState(()=>new Set),U=x.useRef(0),B=x.useRef([]);B.current=O;const Q=O.some(K=>K.state==="running"),W=Z7(Q);x.useEffect(()=>{let K=!0;return(async()=>{try{const be=Ff().workbuddyDesktop?.getProxyPool;if(typeof be!="function")throw new Error(r("当前环境不支持代理池"));const ne=await be();if(!K)return;if(!ne||typeof ne!="object"||!Array.isArray(ne.items))throw new Error(r("代理池响应异常"));N(ne.items),E("")}catch(be){if(!K)return;N([]),E(ko(be))}})(),()=>{K=!1}},[]);const Z=x.useCallback((K=!1)=>{const be=B.current.filter(ne=>ne.state==="running");U.current+=1;for(const ne of be)Ff().workbuddyDesktop?.terminateStatsRequest?.(ne.testId)?.catch(()=>{});_([]),be.length&&!K&&vr(r("已中止在途测试({n} 个账号)",{n:be.length}))},[]);x.useEffect(()=>()=>{Z(!0)},[Z]);async function Y(K,be){const ne={provider:a,model:e.id,account_id:K.accountId,prompt:g.trim(),system_prompt:f.trim(),reasoning:R,stream:A,protocol:y,...j?{proxy:j}:{},test_id:K.testId},ce=we=>{U.current===be&&_(Ee=>Ee.map(ve=>ve.testId===K.testId?{...ve,...we}:ve))};try{const we=await Ff().workbuddyDesktop?.testModel(ne);if(!we){ce({state:"done",transport:r("桥接调用返回空(本机网关没有响应这次测试)")});return}ce({state:"done",result:we})}catch(we){ce({state:"done",transport:ko(we)})}}function q(){const K=c.filter(we=>I.includes(we.id));if(!K.length){vr(r("至少选一个测试账号"),"err");return}const be=U.current+1;U.current=be;const ne=Date.now(),ce=K.map(we=>({accountId:we.id,label:kM(we),position:d.get(we.id)?.position||0,testId:Y7(),startedAt:ne,state:"running"}));z(new Set),_(ce);for(const we of ce)Y(we,be)}function G(){Q?Z():_([])}const F=s.jsx("span",{className:"ml-2 font-mono text-[12px] font-normal text-subtle",children:e.id});if(!o)return s.jsx(Kt,{open:!0,onOpenChange:K=>{K||t()},children:s.jsxs(Yt,{children:[s.jsx($t,{children:s.jsx(Ft,{children:r("测试模型")})}),s.jsx(_t,{children:s.jsx("p",{className:"text-sm leading-[1.7] text-subtle",children:r("这一行已不在当前清单里(模型被移除、或目录刷新后上游不再提供它)。关闭后刷新列表再试。")})}),s.jsxs(en,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("关闭")})]})]})});const $=Nu(o).find(K=>K.isDefault)?.enabled===!1,X=yw(o.id,o.id,a),re=Nu(o).filter(K=>!K.isDefault).map(K=>K.alias),P=If(_f().data,o).filter(K=>K!=="off"&&K!=="none"),V=$?r("跟随映射(该行未启用,本次不注入)"):X?r("跟随映射(当前 {level})",{level:X}):r("跟随映射(未绑定等级)"),J=[r("以模型本名直发"),re.length?r("另有 {n} 条别名映射({aliases}),别名不参与本次",{n:re.length,aliases:re.join(r("、"))}):"",$?r("该行当前未启用:测试照常按本名直发(「先测通、再决定要不要启用」正是这颗按钮的用法),但本行的思考等级绑定不参与本次,生产路由也要等绑定打开后才会放行"):X?r("映射上绑定的思考等级是 {level},「跟随映射」按它注入",{level:X}):r("映射上未绑定思考等级,「跟随映射」等于这次不注入")].filter(Boolean).join(r(";"))+r("。"),ie=Ff().wbProviders?.PROTOCOL_OPTIONS||F7,me=ie.find(K=>K.value===y)?.label||y,he=[{value:"",label:r("跟随账号配置")},{value:q7,label:r("直连(不使用代理)")},...(S??[]).map(K=>({value:`${Ka}${K.id}`,label:lf(K)}))];S===null?he.push({value:"__hint_pool__",label:r("正在读取代理列表…"),disabled:!0}):S.length||he.push({value:"__hint_pool__",label:r(k?"代理列表读取失败":"还没有代理(去「网络代理」页添加)"),disabled:!0});const ae=he.find(K=>K.value===j)?.label||r("跟随账号配置"),oe=c.map(K=>({value:K.id,label:`#${d.get(K.id)?.position||0} ${kM(K)}`+(uf(K,e.id)?r(" · 限额中"):"")}));function ee(K){const be=(ke,Ce)=>s.jsxs("div",{className:"flex items-center gap-2.5 border-b border-hairline px-3 py-2",children:[ke,s.jsx("b",{className:"min-w-0 truncate text-[12.5px] text-foreground",title:K.label,children:K.label}),K.position?s.jsxs("span",{className:"flex-none text-xs text-subtle",children:["#",K.position]}):null,s.jsx("span",{className:"ml-auto flex-none font-mono text-[11.5px] tabular-nums text-subtle",children:Ce})]},"head");if(K.state==="running"){const ke=(W-K.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($d,{className:"flex-none"}),s.jsxs("span",{className:"min-w-0 truncate",children:[r("账号 "),s.jsx("b",{className:"text-foreground",children:K.label}),r(" 已发出,等待上游首帧…")]}),s.jsx("span",{className:"ml-auto flex-none font-mono tabular-nums",children:r("已等待 {seconds}s",{seconds:ke.toFixed(1)})})]},K.testId)}const ne=K.result;if(!TM(K)){const ke=Number(ne?.status)||0,Ce=K7.find(Se=>Se.test(ke))?.hint??(K.transport?r("确认桌面端还在运行,再重试一次。"):"");return s.jsxs("div",{className:"rounded-md border border-border bg-surface-2",children:[be(s.jsx(ze,{shape:"tag",variant:"destructive",className:"flex-none",children:ke||r("失败")}),r("用时 {time}",{time:jw(ne?.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:[K.transport?s.jsxs(s.Fragment,{children:[s.jsx("b",{className:"text-destructive",children:r("本机网关没有返回结论")}),r(":"),K.transport]}):s.jsxs(s.Fragment,{children:[s.jsx("b",{className:"text-destructive",children:r("测试未通过")}),r(":"),ne?.error||r("上游没有给出可读的错误说明")]}),Number(ne?.attempts)>1?r("(中间共尝试 {n} 次)",{n:Number(ne?.attempts)}):""]}),Ce?s.jsx("p",{className:"text-xs leading-[1.65] text-subtle",children:Ce}):null]})]},K.testId)}const ce=String(ne?.reply??""),we=String(ne?.reasoning??""),Ee=`think-${K.testId}`,ve=[ne?.upstream_model&&ne.upstream_model!==e.id?r("上游 {model}",{model:ne.upstream_model}):"",ne?.upstream_reasoning?r("思考等级 {level}",{level:ne.upstream_reasoning}):"",ne?.protocol&&ne.protocol!=="chat_completions"?$7[ne.protocol]||ne.protocol:"",ne?.proxy?r("节点 {proxy}",{proxy:ne.proxy}):"",Number(ne?.attempts)>1?r("尝试 {n} 次",{n:Number(ne?.attempts)}):""].filter(Boolean).join(" · ");return s.jsxs("div",{className:"rounded-md border border-border bg-surface-2",children:[be(s.jsx(ze,{shape:"tag",variant:"success",className:"flex-none",children:Number(ne?.status)||200}),r("用时 {time} · 首字 {ttfb}",{time:jw(ne?.duration_ms),ttfb:jw(ne?.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":ce,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:ce||s.jsx("span",{className:"text-subtle",children:r("(上游这一次返回了空正文)")})}),we?s.jsx(Q7,{open:L.has(Ee),label:r("思考过程({n} 字)",{n:we.length}),text:we,onToggle:()=>z(ke=>{const Ce=new Set(ke);return Ce.has(Ee)?Ce.delete(Ee):Ce.add(Ee),Ce})}):null]})]},K.testId)}function de(){if(Q){const be=O.length-O.filter(ne=>ne.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(" 个账号"),be?s.jsxs(s.Fragment,{children:[r(",已完成 "),s.jsx("b",{className:"text-foreground",children:be})]}):null,r("。")]}):null,O.map(ne=>ee(ne))]})}const K=O.filter(TM).length;return s.jsxs(s.Fragment,{children:[O.length>1?s.jsxs("p",{className:"text-xs text-subtle",children:[s.jsx("b",{className:K?"text-success":"text-foreground",children:K}),r(" 成功 ·"),s.jsxs("b",{className:O.length-K?"text-destructive":"text-foreground",children:[" ",O.length-K]}),r(" 失败")]}):null,O.map(be=>ee(be)),K===0?s.jsxs(CM,{children:[r("两边原因不一样时各自处理。如果"),s.jsx("b",{className:"text-foreground",children:r("同一条错误出现在所有账号上")}),r(",通常就不是账号问题了:先确认这个模型还在上游目录里(「获取模型」刷一次),再看默认绑定指向的上游模型对不对。")]}):null]})}return s.jsx(Kt,{open:!0,onOpenChange:K=>{K||t()},children:s.jsxs(Yt,{children:[s.jsx($t,{children:s.jsxs(Ft,{children:[r("测试模型"),F]})}),s.jsxs(_t,{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:vw(a)}),s.jsx(ze,{shape:"tag",variant:"outline",children:Jn(a)?r("自定义家"):G7[o.source]||r("来源未知")}),s.jsxs(Ri,{children:[s.jsx(Ai,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("本次测试的发送口径")}),children:"?"}),s.jsx(Oi,{children:J})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(st,{htmlFor:"model-test-system",children:r("系统提示词")}),s.jsx(Fd,{id:"model-test-system",rows:2,maxLength:wM,placeholder:r("留空则不携带;设置页的提示词模式照常生效"),value:f,onChange:K=>p(K.currentTarget.value)})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(st,{htmlFor:"model-test-prompt",children:r("用户提示词")}),s.jsx(Fd,{id:"model-test-prompt",rows:2,maxLength:wM,placeholder:r("留空用默认问候「你好」"),value:g,onChange:K=>v(K.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(st,{htmlFor:"model-test-protocol",children:r("对话协议")}),s.jsxs(Ri,{children:[s.jsx(Ai,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("对话协议的说明")}),children:"?"}),s.jsx(Oi,{children:r("按所选网关对话协议组装请求并校验响应转换(Chat Completions / Responses / Anthropic Messages)。")})]})]}),s.jsxs(ut,{value:y,onValueChange:K=>b(String(K)),children:[s.jsx(ft,{id:"model-test-protocol",className:"w-full",children:s.jsx(dt,{className:"min-w-0 truncate",children:me})}),s.jsx(pt,{children:ie.map(K=>s.jsx(Xe,{value:K.value,children:K.label},K.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(st,{htmlFor:"model-test-proxy",children:r("测试节点")}),s.jsxs(Ri,{children:[s.jsx(Ai,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("测试节点的说明")}),children:"?"}),s.jsx(Oi,{children:r("仅本次测试临时生效,不修改账号保存的代理配置。可选「网络代理」页里的节点或强制直连。")})]})]}),s.jsxs(ut,{value:j,onValueChange:K=>w(String(K)),children:[s.jsx(ft,{id:"model-test-proxy",className:"w-full",children:s.jsx(dt,{className:"min-w-0 truncate",children:ae})}),s.jsx(pt,{children:he.map(K=>s.jsx(Xe,{value:K.value,disabled:K.disabled,children:K.label},K.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(st,{htmlFor:"model-test-reasoning",children:r("思考等级")}),s.jsxs(ut,{value:R,onValueChange:K=>C(String(K)),children:[s.jsx(ft,{id:"model-test-reasoning",className:"w-full",children:s.jsx(dt,{children:R?r("{level}(本次指定)",{level:R}):V})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"",children:V}),P.map(K=>s.jsx(Xe,{value:K,children:r("{level}(本次指定)",{level:K})},K))]})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(st,{htmlFor:"model-test-stream",children:r("流式请求")}),s.jsxs(Ri,{children:[s.jsx(Ai,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("流式请求的说明")}),children:"?"}),s.jsx(Oi,{children:r("默认开,与真实请求一致:可同时验证 SSE 链路与首字延迟。")})]})]}),s.jsx(ps,{id:"model-test-stream",checked:A,onCheckedChange:K=>D(!!K)})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(st,{htmlFor:"model-test-accounts",children:r("测试账号")}),s.jsxs(Ri,{children:[s.jsx(Ai,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("测试账号的说明")}),children:"?"}),s.jsx(Oi,{children:r("勾几个就并行测几次;默认选队列里最靠前的一个。")})]}),s.jsx(se,{variant:"ghost",size:"xs",className:"ml-auto",disabled:!c.length||I.length===c.length,onClick:()=>M(c.map(K=>K.id)),children:r("全选({n})",{n:c.length})})]}),s.jsx(_y,{id:"model-test-accounts",value:I,onValueChange:M,options:oe,placeholder:r("选一个账号(至少一个)"),searchPlaceholder:r("搜索账号…"),emptyHint:r("这家没有可用账号(要在账号页启用一个、且凭证完整)")})]}),s.jsx(CM,{plain:!0,children:r("真实链路 · 消耗少量额度 · 日志带「测试」标记,不计报表")})]}),s.jsxs(en,{className:"justify-end",children:[s.jsx(se,{variant:"outline",onClick:t,children:r("关闭")}),s.jsx(se,{variant:"default",disabled:!I.length||!c.length,onClick:q,children:r("开始测试")})]}),s.jsx(Kt,{open:O.length>0,onOpenChange:K=>{K||G()},children:s.jsxs(Yt,{overlayForceRender:!0,className:"w-[min(680px,calc(100vw-48px))]",children:[s.jsx($t,{children:s.jsxs(Ft,{children:[r(Q?"测试中…":"测试结果"),F]})}),s.jsx(_t,{children:de()}),s.jsx(en,{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:()=>Z(),children:r("中止测试")}),s.jsx(se,{variant:"default",disabled:!0,children:r("测试中…")})]}):s.jsxs(s.Fragment,{children:[s.jsx(se,{variant:"outline",onClick:G,children:r("关闭")}),s.jsx(se,{variant:"default",onClick:q,children:r("再测一次")})]})})]})})]})})}const EM=[{value:"enable",label:r("启用")},{value:"disable",label:r("禁用")},{value:"reasoning",label:r("设置思考等级")},{value:"delete",label:r("删除")}];function RM(e){return e.source==="manual"||Jn(e.provider)}function J7(e){return(e.name&&e.name!==e.id?r("{name}({id})",{name:e.name,id:e.id}):e.id)||e.id}function eK({models:e,onClose:t,onDone:a}){const[o,c]=x.useState("enable"),d=l7(_f().data,e),[f,p]=x.useState(()=>({select:d[0]||"",custom:""})),[g,v]=x.useState(!1),[y,b]=x.useState(""),j=f.select===oa?f.custom.trim():f.select,w=e.filter(RM).length,S=EM.find(E=>E.value===o)?.label||r("操作");async function N(E){return Promise.resolve(Xt().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){vr(r("没有选中的模型"),"err");return}if(o==="reasoning"&&f.select===oa&&!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,R=0,C=0,A="";for(const D of e){const I=D.provider||"";try{if(o==="delete"){if(!RM(D)){R+=1;continue}Vi(await gM(I,D.id))}else if(o==="enable"||o==="disable"){const M=o==="enable";for(const O of Nu(D))Vi(await Eg(I,O.alias,D.id,{enabled:M}))}else for(const M of Nu(D))Vi(await Eg(I,M.alias,D.id,{reasoning:j}));E+=1}catch(M){C+=1,A||(A=ko(M)),b(s.jsx("span",{className:"text-destructive",children:r("失败 {n} 个 · 首个失败:{error}",{n:C,error:A})}))}}C===0?(vr(R?r("✅ 批量{action}完成:共 {n} 个模型(跳过不可删除的 {skipped} 个)",{action:S,n:E,skipped:R}):r("✅ 批量{action}完成:共 {n} 个模型",{action:S,n:E})),a()):(vr(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}),R?r(",跳过 {n} 个",{n:R}):"",A?r(";首个失败:{error}",{error:A}):""]}))),v(!1)}return s.jsx(Kt,{open:!0,onOpenChange:E=>{E||g||t()},children:s.jsxs(Yt,{children:[s.jsx($t,{children:s.jsx(Ft,{children:r("批量操作 · 已选 {n} 个模型",{n:e.length})})}),s.jsxs(_t,{children:[s.jsxs(Hn,{children:[s.jsx("h3",{children:r("将作用于以下模型")}),s.jsx("p",{style:{maxHeight:84,overflowY:"auto"},children:e.map(J7).join(r("、"))})]}),s.jsxs(Hn,{children:[s.jsx("h3",{children:r("操作")}),s.jsx(dh,{value:o,onValueChange:E=>c(E),className:"flex-row flex-wrap items-center gap-5","aria-label":r("批量动作"),children:EM.map(E=>s.jsxs(st,{className:"inline-flex cursor-pointer items-center gap-2 font-normal",children:[s.jsx(Mi,{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(ut,{value:f.select,onValueChange:E=>p(R=>({...R,select:String(E)})),children:[s.jsx(ft,{id:"batch-model-reasoning",className:"min-w-[220px]",children:s.jsx(dt,{children:f.select===oa?r("自定义等级…"):f.select||r("清除(不覆盖)")})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"",children:r("清除(不覆盖)")}),d.map(E=>s.jsx(Xe,{value:E,children:E},E)),s.jsx(Xe,{value:oa,children:r("自定义等级…")})]})]})]}),f.select===oa?s.jsxs("div",{className:"field-row mt-2",children:[s.jsx("label",{htmlFor:"batch-model-reasoning-custom",children:r("自定义等级")}),s.jsx(Ye,{id:"batch-model-reasoning-custom",maxLength:32,value:f.custom,onChange:E=>p(R=>({...R,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(en,{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 AM={intl:"fm-table-intl",custom:"fm-table-custom"},OM={intl:"fetch-models",custom:"fetch-models-custom"},ww=["provider","source","state","count","note","updated","op"],Sw=["pick","model","state"],tK={provider:"w-[13%]",source:"w-[21%]",state:"w-[9%]",count:"w-[6%]",note:"w-[20%]",updated:"w-[16%]",op:"w-[15%]"},nK={pick:"w-[8%]",model:"w-[74%]",state:"w-[18%]"},sK={pick:"",provider:r("提供商"),source:r("模型来源"),state:r("状态"),count:r("模型数"),note:r("说明"),updated:r("更新日期"),model:r("上游模型"),op:r("操作")},rK={refreshed:{variant:"brand",label:r("已刷新")},failed:{variant:"destructive",label:r("失败")},skipped:{variant:"outline",label:r("跳过")}},MM=new Set(["cline-free","cline-pass"]),DM="workbuddy-desktop-fetch-model-source";function $f(e){return String(e??"").trim().toLowerCase()}function Nw(e,t){er().wbApp?.toast?.(e,t)}function kw(e){return e instanceof Error?e.message:String(e)}function IM(e){const t=er().formatTime??er().wbApp?.formatTime;return String(t?.(e)??"")}function PM(){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=>$f(o?.id)).filter(Boolean))}function _M(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 lK(e){if(MM.has(e))return[];const t=er().wbAccountsModel?.byPriorityOrder,a=PM().filter(o=>(o?.provider||"workbuddy")===e&&o?.available!==!1&&o?.enabled!==!1);return t?a.sort(t):a}function LM(){const e=new Set(er().wbModelsPanel?.builtinProviders?.()||[]);for(const t of PM())t?.available===!1||t?.enabled===!1||e.add(t?.provider||"workbuddy");return[...e]}function oK(){const e=new Set(LM());return(er().wbProviders?.all?.()||[]).filter(t=>e.has(t?.id??""))}function iK(e){return IM(Number(e.refreshedAt)||0)||"—"}function cK(e){return rK[String(e.status)]??{variant:"outline",label:String(e.status||r("未知"))}}function uK(){try{const e=JSON.parse(localStorage.getItem(DM)||"{}");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 dK(e){er().wbFilterMemory?.save?.(DM,e)}function fK({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,[R,C]=x.useState(!1),[A,D]=x.useState([]),[I,M]=x.useState(()=>new Set),[O,_]=x.useState(()=>new Set),[L,z]=x.useState([]),[U,B]=x.useState(""),[Q,W]=x.useState(uK);x.useEffect(()=>{er().wbTableColumns?.repaint?.(o?OM.custom:OM.intl)},[o]);const Z=o?[]:oK(),Y=o?[]:$(),q=U.trim().toLowerCase(),G=A.filter(ve=>!q||ve.toLowerCase().includes(q)),F=o?R?r("已选 {picked} 个 · 上游共 {upstream} 个 · 清单已有 {managed} 个",{picked:O.size,upstream:A.length,managed:I.size}):r("尚未获取"):X(Y);function $(){const ve=new Map(L.map(Se=>[String(Se.provider||""),Se])),ke=Z.map(Se=>{const ge=String(Se.id||"");return{provider:ge,label:String(Se.label||ge),item:ve.get(ge)}}),Ce=new Set(ke.map(Se=>Se.provider));for(const Se of L){const ge=String(Se.provider||"");Ce.has(ge)||ke.push({provider:ge,label:String(Se.providerLabel||ge),item:Se})}return ke}function X(ve){if(p==="loading")return r("正在刷新…");if(p==="error")return"";const ke=ve.map(ge=>ge.item).filter(ge=>!!ge);if(!ke.length)return R?r("刷新完成,但没有得到任何结果"):ve.length?r("共 {n} 家 · 点「获取模型」开始",{n:ve.length}):r("0 家");const Ce=ke.filter(ge=>ge.status==="refreshed").length,Se=ke.filter(ge=>ge.status==="failed").length;return Se?r("{total} 家 · 成功 {done} · 失败 {failed}",{total:ve.length,done:Ce,failed:Se}):r("{total} 家 · 成功 {done}",{total:ve.length,done:Ce})}function re(ve,ke){const Ce=lK(ve);if(!Ce.length)return{list:Ce,selected:""};const Se=String(Q[ve]||""),ge=String(ke||""),Te=Oe=>Ce.some(Ne=>String(Ne.id)===Oe);return{list:Ce,selected:Te(Se)?Se:Te(ge)?ge:String(Ce[0].id)}}function P(ve){const ke={};for(const[Ce,Se]of Object.entries(Q))Se&&(ke[Ce]=Se);for(const Ce of ve){const{selected:Se}=re(Ce.provider,Ce.reported);Se&&(ke[Ce.provider]=Se)}return ke}const V=Y.map(ve=>({provider:ve.provider,reported:ve.item?.accountId}));function J(ve,ke){W(Ce=>({...Ce,[ve]:ke})),dK({[ve]:ke})}async function ie(){if(!E){S("load"),j(""),y(""),g("loading");try{if(o){const ke=await er().wbProviders?.customRequest?.("POST","/api/custom-providers/fetch-models",{providerId:a}),Ce=new Set,Se=(Array.isArray(ke?.models)?ke.models:[]).map(Te=>String(Te??"").trim()).filter(Te=>{const Oe=$f(Te);return!Te||Ce.has(Oe)?!1:(Ce.add(Oe),!0)}),ge=aK(a);D(Se),M(ge),_(new Set(Se.filter(Te=>!ge.has($f(Te))))),C(!0),g("ready");return}const ve=await er().workbuddyDesktop?.refreshModels({accounts:P(V),providers:LM()});z(Array.isArray(ve?.results)?ve.results:[]),C(!0),g("ready"),Number(ve?.refreshed)>0&&f?.()}catch(ve){const ke=kw(ve);y(ke),g("error"),j(ke)}finally{S(null)}}}async function me(ve){if(!(E||!ve.provider)){S("row"),k(ve.provider),j("");try{const ke=await er().workbuddyDesktop?.refreshModels({accounts:P([{provider:ve.provider,reported:ve.item?.accountId}]),providers:[ve.provider]});z(Ce=>he(Ce,Array.isArray(ke?.results)?ke.results:[])),C(!0),g("ready"),Number(ke?.refreshed)>0&&f?.()}catch(ke){const Ce=kw(ke);j(Ce),Nw(r("获取失败:{message}",{message:Ce}),"err")}finally{S(null),k("")}}}function he(ve,ke){const Ce=new Map(ke.map(Te=>[String(Te.provider||""),Te])),Se=ve.map(Te=>Ce.get(String(Te.provider||""))??Te),ge=new Set(Se.map(Te=>String(Te.provider||"")));for(const Te of ke)ge.has(String(Te.provider||""))||Se.push(Te);return Se}async function ae(){if(!o||E||!O.size)return;const ve=[...O];S("import"),j("");try{const ke=Number(await er().wbModelsCustom?.addModels?.(a,ve))||0;Nw(r("✅ 已导入 {added} 个模型({skipped} 个已存在,跳过)",{added:ke,skipped:ve.length-ke})),S(null),t(),d?.()}catch(ke){const Ce=kw(ke);Nw(r("导入失败:{message}",{message:Ce}),"err"),j(Ce),S(null)}}function oe(){E||t()}function ee(){const ve=new Set(O);for(const ke of A)I.has($f(ke))||ve.add(ke);_(ve)}function de(ve){return s.jsx(jl,{children:s.jsx(yn,{colSpan:o?Sw.length:ww.length,className:"py-[26px] text-center text-muted-foreground",children:ve})})}function K(ve){return s.jsx("span",{className:"font-mono text-[11.5px] tabular-nums text-muted-foreground",children:ve})}function be(ve){return s.jsx("div",{className:"truncate font-mono text-[12px] font-semibold",children:ve})}function ne(ve,ke){const{list:Ce,selected:Se}=re(ve,ke);if(!Ce.length){const Te=MM.has(ve)?r("这家的模型清单是全局的,不跟账号走"):r("这家还没有可用账号,刷新会使用默认登录态");return s.jsx("span",{className:"text-[11.5px] text-muted-foreground",title:Te,children:"—"})}const ge=Ce.find(Te=>String(Te.id)===Se);return s.jsxs(ut,{value:Se,onValueChange:Te=>J(ve,String(Te)),children:[s.jsx(ft,{className:"w-full",title:r("用哪个账号去拉这家的模型清单"),"aria-label":r("模型来源"),children:s.jsx(dt,{children:ge?_M(ge):"—"})}),s.jsx(pt,{children:Ce.map(Te=>s.jsx(Xe,{value:String(Te.id),children:_M(Te)},String(Te.id)))})]})}function ce(){return p==="idle"?de(r("点右侧「获取模型」从上游拉取这家的模型清单")):p==="loading"?de(r("正在获取…")):p==="error"?de(r("获取失败:{message}",{message:v})):G.length?G.map(ve=>{const ke=I.has($f(ve));return s.jsxs(jl,{className:ke?"opacity-50":void 0,children:[s.jsx(yn,{children:s.jsx(ta,{checked:O.has(ve),disabled:ke,"aria-label":ve,onCheckedChange:Ce=>_(Se=>{const ge=new Set(Se);return Ce?ge.add(ve):ge.delete(ve),ge})})}),s.jsx(yn,{children:be(ve)}),s.jsx(yn,{children:ke?s.jsx(ze,{variant:"brand",title:r("这个模型已经在这家的清单里,不重复导入"),children:r("已添加")}):s.jsx(ze,{variant:"outline",title:r("勾上它,导入后即进入这家的清单"),children:r("未添加")})})]},ve)}):de(A.length?r("没有匹配「{keyword}」的模型",{keyword:q}):r("上游没有返回任何模型"))}function we(ve){const ke=w==="row"&&N===ve.provider;return s.jsx(se,{variant:"outline",size:"sm",className:"w-full",disabled:E,title:r("只刷新这一家的模型清单"),onClick:()=>{me(ve)},children:ke?r("获取中…"):ve.item?r("重新获取"):r("获取")})}function Ee(){return p==="loading"?de(r("正在获取…")):p==="error"?de(r("获取失败:{message}",{message:v})):Y.length?Y.map(ve=>{const ke=ve.item;if(!ke){const Te=IM(Number(er().wbModelsPanel?.providerRefreshedAt?.(ve.provider))||0);return s.jsxs(jl,{children:[s.jsx(yn,{children:be(ve.label)}),s.jsx(yn,{children:ne(ve.provider)}),s.jsx(yn,{children:s.jsx(ze,{variant:"outline",children:r("待获取")})}),s.jsx(yn,{children:K("—")}),s.jsx(yn,{children:K("—")}),s.jsx(yn,{children:K(Te||"—")}),s.jsx(yn,{children:we(ve)})]},ve.provider)}const Ce=cK(ke),Se=Number(ke.count),ge=ke.status==="refreshed"?r("远程目录已更新,「来源」列会显示为「远程」"):ke.message||(ke.fixed?r("这家用固定模型清单,无可刷新"):r("本次没有取到新内容"));return s.jsxs(jl,{children:[s.jsx(yn,{children:be(ve.label)}),s.jsx(yn,{children:ne(ve.provider,ke.accountId)}),s.jsx(yn,{children:s.jsx(ze,{variant:Ce.variant,children:Ce.label})}),s.jsx(yn,{children:K(Se?r("{n} 个",{n:Se}):"—")}),s.jsx(yn,{children:s.jsx("span",{className:"text-[11.5px] leading-[1.5] text-muted-foreground",children:ge})}),s.jsx(yn,{children:K(iK(ke))}),s.jsx(yn,{children:we(ve)})]},ve.provider)}):de(r("还没有可刷新的提供商:先在账号页添加一个账号"))}return s.jsx(Kt,{open:!0,onOpenChange:(ve,ke)=>{if(!ve){if(E){ke.cancel();return}t()}},children:s.jsxs(Yt,{className:o?"w-[min(552px,calc(100vw-48px))]":"w-[min(920px,calc(100vw-48px))]",children:[s.jsx($t,{children:s.jsx(Ft,{children:r("获取模型 — {name}",{name:c})})}),s.jsxs(_t,{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(ji,{className:"w-[240px] flex-none",children:[s.jsx(Si,{type:"search",placeholder:r("搜索模型 ID…"),autoComplete:"off",value:U,onChange:ve=>B(ve.currentTarget.value)}),s.jsx(wi,{"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:()=>{ie()},children:r(w==="load"?"获取中…":R?"重新获取":"获取模型")})]}),s.jsxs(Ny,{id:o?AM.custom:AM.intl,className:"table-fixed",containerClassName:"max-h-[min(48vh,460px)]",children:[s.jsx("colgroup",{children:(o?Sw:ww).map(ve=>s.jsx("col",{"data-col":ve,className:o?nK[ve]:tK[ve]},ve))}),s.jsx(FT,{children:s.jsx(jl,{children:(o?Sw:ww).map(ve=>s.jsx($T,{"data-col":ve,children:sK[ve]},ve))})}),s.jsx(ky,{className:"[&_tr:last-child>td]:border-b-0",children:o?ce():Ee()})]})]}),s.jsxs(en,{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:oe,children:r(o?"取消":"完成")}),o&&s.jsx(se,{variant:"default",disabled:!O.size||E,onClick:()=>{ae()},children:w==="import"?r("导入中…"):O.size?r("导入选中的 {n} 个模型",{n:O.size}):r("导入")})]})]})})}let qf=null,ku=null;function zM(){qf&&(qf.unmount(),qf=null),ku&&(ku.remove(),ku=null)}function pK(e){e?.providerId&&(zM(),ku=document.createElement("div"),document.body.append(ku),qf=wn.createRoot(ku),qf.render(s.jsx(fK,{options:e,onClose:zM})))}window.wbModelsFetchModal={open:pK};const To=(e,t)=>t?`${e} ta-${t}`:e;function BM(e,t){const a=(t||"").trim();if(a)return Bf().find(o=>Co(o.provider,e)&&Co(o.id,a))}const mK="[.pv-row:hover_&_[data-slot=nav-item-count]]:invisible";function hK(e){const t=/x\s*([\d.]+)/i.exec(String(e||""));return t?`${t[1]}x`:String(e||"")}function HM(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 gK={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 xK(e){const t=gK[e];if(t!==void 0)return t;let a=0;for(let o=0;o>>0;return a%360}function bK(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 vK=e=>({"--av-h":String(xK(e))}),Cw=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 yK(e){if(!e)return"";const t=Xt().wbPresetProviders?.list;if(!Array.isArray(t))return"";const a=t.find(o=>o.name===e);return a&&Xt().wbPresetProviders?.iconOf?.(String(a.key||""))||""}function jK(e,t){return Jn(e)?yK(t):Xh[e==="workbuddy-intl"?"workbuddy":e]||""}function Cu(e,t,a){const o=a?"":jK(e,t),c=e==="all"||e==="custom-all";return s.jsx("span",{className:Ve("pv-ico",c&&"mute",o&&"img"),style:o?void 0:vK(e),"aria-hidden":"true",children:o?s.jsx("img",{src:o,alt:""}):a??bK(t)})}const wK={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 SK(e,t,a,o){return o==="enabled"&&!Uf(e)||o==="disabled"&&Uf(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 NK(){const e=x.useSyncExternalStore(p7,_f),t=Ng(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&&!Su()&&uw()&&!No(t);x.useEffect(()=>{y7(),kg(),cM(),Xt().wbApp?.currentPage==="gateway"&&hM().then(()=>Xt().wbProviders?.refreshCustom?.()).then(()=>{Ui()})},[]),x.useEffect(()=>{_7()});const y=fw(),b=Array.isArray(y.models)?y.models:[],j=e.search.trim().toLowerCase(),w=b.filter($=>SK($,j,t,e.stateFilter)),S=e.sort,N=mM(),k=N.length,E=t==="all"?r("全部"):t==="custom-all"?r("自定义 · 全部"):a?String(No(t)?.name||t):pw().get(t)?.label||vw(t),R=b.filter(Uf).length,C=b.filter($=>($.aliases||[]).length>0).length,A=$h(w.length,"models"),D=b.filter($=>p.has(Fi($))),I=($,X)=>{const re=new Set(p);X?re.add($):re.delete($),g(re)},M=w.map(Fi),O=M.length>0&&M.every($=>p.has($)),_=M.some($=>p.has($)),L=s.jsx(ta,{checked:O,indeterminate:!O&&_,disabled:!M.length,"aria-label":r("全选当前筛选结果"),title:r("全选当前筛选出的模型(跨分页);再点取消"),onCheckedChange:$=>{const X=new Set(p);for(const re of M)$===!0?X.add(re):X.delete(re);g(X)}});function z(){const $=pw(),X=Bi(),re=g7(),P=[...$.values()].reduce((me,he)=>me+he.n,0),V=r("全部({n} 家)",{n:$.size}),J=[...re.values()].reduce((me,he)=>me+he.n,0),ie=r("全部({n} 家)",{n:[...re.values()].filter(me=>me.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(eu,{active:t==="all","data-provider":"all",title:V,count:P,icon:Cu("all","",Cw),className:"shadow-none",onClick:()=>Vf("all"),children:V}),[...$].map(([me,he])=>s.jsx(eu,{active:t===me,"data-provider":me,title:he.label,count:he.n,icon:Cu(me,he.label),className:"shadow-none",onClick:()=>Vf(me),children:he.label},me)),s.jsx("div",{className:"rail-label",children:r("自定义提供商")}),X.length?[...J>0?[s.jsx(eu,{active:Su(),"data-provider":"custom-all",title:ie,count:J,icon:Cu("custom-all","",Cw),className:"shadow-none",onClick:()=>Vf("custom-all"),children:ie},"custom-all")]:[],...X.map(me=>{const he=String(me.id||""),ae=String(me.name||he);return s.jsxs("div",{className:"pv-row",children:[s.jsx(eu,{active:t===he,"data-provider":he,title:ae,count:re.get(he)?.n??0,icon:Cu(he,ae),className:Ve("shadow-none",mK),onClick:()=>Vf(he),children:ae}),s.jsx("button",{type:"button",className:"pv-del","aria-label":r("删除自定义提供商"),title:r("删除这个自定义提供商(连同名下账号)"),onClick:()=>{R7(he)},children:"×"})]},he)})]:s.jsx("div",{className:"rail-empty",children:r("还没有自定义提供商")})]}),s.jsx("div",{className:"rail-foot",children:s.jsx(eu,{variant:"add",id:"rail-add-custom",title:r("新建一个自定义提供商(同时创建它的第一个账号)"),onClick:()=>A7(),children:r("+ 新建自定义提供商")})})]})}function U($,X,re,P){const V=yw($,X,re);return s.jsx(se,{variant:V?"secondary":"dashed",size:"2xs",disabled:P,className:"font-mono font-bold shadow-none",title:V?r("思考等级 {level}(点击修改)",{level:V}):r("设置思考等级(当前未绑定)"),onClick:()=>xM({alias:$,target:X,provider:re}),children:V||r("+等级")})}function B($){const X=$.provider||"",re=Nu($),[P,...V]=re;async function J(me){await Xt().wbConfirm?.ask?.({title:r("删除映射"),html:r("确定删除映射「{alias} → {target}」?",{alias:rw(me),target:rw($.id)}),okText:r("删除"),okClass:"danger"})&&xw(bw(me,$.id,X),()=>j7(X,me,$.id),r("映射已删除"))}const ie=me=>{const he=me.alias,ae=me.enabled!==!1,oe=e.pending.has(bw(he,$.id,X));return s.jsxs("span",{className:Ve("alias",!ae&&"map-off"),children:[s.jsx(ps,{size:"sm",checked:ae,disabled:oe,title:r(ae?"映射已启用,点击关闭":"映射已关闭,点击启用"),"aria-label":r("{action}映射 {alias}",{action:r(ae?"关闭":"启用"),alias:he}),onCheckedChange:ee=>{xw(bw(he,$.id,X),()=>Eg(X,he,$.id,{enabled:ee}),r(ee?"映射已启用":"映射已关闭"))}}),s.jsx("span",{className:"t","data-copy":he,title:r("点击复制:{name}",{name:he}),children:he}),me.isDefault?s.jsx("span",{className:"binding-default",children:r("默认")}):null,U(he,$.id,X,oe),me.isDefault?null:s.jsx(se,{variant:"ghost",size:"icon-2xs",className:"text-[12px] leading-none",disabled:oe,title:r("删除映射 {alias}",{alias:he}),onClick:()=>{J(he)},children:"×"})]},`${he}${me.isDefault?"d":"m"}`)};return s.jsxs("div",{className:"aliases",children:[s.jsxs("div",{className:"alias-row",children:[P?ie(P):null,s.jsx(se,{variant:"dashed",size:"xs",onClick:()=>xM({target:$.id,provider:X}),children:r("+ 映射")})]}),V.map(ie)]})}function Q($){if($.source==="manual")return s.jsxs("span",{className:"src manual",title:r("手动登记的上游模型;移除它会直接删掉这条登记"),children:[s.jsx("i",{"aria-hidden":"true"}),r("手动")]});if(!$.source&&Jn($.provider))return s.jsxs("span",{className:"src manual",title:r("用户登记的自定义模型;整份清单只属于这一家"),children:[s.jsx("i",{"aria-hidden":"true"}),r("自定义")]});if($.source!=="remote"&&$.source!=="builtin")return s.jsx("span",{className:"rate",children:"—"});const X=$.source==="remote",re=i7(Number($.refreshedAt)||0),P=X?re?r("来自上游目录接口,清单拉取于 {at};刷新失败时保留上一份成功结果",{at:re}):r("来自上游目录接口;刷新失败时保留上一份成功结果"):r("上游目录尚未拉到,用的是内置静态清单;点「刷新模型清单」可重试");return s.jsxs("span",{className:Ve("src",X?"remote":"builtin"),title:P,children:[s.jsx("i",{"aria-hidden":"true"}),r(X?"远程":"内置")]})}function W($){const X=nw($),re=tw($.capOverrides),P=typeof X.maxInputTokens=="number"?X.maxInputTokens:null,V=typeof X.maxOutputTokens=="number"?X.maxOutputTokens:null,J=r("上下文窗口 {input} / 最大输出 Token {output} —— 点击修改模型能力",{input:Mf(P),output:Mf(V)})+Z($);return s.jsxs("button",{type:"button",className:"caps-open",title:J,onClick:()=>bM($.provider||"",$.id),children:[s.jsxs("span",{className:Ve("cap-num",P===null&&"unset",ju($,"maxInputTokens")==="modelsdev"&&"filled"),children:[$O(P),re.includes("maxInputTokens")?s.jsx("i",{className:"cap-mark",title:r("已覆盖上游值")}):null]}),s.jsx("span",{className:"cap-sep",children:"/"}),s.jsxs("span",{className:Ve("cap-num",V===null&&"unset",ju($,"maxOutputTokens")==="modelsdev"&&"filled"),children:[$O(V),re.includes("maxOutputTokens")?s.jsx("i",{className:"cap-mark",title:r("已覆盖上游值")}):null]})]})}function Z($){const X=["maxInputTokens","maxOutputTokens"].filter(re=>ju($,re)==="modelsdev").map(re=>yu[re]);return X.length?r(";其中 {keys} 由 models.dev 补齐",{keys:X.join(r("、"))}):""}function Y($){const X=nw($),re=tw($.capOverrides);return s.jsx("button",{type:"button",className:"caps-open caps-badges",title:r("对下游声明的能力(工具调用 / 图片识别 / 视频识别 / 支持思考)—— 点击修改"),onClick:()=>bM($.provider||"",$.id),children:VO.map(P=>{const V=X[P]??null,J=sw(V),ie=re.includes(P),me=ju($,P);return s.jsxs("span",{className:Ve("cap-dot",J,me==="modelsdev"&&"filled",ie&&"marked"),title:JG(P,V,ie,me),children:[wK[P],ie?s.jsx("i",{className:"cap-mark"}):null]},P)})})}function q($,X,re){async function P(){await Xt().wbConfirm?.ask?.({title:r("移除自定义模型"),html:r("确定移除自定义模型「{id}」?这条登记会被直接移除,之后 /v1/models 不再广告它、请求它也会被拒。",{id:rw(X.id)}),okText:r("移除"),okClass:"danger"})&&xw(Fi(X),()=>gM(X.provider||"",X.id),Jn(X.provider||"")?r("模型已移除"):r("自定义模型已移除"))}switch($.key){case"check":return s.jsx("td",{className:To("cell-check",$.align),children:s.jsx(ta,{checked:p.has(Fi(X)),title:r("勾选后可批量操作"),"aria-label":r("勾选后可批量操作"),onCheckedChange:V=>I(Fi(X),V===!0)})});case"model":return s.jsxs("td",{className:To("cell-model",$.align),children:[s.jsx("div",{className:"mid",children:s.jsx("span",{className:"t","data-copy":X.id,title:r("点击复制:{name}",{name:X.id}),children:X.id})}),X.name&&X.name!==X.id?s.jsx("div",{className:"mname",children:X.name}):null]});case"rate":return s.jsx("td",{className:To("cell-rate",$.align),children:s.jsx("span",{className:"rate",children:X.credits?hK(X.credits):"—"})});case"source":return s.jsx("td",{className:To("cell-source",$.align),children:Q(X)});case"budget":return s.jsx("td",{className:To("cell-budget",$.align),children:W(X)});case"caps":return s.jsx("td",{className:To("cell-caps",$.align),children:Y(X)});case"alias":return s.jsx("td",{className:To("cell-alias",$.align),children:B(X)});case"act":{const V=X7(X.provider||""),J=X.source==="manual"||Jn(X.provider||"");return s.jsx("td",{className:To("cell-act r",$.align),children:s.jsxs("div",{className:"row-actions",children:[s.jsx(se,{variant:"ghost",size:"sm",disabled:!!V,title:V||r("以这个上游模型发一次最小请求,走真实转发链路"),onClick:()=>c({provider:X.provider||"",id:X.id}),children:r("测试")}),J?s.jsx(se,{variant:"ghost",size:"sm",className:"text-destructive",disabled:re,onClick:()=>{P()},children:r("移除")}):null]})})}default:return null}}function G($){const X=e.pending.has(Fi($)),re=p.has(Fi($));return s.jsx("tr",{className:Ve(re&&"sel"),children:N.map(P=>s.jsx(x.Fragment,{children:q(P,$,X)},P.key))},`${$.provider||""}${$.id}`)}function F(){if(!b.length){const J=a?uw()?Su()?r("自定义提供商还没有模型:先在左栏选一家,点「添加模型」登记,或「获取上游模型」从上游拉取"):r(v?"该提供商已不存在(可能已被删除),请刷新列表":"这家还没有模型:点「添加模型」登记,或「获取上游模型」从上游拉取"):r("加载中…"):e.data?r("暂无模型(请先添加账号)"):r("加载中…");return s.jsx("tr",{children:s.jsx("td",{colSpan:k,className:"empty",children:J})})}if(!w.length)return s.jsx("tr",{children:s.jsx("td",{colSpan:k,className:"empty",children:j?r("没有匹配「{keyword}」的模型",{keyword:j}):r("没有匹配当前筛选的模型")})});const $=t==="all"||Su(),X=$&&!j&&e.stateFilter==="all"&&!A.paged,re=new Map;for(const J of w){const ie=J.provider||"";re.has(ie)||re.set(ie,{label:J.providerLabel||ie||r("未知"),items:[]}),re.get(ie)?.items.push(J)}const P=[];let V=0;for(const[J,ie]of re){ie.items.sort((K,be)=>{const ne=+!Uf(K)-+!Uf(be);if(ne!==0||S==="default")return ne;const ce=HM(K.credits),we=HM(be.credits);return ce===null||we===null?ce===we?0:ce===null?1:-1:S==="rate-asc"?ce-we:we-ce});const me=e.expanded.has(J)||!X,he=me?ie.items:ie.items.slice(0,sM),ae=ie.items.length-he.length,oe=A.paged?Math.max(0,A.rangeStart-1-V):0,ee=A.paged?Math.min(he.length,A.rangeEnd-V):he.length,de=oe0?r("(续)"):"",r("{n} 个模型",{n:ie.items.length})]})},`group:${J}`));for(const K of de)P.push(G(K));V+=he.length,ae>0?P.push(s.jsx("tr",{className:"tr-more",children:s.jsx("td",{colSpan:k,children:s.jsx(se,{variant:"ghost",size:"sm",onClick:()=>N7(J),children:r("展开其余 {n} 个模型 ▾",{n:ae})})})},`more:${J}`)):me&&X&&ie.items.length>sM&&P.push(s.jsx("tr",{className:"tr-more",children:s.jsx("td",{colSpan:k,children:s.jsx(se,{variant:"ghost",size:"sm",onClick:()=>k7(J),children:r("收起 ▴")})})},`collapse:${J}`))}return P}return s.jsxs(s.Fragment,{children:[s.jsx("section",{className:"panel",children:s.jsxs("div",{className:"mm",children:[z(),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"?Cu(t,"",Cw):Cu(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:R}),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:()=>yM(),children:r("获取模型")}),s.jsx(se,{id:"btn-add-custom-model",variant:"outline",size:"sm",onClick:()=>M7(),children:r("+ 添加模型")})]})]}),s.jsxs("div",{className:"mm-filters",children:[s.jsx(Pn,{options:u7,value:e.stateFilter,onValueChange:C7,"aria-label":r("按状态筛选"),className:"shrink-0"}),s.jsx(Pn,{options:f7,value:e.sort,onValueChange:T7,"aria-label":r("按倍率排序"),className:"shrink-0"}),s.jsxs(ji,{className:"w-full min-[768px]:w-[240px] flex-none min-[768px]:flex-none",id:"models-search",children:[s.jsx(Si,{type:"search",placeholder:r("搜索模型 ID / 名称 / 映射名…"),"aria-label":r("搜索模型"),autoComplete:"off",value:e.search,onChange:$=>E7($.currentTarget.value)}),s.jsx(wi,{"aria-hidden":"true",children:"⌕"})]}),D.length>0?s.jsxs("span",{className:"batch-chip",children:[r("已选 "),s.jsx("b",{children:D.length}),r(" 个"),s.jsx(se,{id:"btn-batch-models",variant:"outline",size:"xs",title:r("对选中的 {n} 个模型执行批量操作",{n:D.length}),onClick:()=>f(!0),children:r("批量操作")})]}):null]})]}),s.jsx("div",{className:"models-table-wrap",children:s.jsxs("table",{className:"models-table",ref:$=>P7($),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(Di,{className:"models-panel-foot",leading:Su()?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(CK,{context:e.mapping,onClose:O7}):null,e.customModel?s.jsx(TK,{initial:e.customModel,onClose:D7}):null,e.capability?s.jsx(U7,{context:e.capability,onClose:I7}):null,o?s.jsx(W7,{target:o,onClose:()=>c(null)}):null,d?s.jsx(eK,{models:D,onClose:()=>f(!1),onDone:()=>{g(new Set),f(!1)}}):null]})}const kK=r("绑定在「对外名 → 上游模型」这一条映射上的思考等级(列表照抄 OmniProxy 的手动绑定),选「不覆盖」表示不给这条映射指定等级。它会跟着这条映射注入转发,由承载的那家翻译成自己的档位字段(CatPaw 归并成 low/high/max,Qoder 按模型声明的档位归一)。以下几种情况故意不注入:① off / none(关闭思考)—— 本项目没有安全的表达方式;② 表外的自定义等级(各家能力范围不同,无法判断上游收不收);③ 客户端请求体里已经自己指定了档位(那是更明确的意图,绑定不覆盖);④ 这家上游不认识档位字段(如 WorkBuddy / 小浣熊 / AutoClaw / Cline)。注入与跳过都会写进详细日志。");function UM(e,t,a){const o=pM(e),c=(t||"").trim(),d=o.find(f=>f.id.toLowerCase()===c.toLowerCase());return d?d.id:c||o[0]?.id||""}function CK({context:e,onClose:t}){const a=!!e.alias,[o,c]=x.useState(()=>e.provider||mw()[0]?.id||""),[d,f]=x.useState(e.alias||""),[p,g]=x.useState(()=>UM(o,e.target)),[v,y]=x.useState(""),[b,j]=x.useState(!1),[w,S]=x.useState(()=>{const _=If(_f().data,BM(o,p)),L=a?yw(e.alias,e.target,e.provider):"";return L&&_.includes(L)?{select:L,custom:""}:{select:L?oa:"",custom:L}}),N=If(_f().data,BM(o,p)),k=(()=>{const _=mw();for(const L of[e.provider,o])L&&!_.some(z=>z.id===L)&&_.push({id:L,label:Xt().wbProviders?.labelOf?.(L)||L});return _})(),E=(()=>{const _=pM(o),L=(p||"").trim();return L&&!_.some(z=>z.id.toLowerCase()===L.toLowerCase())&&_.unshift({id:L,label:r("{name}(不在该家当前清单里)",{name:L}),off:!0}),_})(),R=k.find(_=>_.id===o)?.label||o||r("(全局)"),C=w.select&&w.select!==oa&&!N.includes(w.select)?{select:oa,custom:w.custom||w.select}:w,A=C.select===oa?C.custom.trim():C.select,D=C.select===oa;function I(_){c(_),g(UM(_,p))}async function M(){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&&Co(_,L)&&Bf().some(z=>Co(z.id,L)&&Co(z.provider,o))){y(r("原始 ID 已作为默认绑定,请直接使用该绑定的开关或等级按钮"));return}j(!0),y(r("保存中…"));try{Vi(await Eg(o,_,L,{reasoning:A})),j(!1),t();const z=A?r(" · 思考等级 {level}",{level:A}):"",U=Xt().wbProviders?.labelOf?.(o)||o;vr(a?r("✅ 已更新 {name} 的思考等级",{name:_}):r("✅ 已添加映射 {name} → {target}({label}){suffix}",{name:_,target:L,label:U,suffix:z}))}catch(z){y(r("保存失败:{message}",{message:ko(z)})),j(!1)}}const O=_=>{_.key==="Enter"&&(_.preventDefault(),M())};return s.jsx(Kt,{open:!0,onOpenChange:(_,L)=>{if(!_){if(b){L.cancel();return}t()}},children:s.jsxs(Yt,{children:[s.jsx($t,{children:s.jsx(Ft,{children:r(a?"设置思考等级":"添加模型映射")})}),s.jsxs(_t,{children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(st,{htmlFor:"mapping-provider",children:r("提供商")}),s.jsxs(ut,{value:o,disabled:!0,onValueChange:_=>I(String(_)),children:[s.jsx(ft,{id:"mapping-provider",className:"w-full",children:s.jsx(dt,{children:k.find(_=>_.id===o)?.label||o})}),s.jsx(pt,{children:k.map(_=>s.jsx(Xe,{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(st,{htmlFor:"mapping-alias",children:r("对外映射名(下游请求时用)")}),s.jsx(Ye,{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(st,{htmlFor:"mapping-upstream",children:r("转发到上游模型")}),s.jsxs(ut,{value:p,disabled:!0,onValueChange:_=>g(String(_)),children:[s.jsx(ft,{id:"mapping-upstream",className:"w-full",children:s.jsx(dt,{children:E.find(_=>_.id===p)?.label||p})}),s.jsx(pt,{children:E.map(_=>s.jsxs(Xe,{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:R}),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(st,{htmlFor:"mapping-reasoning",children:r("思考等级")}),s.jsxs(Ri,{children:[s.jsx(Ai,{render:s.jsx("span",{className:"tip-q",tabIndex:0,"aria-label":r("思考等级的注入规则")}),children:"?"}),s.jsx(Oi,{children:kK})]})]}),s.jsxs(ut,{value:C.select,onValueChange:_=>{const L=String(_);S(z=>({...z,select:L}))},children:[s.jsx(ft,{id:"mapping-reasoning",className:"w-full",autoFocus:a,children:s.jsx(dt,{children:C.select===oa?r("自定义等级…"):C.select||r("不覆盖")})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"",children:r("不覆盖")}),N.map(_=>s.jsx(Xe,{value:_,children:_},_)),s.jsx(Xe,{value:oa,children:r("自定义等级…")})]})]}),D?s.jsx(Ye,{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(en,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",onClick:t,children:r("取消")}),s.jsx(se,{variant:"default",disabled:b,onClick:()=>{M()},children:r(a?"保存等级":"保存映射")})]})]})})}function TK({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=v7();return a&&!N.some(k=>k.id===a)&&N.push({id:a,label:Xt().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 w7(b,N);Vi(k),v(!1),t();const E=y.find(R=>R.id===b)?.label||b;if(Jn(wu()))vr(r("✅ 已登记模型 {name}({label})",{name:N,label:E}));else{const R=k;Array.isArray(R?.models)&&R.models.some(A=>A.id===N&&(A.provider||"")===b)?vr(r("✅ 已登记自定义模型 {name}({label})",{name:N,label:E})):vr(r("✅ 已登记 {name}({label}),但该提供商还没有可用账号,这一行要加上账号后才会显示",{name:N,label:E}),"err")}}catch(k){p(r("保存失败:{message}",{message:ko(k)})),v(!1)}}const S=N=>{N.key==="Enter"&&(N.preventDefault(),w())};return s.jsx(Kt,{open:!0,onOpenChange:(N,k)=>{if(!N){if(g){k.cancel();return}t()}},children:s.jsxs(Yt,{children:[s.jsx($t,{children:s.jsx(Ft,{children:r("添加自定义模型")})}),s.jsxs(_t,{children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(st,{htmlFor:"custom-model-provider",children:r("提供商")}),s.jsxs(ut,{value:b,disabled:e.locked,onValueChange:N=>o(String(N)),children:[s.jsx(ft,{id:"custom-model-provider",className:"w-full",children:s.jsx(dt,{children:j})}),s.jsx(pt,{children:y.map(N=>s.jsx(Xe,{value:N.id,children:N.label},N.id))})]})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(st,{htmlFor:"custom-model-id",children:r("上游模型 ID")}),s.jsx(Ye,{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(en,{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 VM='.page[data-page="gateway"]';let Tw=null;function FM(){if(Tw)return;const e=document.querySelector(VM);e&&(e.replaceChildren(),Tw=wn.createRoot(e),Tw.render(s.jsx(NK,{})))}document.querySelector(VM)?FM():document.addEventListener("DOMContentLoaded",FM,{once:!0});const $M=3065;function EK(){if(Qa().workbuddyDesktop?.platform!=="web")return null;const e=typeof window>"u"?"":window.location?.origin;return e&&e!=="null"?e:null}function qM(e,t){return EK()??(e?`http://127.0.0.1:${e}`:t)}function Qa(){return window}function Rg(e){return e instanceof Error?e.message:String(e)}function Tu(e,t){Qa().wbApp?.toast?.(e,t)}let Gf={backend:null,gatewayBase:qM(0,`http://127.0.0.1:${$M}`)};const Ew=new Set;function Rw(){return Gf}function RK(e){return Ew.add(e),()=>{Ew.delete(e)}}function AK(e){Gf=e;for(const t of Ew)t()}function GM(){return Gf.gatewayBase.replace(/^https?:\/\//,"")}function OK(){return Gf.backend?.ready===!0}function KM(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 Aw=!1;async function Eu(){if(!Aw){Aw=!0;try{const e=Qa().workbuddyDesktop;if(!e)throw new Error("后端桥不可用");const t=await e.getBackendStatus(),a=Number(t?.port)||0,o=Rw(),c={backend:t??null,gatewayBase:qM(a,o.gatewayBase)};c.gatewayBase!==o.gatewayBase&&KM(c.gatewayBase),AK(c),Qa().wbApp?.renderTopbarStatus?.()}catch(e){console.warn("读取后端状态失败:",Rg(e))}finally{Aw=!1}}}function MK(){KM(Gf.gatewayBase),Eu()}async function YM(e){Tu(e||r("正在重启…"));try{await Qa().workbuddyDesktop?.restartApp()}catch(t){Tu(r("重启失败:{reason}",{reason:Rg(t)}),"err")}}const DK={idle:r("结束占用进程"),querying:r("查询中…"),ending:r("结束中…")};function IK({container:e}){const{backend:t,gatewayBase:a}=x.useSyncExternalStore(RK,Rw),[o,c]=x.useState("idle"),d=t?.failure||null,f=GM(),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(()=>{Eu()},[]),x.useEffect(()=>{const j=Qa().workbuddyDesktop?.onBackendError?.(()=>{Eu()});return typeof j=="function"?j:void 0},[]),x.useEffect(()=>{e.title=y},[e,y]);async function b(){if(o!=="idle")return;const j=Qa().workbuddyDesktop;if(j){c("querying");try{const w=await j.getPortOccupant(),S=w?.occupant;if(!S){Tu(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=Qa().wbConfirm?.ask;if(!k||!await k({title:r("结束占用端口的进程"),text:N.join(` +`),okText:r("结束进程"),okClass:"danger"}))return;c("ending"),(await j.endPortOccupant())?.released?(Tu(r("已结束进程 {name}(PID {pid}),端口已释放",{name:String(S.name),pid:String(S.pid)})),await k({title:r("重启程序"),text:r("端口已释放。现在重启程序让网关用这个端口启动?"),okText:r("重启")})?await YM(r("重启中…")):await Eu()):(Tu(r("进程已结束,但端口仍被占用,建议改用「更换端口」"),"err"),await Eu())}catch(w){Tu(r("结束失败:{reason}",{reason:Rg(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:DK[o]}):null,s.jsx(se,{size:"sm",onClick:()=>{LK()},children:r("更换端口")})]}):null]})}let Ow=null;function XM(){if(Ow)return;const e=document.getElementById("sidebar-status");e&&(e.replaceChildren(),Ow=wn.createRoot(e),Ow.render(s.jsx(IK,{container:e})))}const PK={idle:r("保存并重启"),checking:r("校验中…"),saving:r("保存中…")};function _K({status:e,onClose:t}){const a=Number(e?.port)||$M,[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=Qa().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 YM(r("端口已改为 {port},正在重启…",{port:k}))}catch(E){y(Rg(E))}finally{f("idle")}}return s.jsx(Kt,{open:!0,onOpenChange:N=>{N||t()},children:s.jsxs(Yt,{children:[s.jsx($t,{children:s.jsx(Ft,{children:r("更换网关端口")})}),s.jsxs(_t,{children:[s.jsxs(Hn,{children:[s.jsx("h3",{children:r("当前状态")}),s.jsx("p",{children:w})]}),s.jsxs(Hn,{children:[s.jsx("h3",{children:r("新端口")}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2.5",children:[s.jsx(st,{htmlFor:"port-input",className:"text-[12.5px] whitespace-nowrap text-subtle",children:r("端口号")}),s.jsx(Ye,{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(Hn,{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(en,{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:PK[d]})]})]})})}let Kf=null,Ru=null;function QM(){Kf&&(Kf.unmount(),Kf=null),Ru&&(Ru.remove(),Ru=null)}async function LK(){let e=Rw().backend;e||(e=await Qa().workbuddyDesktop?.getBackendStatus().catch(()=>null)??null),QM(),Ru=document.createElement("div"),document.body.append(Ru),Kf=wn.createRoot(Ru),Kf.render(s.jsx(_K,{status:e,onClose:QM}))}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",XM,{once:!0}):XM(),window.wbPortPanel={render:MK,sync:Eu,portLabel:GM,isReady:OK};function Mw(e){return e.source==="subscription"&&(e.port===null||e.port===void 0)}function Fs(){return window}function Un(e,t){Fs().wbApp?.toast?.(e,t)}function Ea(e){return e instanceof Error?e.message:String(e)}function ZM(e){return Fs().wbApp?.formatTime?.(e)||""}function Dw(e){const t=Number(e);return!Number.isFinite(t)||t<0?"":t<1e3?`${Math.round(t)}ms`:`${(t/1e3).toFixed(1)}s`}function Iw(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]||t)}function Au(e){return String(e?.name||e?.id||"")}function zK(e){return e.source==="clash"}function Pw(e){return e.source==="subscription"}function Yf(e){return zK(e)||Pw(e)}function _w(e){return Pw(e)&&e.orphan===!0}function WM(e){return!Yf(e)||_w(e)}const BK=r("来自 Clash Verge 同步(名称 / 端口 / 启用都跟随 Clash),请到 Clash Verge 中修改"),HK=r("该节点来自订阅(名称 / 端口 / 启用跟随订阅与内核),请在「订阅管理」里修改"),UK=r("该节点所属订阅已删除,不会再被同步更新,可手动删除清理");function Ag(e){return _w(e)?UK:Pw(e)?HK:BK}let hs={data:null,loading:!1,error:"",testing:null,pending:new Set,syncing:!1,batchBusy:!1,batchProgress:null,selected:new Set};const Lw=new Set;function VK(e){return Lw.add(e),()=>{Lw.delete(e)}}function FK(){return hs}function Xn(e){hs={...hs,...e},Lw.forEach(t=>t())}function zw(){return hs.data?.items??[]}function $K(e){return hs.selected.has(e)}function qK(e,t){const a=new Set(hs.selected);t?a.add(e):a.delete(e),Xn({selected:a})}function GK(e,t){const a=new Set(hs.selected);for(const o of e)t?a.add(o):a.delete(o);Xn({selected:a})}function KK(){Xn({selected:new Set})}function Eo(e){if(!e||typeof e!="object"||!Array.isArray(e.items))return;const t=new Set(e.items.map(o=>o.id)),a=new Set([...hs.selected].filter(o=>t.has(o)));Xn({data:e,error:"",selected:a})}async function Xf(e=!1){const t=Fs().workbuddyDesktop;if(typeof t?.getProxyPool!="function"){Xn({error:r("当前环境不支持代理池(桥接方法缺失)")});return}e||Xn({loading:!0});try{Eo(await t.getProxyPool())}catch(a){Xn({error:Ea(a)}),e||Un(r("代理列表加载失败:{reason}",{reason:Ea(a)}),"err")}finally{Xn({loading:!1})}}async function YK(){const e=Fs().workbuddyDesktop;if(typeof e?.syncClashToProxyPool!="function"){Un(r("当前环境不支持同步(桥接方法缺失)"),"err");return}if(!hs.syncing){Xn({syncing:!0});try{const t=await e.syncClashToProxyPool();Eo(t),t?.syncError?Un(r("没能同步:{reason}",{reason:t.syncError}),"err"):t?.changes?Un(r("✅ 已同步 Clash Verge 出口({n} 项变更)",{n:t.changes})):Un(r("已是最新,没有需要同步的变更"))}catch(t){Un(r("同步失败:{reason}",{reason:Ea(t)}),"err")}finally{Xn({syncing:!1})}}}async function XK(e){const t=Fs().workbuddyDesktop;if(typeof t?.testProxyPoolItem!="function"){Un(r("当前环境不支持代理测试(桥接方法缺失)"),"err");return}if(!hs.testing){Xn({testing:e.id});try{const a=await t.testProxyPoolItem(e.id);if(a?.items&&Eo({items:a.items}),a?.success){Mw(e)&&Xf(!0);const o=Dw(a.durationMs);Un(r("✅ 「{name}」出口可用{ip}{took}",{name:Au(e),ip:a.ip?r(" 出口 IP {ip}",{ip:a.ip}):"",took:o?` ${o}`:""}))}else Un(r("❌ 「{name}」{error}",{name:Au(e),error:a?.error||r("连接失败")}),"err");a?.saveError&&Un(r("测试结果没能记下:{reason}",{reason:a.saveError}),"err")}catch(a){Un(r("测试失败:{reason}",{reason:Ea(a)}),"err")}finally{Xn({testing:null})}}}async function QK(e,t){const a=Fs().workbuddyDesktop;if(typeof a?.updateProxyPoolItem!="function")return;if(Yf(e)){Un(Ag(e),"err");return}const o=new Set(hs.pending);o.add(e.id),Xn({pending:o});try{Eo(await a.updateProxyPoolItem({...e9(e),enabled:t}));const c=Au(e);Un(t?r("已启用「{name}」",{name:c}):r("已禁用「{name}」",{name:c}))}catch(c){Un(r("保存失败:{reason}",{reason:Ea(c)}),"err")}finally{const c=new Set(hs.pending);c.delete(e.id),Xn({pending:c})}}async function JM(e){const t=Fs().workbuddyDesktop;if(typeof t?.removeProxyPoolItem!="function")return;if(!WM(e)){Un(Ag(e),"err");return}const a=e.usedBy||[],o=a.length?`

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

`:"";if(!await Fs().wbConfirm?.ask?.({title:r("删除代理"),html:r("确定删除「{name}」?{used}",{name:Iw(Au(e)),used:o}),okText:r("删除"),okClass:"danger"}))return;const d=new Set(hs.pending);d.add(e.id),Xn({pending:d});try{const f=await t.removeProxyPoolItem(e.id);Eo(f),Un(r("已删除「{name}」",{name:Au(e)}))}catch(f){Un(r("删除失败:{reason}",{reason:Ea(f)}),"err")}finally{const f=new Set(hs.pending);f.delete(e.id),Xn({pending:f})}}async function ZK(){const e=Fs().workbuddyDesktop;if(typeof e?.testProxyPoolItem!="function"){Un(r("当前环境不支持代理测试(桥接方法缺失)"),"err");return}if(hs.batchBusy||hs.testing)return;const t=zw().filter(p=>hs.selected.has(p.id));if(!t.length)return;Xn({batchBusy:!0,batchProgress:{done:0,total:t.length}});const a=t.filter(Mw).map(p=>p.id);if(a.length){const{ready:p}=await t9(a);if(!p){Xn({testing:null,batchBusy:!1,batchProgress:null}),Un(r("这些节点的监听器还没建好(内核可能卡在拉取订阅),批量测试已中止;稍后重试,或看「订阅」区块的内核状态与日志"),"err");return}}let o=0,c=0,d="";for(const[p,g]of t.entries()){Xn({testing:g.id,batchProgress:{done:p,total:t.length}});try{const v=await e.testProxyPoolItem(g.id);v?.items&&Eo({items:v.items}),v?.success?o+=1:c+=1,v?.saveError&&!d&&(d=v.saveError)}catch{c+=1}}Xn({testing:null,batchBusy:!1,batchProgress:null});const f=c?r("批量测试完成:{ok} 个可用、{failed} 个失败(共 {total} 个)",{ok:o,failed:c,total:t.length}):r("批量测试完成:{ok} 个可用(共 {total} 个)",{ok:o,total:t.length});Un(c?f:`✅ ${f}`,c?"err":"ok"),d&&Un(r("部分测试结果没能记下:{reason}",{reason:d}),"err")}async function WK(){const e=Fs().workbuddyDesktop;if(typeof e?.removeProxyPoolItem!="function"||hs.batchBusy||hs.testing)return;const t=zw().filter(S=>hs.selected.has(S.id)),a=t.filter(S=>WM(S)),o=t.length-a.length;if(!a.length){Un(o?r("选中的 {n} 条都是同步来的只读条目(Clash / 订阅),不能删除",{n:o}):r("没有可删除的条目"),"err");return}const c=a.slice(0,8).map(S=>Iw(Au(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 Fs().wbConfirm?.ask?.({title:r("批量删除代理"),html:`${r("确定删除选中的 {n} 个代理?",{n:a.length})}

${d}

${p}${g}`,okText:r("删除"),okClass:"danger"}))return;Xn({batchBusy:!0,batchProgress:{done:0,total:a.length}});let y=0,b=0,j="";for(const[S,N]of a.entries()){Xn({batchProgress:{done:S,total:a.length}});try{const k=await e.removeProxyPoolItem(N.id);Eo(k),y+=1}catch(k){b+=1,j||(j=Ea(k))}}Xn({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})),Un(b?w.join(r(",")):`✅ ${w.join(r(","))}`,b?"err":"ok")}async function JK(e,t){const a=Fs().workbuddyDesktop,o=e?{...t,id:e.id}:t,c=e?await a?.updateProxyPoolItem?.(o):await a?.createProxyPoolItem?.(o);return Eo(c),c}function e9(e){return{name:e.name,source:"manual",protocol:e.protocol,host:e.host,port:e.port,username:e.username,password:e.password,enabled:e.enabled}}async function e2(){const e=Fs().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 t9(e=[]){const t=Fs().workbuddyDesktop;if(typeof t?.provisionProxyPool!="function")return{pending:!1,ready:!0};try{const a=await t.provisionProxyPool(e.length?{ids:e}:{});return{pending:a?.pending===!0,ready:a?.ready!==!1}}catch{return{pending:!1,ready:!0}}}async function n9(e){const t=Fs().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 s9({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,R]=x.useState(!1),[C,A]=x.useState(!1),[D,I]=x.useState(null);function M(){const L=o.trim();if(!L)return{error:r("请填写代理名称")};const z=p.trim();if(!z)return{error:r("请填写代理主机地址")};const U=Number(v);return!Number.isInteger(U)||U<1||U>65535?{error:r("代理端口必须是 1-65535 的整数")}:{payload:{name:L,source:"manual",protocol:d,host:z,port:U,username:b.trim(),password:w,enabled:N}}}async function O(){if(C)return;const L=M();if("error"in L){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",L.error]}));return}const z=L.payload,U={source:"custom",protocol:z.protocol,host:z.host,port:z.port,username:z.username,password:z.password};A(!0),I(r("正在连接上游…"));try{const B=await Fs().workbuddyDesktop?.testProxy?.({proxy:U});if(B?.success){const Q=Dw(B.durationMs);I(s.jsxs("span",{className:"text-success",children:[r("✅ 出口可用"),B.ip?r(" 出口 IP {ip}",{ip:B.ip}):"",Q?` ${Q}`:""]}))}else I(s.jsxs("span",{className:"text-destructive",children:["❌ ",B?.error||r("连接失败")]}))}catch(B){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",Ea(B)]}))}finally{A(!1)}}async function _(){if(E)return;const L=M();if("error"in L){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",L.error]}));return}R(!0),I(null);try{await JK(e,L.payload),Un(a?r("已保存「{name}」",{name:o.trim()}):r("已新增「{name}」",{name:o.trim()})),t()}catch(z){I(s.jsxs("span",{className:"text-destructive",children:["❌ ",Ea(z)]})),R(!1)}}return s.jsx(Kt,{open:!0,onOpenChange:L=>{!L&&!E&&t()},children:s.jsxs(Yt,{className:"max-w-[560px]",children:[s.jsx($t,{children:s.jsx(Ft,{children:r(a?"编辑代理":"新增代理")})}),s.jsxs(_t,{className:"flex flex-col gap-3.5",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(st,{htmlFor:"proxy-name",children:r("名称")}),s.jsx(Ye,{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(st,{htmlFor:"proxy-protocol",children:r("协议")}),s.jsxs(ut,{value:d,onValueChange:L=>f(L),children:[s.jsx(ft,{id:"proxy-protocol",className:"min-w-[110px]",children:s.jsx(dt,{children:d==="socks5"?"SOCKS5":"HTTP"})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"http",children:"HTTP"}),s.jsx(Xe,{value:"socks5",children:"SOCKS5"})]})]})]}),s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1.5",children:[s.jsx(st,{htmlFor:"proxy-host",children:r("主机")}),s.jsx(Ye,{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(st,{htmlFor:"proxy-port",children:r("端口")}),s.jsx(Ye,{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(st,{htmlFor:"proxy-user",children:r("用户名")}),s.jsx(Ye,{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(st,{htmlFor:"proxy-pass",children:r("密码")}),s.jsx(Ye,{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(ps,{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:D})]}),s.jsxs(en,{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 r9({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 D=await e2();if(!A||D===null)return;f(String(D.listenerPortBase??"")),g(String(D.listenerPortEnd??"")),y(String(D.testUrl??"")),j(D.defaults??{}),a(!1)}catch(D){if(!A)return;S(Ea(D)),a(!1)}})(),()=>{A=!1}},[]);function E(){const A=Number(d),D=Number(p);if(!Number.isInteger(A)||A<1||A>65535||!Number.isInteger(D)||D<1||D>65535)return S(r("端口范围必须是 1-65535 的整数")),null;if(A>D)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:D,testUrl:I})}async function R(){if(o||t)return;const A=E();if(A){c(!0);try{await n9(A),k(!0)}catch(D){S(Ea(D))}finally{c(!1)}}}function C(){f(String(b.listenerPortBase??"")),g(String(b.listenerPortEnd??"")),y(String(b.testUrl??"")),k(!1),S("")}return s.jsx(Kt,{open:!0,onOpenChange:A=>{!A&&!o&&e()},children:s.jsxs(Yt,{className:"max-w-[560px]",children:[s.jsx($t,{children:s.jsx(Ft,{children:r("代理设置")})}),s.jsx(_t,{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(st,{htmlFor:"proxy-settings-base",children:r("节点端口范围(起始)")}),s.jsx(Ye,{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(st,{htmlFor:"proxy-settings-end",children:r("节点端口范围(结束)")}),s.jsx(Ye,{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(st,{htmlFor:"proxy-settings-url",children:r("出口测试网址")}),s.jsx(Ye,{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(en,{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:()=>{R()},children:r(o?"保存中…":"保存")})]})]})})}function Mn(){return window}function tr(e,t){Mn().wbApp?.toast?.(e,t)}function Dr(e){return e instanceof Error?e.message:String(e)}function t2(e){const t=String(e||"").trim();return/^https?:\/\//i.test(t)?t:""}async function n2(e){const t=t2(e);if(!t){tr(r("链接地址不受支持"),"err");return}try{await Mn().workbuddyDesktop?.openReleasePage(t)}catch(a){tr(r("打开链接失败:{error}",{error:Dr(a)}),"err")}}const Og="1127656296",a9=`assets/qq-group/${Og}.jpg`;function s2(e){return Mn().wbMarkdown?.render?.(e)||""}function r2(e){const a=e.target?.closest?.("[data-external]");a&&(e.preventDefault(),n2(a.dataset.external||""))}const Qf="__proxy_other__",a2={proxyChoice:null,pool:null,poolError:""};async function l9(){const e=Mn().workbuddyDesktop,t={...a2};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=Dr(a)}return t}async function o9(e){if(e===Qf)return null;const t=Mn().workbuddyDesktop;if(!t?.setUpdateProxy)return null;const a=e===""?null:{source:"pool",proxyId:e.slice(Ka.length)};try{const o=await t.setUpdateProxy({proxy:a}),c=o?.proxy??null,d=o?.saved!==!1;return d?tr(c?r("✅ 更新出网已切换为 {label}",{label:c.label||r("指定代理")}):r("✅ 更新出网已切换为直连")):tr(r("出网线路已切换,但写入磁盘失败(重启后会恢复原线路)"),"err"),{choice:c,saved:d}}catch(o){return tr(r("保存失败:{error}",{error:Dr(o)}),"err"),null}}function l2(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=`${Ka}${t.config.proxyId}`:t&&(f=Qf);const p=[{value:"",label:r("直连")}];for(const g of d)p.push({value:`${Ka}${g.id}`,label:lf(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===Qf){const g=a==="clash"?r("Clash 出口:"):a==="custom"?r("自定义:"):"";p.push({value:Qf,label:`${g}${o}${c?r("(不可用)"):""}`})}else a==="pool"&&!d.some(g=>`${Ka}${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 cr(){return window}function Sn(e,t){cr().wbApp?.toast?.(e,t)}function ia(e){return e instanceof Error?e.message:String(e)}let dn={data:null,loading:!1,error:"",pending:!1,refreshing:null};const Bw=new Set;function Mg(e){return Bw.add(e),()=>{Bw.delete(e)}}function Dg(){return dn}function Vn(e){dn={...dn,...e},Bw.forEach(t=>t())}function i9(){return dn.data?.items??[]}function Ou(){return dn.data?.kernel??null}function $i(e){!e||typeof e!="object"||!Array.isArray(e.items)||Vn({data:e,error:""})}function Ro(){Xf(!0)}async function qi(e=!1){const t=cr().workbuddyDesktop;if(typeof t?.getSubscriptions!="function"){Vn({error:r("当前环境不支持订阅(桥接方法缺失)")});return}e||Vn({loading:!0});try{$i(await t.getSubscriptions())}catch(a){Vn({error:ia(a)})}finally{e||Vn({loading:!1})}}const c9=20;function u9(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 Gi(){const e=cr().workbuddyDesktop;if(typeof e?.getSubscriptions=="function")for(let t=0;tsetTimeout(o,1500)),Ro();let a;try{a=await e.getSubscriptions()}catch{return}if($i(a),t>=1&&a&&Array.isArray(a.items)&&u9(a))return}}async function d9(e,t){const o=await cr().workbuddyDesktop?.addSubscription?.({name:e.trim(),url:t.trim(),enabled:!0});return $i(o),Sn(r("已新增订阅「{name}」,内核正在同步节点…",{name:e.trim()})),Ro(),Gi(),o??null}async function f9(e,t){const o=await cr().workbuddyDesktop?.saveSubscription?.({id:e.id,...t});$i(o),Sn(r("已保存「{name}」",{name:t.name.trim()})),Ro(),Gi()}async function p9(e,t){const a=cr().workbuddyDesktop;if(!dn.pending){Vn({pending:!0});try{const o=await a?.saveSubscription?.({id:e.id,name:e.name,url:e.url,enabled:t});$i(o),Sn(t?r("已启用「{name}」",{name:e.name}):r("已禁用「{name}」",{name:e.name})),Ro(),Gi()}catch(o){Sn(r("保存失败:{reason}",{reason:ia(o)}),"err")}finally{Vn({pending:!1})}}}async function m9(e){const t=cr().workbuddyDesktop;if(!(dn.refreshing||dn.pending)){Vn({refreshing:e.id});try{const a=await t?.refreshSubscription?.(e.id);$i(a),Sn(r("已刷新「{name}」,正在同步节点…",{name:e.name})),Ro(),Gi()}catch(a){Sn(r("刷新失败:{reason}",{reason:ia(a)}),"err")}finally{Vn({refreshing:null})}}}async function h9(e){const t=cr().workbuddyDesktop;if(await window.wbConfirm?.ask?.({title:r("删除订阅"),html:r("确定删除「{name}」?它在代理池里的节点会一并移除,引用这些节点的账号会回退直连。",{name:e.name||e.id}),okText:r("删除"),okClass:"danger"})&&!dn.pending){Vn({pending:!0});try{const o=await t?.removeSubscription?.(e.id);$i(o),Sn(r("已删除「{name}」",{name:e.name||e.id})),Ro(),Gi()}catch(o){Sn(r("删除失败:{reason}",{reason:ia(o)}),"err")}finally{Vn({pending:!1})}}}async function g9(e){const t=cr().workbuddyDesktop;if(typeof t?.downloadKernel!="function"){Sn(r("当前环境不支持订阅(桥接方法缺失)"),"err");return}if(!dn.pending){Vn({pending:!0});try{const a=await t.downloadKernel(e);a&&dn.data&&Vn({data:{...dn.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&&dn.data&&Vn({data:{...dn.data,kernel:d}}),!d||d.download.state!=="downloading")break}const o=dn.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("✅ 内核下载完成,正在启动…")),Gi())}catch(a){Sn(r("内核下载失败:{reason}",{reason:ia(a)}),"err")}finally{Vn({pending:!1})}}}async function x9(){const e=cr().workbuddyDesktop;if(typeof e?.cancelKernelDownload!="function")return"none";try{const t=await e.cancelKernelDownload();if(t&&dn.data&&Vn({data:{...dn.data,kernel:t}}),t?.canceled===!1)return"none";for(let o=0;o<20;o+=1){const c=await e.getKernelStatus?.();if(c&&dn.data&&Vn({data:{...dn.data,kernel:c}}),c&&c.download.state!=="downloading")break;await new Promise(d=>setTimeout(d,250))}const a=dn.data?.kernel?.download.state;return a==="canceled"?"canceled":a==="done"?"done":"stalled"}catch(t){return Sn(r("停止下载失败:{reason}",{reason:ia(t)}),"err"),"none"}}async function b9(){const e=cr().workbuddyDesktop;if(!dn.pending){Vn({pending:!0});try{const t=await e?.restartKernel?.();t&&dn.data&&Vn({data:{...dn.data,kernel:t}}),Sn(r("内核正在启动…")),Ro(),Gi()}catch(t){Sn(r("内核启动失败:{reason}",{reason:ia(t)}),"err")}finally{Vn({pending:!1})}}}async function v9(){const e=cr().workbuddyDesktop;if(typeof e?.removeKernel!="function"){Sn(r("当前环境不支持订阅(桥接方法缺失)"),"err");return}const t=Ou()?.version;if(!await window.wbConfirm?.ask?.({title:r("删除内核"),html:r("确定删除已下载的内核{version}?内核文件与端口映射会被移除,订阅节点会变成「未分配端口」,引用它们的账号会暂时回退直连;订阅本身保留,重新下载内核后会重新分配端口。",{version:t?`(${t})`:""}),okText:r("删除内核"),okClass:"danger"})||dn.pending)return;Vn({pending:!0});const o=Ou()?.lastError||"";try{const c=await e.removeKernel();c&&dn.data&&Vn({data:{...dn.data,kernel:c}});for(let f=0;f<20;f+=1){const p=await e.getKernelStatus?.();if(p&&dn.data&&Vn({data:{...dn.data,kernel:p}}),p&&p.installed===!1||p?.lastError&&p.lastError!==o)break;await new Promise(g=>setTimeout(g,500))}const d=dn.data?.kernel;if(d?.installed===!1)Sn(r("已删除内核(订阅与账号引用保留,重新下载后会重新分配端口)")),Ro();else{const f=d?.lastError&&d.lastError!==o?d.lastError:r("内核目录没能删掉(可能仍被进程占用),稍后重试一次");Sn(r("删除内核失败:{reason}",{reason:f}),"err")}qi(!0)}catch(c){Sn(r("删除内核失败:{reason}",{reason:ia(c)}),"err"),qi(!0)}finally{Vn({pending:!1})}}async function y9(e){const t=cr().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 o2(e){return(Math.max(0,Number(e)||0)/1024/1024).toFixed(1)}function j9(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")||e.startsWith("/")}function w9({onClose:e}){const t=x.useSyncExternalStore(Mg,Dg),a=Ou(),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),[R,C]=x.useState("");x.useEffect(()=>{let z=!0;return(async()=>{try{const U=(await cr().workbuddyDesktop?.getProxyPool?.())?.items;if(!Array.isArray(U))throw new Error(r("代理池响应异常"));z&&p(U)}catch(U){if(!z)return;p([]),v(ia(U))}})(),()=>{z=!1}},[]),x.useEffect(()=>{a?.installed&&e()},[a?.installed]);const A=l2({proxyChoice:a?.downloadProxy??null,pool:f,poolError:g}),D=y??A.current,I=A.items.find(z=>z.value===D)??A.selected,M=a?.kernelDirDefault||"";async function O(){if(S)return;const z=j.trim();if(z&&!j9(z)){C(r("存放位置要填绝对路径,例如 D:\\proxy-kernel"));return}C(""),N(!0);try{const U={dir:z};D!==Qf&&(U.proxy=D===""?null:{source:"pool",proxyId:D.slice(Ka.length)}),g9(U)}finally{N(!1)}}async function _(){if(!k){E(!0);try{const z=await x9();z==="done"?Sn(r("下载已经完成,停止没赶上(内核已安装)")):z==="none"?Sn(r("当前没有正在进行的下载"),"err"):z==="stalled"&&Sn(r("停止请求已发出,但下载还没收手,稍后再看一次进度"),"err")}finally{E(!1)}}}async function L(){const z=cr().workbuddyDesktop;if(typeof z?.pickFolder!="function"){Sn(r("当前环境不支持选择文件夹,直接填写绝对路径即可"),"err");return}try{const U=await z.pickFolder(j.trim()||M||null);if(U?.unsupported){Sn(r("当前环境不支持选择文件夹,直接填写绝对路径即可"),"err");return}if(U?.canceled||!U?.path)return;w(U.path)}catch(U){Sn(r("打开文件夹选择框失败:{reason}",{reason:ia(U)}),"err")}}return s.jsx(Kt,{open:!0,onOpenChange:z=>{z||e()},children:s.jsxs(Yt,{className:"w-[min(520px,calc(100vw-48px))]",children:[s.jsxs($t,{children:[s.jsx(Ft,{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(_t,{className:"flex flex-col gap-3",children:[s.jsx(qd,{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:o2(o?.received),total:o2(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(_t,{className:"flex flex-col gap-3.5",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(st,{htmlFor:"kernel-proxy",children:r("下载线路")}),s.jsxs(ut,{value:D,onValueChange:z=>b(String(z)),children:[s.jsx(ft,{id:"kernel-proxy",className:Ve("w-full",A.broken&&"border-destructive-bd"),children:s.jsx(dt,{className:"min-w-0 truncate",children:I?.label||r("直连")})}),s.jsx(pt,{children:A.items.map(z=>s.jsx(Xe,{value:z.value,disabled:z.disabled,children:z.label},z.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(st,{htmlFor:"kernel-dir",children:r("存放位置")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ye,{id:"kernel-dir",className:"min-w-0 flex-1 font-mono text-[12px]",autoComplete:"off",spellCheck:!1,value:j,placeholder:M,onChange:z=>w(z.currentTarget.value)}),s.jsx(se,{variant:"outline",size:"sm",className:"flex-none",onClick:()=>{L()},children:r("选择目录…")}),M&&j.trim()!==M?s.jsx(se,{variant:"ghost",size:"sm",className:"flex-none",title:M,onClick:()=>w(M),children:r("恢复默认")}):null]}),s.jsx("div",{className:"text-[12px] text-subtle",children:r("内核二进制 / 配置 / 端口映射都会放在这里,默认 {dir};目录不存在会在下载开始时自动创建。",{dir:M||"—"})})]}),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,R?s.jsx("span",{className:"text-[12px] text-destructive",children:R}):null]}),s.jsx(en,{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 i2({showPortRange:e=!1}){const t=x.useSyncExternalStore(Mg,Dg),a=Ou(),[o,c]=x.useState(null),[d,f]=x.useState(!1);x.useEffect(()=>{let v=!0;return(async()=>{try{const y=await e2();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:()=>{b9()},children:a?.running?r("重启内核"):r("启动内核")}),s.jsx(se,{size:"sm",variant:"destructive",disabled:t.pending||p,onClick:()=>{v9()},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(qd,{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:c2(a.download.received),total:c2(a.download.total)}):r("下载中…")})]}):null,a?.lastError?s.jsx("span",{className:"text-[12px] text-destructive",children:a.lastError}):null,d?s.jsx(w9,{onClose:()=>f(!1)}):null]})}function S9({onClose:e}){const t=x.useSyncExternalStore(Mg,Dg),a=i9(),o=t.data!==null,[c,d]=x.useState(null);return x.useEffect(()=>{qi()},[]),s.jsxs(Kt,{open:!0,onOpenChange:f=>{f||e()},children:[s.jsxs(Yt,{className:"w-[min(880px,calc(100vw-48px))]",children:[s.jsxs($t,{children:[s.jsx(Ft,{children:r("订阅管理")}),s.jsxs("span",{className:"text-[11.5px] text-subtle",children:[o?r("{n} 条订阅",{n:a.length}):r("加载中…")," · ",r("节点由内核起成本地监听器,镜像进代理池")]})]}),s.jsxs(_t,{className:"flex flex-col gap-3",children:[s.jsx(i2,{}),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=Ou()?.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.jsxs("div",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"font-mono text-[12px] text-text-2",title:f.url,children:N9(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:u2(p,f)>0?s.jsx(ze,{variant:"secondary",children:r("{n} 个",{n:u2(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:ZM(p.at)}):s.jsx("span",{className:"text-subtle",children:r("未同步")})}),s.jsx("td",{className:"ta-center",children:s.jsx(ps,{checked:f.enabled,disabled:t.pending,"aria-label":r("启用订阅「{name}」",{name:f.name||r("未命名")}),onCheckedChange:g=>{p9(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,onClick:()=>{m9(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:()=>{h9(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("还没有订阅:粘贴订阅链接,或从图片识别二维码导入。")}),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(en,{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(k9,{item:c.item,onClose:()=>d(null)}):null]})}function c2(e){return!Number.isFinite(e)||e<=0?"—":(e/1e3/1e3).toFixed(1)}function N9(e){try{const t=new URL(e);return t.host+(t.pathname!=="/"?"/…":"")}catch{return e.slice(0,60)}}function u2(e,t){return e?.count??t.nodeCount}function k9({item:e,onClose:t}){const a=e!==null,[o,c]=x.useState(e?.name||""),[d,f]=x.useState(e?.url||""),[p,g]=x.useState(e?e.enabled:!0),[v,y]=x.useState(!1),[b,j]=x.useState(!1),[w,S]=x.useState(null),N=x.useRef(null);async function k(){if(v)return;const C=o.trim(),A=d.trim();if(!C){S(s.jsxs("span",{className:"text-destructive",children:["❌ ",r("请填写订阅名称")]}));return}if(!(A.startsWith("http://")||A.startsWith("https://"))){S(s.jsxs("span",{className:"text-destructive",children:["❌ ",r("订阅链接必须是 http:// 或 https:// 开头")]}));return}y(!0);try{a?await f9(e,{name:C,url:A,enabled:p}):await d9(C,A),t()}catch(D){S(s.jsxs("span",{className:"text-destructive",children:["❌ ",ia(D)]})),y(!1)}}async function E(C){if(!b){j(!0),S(r("正在识别二维码…"));try{const A=await y9(C);f(A),S(s.jsxs("span",{className:"text-success",children:["✅ ",r("已识别订阅链接")]}))}catch(A){S(s.jsxs("span",{className:"text-destructive",children:["❌ ",ia(A)]}))}finally{j(!1)}}}function R(C){const D=Array.from(C.clipboardData?.files||[]).find(I=>I.type.startsWith("image/"));D&&(C.preventDefault(),E(D))}return s.jsx(Kt,{open:!0,onOpenChange:C=>{!C&&!v&&t()},children:s.jsxs(Yt,{className:"max-w-[560px]",overlayForceRender:!0,onPaste:R,children:[s.jsx($t,{children:s.jsx(Ft,{children:r(a?"编辑订阅":"新增订阅")})}),s.jsxs(_t,{className:"flex flex-col gap-3.5",children:[s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(st,{htmlFor:"sub-name",children:r("名称")}),s.jsx(Ye,{id:"sub-name",maxLength:60,autoComplete:"off",spellCheck:!1,placeholder:r("例如:我的机场"),value:o,onChange:C=>c(C.currentTarget.value)})]}),s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsx(st,{htmlFor:"sub-url",children:r("订阅链接")}),s.jsx(Ye,{id:"sub-url",autoComplete:"off",spellCheck:!1,placeholder:"https://…",value:d,onChange:C=>f(C.currentTarget.value)}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(se,{size:"sm",variant:"outline",disabled:b,onClick:()=>N.current?.click(),children:r(b?"识别中…":"从图片识别二维码")}),s.jsx("span",{className:"text-[11px] text-subtle",children:r("也可以把二维码截图直接粘贴到弹窗里(Ctrl+V)")}),s.jsx("input",{ref:N,type:"file",accept:"image/*",className:"hidden",onChange:C=>{const A=C.currentTarget.files?.[0];A&&E(A),C.currentTarget.value=""}})]})]}),s.jsxs("div",{className:"flex flex-row items-center gap-2.5",children:[s.jsx(ps,{checked:p,onCheckedChange:g,"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("订阅内容由内核定时刷新(每 24 小时);节点数与同步状态在保存后由轮询刷新,稍等几秒。")}),s.jsx("div",{className:"min-h-[18px] text-xs text-subtle",children:w})]}),s.jsxs(en,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{variant:"outline",disabled:v,onClick:t,children:r("取消")}),s.jsx(se,{variant:"default",disabled:v||b,onClick:()=>{k()},children:r(v?"保存中…":"保存")})]})]})})}const Hw=[{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"}],C9={pick:"p-pick",name:"",addr:"p-addr",state:"p-state",test:"p-test",act:"p-act"},d2="proxies";function Uw(){return window}let Ig=null,f2=null;function p2(){return Ig?Ig.apply([...Hw]):Hw.map(e=>({...e,align:e.align??"left"}))}function T9(){Uw().wbTableColumns?.repaint?.(d2)}function E9(e){if(f2=e,Ig)return!0;const t=Uw().wbColSettings;return t?.register?(Ig=t.register({id:d2,label:r("代理池表"),columns:Hw.map(a=>({key:a.key,label:a.label,align:a.align??"left"})),mount:()=>document.querySelector('.page[data-page="proxies"] .panel-head .head-actions'),onChange:()=>f2?.()}),!0):!1}function R9(){Uw().wbColSettings?.close?.()}function A9(){const e=x.useSyncExternalStore(VK,FK),t=x.useSyncExternalStore(Mg,Dg).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),[,R]=x.useReducer(ae=>ae+1,0),C=zw(),A=e.data!==null,D=e.selected.size,I=C.filter(ae=>e.selected.has(ae.id)&&Yf(ae)).length,M=e.batchProgress;x.useEffect(()=>{qi()},[]),x.useLayoutEffect(()=>{if(!E9(()=>R())){const ae=window.setTimeout(()=>E(oe=>oe+1),50);return()=>window.clearTimeout(ae)}R()},[k]),x.useLayoutEffect(()=>{T9()}),x.useEffect(()=>()=>{R9()},[]);function O(ae){return ae.port===null||ae.port===void 0?"wait":ae.lastTest?.at?ae.lastTest.success?"ok":"fail":"none"}const _=g.trim().toLowerCase(),L=D9(C,t);function z(ae){return j==="all"?!0:j==="manual"||j==="clash"||j==="subscription"?Za(ae)===j:j===h2?!!ae.orphan:ae.source==="subscription"&&!ae.orphan&&ae.providerId===j}function U(ae){return!(y!=="all"&&Za(ae)!==y||!z(ae)||S!=="all"&&O(ae)!==S||_&&![ae.name,Sh(ae),ae.host,ae.protocol,String(ae.port??"")].join(" ").toLowerCase().includes(_))}function B(ae){const oe=ae??"all";w(oe),b(oe==="all"?"all":oe==="manual"||oe==="clash"?oe:"subscription")}function Q(ae){b(ae),w("all")}const W=C.filter(U),Z=W.map(ae=>ae.id),Y=Z.length>0&&Z.every(ae=>e.selected.has(ae)),q=Z.some(ae=>e.selected.has(ae))&&!Y,G=p2(),F=[];for(const ae of m2())F.push(...W.filter(oe=>Za(oe)===ae.key));const $=$h(W.length,"proxies"),X=$.paged?$.slice(F):F,re=new Map;for(const ae of W)re.set(Za(ae),(re.get(Za(ae))??0)+1);x.useEffect(()=>{$.goto(1)},[_,y,j,S]);function P(ae){const oe=ae.lastTest;if(!oe||!oe.at)return s.jsx("span",{className:"text-subtle",children:r("未测试")});const ee=Dw(oe.durationMs);return s.jsxs("div",{className:"flex flex-col gap-0.5 leading-[1.5] min-w-0",children:[s.jsxs("span",{className:oe.success?"text-success":"text-destructive",children:[oe.success?r("✅ {ip}",{ip:oe.ip||r("连接成功")}):r("❌ 连接失败"),ee?` ${ee}`:"",s.jsxs("span",{className:"text-[11px] text-subtle",children:[" ",ZM(oe.at)]})]}),oe.success?null:s.jsx("span",{className:"overflow-hidden text-ellipsis whitespace-nowrap text-[11px] text-subtle",title:String(oe.error||r("连接失败")),children:String(oe.error||r("连接失败"))})]})}function V(ae){const oe=ae.usedBy||[],ee=[];return ae.protocol&&ee.push(ae.protocol),oe.length&&ee.push(s.jsx("span",{className:"text-warn",title:oe.map(de=>String(de.name||de.id||"")).join(r("、")),children:r("{n} 个账号在用",{n:oe.length})})),ee.length?s.jsx("span",{className:"text-[11px] text-subtle",children:ee.map((de,K)=>s.jsxs(x.Fragment,{children:[K?" · ":"",de]},K))}):null}function J(ae){if(ae.resolveError)return s.jsx("span",{className:"text-destructive",title:ae.resolveError,children:r("解析失败")});if(Mw(ae)){const ee=Ou()?.installed===!1;return s.jsx("span",{className:"text-subtle",title:r(ee?"代理内核未安装(在「订阅管理」里下载内核后,节点会自动分配监听端口)":"还没有监听端口(点「测试」会自动补建并等它就绪;或在账号里引用它,保存后自动补建)"),children:Sh(ae)||r("未分配端口")})}const oe=Sh(ae);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:oe||void 0,children:oe||"—"}),oe?s.jsx(se,{variant:"ghost",size:"icon-xs",className:"copy-btn flex-none","data-copy":oe,title:r("复制地址"),children:"⧉"}):null]})}function ie(ae,oe,ee,de){const K=ee||e.batchBusy;switch(ae){case"pick":return s.jsx(ta,{checked:de,title:r("勾选后可批量操作"),"aria-label":r("勾选「{name}」",{name:oe.name||r("未命名")}),onCheckedChange:be=>qK(oe.id,be)});case"name":return s.jsxs("div",{className:"flex flex-col gap-0.5 leading-[1.5] min-w-0",children:[s.jsx("b",{children:oe.name||r("未命名")}),V(oe)]});case"addr":return J(oe);case"state":{const be=Yf(oe),ne=Ag(oe);return s.jsx(ps,{checked:oe.enabled,disabled:K||be,"aria-label":r("启用「{name}」",{name:oe.name||r("未命名")}),title:be?ne:void 0,onCheckedChange:ce=>{QK(oe,ce)}})}case"test":return P(oe);case"act":{const be=_w(oe);Yf(oe);const ne=Ag(oe),ce=e.testing===oe.id;return s.jsxs("div",{className:"row-actions",children:[s.jsx(se,{size:"sm",variant:"ghost",disabled:K||e.testing!==null,onClick:()=>{XK(oe)},children:r(ce?"测试中…":"测试")}),oe.source!=="clash"&&oe.source!=="subscription"?s.jsxs(s.Fragment,{children:[s.jsx(se,{size:"sm",variant:"ghost",disabled:K,onClick:()=>o({item:oe}),children:r("编辑")}),s.jsx(se,{size:"sm",variant:"destructive",disabled:K,onClick:()=>{JM(oe)},children:r("删除")})]}):null,be?s.jsx(se,{size:"sm",variant:"destructive",disabled:K,title:ne,onClick:()=>{JM(oe)},children:r("删除")}):null]})}default:return null}}function me(ae){const oe=e.pending.has(ae.id),ee=$K(ae.id);return s.jsx("tr",{className:Ve(ae.enabled?"":"off",ee&&"bg-primary-soft"),"data-id":ae.id,children:G.map(de=>s.jsx("td",{className:`ta-${de.align}`,children:ie(de.key,ae,oe,ee)},de.key))},ae.id)}function he(){if(!C.length)return s.jsx("tr",{children:s.jsx("td",{colSpan:G.length,className:"empty",children:r(A?"还没有代理。点右上角「+ 新增代理」手填一个,点「同步 Clash Verge」把 Clash 的出口导进来,或在「订阅管理」里导入订阅节点。":"加载中…")})});if(!W.length)return s.jsx("tr",{children:s.jsx("td",{colSpan:G.length,className:"empty",children:_?r("没有匹配「{kw}」的出口",{kw:g.trim()}):r("没有匹配当前筛选的出口")})});const ae=[];let oe="";for(const ee of X){const de=Za(ee);if(de!==oe){oe=de;const K=m2().find(be=>be.key===de);ae.push(s.jsx("tr",{className:"tr-group",children:s.jsxs("td",{colSpan:G.length,children:[s.jsx("span",{className:"prov-tag",children:K?.label??de}),r("{n} 个",{n:re.get(de)??0}),K?.note?s.jsxs("span",{className:"font-normal",children:[" · ",K.note]}):null]})},`group:${de}:${ae.length}`))}ae.push(me(ee))}return s.jsx(s.Fragment,{children:ae})}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:()=>{YK()},children:e.syncing?r("同步中…"):r("同步 Clash Verge")}),s.jsx(se,{variant:"outline",disabled:e.loading||e.batchBusy,onClick:()=>{Xf(),qi()},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(i2,{showPortRange:!0})}),D>0?s.jsxs("div",{className:"batch-bar active",children:[s.jsxs("span",{className:"batch-count",children:[r("已选")," ",s.jsx("b",{children:D})," ",r("个 · 共")," ",s.jsx("b",{children:W.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:()=>{ZK()},children:M?r("测试中 {done}/{total}",{done:M.done,total:M.total}):r("批量测试")}),s.jsx(se,{variant:"destructive",disabled:e.batchBusy,onClick:()=>{WK()},children:r("批量删除")}),s.jsx(se,{variant:"outline",disabled:e.batchBusy,onClick:()=>KK(),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(ji,{className:"w-[clamp(150px,22vw,220px)]",children:[s.jsx(Si,{type:"search",value:g,"aria-label":r("搜索节点"),placeholder:r("搜索名称 / 地址 / 端口"),onChange:ae=>v(ae.currentTarget.value)}),s.jsx(wi,{align:"inline-start","aria-hidden":"true",children:s.jsx(I9,{})})]}),s.jsxs(ut,{value:j,onValueChange:B,children:[s.jsx(ft,{className:"w-[clamp(150px,18vw,210px)]","aria-label":r("按提供方筛选"),children:s.jsx(dt,{children:L.find(ae=>ae.value===j)?.label??r("全部提供方")})}),s.jsx(pt,{children:L.map(ae=>s.jsx(Xe,{value:ae.value,children:s.jsxs("span",{className:"flex w-full items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate"+(ae.count?"":" text-subtle"),children:ae.label}),s.jsx("span",{className:"flex-none text-[11px] text-subtle",children:ae.count})]})},ae.value))})]}),s.jsx(Pn,{options:O9(C),value:y,onValueChange:Q,"aria-label":r("按来源筛选")}),s.jsx(Pn,{options:M9(C),value:S,onValueChange:N,"aria-label":r("按状态筛选")}),s.jsx("span",{className:"ml-auto text-[11px] text-subtle",children:r("显示 {n} / 共 {total} 个出口",{n:W.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:G.map(ae=>s.jsx("col",{"data-col":ae.key,className:C9[ae.key]||void 0},ae.key))}),s.jsx("thead",{children:s.jsx("tr",{children:G.map(ae=>s.jsx("th",{"data-col":ae.key,className:`ta-${ae.align}`,children:ae.key==="pick"?s.jsx(ta,{checked:Y,indeterminate:q,disabled:!Z.length,title:r("全选当前筛选出的出口"),"aria-label":r("全选当前筛选出的出口"),onCheckedChange:oe=>GK(Z,oe)}):ae.label},ae.key))})}),s.jsx("tbody",{children:he()})]})}),s.jsx(Di,{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:W.length,page:$.page,pageCount:$.pageCount,size:$.size,onSizeChange:$.setSize,onPageChange:$.goto,range:$.paged?{start:$.rangeStart,end:$.rangeEnd}:null}),a?s.jsx(s9,{item:a.item,onClose:()=>o(null)}):null,c?s.jsx(r9,{onClose:()=>d(!1)}):null,f?s.jsx(S9,{onClose:()=>p(!1)}):null]})})}function Za(e){return e.source==="clash"?"clash":e.source==="subscription"?"subscription":"manual"}function m2(){return[{key:"manual",label:r("手动"),note:r("本页可编辑、可删除")},{key:"clash",label:"Clash Verge",note:r("只读:在 Clash Verge 里改")},{key:"subscription",label:r("订阅"),note:r("只读:在「订阅管理」里改")}]}function O9(e){const t=a=>e.filter(o=>Za(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 M9(e){const t=o=>o.port===null||o.port===void 0?"wait":o.lastTest?.at?o.lastTest.success?"ok":"fail":"none",a=o=>e.filter(c=>t(c)===o).length;return[{value:"all",label:r("全部状态"),count:e.length},{value:"ok",label:r("可用"),count:a("ok")},{value:"fail",label:r("失败"),count:a("fail")},{value:"wait",label:r("未就绪"),count:a("wait")}]}const h2="__orphan";function D9(e,t){const a=e.filter(d=>Za(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=>Za(d)==="manual").length},{value:"clash",label:"Clash Verge",count:e.filter(d=>Za(d)==="clash").length},{value:"subscription",label:r("全部订阅"),count:a.length},...o,...c?[{value:h2,label:r("已移除的订阅"),count:c}]:[]]}function I9(){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 Xf(),await qi()},visibleColumns:()=>p2().map(e=>({key:e.key}))};const g2='.page[data-page="proxies"]';function x2(){const e=document.querySelector(g2);!e||e.dataset.mounted==="1"||(e.dataset.mounted="1",e.replaceChildren(),wn.createRoot(e).render(s.jsx(A9,{})),Fs().wbApp?.currentPage==="proxies"&&(Xf(),qi()))}document.querySelector(g2)?x2():document.addEventListener("DOMContentLoaded",x2,{once:!0});const Pg=["today","7","30","month","all","custom"],Vw="7",Fw="custom",b2="workbuddy-desktop-report-range",v2="workbuddy-desktop-report-custom-range",y2={today:r("今天"),7:r("近 7 天"),30:r("近 30 天"),month:r("本月"),all:r("全部"),custom:r("自定义区间")},P9={today:r("今天"),7:r("7 天"),30:r("30 天"),month:r("本月"),all:r("全部"),custom:r("自定义")};function _9(){try{const e=localStorage.getItem(b2);return e!==null&&Pg.includes(e)?e:Vw}catch{return Vw}}function $w(e){const t=a=>String(a).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())}`}function L9(){const e=new Date;return{start:$w(new Date(e.getFullYear(),e.getMonth(),e.getDate()-6)),end:$w(e)}}const _g=/^\d{4}-\d{2}-\d{2}$/;function z9(){try{const e=localStorage.getItem(v2);if(e){const t=JSON.parse(e),a=typeof t?.start=="string"?t.start:"",o=typeof t?.end=="string"?t.end:"";if(_g.test(a)&&_g.test(o)&&a<=o)return{start:a,end:o}}}catch{}return L9()}function B9(e){try{localStorage.setItem(v2,JSON.stringify(e))}catch{}}const H9=[[0,r("一")],[2,r("三")],[4,r("五")]],j2=400;function Ki(e){const t=qw();return t.formatInt?t.formatInt(e):(Number(e)||0).toLocaleString("zh-CN")}function qw(){return window.wbUnits||{}}function ts(e){const t=qw();return t.formatTokens?t.formatTokens(e):String(Number(e)||0)}function w2(e,t){const a=qw();return a.formatAxis?a.formatAxis(e,t):String(e)}function Yi(e){return`${((Number(e)||0)*100).toFixed(1)}%`}function Lt(e){return Math.round(e*10)/10}function Gw(e){return[...e].reduce((t,a)=>t+(/[\u2e80-\u9fff]/.test(a)?9.7:5.4),0)}function Lg(e){const[t,a,o]=String(e||"").split("-").map(Number);return new Date(t||1970,(a||1)-1,o||1)}const U9=[r("日"),r("一"),r("二"),r("三"),r("四"),r("五"),r("六")];function zg(e){const t=Lg(e);return r("{m}月{d}日 周{wd}",{m:t.getMonth()+1,d:t.getDate(),wd:U9[t.getDay()]})}function S2(e){const t=String(e||"").slice(11,13);return t?`${t}:00`:"—"}const V9=8;function N2(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,V9),c=o.map(d=>`${t?`[${t(d.name)}]`:""}${r("{model}:{tokens} tokens",{model:d.name,tokens:ts(d.tokens)})}`);return a.length>o.length&&c.push(r("…还有 {n} 个模型",{n:a.length-o.length})),c}function k2(e,t){return[zg(e.date),r("总 Token:{tokens}({n} 次请求)",{tokens:ts(e.tokens),n:Ki(e.requests)}),...N2(e.models,t)].join(` +`)}function F9(e,t){return[`${zg(String(e.hour).slice(0,10))} ${S2(e.hour)}`,r("命中率 {rate}(命中 {hit} / 输入 {input})",{rate:Yi(e.rate),hit:ts(e.hitTokens),input:ts(e.inputTokens)}),r("总 Token:{tokens}",{tokens:ts(e.totalTokens)}),...N2(e.models,t)].join(` +`)}const $9=[1,1.5,2,2.5,3,4,5,6,8,10];function q9(e){if(!(e>0))return 1;const t=10**Math.floor(Math.log10(e)),a=e/t;return($9.find(c=>c>=a-1e-9)??10)*t}function Kw(e){return q9(e/4)*4}function G9(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:Ki(d),sub:y2[t]||"",mono:!1},{key:"successful",label:r("成功请求数"),value:Ki(f),sub:r("成功率 {rate}",{rate:p}),mono:!1},{key:"tokens",label:r("总 Token"),value:ts(o.tokens),sub:r("输入 + 输出"),mono:!1},{key:"activeDays",label:r("活跃天数"),value:Ki(o.activeDays),sub:r("区间共 {n} 天",{n:a}),mono:!1},{key:"streak",label:r("当前连续天数"),value:Ki(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:ts(c.tokens),pct:Yi(c.percentage)}),mono:!0}:{key:"topModel",label:r("Top 模型"),value:"—",sub:r("所选范围内还没有模型用量"),mono:!1}),g}function C2(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=ts(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 T2(e){return`${ts(e.reduce((t,a)=>t+(Number(a?.totalTokens??a?.tokens)||0),0))} tokens`}const Bg=["#f73b00","#f7bb07","#4aaa4d","#1872cb","#3444a3","#13c2c2","#722ed1","#eb2f96","#a0d911","#34d399","#d946ef","#ff85c0","#b37feb","#9d174d","#ffa39e","#69b1ff"],K9={size:220,inner:.62,outer:.88,padAngle:2};function Y9(e,t,a,o,c,d){const f=R=>(R-90)*Math.PI/180,p=(R,C)=>[Lt(e+R*Math.cos(f(C))),Lt(t+R*Math.sin(f(C)))],g=d-c;if(g>=359.999){const[R,C]=p(a,0),[A,D]=p(a,180),[I,M]=p(o,0),[O,_]=p(o,180);return`M ${R} ${C} A ${a} ${a} 0 1 1 ${A} ${D} A ${a} ${a} 0 1 1 ${R} ${C} Z M ${I} ${M} A ${o} ${o} 0 1 0 ${O} ${_} A ${o} ${o} 0 1 0 ${I} ${M} 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 X9="#9aa0a6";function E2(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,Bg[t.size%Bg.length])}return t}function R2(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=E2(e),{size:d,inner:f,outer:p,padAngle:g}=K9,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 R=k.tokens/o,C=R*360,A=a.length>1?Math.min(g/2,C/4):0,D=w+A,I=w+C-A;w+=C;const M=c.get(k.label)??Bg[E%Bg.length];let O=null;if(R>=.03){const _=(D+I)/2,L=j+(b-j)*.6,z=(_-90)*Math.PI/180;O={x:Lt(v+L*Math.cos(z)),y:Lt(y+L*Math.sin(z)),text:`${Math.round(R*100)}%`}}I>D&&S.push({key:`${E}-${k.label}`,d:Y9(v,y,b,j,D,I),fill:M,evenOdd:C>=359.999,label:O,tip:`${k.label} · ${ts(k.tokens)} tokens · ${Yi(R)}`}),N.push({key:`${E}-${k.label}`,fill:M,name:k.label,tokensText:ts(k.tokens),percentText:Yi(R),tip:r("{name} · {tokens} tokens · {n} 次请求 · {pct}",{name:k.label,tokens:ts(k.tokens),n:Ki(k.requests),pct:Yi(R)})})}),{size:d,slices:S,legend:N,totalText:ts(o)}}const Q9=[1,1.25,1.5,2,2.5,3,4,5,6,8,10];function Z9(e){if(!(e>0))return 1;const t=10**Math.floor(Math.log10(e)),a=e/t;let o=1;for(const c of Q9)c<=a+1e-9&&(o=c);return o*t}function W9(e){const t=Number(e)||0;if(t<=0)return[0,1,2,3,1/0];const a=Math.max(1,Z9(t/4));return[0,a,a*2,a*3,1/0]}function J9(e,t){if(e===0)return"0";const a=t[e-1],o=t[e];return Number.isFinite(o)?a===0?`≤${ts(o)}`:`${ts(a)}–${ts(o)}`:`>${ts(a)}`}function A2(e){const t=Array.isArray(e)?e:[];return W9(t.reduce((a,o)=>Math.max(a,Number(o?.tokens)||0),0))}function eY(e,t){const a=Array.isArray(e)?e:[];if(!a.length)return null;const o=(Lg(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=A2(a),R=O=>E.findIndex(_=>Number(O)<=_),C=[];for(let O=0;O({key:_,x:S+p-6,y:Lt(b+O*j+y/2),text:_})),D=[];let I=-1,M=-9;for(let O=0;O({level:t,text:J9(t,e)}))}function nY(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?Yi(d.rate):"—",sub:r("命中 {hit} / 输入 {input}",{hit:ts(d.hitTokens),input:ts(f)})}})}function sY(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(Y=>Number(Y.rate)||0),v=o.map(Y=>Number(Y.totalTokens)||0),y=Math.max(1,Kw(Math.max(...g))),b=Math.max(...v),j=Kw(b),w=b>0,S=Y=>d.left+(o.length>1?f*Y/(o.length-1):f/2),N=Y=>d.top+p-p*Y/y,k=Y=>d.top+p-p*Y/j,E=[],R=[],C=[];for(let Y=0;Y<=4;Y+=1){const q=y*Y/4,G=Lt(N(q)),F=q*100;E.push({key:`g${Y}`,y:G}),R.push({key:`r${Y}`,x:d.left-8,y:G,anchor:"end",text:`${Number.isInteger(F)?F:F.toFixed(1)}%`}),w&&C.push({key:`t${Y}`,x:Lt(d.left+f+8),y:G,anchor:"start",text:w2(j*Y/4,j)})}const A=o.length===1?4.5:2.5,D=(Y,q)=>({points:Y.map((G,F)=>`${Lt(S(F))},${Lt(q(G))}`).join(" "),dots:Y.map((G,F)=>({key:`d${F}`,cx:Lt(S(F)),cy:Lt(q(G))}))}),I=[],M=(Y,q,G,F)=>{const $=Gw(G),X=F==="middle"?Y-$/2:F==="end"?Y-$:Y,re={left:X,right:X+$,top:q-8.5,bottom:q+2.5};return I.some(P=>re.leftP.left-2&&re.topP.top-1)?null:(I.push(re),{key:`${G}-${Y}-${q}`,x:Lt(Y),y:Lt(q),text:G,anchor:F})},O=(Y,q)=>{const G=Gw(q)/2;return Y-Gd.left+f+6?"end":"middle"},_=[];w&&o.forEach((Y,q)=>{if(!(Number(Y.totalTokens)>0))return;const G=k(v[q]),F=G-12>=d.top-10,$=ts(v[q]),X=M(S(q),F?G-12:G+13,$,O(S(q),$));X&&_.push({...X,key:`tl${q}`})});const L=[];o.forEach((Y,q)=>{if(!((Number(Y.inputTokens)||0)+(Number(Y.hitTokens)||0)>0))return;const F=N(g[q]),$=F+15<=d.top+p+8,X=Yi(g[q]),re=M(S(q),$?F+13:F-7,X,O(S(q),X));re&&L.push({...re,key:`rl${q}`})});const z=o.length>1?f/(o.length-1):f,U=d.left,B=d.left+f,Q=o.length<=j2?o.map((Y,q)=>{const G=Math.max(U,S(q)-z/2),F=Math.min(B,S(q)+z/2);return{key:`h${q}`,x:Lt(G),width:Lt(F-G),tip:F9(Y,a)}}):null,W=Math.max(1,Math.ceil(o.length/8)),Z=[];for(let Y=0;Y=o.length;Z.push({key:`x${Y}`,x:Lt(S(Y)),y:c-8,anchor:Y===0?"start":q?"end":"middle",text:S2(o[Y].hour)})}return{width:t,height:c,plotLeft:U,plotW:f,plotH:p,plotTop:d.top,grid:E,rateTicks:R,tokenTicks:C,rateLine:D(g,N),tokenLine:w?D(v,k):null,dotR:A,rateLabels:L,tokenLabels:_,hourTicks:Z,hits:Q}}function rY(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=c-d.top-d.bottom,g=o.map(B=>Number(B.tokens)||0),v=Math.max(...g),y=Kw(v),b=f/o.length,j=Math.max(1,Math.min(28,b*.68)),w=d.top+p,S=B=>d.top+p-p*B/y,N=o.length<=j2,k=v<=0,E=[],R=[];if(!k)for(let B=0;B<=4;B+=1){const Q=y*B/4,W=Lt(S(Q));E.push({key:`g${B}`,x1:d.left,y:W,x2:Lt(d.left+f)}),R.push({key:`v${B}`,x:d.left-8,y:W,anchor:"end",text:w2(Q,y)})}const C=[];o.forEach((B,Q)=>{const W=Number(B.tokens)||0;if(W<=0)return;const Z=S(W);C.push({key:String(B.date??Q),x:Lt(d.left+b*Q+(b-j)/2),y:Lt(Z),width:Lt(j),height:Lt(Math.max(1,w-Z)),rx:j>4?2:1,tip:k2(B),nativeTip:!N})});const A=o.map(B=>Number(B.tokens)>0?ts(B.tokens):""),D=Math.max(0,...A.map(Gw)),I=A.every(B=>!B)||D+4<=b,M=new Set;I||o.map((B,Q)=>({index:Q,value:Number(B.tokens)||0})).filter(B=>B.value>0).sort((B,Q)=>Q.value-B.value).slice(0,8).forEach(B=>M.add(B.index));const O=[];o.forEach((B,Q)=>{if(!A[Q]||!I&&!M.has(Q))return;const W=S(Number(B.tokens)||0)-6,Z=W-9({key:`h${Q}`,x:Lt(d.left+b*Q),width:Lt(b),tip:k2(B,a)})):null,L=Math.max(1,Math.ceil(o.length/6)),z=[];for(let B=0;B{const Q=o.length===1,W=!Q&&B===o.length-1,Z=Lg(o[B].date);return{key:`d${B}`,x:Q?d.left+f/2:W?d.left+f:Lt(d.left+b*B+b/2),y:c-8,anchor:Q?"middle":W?"end":B===0?"start":"middle",text:`${Z.getMonth()+1}/${Z.getDate()}`}});return{width:t,height:c,plotLeft:d.left,plotW:f,plotH:p,plotTop:d.top,grid:E,valueTicks:R,bars:C,barLabels:O,dateTicks:U,hits:_,blank:k}}function Xi(){return window}const O2=1e3,aY=Pg.map(e=>({value:e,label:P9[e]})),lY=r("所选范围内每个账号各消耗了多少 Token,按 Token 用量从多到少排。账号是比提供商更细的一维:同一家可以挂多个账号,转发时按优先级在候选链上依次尝试,所以这里反映的是「具体哪个登录态在出力」。百分比按本区间的总 Token 数算(这一块只看用量,请求次数与成功率在概览卡片里)。「未知账号」是指那批请求没有账号身份:走默认登录态转发(未配置账号列表)时会这样;这一维上线前写出的旧聚合行也没有账号明细,但它们会在升级导入旧数据时按明细自动补算回来 —— 只有明细已被手动清理掉的那几天补不回来,仍留在「未知账号」里,那是确实无从恢复的部分。"),oY=r("所选范围内每个提供商各消耗了多少 Token,按 Token 用量从多到少排。同一个模型名可能有多家都能提供,网关按设置页「转发路由」的优先级依次尝试,所以占比也反映了实际落到谁身上。百分比按本区间的总 Token 数算(这一块只看用量,请求次数与成功率在概览卡片里)。「未知」是指那批请求没记下承载它的提供商 —— 主要是记录提供商这个功能上线之前的旧明细,其次是请求在选定上游之前就失败了(请求体非法、模型不存在、没有可用账号)。这一维与账号那一维不同:旧明细里根本没有「哪家承载」的信息(早期版本只有单一上游,但那是配置事实而非逐条记录),所以无法回算,旧数据会一直留在「未知」里;此后新产生的请求都会记上具体的提供商。"),iY=r("所选范围内每个模型各消耗了多少 Token,按用量从多到少排,扇区角度即占比。中心是这一维的合计(等于概览里的总 Token),右侧每行给出该模型的 Token 用量与百分比。扇区内的百分比只在 ≥3% 时标出,更小的会挤成一团 —— 完整读数在右侧列表与悬停气泡里。颜色按用量排名分配:最大的那段是红色,依次往后;同一份报表里换个维度看,配色口径不变。"),cY=r("所选范围内每个提供商各消耗了多少 Token,按用量从多到少排,扇区角度即占比。同一个模型名可能有多家都能提供,网关按设置页「转发路由」的优先级依次尝试,所以占比也反映了实际落到谁身上。中心是这一维的合计(等于概览里的总 Token),右侧每行给出该提供商的 Token 用量与百分比。「未知」是指那批请求没记下承载它的提供商 —— 主要是记录提供商这个功能上线之前的旧明细,其次是请求在选定上游之前就失败了。"),uY=r("命中率 = 缓存读取 Token / 输入 Token(promptTokens)。窗口越短越贴近「此刻」:上游把缓存读取与输入分开上报时,该比值合法地可能超过 100%,此处不夹取值、如实展示。"),dY=r("每天的总 Token 用量(输入 + 输出)。柱顶标出当天的读数;区间很长、柱子挤到放不下时只标最高的那几天,其余悬停柱子即可读到。");let Hg=O2,Ug=!0,Yw=!1,Xw=!1,Qw=0,Ao=null,Qi=null,Vg=null;function Zi(e,t="empty"){return s.jsx("div",{className:t,style:{padding:"14px 0"},children:e})}function Fg({text:e}){return s.jsx("span",{className:"tip-q","data-tip":e})}function fY({accountId:e}){const t=(Xi().wbApp?.getState?.()?.accounts?.accounts||[]).find(f=>f?.id===e),a=typeof t?.provider=="string"?t.provider:"";if(!a)return null;const o=Xi().wbProviders?.labelOf?.(a)||a,c=t&&Xi().wbAccountsModel?.editionSuffix?.(t)||"",d=c?`${o} ${c}`:o;return s.jsx("span",{className:`pbadge p-${a}`,title:r("提供商:{text}",{text:d}),children:d})}function pY({summary:e,range:t}){const a=Array.isArray(e.dailyTrend)?e.dailyTrend:[];return s.jsx(s.Fragment,{children:G9(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 M2({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(Fg,{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(fY,{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)):Zi(g)})})]})}function D2({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(Fg,{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))})]}):Zi(f)})})]})}function mY({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 I2({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 Zw({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,children:a.text},a.key))})}function hY({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:Lt(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(I2,{line:e.tokenLine,cls:"tokens",radius:e.dotR}):null,s.jsx(I2,{line:e.rateLine,cls:"rate",radius:e.dotR}),s.jsx(Zw,{items:e.tokenLabels,cls:"tokens"}),s.jsx(Zw,{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:Lt(f),tabIndex:-1,"data-tip":p.tip,"data-tip-variant":"plain"},p.key))}):null]})}function gY({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(Zw,{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:Lt(o+c/2),y:Lt(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:Lt(f),tabIndex:-1,"data-tip":p.tip,"data-tip-variant":"plain"},p.key))}):null]})}const xY=680;function Ww(){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||xY]}async function P2(){if(!Yw)try{const e=await Xi().workbuddyDesktop?.getScheduledTasks(),t=(e?.tasks||[]).find(a=>a.id==="reportAutoRefresh");Jw(t||null),Yw=Array.isArray(e?.tasks)}catch(e){console.warn("读取报表自动刷新间隔失败,按默认 1 秒:",e instanceof Error?e.message:e),Jw(null)}}function Jw(e){Yw=!0;const t=Number(e?.interval);!!e&&typeof e=="object"&&Number.isFinite(t)&&t>0&&(e.unit==="seconds"||e.unit==="minutes")?(Ug=e.enabled!==!1,Hg=e.unit==="minutes"?t*6e4:t*1e3):(Ug=!0,Hg=O2),Qi?.applyAutoConfig(Hg,Ug)}const bY={summary:null,error:null};function vY(){const[e,t]=x.useState(bY),[a,o]=x.useState(_9),[c,d]=x.useState(z9),[f,p]=x.useState(()=>({ms:Hg,enabled:Ug})),[,g]=x.useState(0),v=x.useRef(a),y=x.useRef(c),b=x.useCallback($=>{t($)},[]),j=x.useCallback(async($={})=>{P2();const X=++Qw,re=v.current,P=re===Fw?y.current:void 0;try{const V=Xi().workbuddyDesktop;if(!V)throw new Error("后端桥不可用");const J=await V.getStatsSummary(re,P);if(X!==Qw)return Ao;if(!J||typeof J!="object")throw new Error("后端未返回报表数据");return Ao=J,b({summary:J,error:null}),Ao}catch(V){if(X!==Qw)return Ao;const J=V instanceof Error?V.message:"";return Ao=null,$.silent||console.warn("读取报表数据失败:",J),b({summary:null,error:J||r("未知错误")}),null}},[b]),w=x.useCallback($=>{$!==void 0&&(Ao=$||null,$&&b({summary:$,error:null}))},[b]),S=x.useCallback($=>{const X=Pg.includes($)?$:Vw;if(X!==v.current){v.current=X,o(X);try{localStorage.setItem(b2,X)}catch{}j()}},[j]),N=x.useCallback($=>{const X={...y.current,...$};if(!_g.test(X.start)||!_g.test(X.end))return;const re=X.start<=X.end?X:$.start?{start:X.start,end:X.start}:{start:X.end,end:X.end};y.current=re,d(re),B9(re),v.current===Fw&&j()},[j]);x.useEffect(()=>{if(Qi={load:j,render:w,applyAutoConfig:($,X)=>p({ms:$,enabled:X})},Vg){const $=Vg;Vg=null,w($.data)}return Xi().wbApp?.currentPage==="overview"&&j({silent:!0}),()=>{Qi=null}},[j,w]),x.useEffect(()=>{if(!f.enabled||f.ms<=0)return;const $=window.setInterval(()=>{document.hidden||Xi().wbApp?.currentPage!=="overview"||Xw||(Xw=!0,j({silent:!0}).finally(()=>{Xw=!1}))},f.ms);return()=>{window.clearInterval($)}},[f,j]),x.useEffect(()=>{const $=()=>g(X=>X+1);return window.addEventListener("wb-units-changed",$),()=>window.removeEventListener("wb-units-changed",$)},[]);const k=Ww(),E=Ww(),R=Ww(),{summary:C,error:A}=e,D=C&&Pg.includes(C.range??"")?C.range:a,I=C&&Array.isArray(C.heatmap)?C.heatmap:[],M=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,z=C&&Array.isArray(C.models)?C.models:null,U=A?Zi(r("读取报表失败:{error}",{error:A}),"empty report-error"):null,B=Zi(r("正在加载…")),Q=U??B,W=x.useMemo(()=>E2(z||[]),[z]),Z=x.useCallback($=>W.get($)||X9,[W]),Y=C?eY(I,k[1]):null,q=C?sY(M,E[1],Z):null,G=C?rY(O,R[1],Z):null,F=$w(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:y2[D]||""}),s.jsxs("div",{className:"head-actions",children:[s.jsx(Pn,{options:aY,value:a,onValueChange:S,"aria-label":r("报表时间范围")}),a===Fw?s.jsxs("span",{className:"report-date-range",children:[s.jsx(Ye,{type:"date",className:"report-date-input w-[132px]",value:c.start,max:c.end||F,"aria-label":r("开始日期"),title:r("起始日期(含当天)"),onChange:$=>N({start:$.target.value})}),s.jsx("span",{className:"report-date-sep","aria-hidden":"true",children:"~"}),s.jsx(Ye,{type:"date",className:"report-date-input w-[132px]",value:c.end,min:c.start||void 0,max:F,"aria-label":r("结束日期"),title:r("结束日期(含当天)"),onChange:$=>N({end:$.target.value})})]}):null]})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"field-grid",id:"report-overview",children:C?s.jsx(pY,{summary:C,range:D}):Q})})]}),s.jsxs("div",{className:"report-rank-grid",children:[L?s.jsx(M2,{panelId:"report-accounts-panel",listId:"report-accounts",labelId:"report-accounts-label",title:r("Top 账号"),tip:lY,rows:C2(L)||[],totalText:T2(L),withBadge:!0,emptyText:r("所选范围内还没有账号用量")}):null,_?s.jsx(M2,{panelId:"report-providers-panel",listId:"report-providers",labelId:"report-providers-label",title:r("Top 提供商"),tip:oY,rows:C2(_)||[],totalText:T2(_),withBadge:!1,emptyText:r("所选范围内还没有请求记录")}):null]}),s.jsxs("div",{className:"report-donut-grid",children:[z?s.jsx(D2,{panelId:"report-models-panel",listId:"report-models-donut",title:r("模型用量"),tip:iY,ariaLabel:r("模型用量占比"),view:R2(z,r("未知模型")),emptyText:r("所选范围内还没有模型用量")}):null,_?s.jsx(D2,{panelId:"report-providers-pie-panel",listId:"report-providers-donut",title:r("提供商用"),tip:cY,ariaLabel:r("提供商用占比"),view:R2(_,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?Y?s.jsx(mY,{view:Y}):Zi(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?tY(A2(I)).map($=>s.jsxs("span",{className:"heat-legend-item",children:[s.jsx("span",{className:`l${$.level}`}),$.text]},$.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(Fg,{text:uY})]}),s.jsx("div",{className:"panel-body",children:s.jsx("div",{className:"field-grid",id:"report-cache-rates",children:C?nY(C.cacheRates).map($=>s.jsxs("div",{className:"field rate",children:[s.jsx("div",{className:"label",children:$.label}),s.jsxs("div",{className:"value big",children:[$.value,s.jsx("div",{className:"sub",children:$.sub})]})]},$.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?q?s.jsx(hY,{view:q}):Zi(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(Fg,{text:dY}),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:R[0],children:C?G?s.jsx(gY,{view:G}):Zi(r("暂无趋势数据")):Q})})]})]})}async function yY(e={}){return Qi?Qi.load(e):Ao}function jY(e){if(e!==void 0){if(!Qi){Vg={data:e??null};return}Qi.render(e)}}function wY(){return Ao}window.wbReport={load:yY,render:jY,lastSummary:wY,applyAutoRefresh:Jw};const _2='.page[data-page="overview"]';let L2=!1;function z2(){if(L2)return;const e=document.querySelector(_2);e&&(L2=!0,e.replaceChildren(),wn.createRoot(e).render(s.jsx(vY,{})))}document.querySelector(_2)?z2():document.addEventListener("DOMContentLoaded",z2,{once:!0}),P2();const e0={all:{title:r("全部删除"),desc:r("删除日志记录本身。当前有筛选时只删命中的条目,按天聚合报表不受影响;无筛选时清空全部并重置报表。此方式无法恢复。")},raw:{title:r("仅清空报文原文"),desc:r("保留统计行与报表,只抹掉请求 / 响应正文。清理后详情弹窗的「预览对话」将无原文可看,统计数字分毫不动。")}},SY=["all","raw"],NY=3e3;function Al(){return window}let Zf=!1;function Wf(e,t){Al().wbApp?.toast?.(e,t)}function kY(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 t0(){const e=Al().wbRequestsPanel?.clearParams?.();return typeof e=="string"?e:""}function B2(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 H2(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}function CY({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=>{Zf=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=Al().workbuddyDesktop;if(!I)return;let M;try{M=await I.getStatsClearPreview(t0())}catch{return}if(!b.current)return;const O=B2(M);N(O),!O.vacuumRunning&&(S(),f(""),Wf(r("✅ 压缩完成")),Al().wbRequestsPanel?.load?.({silent:!0}))},[N,S]),E=x.useCallback(()=>{j.current===null&&(g(!0),j.current=window.setInterval(()=>{k()},NY))},[k]);async function R(){c({status:"loading"});try{const I=Al().workbuddyDesktop;if(!I)throw new Error(r("后端桥不可用"));const M=await I.getStatsClearPreview(t0());if(!b.current)return;const O=B2(M);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,R(),()=>{b.current=!1,S(),Zf=!1}),[]);async function C(){const I=Al().workbuddyDesktop;if(I){g(!0);try{await I.compactStatsDb(),f(r("压缩已在后台开始,完成后会自动提示")),E()}catch(M){const O=n0(M);if(/409|正在进行/.test(O)){Wf(r("压缩已在进行中")),f(r("压缩已在进行中,接上它的进度等待完成")),E();return}g(!1),f(r("压缩失败:{message}",{message:O})),Wf(r("压缩失败:{message}",{message:O}),"err")}}}async function A(){if(Zf)return;const I=Al().workbuddyDesktop,M=Al().wbConfirm?.ask;if(!I||!M)return;const O=e0[t].title,_=t0(),L=_.length>0,z=o.status==="ready"?t==="raw"?o.raw:o.all:0;if(await M({title:r("清理请求日志"),html:L?r("确定按当前筛选执行「{label}」?将处理 {count} 条,此操作无法恢复。",{label:H2(O),count:z}):r("确定对全部请求日志执行「{label}」?将处理 {count} 条,此操作无法恢复。",{label:H2(O),count:z}),okText:r(t==="raw"?"抹掉原文":"删除"),okClass:"danger"})){w(!0);try{const B=L?`mode=${t}&${_}`:`mode=${t}&all=1`,Q=await I.clearStatsRequests(B),W=Number(Q?.deleted)||0;Wf(t==="raw"?r("已抹掉 {count} 条报文原文",{count:W}):r("已删除 {count} 条",{count:W})),w(!1),e(),Al().wbRequestsPanel?.notifyCleared?.()}catch(B){const Q=n0(B);f(r("清理失败:{message}",{message:Q})),Wf(r("清理失败:{message}",{message:Q}),"err"),w(!1)}}}const D=o.status==="ready"?r("将删除 {count} 条日志 · 其中 {raw} 条仍带报文原文 · 数据库占用 {db}",{count:o.all,raw:o.raw,db:kY(o.dbBytes)}):o.status==="failed"?r("预览读取失败"):r("正在统计…");return s.jsx(Kt,{open:!0,onOpenChange:(I,M)=>{if(!I){if(Zf){M.cancel();return}e()}},children:s.jsxs(Yt,{children:[s.jsx($t,{children:s.jsx(Ft,{children:r("清理请求日志")})}),s.jsxs(_t,{children:[s.jsx(dh,{"aria-label":r("清理方式"),value:t,onValueChange:I=>a(I==="raw"?"raw":"all"),children:SY.map(I=>{const M=t===I;return s.jsxs("label",{"data-checked":M?"":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(Mi,{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:e0[I].title}),s.jsx("span",{className:"text-[11.5px] leading-[1.55] text-subtle",children:e0[I].desc})]},I)})}),s.jsx("p",{className:"text-[11.5px] text-muted-foreground",children:D})]}),s.jsxs(en,{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 Jf=null,Mu=null;function U2(){Jf&&(Jf.unmount(),Jf=null),Mu&&(Mu.remove(),Mu=null)}function TY(){Zf||U2()}function EY(){U2(),Mu=document.createElement("div"),document.body.append(Mu),Jf=wn.createRoot(Mu),Jf.render(s.jsx(CY,{onClose:TY}))}window.wbRequestClearModal={open:EY};const V2=[{value:"detail",label:r("请求详情")},{value:"preview",label:r("预览对话")},{value:"raw",label:r("原始报文")}],RY="detail",F2="border-b border-hairline px-2.5 py-[7px] align-top",Oo="border border-hairline px-2 py-1 align-top",AY="border border-hairline bg-surface-2 px-2 py-1 text-[11.5px] tracking-normal",$g="hover:[&>td]:bg-transparent";function Du(){return window}function s0(){const e=Du().workbuddyDesktop;if(!e)throw new Error(r("后端桥不可用"));return e}let r0=0;function OY(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 $2(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 MY(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"-":$2(t)}const DY=r("生成速度:输出 token ÷ 流式段用时(总用时 − 首响);流式段不足总用时一半时按总用时计");function IY(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 qg(e){return Du().wbUnits?.formatTokens?.(e)??(Number(e)||0).toLocaleString("zh-CN")}function PY(e){const t=Math.max(0,Date.now()-(Number(e)||0));return r("{n}秒",{n:Math.max(1,Math.floor(t/1e3))})}function _Y(e){const t=Number(e.status)||0;return t>=200&&t<300&&!e.error}function Gg(e){return(Number(e?.status)||0)===0&&!e?.error}function q2(e){const t=String(e.provider??"").trim();return String(e.providerLabel??"").trim()||(t?Du().wbProviders?.labelOf?.(t)||t:"")}function ep(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function a0(e){if(e==null)return"";if(typeof e=="string")return e;try{return JSON.stringify(e,null,2)}catch{return""}}function l0(e){return e instanceof Error?e.message:String(e)}const G2=[{label:r("请求头"),pick:e=>a0(e.requestHeaders)},{label:r("请求体"),pick:e=>a0(e.requestBody)},{label:r("响应头"),pick:e=>a0(e.responseHeaders)},{label:r("响应体"),pick:e=>e.responseBody?String(e.responseBody):""}];function Kg({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($d,{className:"size-3.5"}):null,e]})}function ca({label:e,children:t}){return s.jsxs(jl,{className:$g,children:[s.jsx("th",{scope:"row",className:`w-[76px] whitespace-nowrap text-left text-[12.5px] font-semibold text-muted-foreground ${F2}`,children:e}),s.jsx(yn,{className:F2,children:t})]})}function LY({row:e}){if(Gg(e)){const c=Du().wbRequestPhase;if(!c?.badgeHtml)return s.jsxs(ze,{variant:"info",shape:"tag",title:r("请求正在转发中,用时列显示的是已用时"),children:[s.jsx(Uv,{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=_Y(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 zY({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 BY(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 HY({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(Ny,{className:"text-[11.5px]",children:[s.jsx(FT,{children:s.jsx(jl,{className:$g,children:[r("轮次"),r("提供商"),r("账号"),r("结果"),r("体积"),r("内部重试"),r("提示")].map(o=>s.jsx($T,{className:AY,children:o},o))})}),s.jsxs(ky,{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(jl,{className:$g,children:[s.jsx(yn,{className:Oo,children:c+1}),s.jsx(yn,{className:Oo,children:q2(o)||(o?.provider?String(o.provider):r("未知"))}),s.jsx(yn,{className:Oo,children:o?.account?String(o.account):"—"}),s.jsx(yn,{className:Oo,children:BY(o)}),s.jsx(yn,{className:`${Oo} whitespace-nowrap`,title:y,children:v}),s.jsx(yn,{className:`${Oo} whitespace-nowrap`,title:f||void 0,children:d.length?r("↻ {n} 次",{n:d.length}):"-"}),s.jsx(yn,{className:Oo,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 VY({row:e}){if(!e)return s.jsx(Kg,{text:r("列表数据已刷新,请重试(关闭后重新打开这条详情)")});const t=String(e.accountName??"").trim(),a=IY(e);return s.jsx(Ny,{className:"text-[12.5px] text-subtle [&_tr:last-child>td]:border-b-0 [&_tr:last-child>th]:border-b-0",children:s.jsxs(ky,{children:[s.jsx(ca,{label:r("时间"),children:OY(e.ts)}),s.jsx(ca,{label:r("状态"),children:s.jsx(LY,{row:e})}),s.jsx(ca,{label:r("耗时"),children:Gg(e)?s.jsxs(s.Fragment,{children:[PY(e.ts),s.jsx("span",{className:"text-[11.5px] text-muted-foreground",children:r("(请求仍在转发中)")})]}):r("{duration} / 首帧 {first}",{duration:$2(e.durationMs),first:MY(e.firstResponseMs)})}),s.jsx(ca,{label:r("重试次数"),children:String(Number(e.attempts)||1)}),s.jsx(ca,{label:r("模型"),children:s.jsx(zY,{row:e})}),s.jsxs(ca,{label:r("提供商"),children:[q2(e)||"—",t?s.jsx("span",{className:"text-[11.5px] text-muted-foreground",children:r("(账号:{account})",{account:t})}):null]}),s.jsxs(ca,{label:r("令牌"),children:[r("输入 {input} · 输出 {output} · 总计 {total} · 缓存读 {cache}",{input:qg(e.promptTokens),output:qg(e.completionTokens),total:qg(e.totalTokens),cache:qg(e.cacheReadTokens)}),a?s.jsxs("span",{title:DY,children:[" · ",a]}):null]}),e.isTest?s.jsx(ca,{label:r("来源"),children:s.jsx(ze,{variant:"brand",shape:"tag",title:r("模型管理页操作列那颗「测试」发起的请求:与真实请求同一条转发链路,但不计入报表统计"),children:r("模型测试")})}):null,s.jsx(ca,{label:r("错误"),children:e.error?s.jsx("span",{className:"text-destructive",children:String(e.error)}):"—"}),s.jsx(ca,{label:r("尝试明细"),children:s.jsx(HY,{row:e})}),e.route?s.jsx(ca,{label:r("路由回放"),children:s.jsx(UY,{row:e})}):null,s.jsx(ca,{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 FY({state:e}){if(!e)return s.jsx(Kg,{text:r("正在读取…"),loading:!0});const t=e==="gone"?null:e.body,a=t&&Du().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(Kg,{text:r("无报文原文(未开启「调试模式」,或已被清理)")})}function $Y({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,G2.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(Kg,{text:r("这条请求没有保存这一段报文")})]},o.label)})]})}function qY({id:e,row:t,token:a,onClose:o}){const[c,d]=x.useState(RY),[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!==r0,[a]);async function R(){try{const O=await s0().getStatsRequestRaw(e);if(E())return;const _=ep(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("读取原始正文失败(预览对话显示空态):",l0(O))}}async function C(){try{const O=await s0().getDebugTraffic(e);if(E())return;const _=ep(O)?O:{};if(!G2.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("读取调试报文失败(原始报文标签隐藏):",l0(O))}}x.useEffect(()=>(S.current=!0,R(),C(),()=>{S.current=!1}),[]),x.useLayoutEffect(()=>{const O=N.current;O&&(O.scrollTop=k.current[c])},[c]);function A(O){if(O==="raw"&&!ep(g)||O===c)return;const _=N.current;_&&(k.current[c]=_.scrollTop),d(O)}async function D(){if(!e||!Gg(t))return;const O=Du().wbConfirm?.ask;if(!(!O||!await O({title:r("终止请求"),html:r("确定终止这条正在转发的请求?
上游连接会立即断开,明细将记为「请求已被手动终止」。"),okText:r("终止"),okClass:"danger"}))){w("pending");try{if(await s0().terminateStatsRequest(e),!S.current)return;w("accepted"),b(r("已受理终止:上游连接已断开,列表稍后刷新为「请求已被手动终止」"))}catch(L){if(!S.current)return;w("idle"),b(r("终止失败:{error}",{error:l0(L)}))}}}const I=ep(g),M=x.useMemo(()=>I?V2:V2.filter(O=>O.value!=="raw"),[I]);return s.jsx(Kt,{open:!0,onOpenChange:O=>{O||o()},children:s.jsxs(Yt,{className:"w-[min(920px,calc(100vw-48px))]",children:[s.jsx($t,{children:s.jsx(Ft,{children:r("请求详情")})}),s.jsxs(_t,{ref:N,className:"gap-3",children:[s.jsx(Pn,{options:M,value:c,onValueChange:A,"aria-label":r("详情内容"),className:"self-start"}),s.jsx("section",{hidden:c!=="detail",children:s.jsx(VY,{row:t})}),s.jsx("section",{hidden:c!=="preview",children:s.jsx(FY,{state:f})}),I?s.jsx("section",{hidden:c!=="raw",children:s.jsx($Y,{data:g.data})}):null]}),s.jsxs(en,{children:[s.jsx("span",{className:"min-w-0 text-[11.5px] text-muted-foreground",children:y}),s.jsx("div",{className:"mr-auto"}),Gg(t)?s.jsx(se,{variant:"destructive",disabled:j!=="idle",onClick:()=>{D()},title:r("断开上游连接,明细记为「请求已被手动终止」"),children:r("终止请求")}):null,s.jsx(se,{variant:"outline",onClick:o,children:r("关闭")})]})]})})}let tp=null,Iu=null;function K2(){tp&&(tp.unmount(),tp=null),Iu&&(Iu.remove(),Iu=null)}function Y2(){r0+=1,K2()}function GY(e,t){const a=String(e??"").trim();if(!a)return;K2();const o=++r0;Iu=document.createElement("div"),document.body.append(Iu),tp=wn.createRoot(Iu),tp.render(s.jsx(qY,{id:a,row:ep(t)?t:null,token:o,onClose:Y2}))}window.wbRequestDetail={open:GY,close:Y2};const KY=150,YY=80,Wi=8,Yg=8,XY=520,QY=220,ZY=1.1,WY=900,o0=12,i0="req-hover-panel",JY=["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(" "),np="rh-row rh-dim min-w-0 break-words text-muted-foreground",eX="rh-row min-w-0 break-words";function tX(){return window}function c0(e){return typeof e=="object"&&e!==null?e:null}const X2=e=>Array.isArray(e?.attemptDetails)?e.attemptDetails:[],Q2=e=>Array.isArray(e?.retries)?e.retries:[],nX=e=>Array.isArray(e?.sensitiveHits)?e.sensitiveHits:[];function u0(e){const t=String(e??"").trim();return t?tX().wbProviders?.labelOf?.(t)||t:""}function sX(e){const t=c0(e);return(Number(t?.attempts)||1)>1?!0:X2(t).some(a=>Q2(a).length>0||!!a?.notice)}function Z2(e){return e.dataset.reqHover==="sensitive"?"sensitive":"chain"}function rX({details:e}){if(e.length<2)return null;const t=e.map(a=>u0(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 aX({item:e}){const t=Q2(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 lX({item:e,index:t,inFlight:a}){const o=u0(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:eX,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(aX,{item:e})]})}function oX({entry:e}){const t=Number(e.attempts)||1,a=X2(e);if(!a.length){const c=u0(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:np,children:d}),s.jsx("div",{className:np,children:r("这条记录的尝试明细未采集(该字段上线前的旧数据,或请求在转发前就失败)")})]})}const o=(Number(e.status)||0)===0&&!e.error;return s.jsxs(s.Fragment,{children:[s.jsx(rX,{details:a}),a.map((c,d)=>s.jsx(lX,{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>o0?s.jsx("div",{className:np,children:r("另有 {n} 个词命中",{n:t.length-o0})}):null]}):s.jsx("div",{className:np,children:r("这条记录命中了敏感词,但没有留下命中明细")})}function cX({kind:e,entry:t,panelRef:a}){return s.jsx("div",{ref:a,id:i0,role:"tooltip","data-kind":e,className:JY,children:e==="sensitive"?s.jsx(iX,{entry:t}):s.jsx(oX,{entry:t})})}let Nn=null,Mo=0,sp=0,rp=null,Xg=null,d0=null,f0=null,Ji=null,ec=null,ap=null,W2="chain";function p0(){window.clearTimeout(Mo),window.clearTimeout(sp),Mo=0,sp=0,rp=null}function uX(){const e=ap?.current,t=Nn;if(!e||!t)return;const a=t.getBoundingClientRect(),o=window.innerWidth-Wi*2;e.style.maxWidth="none",e.style.width="max-content";const c=e.offsetWidth,d=W2==="sensitive",p=Math.max(d?QY:XY,c)*(d?ZY:1),g=Math.min(p,o,WY);e.style.maxWidth=`${g}px`,e.style.width=d?`${g}px`:"auto";const v=e.offsetWidth,y=e.offsetHeight,b=window.innerHeight-a.bottom-Yg-Wi,j=a.top-Yg-Wi,w=bb,S=a.left+a.width/2,N=Math.max(Wi,Math.min(S-v/2,window.innerWidth-Wi-v)),k=w?a.top-Yg-y:a.bottom+Yg;e.style.left=`${Math.round(N)}px`,e.style.top=`${Math.round(Math.max(Wi,Math.min(k,window.innerHeight-Wi-y)))}px`}function J2(e){if(!Nn)return;const t=e.target;t instanceof Node&&(t===Nn||Nn.contains(t)||Ra())}function eD(){Ra()}function tD(){Ra()}let Qg=!1;function dX(){Qg||(Qg=!0,document.addEventListener("click",J2,!0),window.addEventListener("scroll",eD,!0),window.addEventListener("resize",tD))}function fX(){Qg&&(Qg=!1,document.removeEventListener("click",J2,!0),window.removeEventListener("scroll",eD,!0),window.removeEventListener("resize",tD))}function pX(){fX(),ec&&(ec.unmount(),ec=null),Ji&&(Ji.remove(),Ji=null),ap=null}function nD(e,t){W2=e,(!Ji||!ec||!ap)&&(Ji=document.createElement("div"),document.body.append(Ji),ap=x.createRef(),ec=wn.createRoot(Ji));const a=ec,o=ap;Ns.flushSync(()=>{a.render(s.jsx(cX,{kind:e,entry:t,panelRef:o}))}),dX(),uX()}function sD(e){if(!e.isConnected)return;const t=c0(d0?.(e));t&&(p0(),Nn&&Nn!==e&&Ra(),Nn=e,nD(Z2(e),t),e.classList.add("active"),e.setAttribute("aria-describedby",i0))}function Ra(){p0(),Nn&&(Nn.classList.remove("active"),Nn.removeAttribute("aria-describedby"),Nn=null),pX()}function mX(){if(!Nn)return;const e=String(Nn.dataset.reqHover||""),t=String(Nn.dataset.reqId||"");f0=!!(e&&t)&&Nn.matches(":hover")&&!sp?{action:"move",kind:e,key:t}:{action:"close"}}function hX(){const e=f0;if(f0=null,!e||!Nn)return;if(e.action==="close"){Ra();return}const t=Xg?gX(Xg,e.kind,e.key):null,a=t?c0(d0?.(t)):null;if(!t||!a){Ra();return}t!==Nn&&(Nn.classList.remove("active"),Nn.removeAttribute("aria-describedby"),Nn=t,nD(Z2(t),a),t.classList.add("active"),t.setAttribute("aria-describedby",i0))}function gX(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 Zg(e){const t=e.target;return t instanceof Element?t.closest("[data-req-hover]"):null}function xX(e){const t=Zg(e);if(!t||!Xg?.contains(t)||(p0(),Nn===t&&ec))return;const a=Nn?0:KY;Nn&&Ra(),rp=t,Mo=window.setTimeout(()=>{Mo=0,rp=null,sD(t)},a)}function bX(e){const t=Zg(e);if(t){if(rp===t){window.clearTimeout(Mo),Mo=0,rp=null;return}Nn===t&&(window.clearTimeout(Mo),Mo=0,sp=window.setTimeout(()=>{sp=0,Nn===t&&Ra()},YY))}}function vX(e){const t=Zg(e);t&&sD(t)}function yX(e){const t=Zg(e);t&&Nn===t&&Ra()}function jX(e){e.key!=="Escape"||!Nn||Ra()}function wX(e){const t=e?.host;t&&(Xg=t,d0=e?.entryOf??null,t.addEventListener("pointerover",xX),t.addEventListener("pointerout",bX),t.addEventListener("focusin",vX),t.addEventListener("focusout",yX),t.addEventListener("keydown",jX))}window.wbRequestHover={bind:wX,close:Ra,hasProcessFacts:sX,beforeListRedraw:mX,afterListRedraw:hX};function ks(){return window}function m0(e){return e instanceof Error?e.message:String(e)}function Wg(e){return e.replace(/[&<>"']/g,t=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[t]??t)}const Jg={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"}},rD=r("进行中"),SX="running",aD={connecting:r("请求已受理,正在选路、取凭证、建立上游连接"),waiting:r("上游请求已发出,正在等第一个字节到达(模型的思考时间也在这段)"),streaming:r("首帧已到,上游内容正在下发"),retrying:r("本轮尝试失败,正在退避等待或切换到下一个账号"),queued:r("上游模型繁忙,请求已排进上游队列;网关正按上游建议的时长等待后重发(不是登录态或额度问题)"),"":r("请求正在转发中,用时列显示的是已用时")};function h0(e){const t=String(e?.phase??"").trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Jg,t)?t:""}function lD(e){const t=h0(e);return t?Jg[t].label:rD}function oD(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 NX(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 kX(e){const t=h0(e),a=t?Jg[t].label:rD,o=t?Jg[t].cls:SX,c=aD[t]||aD[""];return`${Wg(a)}`}function CX(e){const t=oD(NX(e));if(!t)return"";const a=lD(e),o=r("进入「{phase}」阶段已持续 {time}",{phase:a,time:t});return`${Wg(t)}`}const g0=[{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"}],iD=1e3,TX=Hh;function cD(e){return typeof e=="number"&&e>0?e:lu}const uD="workbuddy-desktop-logs-requests-range",dD="workbuddy-desktop-requests-filters",EX=3e4,x0=["today","7","30","month","all"],b0="all",RX={today:r("今天"),7:r("近 7 天"),30:r("近 30 天"),month:r("本月"),all:r("全部")},AX={today:r("今天"),7:r("7 天"),30:r("30 天"),month:r("本月"),all:r("全部")},OX=x0.map(e=>({value:e,label:AX[e]})),fD=[{value:"",label:r("全部状态")},{value:"ok",label:r("成功")},{value:"error",label:r("失败")}],MX=r("全部状态"),pD=r("全部提供商"),mD=r("全部模型"),ex={status:"",provider:"",model:""};function tx(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}function DX(e){const t=new Date;switch(e){case"today":return tx(t);case"7":return tx(new Date(t.getFullYear(),t.getMonth(),t.getDate()-6));case"30":return tx(new Date(t.getFullYear(),t.getMonth(),t.getDate()-29));case"month":return tx(new Date(t.getFullYear(),t.getMonth(),1));default:return null}}const Zt={filters:{...ex},range:IX(),runningOnly:!1,offset:0,size:cD(Vh("requests",Hh))};let nx={...ex},v0=!1,hD=!1,y0=[],sx=iD,rx=!0,j0=!1,w0=!1,gD=0,S0=0,N0=null,xD=!1,Pu=null;function IX(){try{const e=localStorage.getItem(uD);return e!==null&&x0.includes(e)?e:b0}catch{return b0}}function PX(e){try{localStorage.setItem(uD,e)}catch{}}function bD(){const e=ks().wbFilterMemory;return e?(v0=!0,nx=e.load(dD,{...ex}),Zt.filters={...nx},{...nx}):{...ex}}function _X(e){nx={...e},ks().wbFilterMemory?.save(dD,{status:e.status||"",provider:e.provider||"",model:e.model||""})}function vD(){const e=new URLSearchParams,t=DX(Zt.range);t!==null&&e.set("start",String(t));const a=Zt.runningOnly?"running":Zt.filters.status;return a&&e.set("status",a),Zt.filters.provider&&e.set("provider",Zt.filters.provider),Zt.filters.model&&e.set("model",Zt.filters.model),e}function LX(){const e=vD();return e.set("offset",String(Zt.offset)),e.set("limit",String(Zt.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 zX=r("生成速度:输出 token ÷ 流式段用时(总用时 − 首响);流式段不足总用时一半时按总用时计"),BX=500;function HX(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=BX&&c*2>=a,f=t/((d?c:a)/1e3);return`${f>=100?Math.round(f):f.toFixed(1)} tok/s`}function UX(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"-":k0(t)}function ax(e){return ks().wbUnits?.formatTokens?.(e)??(Number(e)||0).toLocaleString("zh-CN")}function VX(e){const t=Math.max(0,Date.now()-(Number(e)||0));return r("{n}秒",{n:Math.max(1,Math.floor(t/1e3))})}function FX(e){const t=Number(e.promptTokens)||0;return t<=0?"-":`${((Number(e.cacheReadTokens)||0)/t*100).toFixed(2)}%`}function C0(e){const t=Number(e.status)||0;return t>=200&&t<300&&!e.error}function lp(e){return(Number(e?.status)||0)===0&&!e?.error}const yD=e=>String(e?.id||e?.ts||"");function $X(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 jD(e){return ks().wbProviders?.labelOf?.(e)||e}function qX(e){const t=new Set;return e.map((a,o)=>{const c=yD(a)||`i${o}`;let d=c,f=1;for(;t.has(d);)d=`${c}#${f++}`;return t.add(d),d})}async function wD(){if(!(Date.now()-S0({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);Pu?.setFilterOptions(t,a)}catch(e){console.warn("读取请求日志筛选清单失败,筛选项退化为「全部」:",m0(e))}}}async function GX(){if(!j0)try{const e=await ks().workbuddyDesktop?.getScheduledTasks(),t=(e?.tasks||[]).find(a=>a.id==="requestsAutoRefresh");T0(t||null),j0=Array.isArray(e?.tasks)}catch(e){console.warn("读取请求日志自动刷新间隔失败,按默认 1 秒:",m0(e)),T0(null)}}function T0(e){j0=!0;const t=Number(e?.interval),a=e?.unit;!!e&&typeof e=="object"&&Number.isFinite(t)&&t>0&&(a==="seconds"||a==="minutes")?(rx=e.enabled!==!1,sx=a==="minutes"?t*6e4:t*1e3):(rx=!0,sx=iD),Pu?.setAuto({ms:sx,enabled:rx})}function KX(){if(xD)return;const e=ks().wbColSettings;e&&(xD=!0,N0=e.register({id:"requests",label:r("请求日志表"),columns:g0.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:()=>{Ns.flushSync(()=>Pu?.repaint()),ks().wbTableColumns?.repaint?.("requests")}}))}function E0(){return(N0?N0.apply(g0):g0).map(t=>({...t,align:t.align||"left"}))}const YX={entries:[],total:0,matched:0,running:0,loaded:!1,error:""};function XX(e){return e.loaded?e.total?r("没有符合筛选条件的请求"):r("暂无请求日志,网关还没有转发过请求"):r("正在加载请求日志…")}function QX(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 ZX(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?jD(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=yD(e),g=[];if(e.isTest&&g.push(s.jsx(ze,{variant:"brand",shape:"tag",title:r("这条明细是一次模型测试(人工发起):走的是真实转发链路,但不计入报表统计"),children:r("测试")},"test")),ks().wbRequestHover?.hasProcessFacts?.(e)??f>1){const y=f>1?f:$X(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(lp(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(Uv,{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=C0(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 lp(e)?s.jsxs("span",{className:d,children:[s.jsx("span",{className:"req-dur-line",title:r("已用时(请求仍在转发中)"),children:VX(e.ts)}),QX(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:UX(e.firstResponseMs)})})]},o);case"usage":{if(lp(e))return s.jsx("span",{className:d},o);if(!C0(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: ${ax(e.promptTokens)} / out: ${ax(e.completionTokens)} / all: ${ax(e.totalTokens)}`,p=r("缓存读取: {cache} / 命中率: {rate}",{cache:ax(e.cacheReadTokens),rate:FX(e)}),g=HX(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:zX,children:[" · ",g]}):null]})]},o)}case"error":return lp(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:()=>{ks().wbRequestDetail?.open?.(f,e)},children:r("详情")})},o):s.jsx("span",{className:`req-none ${c} ta-${a}`,children:"-"},o)}default:return null}}function WX(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 JX(){const[e,t]=x.useState(YX),[a,o]=x.useState(()=>bD()),[c,d]=x.useState(()=>Zt.range),[f,p]=x.useState(!1),[g,v]=x.useState(0),[y,b]=x.useState(()=>Zt.size),[j,w]=x.useState(()=>({ms:sx,enabled:rx})),[S,N]=x.useState([]),[k,E]=x.useState([]),[,R]=x.useState(0),C=x.useRef(null),A=x.useRef(null),D=x.useRef(!1),I=x.useCallback(ee=>(Zt.filters={...Zt.filters,...ee},o({...Zt.filters}),Zt.filters),[]),M=x.useCallback(ee=>{Zt.range=ee,d(ee)},[]),O=x.useCallback(ee=>{Zt.offset=ee,v(ee)},[]),_=x.useCallback(ee=>{Zt.runningOnly=ee,p(ee)},[]),L=x.useCallback(()=>{v0||!ks().wbFilterMemory||(v0=!0,!hD&&I(bD()))},[I]),z=x.useCallback((ee,de)=>{ks().wbRequestHover?.beforeListRedraw?.(),de&&(y0=de),D.current=!0,t(ee)},[]),U=x.useCallback(ee=>{ks().wbRequestHover?.beforeListRedraw?.(),D.current=!0,t(de=>({...de,error:ee}))},[]),B=x.useCallback(async(ee={})=>{const{silent:de=!1,resetPage:K=!1}=ee;K&&O(0),GX(),L(),de||wD();const be=++gD;try{const ne=ks().workbuddyDesktop;if(!ne)throw new Error(r("后端桥不可用"));const ce=await ne.getStatsRequests(LX());if(be!==gD)return;const we={entries:Array.isArray(ce?.entries)?ce.entries:[],total:Number(ce?.total)||0,matched:Number(ce?.matched)||0,running:Number(ce?.running)||0,loaded:!0,error:""},Ee=Math.max(0,(Math.ceil(we.matched/Zt.size)-1)*Zt.size);if(Zt.offset>Ee)return O(Ee),B({silent:de});K&&(A.current=0),z(we,we.entries)}catch(ne){de||(console.warn("读取请求日志失败:",m0(ne)),U(r("读取请求日志失败,详见控制台")))}},[O,z,U,L]);x.useEffect(()=>(Pu={load:B,setAuto:ee=>w(ee),setFilterOptions:(ee,de)=>{N(ee),E(de)},repaint:()=>R(ee=>ee+1)},ks().wbRequestHover?.bind?.({host:C.current,entryOf:ee=>{const de=ee?.dataset?.reqId||"";return de&&(y0.find(K=>String(K?.id||"")===de)||y0.find(K=>String(K?.ts||"")===de))||null}}),B({silent:!0}),wD(),()=>{Pu=null}),[B]),x.useLayoutEffect(()=>{KX(),R(ee=>ee+1)},[]);const Q=e.error||!e.entries.length?"":E0().map(ee=>ee.key).join("|");x.useLayoutEffect(()=>{Q&&ks().wbTableColumns?.repaint?.("requests")},[Q]),x.useEffect(()=>{if(!j.enabled||j.ms<=0)return;const ee=window.setInterval(()=>{document.hidden||ks().wbApp?.currentPage!=="requests"||w0||(w0=!0,B({silent:!0}).finally(()=>{w0=!1}))},j.ms);return()=>{window.clearInterval(ee)}},[j,B]),x.useLayoutEffect(()=>{D.current&&(D.current=!1,ks().wbRequestHover?.afterListRedraw?.());const ee=A.current;if(ee===null)return;A.current=null;const de=C.current;de&&(de.scrollTop=ee)});function W(ee){const de=Math.max(1,Math.ceil(e.matched/Zt.size)),be=(Math.min(Math.max(1,ee),de)-1)*Zt.size;be!==Zt.offset&&(O(be),A.current=0,B())}function Z(ee){const de=cD(ee);if(de===Zt.size)return;Zt.size=de,b(de),Fh("requests",de);const K=Zt.offset+1;O(Math.max(0,Math.floor((K-1)/de)*de)),A.current=0,B()}function Y(ee){hD=!0,_X(I(ee)),B({resetPage:!0})}function q(ee){const de=x0.includes(ee)?ee:b0;de!==Zt.range&&(M(de),PX(de),B({resetPage:!0}))}function G(ee){ee!==Zt.runningOnly&&(_(ee),B({resetPage:!0}))}const F=E0(),$=Math.max(1,Math.ceil(e.matched/Zt.size)),X=Math.min($,Math.floor(g/Zt.size)+1),re=e.matched?g+1:0,P=e.matched?g+e.entries.length:0,V=e.error?"—":e.matched===e.total?r("{n} 条",{n:e.total}):r("{matched} / {total} 条",{matched:e.matched,total:e.total}),J=!f&&e.running>0?r(" · {n} 进行中",{n:e.running}):"",ie=[RX[c]||r("全部")];f?ie.push(r("只看进行中")):a.status==="ok"?ie.push(r("只看成功")):a.status==="error"&&ie.push(r("只看失败")),a.provider&&ie.push(jD(a.provider)),a.model&&ie.push(a.model);const me=x.useMemo(()=>!a.provider||S.some(ee=>ee.value===a.provider)?S:[{value:a.provider,label:a.provider},...S],[a.provider,S]),he=x.useMemo(()=>!a.model||k.includes(a.model)?k:[a.model,...k],[a.model,k]),ae=qX(e.entries),oe=e.entries.map((ee,de)=>s.jsx("div",{className:`req-row${lp(ee)?" running":C0(ee)?"":" failed"}`,children:F.map(K=>ZX(ee,K))},ae[de]));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:V+J}),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:()=>{ks().wbRequestClearModal?.open?.()},children:r("清理")})})]}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"log-filters",children:[s.jsx(Pn,{options:OX,value:c,onValueChange:q,"aria-label":r("请求日志时间范围"),className:"shrink-0"}),s.jsxs(ut,{value:a.status,disabled:f,onValueChange:ee=>Y({status:String(ee??"")}),children:[s.jsx(ft,{id:"req-status",className:"min-w-[120px]",title:r(f?"「仅看进行中」开启时,状态固定为进行中":"按请求结果筛选"),"aria-label":r("按请求结果筛选"),children:s.jsx(dt,{children:fD.find(ee=>ee.value===a.status)?.label??MX})}),s.jsx(pt,{children:fD.map(ee=>s.jsx(Xe,{value:ee.value,children:ee.label},ee.value))})]}),s.jsxs(ut,{value:a.provider,onValueChange:ee=>Y({provider:String(ee??"")}),children:[s.jsx(ft,{id:"req-provider",className:"min-w-[120px]",title:r("按提供商筛选(只列日志里出现过的)"),"aria-label":r("按提供商筛选"),children:s.jsx(dt,{children:a.provider?me.find(ee=>ee.value===a.provider)?.label||a.provider:pD})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"",children:pD}),me.map(ee=>s.jsx(Xe,{value:ee.value,children:ee.label},ee.value))]})]}),s.jsxs(ut,{value:a.model,onValueChange:ee=>Y({model:String(ee??"")}),children:[s.jsx(ft,{id:"req-model",className:"min-w-[120px]",title:r("按模型筛选(只列日志里出现过的;精确匹配模型名)"),"aria-label":r("按模型筛选"),children:s.jsx(dt,{children:a.model||mD})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"",children:mD}),he.map(ee=>s.jsx(Xe,{value:ee,children:ee},ee))]})]}),s.jsx(IV,{id:"btn-req-running",variant:"outline",size:"default",pressed:f,onPressedChange:G,title:r("只显示正在转发中的请求(状态列按阶段显示:连接中 / 等待响应 / 响应中 / 重试中,用时列显示已用时)"),children:r("仅看进行中")}),s.jsx("div",{className:"spacer"}),s.jsx("span",{className:"panel-sub",id:"req-summary",children:ie.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?[WX(F),...oe]:s.jsx("div",{className:"log-empty",children:XX(e)})})]}),s.jsx(Di,{total:e.matched,range:{start:re,end:P},page:X,pageCount:$,size:y,sizes:TX,onSizeChange:Z,onPageChange:W,disabled:!e.loaded&&!e.error})]})}async function SD(e={}){await Pu?.load(e)}function eQ(){return vD().toString()}function tQ(){return S0=0,SD({resetPage:!0})}const ND='.page[data-page="requests"]';let kD=!1;function CD(){if(kD)return;const e=document.querySelector(ND);e&&(kD=!0,e.replaceChildren(),wn.createRoot(e).render(s.jsx(JX,{})))}document.querySelector(ND)?CD():document.addEventListener("DOMContentLoaded",CD,{once:!0}),window.wbRequestsPanel={load:SD,applyAutoRefresh:T0,visibleColumns:E0,clearParams:eQ,notifyCleared:tQ},window.wbRequestPhase={labelOf:lD,badgeHtml:kX,elapsedLineHtml:CX,elapsedText:oD,phaseOf:h0};function nQ(e){if(e.status==="loading")return zt.appLoading;if(e.status==="unavailable")return zt.modelsDevUnavailable;const t=e.source==="builtin"?zt.modelsDevSourceBuiltin:e.source==="cache"?zt.modelsDevSourceCache:e.source==="network"?zt.modelsDevSourceNetwork:e.source,a=e.updatedAt>0?String(et().wbApp?.formatTime?.(e.updatedAt)??""):"";if(!t&&!a&&!e.count)return zt.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 et(){return window}function Mt(e){return e instanceof Error?e.message:String(e)}function Ue(e,t){et().wbApp?.toast?.(e,t)}async function sQ(e){try{await et().workbuddyDesktop?.openReleasePage?.(e)}catch(t){Ue(r("打开链接失败:{error}",{error:Mt(t)}),"err")}}const lx=[{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"}],ox=[{value:"order",label:r("顺序优先"),tip:r("排第 1 的接走所有请求,直到它不能答(限流 / 故障 / 额度尽)才轮到下一位 —— 就是「从上往下」的现状行为。")},{value:"rotate",label:r("负载均衡"),tip:r("每条请求轮换到下一个可用账号;新会话交给当前最闲的那位。适合想把手里的号摊开用、不让某一个一直扛。")},{value:"provider",label:r("家内轮询"),tip:r("家之间仍按优先级,只有同一家内部轮流用各账号 —— 想优先用某几家、又不愿把某一家的某个账号焊死时用它。")}],ix=[{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("不做会话识别,每条请求都重新按策略选路。")}],rQ=[{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("连续失败到阈值后把这个账号整个打开(默认关)。与失败退避的分工:退避管「单次失败先凉一会儿」,惩罚轻、自动恢复;熔断管「这个账号现在整体不对劲,别再一条条地试」,要连续成功若干次才关。打开期间该账号被跳过,除非全场只剩它 —— 那时仍放行试一次。")}],TD="workbuddy-desktop-settings-cat",aQ="workbuddy-desktop-theme",lQ="workbuddy-desktop-zoom",ED="wb:theme",RD="wb:zoom",R0=80,AD=130,cx=5,oQ=Array.from({length:(AD-R0)/cx+1},(e,t)=>R0+t*cx),iQ=[{value:"system",label:r("跟随系统")},{value:"light",label:r("浅色")},{value:"dark",label:r("深色")}];function cQ(){try{const e=localStorage.getItem(aQ);return e==="light"||e==="dark"?e:"system"}catch{return"system"}}function uQ(){try{const e=localStorage.getItem(lQ);if(e===null||e.trim()==="")return 100;const t=Number(e);if(!Number.isFinite(t))return 100;const a=Math.round(t/cx)*cx;return Math.min(AD,Math.max(R0,a))}catch{return 100}}const A0=[{key:"logRetentionDays",id:"settings-retention-log",label:r("事件日志保留天数"),unit:r("天"),min:1,max:3650,hint:r("登录 / 账号切换 / 429 切换等系统事件,可填 1–3650 天。")}],OD=[{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 秒。")}],MD=[{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。")}],DD=[{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 秒强制一个固定时长。")}],ID=[{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。")}],PD="noRetryStatusCodes",O0=100,M0=599,_D=50,Do=[{value:"passthrough",optionLabel:r("透传客户端 system(默认)"),toastLabel:r("透传客户端 system")},{value:"custom",optionLabel:r("替换为网关提示词"),toastLabel:r("替换为网关提示词")},{value:"append",optionLabel:r("追加网关提示词"),toastLabel:r("追加网关提示词")}];function LD(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 dQ(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 zD(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 BD(e){if(!Number.isFinite(e)||e<=0)return r("0 B");if(e<1024)return r("{n} B",{n:e});const t=e/1024;if(t<1024)return r("{n} KB",{n:t.toFixed(1)});const a=t/1024;return a<1024?r("{n} MB",{n:a.toFixed(1)}):r("{n} GB",{n:(a/1024).toFixed(2)})}function fQ(e){const t=Number(e);return!Number.isFinite(t)||t<0?"—":t.toLocaleString("zh-CN")}const ns={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 读数的写法:开启后按「万 / 亿」式的本地量级词显示(简体为万 / 亿,繁体为萬 / 億,日文为万 / 億,韩文为만 / 억),关闭则用 k / M 缩写(与上游文档、接口字段的写法一致)。英文 / 葡语的本地量级词就是 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 / developer,换成网关提示词;追加 = 保留客户端内容,只在最前面插一条网关提示词。网关提示词来自「提示词文件」或界面里编辑的正文(正文优先,清空回到文件 / 内置默认)。撞上拦截时会自动改用一段最小中性提示词,次日 00:00 自动恢复,也可以随时解除。"),debug:r("开启后,网关会把每次转发**发给上游的请求**(请求头 + 请求体)与**上游返回的响应**(状态码 + 响应头 + 响应体)完整保存到本地,供请求日志页的「详情」查看;请求日志详情的「预览对话」也依赖本开关 —— 它保存的是客户端发来的请求体与网关下发的响应体(两侧各截断到 128 KiB),不开这个开关时预览对话没有数据可看。请求头里的 Authorization、Cookie、API Key 等凭据字段一律替换成 [redacted],不会明文落盘;请求体与响应体按原样保存(可能包含你的对话内容)。上游报文只保留最近 500 条,超出后丢弃最旧的。这是排障用的临时开关,不需要时建议关闭。"),io:r("导出会把全部账号与自定义提供商定义写入一个 JSON 文件,可以拷到另一台机器上导入后继续使用。导入采用合并策略:同提供商下按业务身份(UID / userId / apiKey 等)去重 —— 已存在的账号只更新凭证,保留本机原有的优先级顺序;新账号追加到转发顺序末尾,不会抢占当前正在使用的账号;自定义提供商定义按 id 合并,本机缺失时自动补建。"),backup:r("把整份数据库(账号、网关配置、事件日志、请求统计、调试报文与桌面设置)导出成一个 SQL 文件,恢复时整体替换本机全部数据 —— 与上面「账号导入 / 导出」的逐条合并是两种语义:恢复会连配置、日志与当前启用状态一起换成备份那台机器的状态。导出默认包含日志与调试报文(文件可能很大),不需要时可以取消勾选只备业务数据。恢复前会自动把当前数据备份到配置目录的 backups/ 下,恢复后需要重新登录管理面板。"),retention:r("超出保留天数的部分会被删除:事件日志是登录、账号切换、429 切换这类系统事件。把天数改小(例如 30 天改成 7 天)保存后会立即删除超出的历史数据,此操作不可恢复;改大或保持不变不会删除任何数据。可填范围为 1–3650 天。请求日志 / 按天聚合 / 签到记录已全量保留、不再自动删除,要清历史请到对应页面手动清空。"),storage:r("全部数据(账号、事件日志、请求记录、调试报文、设置)统一保存在配置目录下的 agent2api.db 这一个 SQLite 数据库里。备份时只需拷贝这个文件;更换保存位置请设置环境变量 AGENT2API_PROXY_HOME 后重启程序。"),modelsDev:r("models.dev 是一个开源的模型资料库(社区维护),这里用它补齐「上游没告诉我们」的模型能力:上下文窗口、最大输出、工具调用、图片、视频、是否支持思考,以及这个模型认识哪些思考档位。优先级是:你在「模型能力」里手工改的值 > 上游清单自己声明的值 > models.dev 的值 —— 它只填上游没声明的空位,从不推翻上游已声明的。网关随包内嵌了一份快照,所以离线、首次启动、访问不通时也有数据;开启时会按「模型目录刷新」任务的间隔联网更新(同一轮里一并刷新,也可在这里立即刷新)。关闭只停联网刷新,已经拿到的数据继续用。")},Fn={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;替换 = 删掉客户端的 system / developer,换成网关提示词;追加 = 保留客户端内容,在最前面多插一条。"),promptFile:r("UTF-8 文本文件路径。留空用内置默认;只在「替换 / 追加」下读取。"),promptText:r("保存后以这份为准(优先于上面的文件);清空回到文件 / 内置默认。"),promptGatewayText:r("三段必须各自成块(上游按结构校验,并成一段会被回 405),所以这里分开编辑。动态段里的运行值写成占位符,发请求时才替换:{cwd} 工作目录、{platform} 平台、{shell} shell、{os_version} 系统版本、{git} 是否 git 仓库、{provider} 提供方标识、{model} 模型名。清空某一段 = 那一段恢复官方原文。"),prompt:r("保存后立即生效,不用重启(下一个请求就用新模式)。"),promptProviders:r("不在这里列出的提供商都用上面的全局配置;「跟随默认」取消这一家的单独配置。带「网关自带」的家列在这里:那段文本是网关自己装上去的(可关、可改正文),与「模式」是两件事。"),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 与面板管理员凭据,可直接用于登录。请妥善保管,不要外传或上传到公共位置。"),modelsDev:r("「模型管理」里每个能力的来源标记(上游 / models.dev / 已覆盖)读的就是这份数据;映射弹窗的思考档位下拉也按这里的数据只列该模型真实认识的档位。")},zt={appLoading:"—",appUnavailable:r("主进程未返回启动设置,请更新桌面端后重试"),appTrayOn:r("关闭窗口时程序不退出,转发继续在后台运行;退出请用托盘菜单"),appTrayOff:r("关闭窗口即退出程序,后台转发随之中断"),appLightOn:r("轻量模式已开启:关窗即销毁界面进程(释放约 200MB 内存),网关在后台继续;界面销毁期间 ZCode 活动套餐通道不可用,相关请求会在请求日志里注明原因"),appLightOff:r("未开启轻量模式:关窗仅隐藏窗口,界面进程常驻内存,随时打开不等待"),unitsOn:r("当前按「万 / 亿」式本地量级词显示(如 1.2亿 / 8400万)。"),unitsOff:r("当前按 k / M 缩写显示(如 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)。切换后整页立即刷新,不影响账号、密钥与转发。")};function HD(){return et().workbuddyDesktop?.platform==="web"}let it={...{category:lx[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:HD()};const D0=new Set;function pQ(e){return D0.add(e),()=>{D0.delete(e)}}function mQ(){return it}function hQ(){return x.useSyncExternalStore(pQ,mQ)}function Ze(e){it={...it,...e};for(const t of D0)t()}function Aa(e){Ze({app:{...it.app,...e}})}function Wa(){Ze({})}let kn=null;function cs(e){kn=e,Ze({busy:e})}function ss(){kn=null,Ze({busy:null})}function I0(e){const t=lx.some(a=>a.id===e)?String(e):lx[0].id;Ze({category:t,scrollReset:it.scrollReset+1})}function gQ(e){I0(e);try{localStorage.setItem(TD,e)}catch{}}function UD(){let e=null;try{e=localStorage.getItem(TD)}catch{e=null}I0(e)}function VD(){Ze({unitsChinese:et().wbUnits?.isChinese?.()!==!1})}function xQ(e){et().wbUnits?.setChinese?.(e),VD(),Ue(r(e?"✅ 已改用本地量级词(万 / 亿式)":"✅ 已改用 k / M 缩写"))}function P0(e){if(e===void 0)return;if(!e||typeof e!="object"){Aa({status:"unavailable"});return}const t=e;Aa({status:"ready",closeToTray:t.closeToTray===!0,autostart:t.autostart===!0,lanAccess:t.lanAccess===!0,lanPanel:t.lanPanel===!0,lightweightMode:t.lightweightMode===!0})}async function FD(){try{P0(await et().workbuddyDesktop?.getAppSettings())}catch(e){console.warn("读取应用设置失败:",Mt(e)),P0(null)}}async function bQ(){const e=et().workbuddyDesktop;if(e?.localIp){try{Aa({lanIp:await e.localIp()||null})}catch{}try{const t=Number((await e.getBackendStatus?.())?.port)||0;t&&Aa({port:t})}catch{}try{const t=(await e.panelAdminStatus?.())?.registered===!0;Aa({adminRegistered:t})}catch{}}}async function _0(e,t){if(kn){Wa();return}const a=it.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};cs("app"),Aa(o);const c=r(e==="autostart"?"开机自动启动":e==="lightweight"?"轻量模式":"关闭窗口时最小化到托盘");try{const d=et().workbuddyDesktop;if(!d)throw new Error(r("主进程桥不可用"));const f=await d.saveAppSettings(o);Aa({status:"ready",...dQ(f,o)}),Ue(r("✅ 已更新「{label}」",{label:c}))}catch(d){Aa(a),Ue(r("保存失败:{message}",{message:Mt(d)}),"err")}finally{ss()}}function vQ(e){if(kn){Wa();return}Ze({lanConfirm:{mode:e?"enable":"disable",panel:it.app.lanPanel}})}function yQ(e){if(kn){Wa();return}Ze({lanConfirm:{mode:"panel",panel:e}})}function L0(e){const t=it.lanConfirm;if(Ze({lanConfirm:null}),!(!t||!e)){if(t.mode==="disable"){ux(!1,!1);return}if(t.mode==="panel"){ux(!0,t.panel);return}jQ()}}async function jQ(){const e=et().workbuddyDesktop;if(!e?.panelAdminStatus){Ue(r("当前环境不支持局域网访问设置"),"err");return}cs("lan");let t;try{t=(await e.panelAdminStatus())?.registered===!0}catch(a){ss(),Ue(r("查询管理员状态失败:{message}",{message:Mt(a)}),"err");return}if(ss(),Aa({adminRegistered:t}),t){await ux(!0,it.app.lanPanel);return}Ze({lanRegister:{busy:!1,error:""}})}async function wQ(e,t){if(kn)return;const a=et().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),it.lanRegister===null)return;Ze({lanRegister:null}),Aa({adminRegistered:!0}),await ux(!0,it.app.lanPanel)}catch(c){Ze({lanRegister:{busy:!1,error:Mt(c)}})}}function $D(){Ze({lanRegister:null})}async function ux(e,t){if(kn)return;const a=et().workbuddyDesktop;if(!a?.changeLanAccess){Ue(r("当前环境不支持局域网访问设置"),"err");return}cs("lan"),Aa({lanAccess:e,lanPanel:t});try{(await a.changeLanAccess(e,t))?.createdKey&&Ue(r("✅ 已自动创建网关 Key「默认」(可在「网关 Key」页查看)")),Ue(r("✅ 设置已保存,应用正在重启…"))}catch(o){Ue(r("保存失败:{message}",{message:Mt(o)}),"err"),await FD()}finally{ss()}}async function SQ(){if(!kn){Ze({ioFailure:null}),cs("export");try{const e=await et().workbuddyDesktop?.exportAccounts();if(e?.canceled){Ue(r("已取消导出"));return}const t=Number(e?.count)||0,a=Number(e?.customProviders)||0;if(!t&&!a){Ue(r("没有可导出的账号"),"err");return}const o=a?r("、{n} 个自定义提供商",{n:a}):"",c=e?.file?r(" 到 {file}",{file:e.file}):"";Ue(r("✅ 已导出 {count} 个账号{note}{file}",{count:t,note:o,file:c}))}catch(e){Ue(r("操作失败:{message}",{message:Mt(e)}),"err")}finally{ss()}}}async function NQ(){if(!kn){Ze({ioFailure:null}),cs("import");try{const e=await et().workbuddyDesktop?.importAccounts();if(e?.canceled){Ue(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){Ue(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 Ue(r("✅ 导入完成:{summary}",{summary:j}));(t||a||p||g)&&await et().wbApp?.refresh?.()}catch(e){Ue(r("操作失败:{message}",{message:Mt(e)}),"err")}finally{ss()}}}function kQ(e){Ze({dbIncludeLogs:e})}async function CQ(){if(!kn){cs("dbExport");try{const e=et().workbuddyDesktop;if(!e?.exportDatabase){Ue(r("当前环境不支持整库备份(仅桌面端可用)"),"err");return}const t=await e.exportDatabase(it.dbIncludeLogs);if(t?.canceled){Ue(r("已取消导出"));return}const a=Number(t?.bytes)||0,o=Array.isArray(t?.tables)?t.tables.length:0;Ue(r("✅ 已备份 {n} 张表({size})到 {file}",{n:o,size:BD(a),file:t?.file||""}))}catch(e){Ue(r("操作失败:{message}",{message:Mt(e)}),"err")}finally{ss()}}}function TQ(){kn||Ze({dbBackupConfirm:{includeLogs:it.dbIncludeLogs}})}function z0(e){Ze({dbBackupConfirm:null}),e&&EQ()}async function EQ(){if(kn)return;const e=et().workbuddyDesktop;if(!e?.importDatabase){Ue(r("当前环境不支持整库恢复(仅桌面端可用)"),"err");return}cs("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}):"";Ue(r("✅ 已恢复 {n} 张表{note}",{n:a,note:o}));const c=typeof t?.warning=="string"?t.warning.trim():"";c&&Ze({dbWarning:c}),await Z0(),await et().wbApp?.refresh?.()}catch(t){Ue(r("恢复失败:{message}",{message:Mt(t)}),"err")}finally{ss()}}function dx(e){if(e===void 0)return;const t=zD(A0,e,it.retention.values);Ze({retention:{status:t===null?"unavailable":"ready",values:t}})}async function fx(){try{dx(await et().workbuddyDesktop?.getRetention())}catch(e){console.warn("读取数据保留设置失败:",Mt(e)),dx(null)}}let px=null;function mx(e){const t=px;px=null,Ze({retentionConfirm:null}),t?.(e)}function RQ(e){return new Promise(t=>{px&&mx(!1),px=t,Ze({retentionConfirm:{head:e}})})}function AQ(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 OQ(e,t){if(kn||it.retentionConfirm)return;const a=LD(t,e.min,e.max,r("天数"));if(!a.ok){Ue(a.message,"err");return}const o=it.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;Ue(a?r("✅ 已保留 {days} 天,超出部分已清理",{days:f}):r("✅ 已保留 {days} 天",{days:f}));return}await fx(),Ue(a?r("✅ 已保留 {days} 天,超出部分已清理",{days:t}):r("✅ 已保留 {days} 天",{days:t}))}catch(c){Ue(r("保存失败:{message}",{message:Mt(c)}),"err"),await fx()}finally{ss()}}function op(e,t){if(t===void 0)return;const a=zD(e.fields,t,e.read().values);e.write({status:a===null?"unavailable":"ready",values:a}),e.syncExtras?.(a===null?null:t)}async function _u(e){try{op(e,await e.get())}catch(t){console.warn(`${e.consoleLabel}失败:`,Mt(t)),op(e,null)}}async function hx(e,t,a){if(kn)return;const o=LD(a,t.min,t.max,t.label);if(!o.ok){Ue(o.message,"err");return}const c=e.read().values?.[t.key];if(Number.isInteger(c)&&o.value===c)return;cs(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});op(e,f);const p=e.read().values?.[t.key],g=Number.isInteger(p)?p:o.value;Ue(r("✅ 已保存:{label} {value}",{label:t.label,value:String(g)}))}catch(f){Ue(r("保存失败:{message}",{message:Mt(f)}),"err"),await _u(e)}finally{ss()}}const qD={scope:"queue",fields:DD,consoleLabel:"读取排队等待设置",get:()=>et().workbuddyDesktop?.getQueue(),save:e=>et().workbuddyDesktop?.saveQueue(e),read:()=>it.queue,write:e=>Ze({queue:e})};async function GD(){await _u(qD)}async function DQ(e,t){await hx(qD,e,t)}const KD={scope:"captchaPool",fields:ID,consoleLabel:"读取验证码令牌池设置",get:()=>et().workbuddyDesktop?.getCaptchaPool(),save:e=>et().workbuddyDesktop?.saveCaptchaPool(e),read:()=>it.captchaPool,write:e=>Ze({captchaPool:e})};async function YD(){await _u(KD)}async function IQ(e,t){await hx(KD,e,t)}const XD="routingStrategy",QD="routingSticky",PQ="routingFailoverBackoff",_Q="routingSink",LQ="routingBreakerEnabled",zQ={[XD]:new Set(ox.map(e=>e.value)),[QD]:new Set(ix.map(e=>e.value))};function ZD(e){const t=e&&typeof e=="object"?e:{},a=(c,d)=>{const f=t[c];return typeof f=="string"&&zQ[c].has(f)?f:d},o=(c,d)=>{const f=t[c];return typeof f=="boolean"?f:d};return{strategy:a(XD,"order"),sticky:a(QD,"auto"),failoverBackoff:o(PQ,!0),sink:o(_Q,!0),breakerEnabled:o(LQ,!1)}}async function gx(){try{const e=await et().workbuddyDesktop?.getRoutingConfig();if(e===void 0){Ze({routing:{...it.routing,status:"unavailable"}});return}Ze({routing:{status:"ready",...ZD(e)}})}catch(e){console.warn("读取路由设置失败:",Mt(e)),Ze({routing:{...it.routing,status:"unavailable"}})}}async function B0(e){if(kn)return;const t=et().workbuddyDesktop;if(!t?.setRoutingConfig){Ue(r("桌面运行时不可用,暂时无法保存"),"err");return}cs("routing");try{const a=await t.setRoutingConfig(e);a!==void 0?Ze({routing:{status:"ready",...ZD(a)}}):await gx(),Ue(r("✅ 路由设置已保存"))}catch(a){Ue(r("保存失败:{message}",{message:Mt(a)}),"err"),await gx()}finally{ss()}}const ip={scope:"retry",fields:OD,consoleLabel:"读取请求重试设置",get:()=>et().workbuddyDesktop?.getRetry(),save:e=>et().workbuddyDesktop?.saveRetry(e),read:()=>it.retry,write:e=>Ze({retry:e}),syncExtras:e=>{if(e===null){Ze({retryCodes:null});return}const t=e[PD];if(!Array.isArray(t))return;Ze({retryCodes:t.filter(o=>typeof o=="number"&&Number.isInteger(o)&&o>=O0&&o<=M0)})}};function BQ(e){op(ip,e)}async function WD(){await _u(ip)}async function HQ(e,t){await hx(ip,e,t)}async function H0(e){if(!kn){Ze({retryCodes:e}),cs("codes");try{const t=await et().workbuddyDesktop?.saveRetry({[PD]:e});op(ip,t),Ue(r("✅ 已保存:指定错误码直接换号"))}catch(t){Ue(r("保存失败:{message}",{message:Mt(t)}),"err"),await _u(ip)}finally{ss()}}}async function UQ(e){const t=it.retryCodes;if(t===null)return;const a=String(e??"").trim();if(!a)return;if(!/^\d+$/.test(a)||Number(a)M0){Ue(r("状态码必须是 {min}–{max} 的整数(收到: {text})",{min:O0,max:M0,text:a}),"err");return}const o=Number(a);if(t.includes(o)){Ue(r("状态码 {code} 已在名单里",{code:o}));return}if(t.length>=_D){Ue(r("名单最多 {max} 个状态码",{max:_D}),"err");return}await H0([...t,o])}async function VQ(e){const t=it.retryCodes;!t||!t.includes(e)||await H0(t.filter(a=>a!==e))}async function FQ(){const e=it.retryCodes;e?.length&&await H0(e.slice(0,-1))}const JD={scope:"timeouts",fields:MD,consoleLabel:"读取请求超时设置",get:()=>et().workbuddyDesktop?.getTimeouts(),save:e=>et().workbuddyDesktop?.saveTimeouts(e),read:()=>it.timeouts,write:e=>Ze({timeouts:e})};async function eI(){await _u(JD)}async function $Q(e,t){await hx(JD,e,t)}function xx(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 U0(){try{xx(await et().workbuddyDesktop?.getDebug())}catch(e){console.warn("读取调试模式设置失败:",Mt(e)),xx(null)}}async function qQ(e){if(kn){Wa();return}cs("debug"),Ze({debug:{...it.debug,on:e}});try{const t=await et().workbuddyDesktop?.saveDebug(e);xx(t),Ue(r(e?"✅ 调试模式已开启":"✅ 调试模式已关闭"))}catch(t){Ue(r("保存失败:{message}",{message:Mt(t)}),"err"),await U0()}finally{ss()}}function bx(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 V0(){try{bx(await et().workbuddyDesktop?.getSanitize())}catch(e){console.warn("读取出站指纹脱敏设置失败:",Mt(e)),bx(null)}}async function GQ(e){if(kn){Wa();return}cs("sanitize"),Ze({sanitize:{status:"ready",on:e}});try{const t=await et().workbuddyDesktop?.saveSanitize(e);bx(t),Ue(r(e?"✅ 出站指纹脱敏已开启":"已关闭出站指纹脱敏"))}catch(t){Ue(r("保存失败:{message}",{message:Mt(t)}),"err"),await V0()}finally{ss()}}function F0(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 $0(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:F0(t.defaults),overrides:F0(t.overrides),effective:F0(t.effective)}})}async function q0(){try{$0(await et().workbuddyDesktop?.getClineHeaders())}catch(e){console.warn("读取 Cline 伪装头失败:",Mt(e)),$0(null)}}async function KQ(){await q0(),Ue(r("Cline 伪装头已刷新"))}async function tI(e){if(kn){Wa();return}cs("clineHeaders");try{const t=await et().workbuddyDesktop?.saveClineHeaders(e);$0(t),Ue(r("✅ Cline 伪装头已保存"))}catch(t){Ue(r("保存失败:{message}",{message:Mt(t)}),"err"),await q0()}finally{ss()}}function G0(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 K0(){try{G0(await et().workbuddyDesktop?.getCors())}catch(e){console.warn("读取网关跨域访问设置失败:",Mt(e)),G0(null)}}async function YQ(e){if(kn){Wa();return}cs("cors"),Ze({cors:{status:"ready",on:e}});try{const t=await et().workbuddyDesktop?.saveCors(e);G0(t),Ue(r(e?"网关跨域访问已开启":"已关闭网关跨域访问"))}catch(t){Ue(r("保存失败:{message}",{message:Mt(t)}),"err"),await K0()}finally{ss()}}async function nI(){try{const e=await et().workbuddyDesktop?.getCaptchaSetting();Ze({captcha:{available:!0,enabled:e?.captchaEnabled===!0}})}catch(e){Ze({captcha:{available:!1,enabled:!1}}),console.warn("读取机器人校验设置失败:",Mt(e))}}async function XQ(e){if(kn){Wa();return}cs("captcha"),Ze({captcha:{...it.captcha,enabled:e}});try{const t=await et().workbuddyDesktop?.saveCaptchaSetting(e);Ze({captcha:{available:!0,enabled:t?.captchaEnabled===!0}}),Ue(r(e?"✅ 机器人校验已开启":"⚠️ 机器人校验已关闭"))}catch(t){Ue(r("保存失败:{message}",{message:Mt(t)}),"err"),await nI()}finally{ss()}}function Y0(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 X0(){try{const e=await et().workbuddyDesktop?.getModelsDev?.();Ze({modelsDev:Y0(e)})}catch(e){Ze({modelsDev:{...it.modelsDev,status:"unavailable"}}),console.warn("读取 models.dev 元数据设置失败:",Mt(e))}}async function QQ(e){if(kn){Wa();return}cs("modelsDev"),Ze({modelsDev:{...it.modelsDev,enabled:e}});try{const t=await et().workbuddyDesktop?.saveModelsDev?.(e);Ze({modelsDev:Y0(t)}),Ue(r(e?"✅ models.dev 模型元数据已开启":"已关闭 models.dev 联网刷新"))}catch(t){Ue(r("保存失败:{message}",{message:Mt(t)}),"err"),await X0()}finally{ss()}}async function ZQ(){if(kn){Wa();return}cs("modelsDevRefresh");try{const e=await et().workbuddyDesktop?.refreshModelsDev?.();Ze({modelsDev:Y0(e?.status)});const t=e?.result,a=String(t?.status||"");a==="refreshed"?Ue(r("models.dev 元数据已更新({count} 条)",{count:Number(t?.count)||0})):a==="failed"?Ue(r("刷新失败:{message}",{message:String(t?.message||"")}),"err"):Ue(String(t?.message||r("本次无需刷新")))}catch(e){Ue(r("刷新失败:{message}",{message:Mt(e)}),"err"),await X0()}finally{ss()}}function Lu(e){if(e===void 0)return;if(!e||typeof e!="object"){Ze({prompt:{...it.prompt,status:"unavailable"}});return}const t=e,a=eZ(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:WQ(t.promptProviders,a),gateway:a,gatewayText:tZ(t.promptGatewayText),options:JQ(t.promptProviderOptions)}})}function WQ(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 JQ(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:nZ(a.gatewayBlocks)}}):[]}function eZ(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 tZ(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 nZ(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 tc(){try{Lu(await et().workbuddyDesktop?.getPrompt())}catch(e){console.warn("读取系统提示词设置失败:",Mt(e)),Lu(null)}}async function cp(e,t){if(kn)return await tc(),!1;cs("prompt");try{const a=await et().workbuddyDesktop?.savePrompt(t);return Lu(a),Ue(r("✅ 已保存:{label}",{label:e})),!0}catch(a){return Ue(r("保存失败:{message}",{message:Mt(a)}),"err"),await tc(),!1}finally{ss()}}async function sZ(e){const t=Do.find(a=>a.value===e);await cp(r("模式改为「{mode}」",{mode:t?.toastLabel??e}),{promptMode:e})}async function rZ(e){await cp(e.trim()?r("提示词文件已更新"):r("已改回内置默认提示词"),{promptFile:e})}async function aZ(e){const t=!e.trim();return cp(r(t?"已清掉界面编辑的提示词(回落文件 / 内置默认)":"提示词正文已更新"),{promptText:t?"":e})}function Io(e,t){return e.options.find(a=>a.id===t)?.label||t}function nc(e){const t=e==null?"":String(e).trim();return t&&it.prompt.options.some(a=>a.id===t)?t:""}async function up(e,t,a){return cp(e,{promptProviders:{[t]:a}})}function vx(e,t){const a=!t.configured;return{promptMode:t.mode,promptFile:t.file,promptText:a&&e.source==="inline"?e.text:""}}async function lZ(e){const t=nc(e);if(!t)return;const a=it.prompt;await up(r("已为「{label}」单独配置提示词",{label:Io(a,t)}),t,vx(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 oZ(e,t){const a=nc(e.id);if(!a||!Do.some(c=>c.value===t))return;const o=Do.find(c=>c.value===t);await up(r("「{label}」的模式改为「{mode}」",{label:Io(it.prompt,a),mode:o?.toastLabel??t}),a,{...vx(it.prompt,e),promptMode:t})}async function iZ(e,t){const a=nc(e.id);a&&await up(t.trim()?r("「{label}」的提示词文件已更新",{label:Io(it.prompt,a)}):r("「{label}」改用内置默认提示词",{label:Io(it.prompt,a)}),a,{...vx(it.prompt,e),promptFile:t})}async function cZ(e,t){const a=nc(e.id);if(!a)return!1;const o=!t.trim(),c=Io(it.prompt,a);return up(o?r("已清掉「{label}」界面编辑的正文",{label:c}):r("「{label}」的提示词正文已更新",{label:c}),a,{...vx(it.prompt,e),promptText:o?"":t})}async function uZ(e){const t=nc(e);t&&await up(r("已取消「{label}」的单独配置",{label:Io(it.prompt,t)}),t,null)}async function dZ(e,t){const a=nc(e);if(!a)return;const o=Io(it.prompt,a);if(kn){await tc();return}cs("prompt");try{const c=await et().workbuddyDesktop?.savePrompt({promptGateway:{[a]:t}});Lu(c),Ue(t?r("✅ 已为「{label}」装上网关自带提示词",{label:o}):r("已关闭「{label}」的网关自带提示词:能否通过上游校验取决于上游当前口径",{label:o}),t?"ok":"err")}catch(c){Ue(r("保存失败:{message}",{message:Mt(c)}),"err"),await tc()}finally{ss()}}async function fZ(e,t){const a=nc(e);if(!a)return!1;const o=Io(it.prompt,a),c=!t||!(t.identity.trim()||t.stable.trim()||t.dynamic.trim());return cp(c?r("「{label}」的网关自带提示词已改回官方原文",{label:o}):r("「{label}」的网关自带提示词正文已更新",{label:o}),{promptGatewayText:{[a]:c?null:t}})}async function pZ(){if(!kn){cs("prompt");try{const e=await et().workbuddyDesktop?.savePrompt({clearDegrade:!0});Lu(e),Ue(r("✅ 已解除内容拦截降级"))}catch(e){Ue(r("解除失败:{message}",{message:Mt(e)}),"err"),await tc()}finally{ss()}}}function dp(e){const t=Number(e);return Number.isFinite(t)?t:null}function Q0(e){if(e===void 0)return;const t=e&&typeof e=="object"?e.database:null;if(!t||typeof t!="object"){Ze({storage:{...it.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:dp(a.accounts),logs:dp(a.logs),requests:dp(a.requests),dailyDays:dp(a.dailyDays),debug:dp(a.debug)}})}async function sI(){try{Q0(await et().workbuddyDesktop?.getStorage())}catch(e){console.warn("读取数据存储概况失败:",Mt(e)),Q0(null)}}async function mZ(){try{return await et().workbuddyDesktop?.panelLogout(),window.location.href="/login",!0}catch(e){return Ue(r("退出失败:{message}",{message:Mt(e)}),"err"),!1}}async function Z0(){UD(),VD(),Ze({panelLogin:HD()}),await Promise.all([FD(),bQ(),fx(),WD(),eI(),GD(),YD(),gx(),U0(),V0(),q0(),K0(),tc(),sI(),nI(),X0(),et().wbUpdatePanel?.load?.()])}async function hZ(){await fx(),Ue(r("保留天数已刷新"))}async function gZ(){await WD(),Ue(r("重试设置已刷新"))}async function xZ(){await eI(),Ue(r("超时设置已刷新"))}async function bZ(){await GD(),Ue(r("排队等待设置已刷新"))}async function vZ(){await YD(),Ue(r("验证码令牌池设置已刷新"))}async function yZ(){await gx(),Ue(r("路由设置已刷新"))}async function jZ(){await U0(),Ue(r("调试模式设置已刷新"))}async function wZ(){await V0(),Ue(r("指纹脱敏设置已刷新"))}async function SZ(){await K0(),Ue(r("网关跨域访问设置已刷新"))}async function NZ(){await tc(),Ue(r("系统提示词设置已刷新"))}async function kZ(){await sI(),Ue(r("存储概况已刷新"))}const yx=[{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 CZ(e){return r(e==="inline"?"界面里编辑的正文":e==="file"?"提示词文件":e==="builtin"?"内置默认提示词":"(未生效)")}function rI({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(Kt,{open:!0,onOpenChange:S=>{S||b||f()},children:s.jsxs(Yt,{className:"w-[min(880px,calc(100vw-48px))]",children:[s.jsx($t,{children:s.jsx(Ft,{children:e})}),s.jsxs(_t,{children:[s.jsxs(Hn,{children:[s.jsx("h3",{children:r("保存后以这里的文本为准")}),s.jsxs("p",{children:[r("这一份就是「替换 / 追加」模式下网关要发的 system 正文。"),a==="none"?r("当前是透传模式:存下来也不会发出,切成「替换 / 追加」之后才生效。"):r("当前生效的正文来自{source}{file}。保存后这一份会盖过提示词文件与内置默认{note}。",{source:CZ(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(st,{htmlFor:"settings-prompt-body",children:r("提示词正文")}),s.jsx(Fd,{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(en,{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 TZ({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(rI,{title:r("编辑提示词正文 · 全局"),text:e.text,source:e.source,file:e.file,disabled:a,save:aZ,onClose:()=>c(!1)}):null]})}function EZ({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(rI,{title:r("编辑提示词正文 · {label}",{label:t}),text:e.text,source:e.source,file:e.file,disabled:o,save:f=>cZ(e,f),onClose:()=>d(!1)}):null]})}function RZ({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=yx.some(N=>p[N.key]!==a[N.key]),w=yx.filter(N=>o?.[N.key]?.trim()).map(N=>N.label);async function S(N){y(!0);try{await fZ(e,N)&&f()}finally{y(!1)}}return s.jsx(Kt,{open:!0,onOpenChange:N=>{N||b||f()},children:s.jsxs(Yt,{className:"w-[min(880px,calc(100vw-48px))]",children:[s.jsx($t,{children:s.jsx(Ft,{children:t})}),s.jsxs(_t,{children:[s.jsxs(Hn,{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:Fn.promptGatewayText})]}),yx.map(N=>s.jsxs("div",{className:"flex flex-col gap-1.5",children:[s.jsxs(st,{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(Fd,{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(R=>({...R,[N.key]:E}))}}),s.jsx("div",{className:"hint",children:N.hint})]},N.key))]}),s.jsxs(en,{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 AZ({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(RZ,{id:e.id,title:r("编辑网关自带提示词 · {label}",{label:t.label}),official:p,over:a,enabled:e.gateway,disabled:c,onClose:()=>f(!1)}):null]}):null}function OZ(e){return e?yx.filter(t=>(e[t.key]||"").trim()).map(t=>t.short).join(r("、")):""}function aI(e,t){return et().wbIcons?.icon?.(e,t)||""}function an({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 MZ({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:aI("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 ua({id:e,label:t,checked:a,disabled:o,tip:c,onCheckedChange:d}){return s.jsxs("label",{className:"switch",children:[s.jsx(ps,{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 fp({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(Ye,{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 pp(e){return e.status==="ready"?s.jsx(an,{tone:"ok",children:r("已生效")}):e.status==="unavailable"?s.jsx(an,{tone:"bad",children:r("不可用")}):s.jsx(an,{tone:"idle",children:r("检测中…")})}function Ir({id:e,onClick:t}){return s.jsx(se,{id:e,variant:"outline",onClick:t,children:r("刷新")})}function DZ(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 IZ(){const e=window.wbI18n,t=e?.rawLocale?.()??"auto",a=e?.LOCALES??[],o=d=>{const f=r(d.nameKey);return f&&f!==d.label?`${d.label}(${f})`:d.label},c=d=>d==="auto"?r("跟随系统"):a.find(f=>f.code===d)?.label??d;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(ut,{value:t,onValueChange:d=>{d&&e?.setLocale(d)},children:[s.jsx(ft,{id:"settings-language",className:"w-[200px]","aria-label":r("界面语言"),children:s.jsx(dt,{children:c(t)})}),s.jsxs(pt,{children:[s.jsx(Xe,{value:"auto",children:r("跟随系统")}),a.map(d=>s.jsx(Xe,{value:d.code,children:o(d)},d.code))]})]})})]})})}function PZ({snap:e}){const t=e.app,a=t.status==="unavailable"?zt.appUnavailable:t.status==="loading"?zt.appLoading:t.closeToTray?t.lightweightMode?zt.appLightOn:zt.appTrayOn:zt.appTrayOff;return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("语言设置"),tip:ns.displayLanguage}),s.jsxs("div",{className:"panel-body",children:[s.jsx(IZ,{}),s.jsx("div",{className:"settings-state",children:zt.languageHint})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("启动与托盘"),tip:ns.tray,badge:t.status==="ready"?s.jsx(an,{tone:"ok",children:r("已应用")}):t.status==="unavailable"?s.jsx(an,{tone:"bad",children:r("不可用")}):s.jsx(an,{tone:"idle",children:r("检测中…")})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"settings-switches",children:[s.jsx(ua,{id:"settings-close-to-tray",label:r("关闭窗口时最小化到托盘"),checked:t.closeToTray,disabled:e.busy==="app",onCheckedChange:o=>{_0("tray",o)}}),s.jsx(ua,{id:"settings-lightweight",label:r("轻量模式(关窗释放界面内存)"),tip:ns.lightweight,checked:t.lightweightMode,disabled:e.busy==="app"||!t.closeToTray,onCheckedChange:o=>{_0("lightweight",o)}}),s.jsx(ua,{id:"settings-autostart",label:r("开机自动启动"),checked:t.autostart,disabled:e.busy==="app",onCheckedChange:o=>{_0("autostart",o)}})]}),s.jsx("div",{className:"settings-state",children:a})]})]}),!e.panelLogin&&s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("局域网访问"),tip:ns.lan}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"settings-switches",children:[s.jsx(ua,{id:"settings-lan-access",label:r("允许局域网内的设备访问网关"),checked:e.app.lanAccess,disabled:e.busy==="lan",onCheckedChange:vQ}),s.jsx(ua,{id:"settings-lan-panel",label:r("同时开放网页管理面板"),checked:e.app.lanPanel,disabled:e.busy==="lan"||!e.app.lanAccess,onCheckedChange:yQ})]}),s.jsx("div",{className:"settings-state",children:DZ(e)})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("Token 读数量级"),tip:ns.units}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"settings-switches",children:s.jsx(ua,{id:"settings-chinese-units",label:r("使用本地量级词(万 / 亿式)"),checked:e.unitsChinese,onCheckedChange:xQ})}),s.jsx("div",{className:"settings-state",children:e.unitsChinese?zt.unitsOn:zt.unitsOff})]})]})]})}function _Z(e){return e==="light"?zt.themeLight:e==="dark"?zt.themeDark:zt.themeSystem}function LZ(){const[e,t]=x.useState(cQ),[a,o]=x.useState(uQ),c=et().workbuddyDesktop?.platform==="web";x.useEffect(()=>{const f=g=>t(String(g.detail||"system")),p=g=>o(Number(g.detail)||100);return window.addEventListener(ED,f),window.addEventListener(RD,p),()=>{window.removeEventListener(ED,f),window.removeEventListener(RD,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:ns.displayTheme}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{children:s.jsx(Pn,{"aria-label":r("显示模式"),options:iQ,value:e,onValueChange:f=>et().wbApp?.applyTheme?.(f)})}),s.jsx("div",{className:"settings-state",children:_Z(e)})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("界面缩放"),tip:ns.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(ut,{value:String(a),onValueChange:f=>et().wbApp?.applyZoom?.(Number(f)),children:[s.jsx(ft,{id:"settings-zoom",className:"w-[140px]",disabled:c,"aria-label":r("界面缩放比例"),children:s.jsx(dt,{children:d})}),s.jsx(pt,{children:oQ.map(f=>s.jsx(Xe,{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?zt.zoomWeb:a===100?zt.zoomDefault:r("当前按 {n}% 显示。",{n:a})})]})]})]})}function zZ({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(),VQ(p)},children:"✕"})]},p)),s.jsx(Ye,{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(),UQ(o),c("");return}p.key==="Backspace"&&!o&&FQ()}})]})}),s.jsx("div",{className:"hint",children:Fn.retryCodes})]})}function BZ({prompt:e,locked:t,busy:a}){const[o,c]=x.useState(null);async function d(){const f=o;if(f!==null)try{await rZ(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(Ye,{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:Fn.promptFile})]})}function HZ(e){if(e.status==="loading")return zt.appLoading;if(e.status==="unavailable")return zt.promptUnavailable;const t=lI(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 lI(e){return e==="inline"?r("界面里编辑的正文"):e==="file"?r("提示词文件"):e==="builtin"?r("内置默认提示词"):""}function UZ(e){return r("已自动改用最小中性提示词(撞了上游内容拦截,多半是 system 指纹误报),到 {until} 自动解除。",{until:e.degradeUntilText||zt.degradeUntilFallback})}function VZ({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 iZ(e,p)}finally{d(null)}}return s.jsx("span",{className:"prompt-input",children:s.jsx(Ye,{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 FZ(e,t){if(!t){const o=Do.find(c=>c.value===e.mode)?.toastLabel??e.mode;return r("未单独配置:模式、提示词文件与正文都跟随上面的全局配置(当前「{mode}」)。",{mode:o})}if(e.mode==="passthrough")return r("客户端 system 原样出站。");const a=r("{mode}生效:上游收到的 system 来自{source}{lines}。",{mode:e.mode==="custom"?r("替换"):r("追加"),source:lI(e.source),lines:e.lines?r("({n} 行)",{n:e.lines}):""});return e.fileError?`${a} ⚠️ ${e.fileError}`:a}function $Z({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=OZ(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(ua,{id:`settings-prompt-gateway-${e.id}`,label:r("装上{size}的官方身份提示词",{size:p}),checked:d,disabled:o||c,onCheckedChange:v=>{dZ(e.id,v)}}),s.jsx(AZ,{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 qZ({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=Do.find(R=>R.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(ut,{value:w.mode,onValueChange:R=>{R!=null&&String(R)&&oZ(w,String(R))},children:[s.jsx(ft,{id:`settings-prompt-mode-${w.id}`,className:"w-[240px]",disabled:t||a,"aria-label":r("{label} 的提示词模式",{label:S}),children:s.jsx(dt,{children:N})}),s.jsx(pt,{children:Do.map(R=>s.jsx(Xe,{value:R.value,children:R.optionLabel},R.value))})]}),s.jsx(VZ,{item:w,label:S,locked:t,busy:a}),s.jsx(EZ,{item:w,label:S,locked:t,busy:a}),w.configured?s.jsx(se,{variant:"outline",disabled:t||a,onClick:()=>{uZ(w.id)},children:r("跟随默认")}):null]}),s.jsx("div",{className:"hint",children:FZ(w,w.configured)})]}),E&&k?s.jsx($Z,{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(ut,{value:g,onValueChange:w=>{v("");const S=w==null?"":String(w);S&&lZ(S)},children:[s.jsx(ft,{id:"settings-prompt-provider-add",className:"w-[240px]",disabled:t||a||p.length===0,"aria-label":r("添加要单独配置的提供商"),children:s.jsx(dt,{children:g?y(g):p.length?r("添加提供商…"):r("全部已配置")})}),s.jsx(pt,{children:p.map(w=>s.jsx(Xe,{value:w.id,children:w.label},w.id))})]})}),s.jsx("div",{className:"hint",children:Fn.promptProviders})]})]})}function GZ({snap:e}){const t=e.prompt,a=t.status!=="ready",o=e.busy==="prompt",c=Do.find(d=>d.value===t.mode)?.optionLabel??t.mode;return s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("系统提示词"),tip:ns.prompt,badge:t.status==="ready"?s.jsx(an,{tone:"ok",children:t.mode==="passthrough"?r("透传"):r("已接管")}):t.status==="unavailable"?s.jsx(an,{tone:"bad",children:r("不可用")}):s.jsx(an,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Ir,{id:"btn-prompt-refresh",onClick:()=>{NZ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"settings-state",children:HZ(t)}),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(ut,{value:t.mode,onValueChange:d=>{d!=null&&String(d)&&sZ(String(d))},children:[s.jsx(ft,{id:"settings-prompt-mode",className:"w-[240px]",disabled:a||o,"aria-label":r("系统提示词模式"),children:s.jsx(dt,{children:c})}),s.jsx(pt,{children:Do.map(d=>s.jsx(Xe,{value:d.value,children:d.optionLabel},d.value))})]})}),s.jsx("div",{className:"hint",children:Fn.promptMode})]}),s.jsx(BZ,{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(TZ,{prompt:t,locked:a,busy:o})}),s.jsxs("div",{className:"hint",children:[Fn.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(qZ,{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:()=>{pZ()},children:r("立即解除")})}),s.jsx("div",{className:"hint",children:UZ(t)})]}):null]}),s.jsx("div",{className:"hint retention-note",children:Fn.prompt})]})]})}function KZ(e){if(e.status==="loading")return zt.appLoading;if(e.status==="unavailable")return zt.debugUnavailable;const t=e.count!==null&&e.limit!==null?r("已保存 {count} / {limit} 条报文(超出后丢弃最旧的)。",{count:e.count,limit:e.limit}):"";return e.on?`${zt.debugOn}${t}${r("凭据类请求头已脱敏。")}`:zt.debugOff}function YZ({snap:e}){return s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("请求超时"),tip:ns.timeouts,badge:pp(e.timeouts),actions:s.jsx(Ir,{id:"btn-timeouts-refresh",onClick:()=>{xZ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"retention-list",children:MD.map(t=>s.jsx(fp,{field:t,value:e.timeouts.values?.[t.key]??null,disabled:e.busy==="timeouts",onCommit:a=>$Q(t,a)},t.key))}),s.jsx("div",{className:"hint retention-note",children:Fn.timeouts})]})]})}function XZ({snap:e}){return s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("请求重试"),tip:ns.retry,badge:pp(e.retry),actions:s.jsx(Ir,{id:"btn-retry-refresh",onClick:()=>{gZ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsxs("div",{className:"retention-list",children:[OD.map(t=>s.jsx(fp,{field:t,value:e.retry.values?.[t.key]??null,disabled:e.busy==="retry",onCommit:a=>HQ(t,a)},t.key)),s.jsx(zZ,{codes:e.retryCodes,status:e.retry.status,busy:e.busy==="codes"||e.busy==="retry"})]}),s.jsx("div",{className:"hint retention-note",children:Fn.retry})]})]})}const QZ={routingFailoverBackoff:"failoverBackoff",routingSink:"sink",routingBreakerEnabled:"breakerEnabled"};function ZZ({snap:e}){const t=e.routing,a=e.busy==="routing"||t.status!=="ready",o=ox.find(d=>d.value===t.strategy)?.value??"order",c=ix.find(d=>d.value===t.sticky)?.value??"auto";return s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("账号路由"),tip:ns.routing,badge:t.status==="ready"?void 0:t.status==="unavailable"?s.jsx(an,{tone:"bad",children:r("不可用")}):s.jsx(an,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Ir,{id:"btn-routing-refresh",onClick:()=>{yZ()}})}),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":ox.find(d=>d.value===o)?.tip}),s.jsx(Pn,{options:ox.map(d=>({value:d.value,label:d.label})),value:o,disabled:a,"aria-label":r("路由策略"),onValueChange:d=>{B0({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":ix.find(d=>d.value===c)?.tip}),s.jsx(Pn,{options:ix.map(d=>({value:d.value,label:d.label})),value:c,disabled:a,"aria-label":r("会话粘性"),onValueChange:d=>{B0({routingSticky:String(d)})}})]})]}),s.jsxs("div",{className:"prompt-group",children:[r("自愈保护"),s.jsx("span",{className:"note",children:r("默认值通常够用,出问题时才需要调")})]}),rQ.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(ps,{id:f,checked:t[QZ[d.key]],disabled:a,onCheckedChange:p=>{B0({[d.key]:p})}})]})]},d.key)})]}),s.jsx("div",{className:"hint retention-note",children:Fn.routing})]})]})}function WZ({snap:e}){return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("排队等待"),tip:ns.queue,badge:pp(e.queue),actions:s.jsx(Ir,{id:"btn-queue-refresh",onClick:()=>{bZ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"retention-list",children:DD.map(t=>s.jsx(fp,{field:t,value:e.queue.values?.[t.key]??null,disabled:e.busy==="queue",onCommit:a=>DQ(t,a)},t.key))}),s.jsx("div",{className:"hint retention-note",children:Fn.queue})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("验证码令牌池"),tip:ns.captchaPool,badge:pp(e.captchaPool),actions:s.jsx(Ir,{id:"btn-captcha-pool-refresh",onClick:()=>{vZ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"retention-list",children:ID.map(t=>s.jsx(fp,{field:t,value:e.captchaPool.values?.[t.key]??null,disabled:e.busy==="captchaPool",onCommit:a=>IQ(t,a)},t.key))}),s.jsx("div",{className:"hint retention-note",children:Fn.captchaPool})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("models.dev 模型元数据"),tip:ns.modelsDev,badge:e.modelsDev.status==="ready"?s.jsx(an,{tone:"ok",children:r("{count} 条",{count:Number(e.modelsDev.count).toLocaleString("zh-CN")})}):e.modelsDev.status==="unavailable"?s.jsx(an,{tone:"bad",children:r("不可用")}):s.jsx(an,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Ir,{id:"btn-modelsdev-refresh",onClick:()=>{ZQ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx(ua,{id:"settings-modelsdev",label:r("用 models.dev 补齐上游没声明的模型能力与思考档位(联网刷新,内嵌快照始终生效)"),checked:e.modelsDev.enabled,disabled:e.modelsDev.status!=="ready"||e.busy==="modelsDev",onCheckedChange:t=>{QQ(t)}}),s.jsx("div",{className:"settings-state",children:nQ(e.modelsDev)}),s.jsx("div",{className:"hint retention-note",children:Fn.modelsDev})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("指纹脱敏"),tip:ns.sanitize,badge:e.sanitize.status==="ready"?s.jsx(an,{tone:"ok",children:r("已生效")}):e.sanitize.status==="unavailable"?s.jsx(an,{tone:"bad",children:r("不可用")}):s.jsx(an,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Ir,{id:"btn-sanitize-refresh",onClick:()=>{wZ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"settings-switches",children:s.jsx(ua,{id:"settings-sanitize",label:r("剥离上游审核黑名单指纹(改写请求体里的模板句与表头)"),checked:e.sanitize.on,disabled:e.sanitize.status!=="ready"||e.busy==="sanitize",onCheckedChange:t=>{GQ(t)}})}),s.jsx("div",{className:"settings-state",children:e.sanitize.status==="loading"?zt.appLoading:e.sanitize.status==="unavailable"?zt.sanitizeUnavailable:e.sanitize.on?zt.sanitizeOn:zt.sanitizeOff}),s.jsx("div",{className:"hint retention-note",children:Fn.sanitize})]})]}),s.jsx(eW,{snap:e}),s.jsx(GZ,{snap:e}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("调试模式"),tip:ns.debug,badge:e.debug.status==="ready"?s.jsx(an,{tone:"ok",children:r("已生效")}):e.debug.status==="unavailable"?s.jsx(an,{tone:"bad",children:r("不可用")}):s.jsx(an,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Ir,{id:"btn-debug-refresh",onClick:()=>{jZ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"settings-switches",children:s.jsx(ua,{id:"settings-debug-mode",label:r("保存上游原始报文(请求头、请求体、响应头、响应体)"),checked:e.debug.on,disabled:e.debug.status!=="ready"||e.busy==="debug",onCheckedChange:t=>{qQ(t)}})}),s.jsx("div",{className:"settings-state",children:KZ(e.debug)}),s.jsx("div",{className:"hint retention-note",children:Fn.debug})]})]})]})}function oI(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 JZ(e,t){const a=Object.keys(e);return a.length!==Object.keys(t).length?!1:a.every(o=>e[o]===t[o])}function eW({snap:e}){const t=e.clineHeaders,[a,o]=x.useState(()=>oI(t));x.useEffect(()=>{o(oI(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&&!JZ(p(),t.overrides);return s.jsx(MZ,{title:r("Cline 伪装头"),tip:ns.clineHeaders,badge:t.status==="ready"?s.jsx(an,{tone:"ok",children:r("已生效")}):t.status==="unavailable"?s.jsx(an,{tone:"bad",children:r("不可用")}):s.jsx(an,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Ir,{id:"btn-cline-headers-refresh",onClick:()=>{KQ()}}),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(Ye,{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(Ye,{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:()=>{tI({})},children:r("恢复默认")}),s.jsx(se,{disabled:c||!d||!g,onClick:()=>{tI(p())},children:r("保存")})]})]}),s.jsx("div",{className:"settings-state",children:t.status==="loading"?zt.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:Fn.clineHeaders})]})})}function tW({snap:e}){const[t,a]=x.useState(!1);async function o(){a(!0),await mZ()||a(!1)}return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("网关跨域访问(CORS)"),tip:ns.cors,badge:e.cors.status==="ready"?e.cors.on?s.jsx(an,{tone:"bad",children:r("已开启")}):s.jsx(an,{tone:"ok",children:r("已关闭")}):e.cors.status==="unavailable"?s.jsx(an,{tone:"bad",children:r("不可用")}):s.jsx(an,{tone:"idle",children:r("检测中…")}),actions:s.jsx(Ir,{id:"btn-cors-refresh",onClick:()=>{SZ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"settings-switches",children:s.jsx(ua,{id:"settings-cors",label:r("允许浏览器里的页面跨来源调用网关(/v1/*)"),checked:e.cors.on,disabled:e.cors.status!=="ready"||e.busy==="cors",onCheckedChange:c=>{YQ(c)}})}),s.jsx("div",{className:"settings-state",children:e.cors.status==="loading"?zt.appLoading:e.cors.status==="unavailable"?zt.corsUnavailable:e.cors.on?zt.corsOn:zt.corsOff}),s.jsx("div",{className:"hint retention-note",children:Fn.cors})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("机器人校验")}),s.jsxs("div",{className:"panel-body",children:[s.jsx(ua,{id:"settings-captcha",label:r("登录 / 注册需要通过 ALTCHA 人机验证(工作量证明)"),checked:e.captcha.enabled,disabled:!e.captcha.available||e.busy==="captcha",onCheckedChange:c=>{XQ(c)}}),s.jsx("div",{className:"hint",children:Fn.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:Fn.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 mp({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 nW(e){return e.status==="loading"?s.jsx(an,{tone:"idle",children:r("检测中…")}):e.status==="unavailable"?s.jsx(an,{tone:"bad",children:r("不可用")}):s.jsx(an,{tone:e.available?"ok":"bad",children:e.available?r("已生效"):r("数据库不可用")})}function sW({snap:e}){const t=e.busy,a=e.storage,o=et().workbuddyDesktop?.platform==="web",c=a.status==="ready",d=c&&a.available,f=c&&a.file?a.file:"—",p=g=>d&&g!==null?fQ(g):"—";return s.jsxs(s.Fragment,{children:[!o&&s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("整库备份 / 恢复"),tip:ns.backup,actions:s.jsxs(s.Fragment,{children:[s.jsx(se,{id:"btn-settings-db-export",variant:"outline",disabled:t==="dbExport"||t==="dbImport",onClick:()=>{CQ()},children:r(t==="dbExport"?"备份中…":"备份整库")}),s.jsx(se,{id:"btn-settings-db-restore",variant:"destructive",disabled:t==="dbExport"||t==="dbImport",onClick:()=>TQ(),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(ps,{id:"settings-db-include-logs",checked:e.dbIncludeLogs,disabled:t!==null,onCheckedChange:kQ}),s.jsx("div",{className:"hint",children:r("取消勾选后只备份业务数据(账号、配置与余额记录),文件显著变小;事件日志、请求统计与调试报文不会进备份文件。")})]}),s.jsx("div",{className:"danger-zone",children:s.jsx("strong",{children:Fn.backupDanger})})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("账号导入 / 导出"),tip:ns.io,actions:s.jsxs(s.Fragment,{children:[s.jsx(se,{id:"btn-settings-export",variant:"outline",disabled:t==="export",onClick:()=>{SQ()},children:r(t==="export"?"导出中…":"导出账号")}),s.jsx(se,{id:"btn-settings-import",variant:"default",disabled:t==="import",onClick:()=>{NQ()},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:ns.retention,badge:pp(e.retention),actions:s.jsx(Ir,{id:"btn-retention-refresh",onClick:()=>{hZ()}})}),s.jsxs("div",{className:"panel-body",children:[s.jsx("div",{className:"retention-list",children:A0.map(g=>s.jsx(fp,{field:g,value:e.retention.values?.[g.key]??null,disabled:e.busy==="retention",onCommit:v=>OQ(g,v)},g.key))}),s.jsx("div",{className:"hint retention-note",children:Fn.retention})]})]}),s.jsxs("section",{className:"panel",children:[s.jsx(Qn,{title:r("数据存储"),tip:ns.storage,badge:nW(a),actions:s.jsx(Ir,{id:"btn-storage-refresh",onClick:()=>{kZ()}})}),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:Fn.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?BD(a.bytes):"—"})}),s.jsx("div",{className:"hint",children:Fn.storageSize})]})]}),s.jsxs("div",{className:"retention-list storage-counts",children:[s.jsx(mp,{label:r("账号"),value:p(a.accounts)}),s.jsx(mp,{label:r("事件日志"),value:p(a.logs)}),s.jsx(mp,{label:r("请求记录"),value:p(a.requests)}),s.jsx(mp,{label:r("报表天数"),value:p(a.dailyDays)}),s.jsx(mp,{label:r("调试报文"),value:p(a.debug)})]}),s.jsx("div",{className:"hint retention-note",children:Fn.storage})]})]})]})}const rW=[{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 aW(){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:rW.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:()=>{sQ(e.url)},children:e.cta})]},e.url))})]})]})}function lW({confirm:e}){const t=x.useRef(null);return s.jsx(Kt,{open:e!==null,onOpenChange:a=>{a||mx(!1)},children:s.jsxs(Yt,{className:"w-[min(440px,calc(100vw-48px))]",initialFocus:t,children:[s.jsx($t,{children:s.jsx(Ft,{children:r("确认缩短保留天数")})}),s.jsx(_t,{children:s.jsxs("div",{className:"danger-zone",children:[e?.head,s.jsx("br",{}),s.jsx("strong",{children:r("超出的历史数据会被立即删除,且不可恢复。")}),r("确定继续?")]})}),s.jsxs(en,{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("继续并清理")})]})]})})}function oW({confirm:e}){const t=x.useRef(null);return s.jsx(Kt,{open:e!==null,onOpenChange:a=>{a||z0(!1)},children:s.jsxs(Yt,{className:"w-[min(440px,calc(100vw-48px))]",initialFocus:t,children:[s.jsx($t,{children:s.jsx(Ft,{children:r("恢复整库备份")})}),s.jsx(_t,{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(en,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{ref:t,variant:"outline",onClick:()=>z0(!1),children:r("取消")}),s.jsx(se,{variant:"destructive",onClick:()=>z0(!0),children:r("选择备份文件并恢复")})]})]})})}const W0={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 iW({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?$D():L0(!1)},p=()=>{wQ(o.current?.value??"",c.current?.value??"")};return s.jsx(Kt,{open:d,onOpenChange:g=>{g||f()},children:s.jsx(Yt,{className:"w-[min(480px,calc(100vw-48px))]",initialFocus:a,children:t!==null?s.jsxs(s.Fragment,{children:[s.jsx($t,{children:s.jsx(Ft,{children:r("注册管理员账号")})}),s.jsxs(_t,{children:[s.jsx("div",{children:r("局域网开放后,管理接口要求登录。请设置管理员账号与密码,注册完成会直接继续开启流程。")}),s.jsxs("form",{onSubmit:g=>{g.preventDefault(),t.busy||p()},children:[s.jsx(st,{htmlFor:"lan-admin-name",className:"mt-3.5 mb-[5px] block text-[12.5px]",children:r("账号")}),s.jsx(Ye,{ref:o,id:"lan-admin-name",autoComplete:"username",placeholder:r("管理员账号"),disabled:t.busy}),s.jsx(st,{htmlFor:"lan-admin-password",className:"mt-3.5 mb-[5px] block text-[12.5px]",children:r("密码")}),s.jsx(Ye,{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(en,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{ref:a,variant:"outline",onClick:$D,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($t,{children:s.jsx(Ft,{children:e?W0[e.mode].title:""})}),s.jsx(_t,{children:s.jsx("div",{children:e?W0[e.mode].body(e.panel):null})}),s.jsxs(en,{children:[s.jsx("div",{className:"mr-auto"}),s.jsx(se,{ref:a,variant:"outline",onClick:()=>L0(!1),children:r("取消")}),s.jsx(se,{onClick:()=>L0(!0),children:e?W0[e.mode].label:r("继续")})]})]})})})}function cW(){const e=hQ(),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:lx.map(o=>s.jsxs("button",{type:"button",className:e.category===o.id?"settings-nav-item active":"settings-nav-item","data-cat":o.id,onClick:()=>gQ(o.id),children:[s.jsx("span",{className:"ico",dangerouslySetInnerHTML:{__html:aI(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(PZ,{snap:e})}),s.jsx("div",{className:a("display"),"data-cat":"display",children:s.jsx(LZ,{})}),s.jsx("div",{className:a("gateway"),"data-cat":"gateway",children:s.jsx(WZ,{snap:e})}),s.jsx("div",{className:a("routing"),"data-cat":"routing",children:s.jsx(ZZ,{snap:e})}),s.jsx("div",{className:a("retry"),"data-cat":"retry",children:s.jsx(XZ,{snap:e})}),s.jsx("div",{className:a("timeout"),"data-cat":"timeout",children:s.jsx(YZ,{snap:e})}),s.jsx("div",{className:a("security"),"data-cat":"security",children:s.jsx(tW,{snap:e})}),s.jsx("div",{className:a("data"),"data-cat":"data",children:s.jsx(sW,{snap:e})}),s.jsx("div",{className:a("feedback"),"data-cat":"feedback",children:s.jsx(aW,{})}),s.jsx("div",{className:a("about"),"data-cat":"about"})]}),s.jsx(lW,{confirm:e.retentionConfirm}),s.jsx(oW,{confirm:e.dbBackupConfirm}),s.jsx(iW,{confirm:e.lanConfirm,register:e.lanRegister})]})}const iI='.page[data-page="settings"]';let J0=null;function cI(){if(J0)return;const e=document.querySelector(iI);e&&(e.replaceChildren(),J0=wn.createRoot(e),Ns.flushSync(()=>{J0?.render(s.jsx(cW,{}))}))}UD(),document.querySelector(iI)?cI():document.addEventListener("DOMContentLoaded",cI,{once:!0}),window.wbSettingsPanel={load:Z0,render:P0,renderRetention:dx,renderRetry:BQ,renderDebug:xx,renderSanitize:bx,renderPrompt:Lu,renderStorage:Q0,showCategory:I0},et().wbApp?.currentPage==="settings"&&Z0();const uI="agent2api-col-config:",eS=[{value:"left",label:r("左")},{value:"center",label:r("中")},{value:"right",label:r("右")}],uW=e=>eS.some(t=>t.value===e),dW=eS.map(e=>`ta-${e.value}`),dI="colset-dragging",fI="open";let tS=null;const pI="grid grid-cols-[18px_minmax(78px,1fr)_44px_minmax(106px,auto)] items-center gap-2";function mI(){return window}const jx=new Map;function nS(e){return e.columns.map(t=>({key:t.key,visible:t.visible!==!1,align:t.align||"left"}))}function fW(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(nS(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=uW(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)||pW(g,e,{...p.get(y.key)});return g}function pW(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 mW(e){try{const t=localStorage.getItem(uI+e.id);return fW(e,t?JSON.parse(t):[])}catch{return nS(e)}}function hW(e){try{const t={};for(const a of e.columns)t[a.key]=a.align||"left";localStorage.setItem(uI+e.id,JSON.stringify({v:2,defaults:t,items:e.config}))}catch{}}const gW=e=>jx.get(e)?.config||null,xW=(e,t)=>e.columns.find(a=>a.key===t)?.label||t;function hI(e,t){const a=jx.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 hp(e,{silent:t=!1}={}){hW(e),t||e.onChange?.(e.config),Ol&&Ol.id===e.id&&Ol.repaint()}let Ol=null;function wx(){if(!Ol)return;const e=Ol;Ol=null,e.destroy()}function bW(e,t){wx();const a=document.createElement("div");document.body.append(a);const o=wn.createRoot(a),c={current:null};Ol={id:e.id,spec:e,repaint:()=>c.current?.(),destroy:()=>{o.unmount(),a.remove()}},o.render(s.jsx(SW,{spec:e,anchor:t,repaintRef:c,onClose:wx}))}function vW(e,t){Ol&&Ol.id===e.id?wx():bW(e,t)}function yW(e,t,a){const o=[...e],[c]=o.splice(t,1);return o.splice(a,0,c),o}function jW(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 wW=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 SW({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(fI),c.setAttribute("aria-expanded","true"),()=>{c.classList.remove(fI),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(),hp(e))},[e]);function b(N,k){const E=e.config.find(R=>R.key===N);E&&(!k&&e.config.filter(R=>R.visible).length<=1||(E.visible=k,hp(e)))}function j(N,k){const E=e.config.find(R=>R.key===N);!E||E.align===k||(E.align=k,hp(e))}function w(){e.config=nS(e),hp(e)}function S(N,k){k.preventDefault(),g.current?.teardown(),p(N),document.body.classList.add(dI);const E=d.current;function R(){window.removeEventListener("pointermove",C),window.removeEventListener("pointerup",A),document.body.classList.remove(dI),g.current=null,p(null)}function C(D){const I=jW(D.clientX,D.clientY,E,e.config);if(!I||I===N)return;const M=e.config.findIndex(_=>_.key===N),O=e.config.findIndex(_=>_.key===I);M<0||O<0||(e.config=yW(e.config,M,O),y())}function A(){R(),hp(e)}g.current={teardown:R},window.addEventListener("pointermove",C),window.addEventListener("pointerup",A)}return s.jsx(rf,{open:!0,modal:!1,onOpenChange:(N,k)=>{N||(k?.reason==="outside-press"&&(tS=k.event??null),o())},children:s.jsxs(af,{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:Ve(pI,"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=xW(e,N.key),E=f===N.key;return s.jsxs("div",{"data-col-key":N.key,className:Ve(pI,"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:R=>S(N.key,R),children:wW}),s.jsx("span",{className:"min-w-0 truncate text-xs text-foreground",title:k,children:k}),s.jsx(ps,{className:"justify-self-center",checked:N.visible,onCheckedChange:R=>b(N.key,R),"aria-label":r("显示「{label}」列",{label:k}),title:N.visible?r("这一列正在显示"):r("这一列已隐藏")}),s.jsx(Pn,{className:"w-full justify-center",options:eS,value:N.align,onValueChange:R=>j(N.key,R),"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 NW(e,t){e&&(e.classList.remove(...dW),e.classList.add(`ta-${t}`))}const gI=new Map;function kW(e,t){const a=gI.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 gI.set(e,d),d}function CW(e,t,a){const o=jx.get(e);if(!o||!t)return;const c=kW(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}NW(y,v.align),d.appendChild(y),b&&f&&f.appendChild(b)}mI().wbTableColumns?.repaint?.(e)}function TW(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=`${mI().wbIcons?.icon?.("settings",14)||""}${r("列设置")}`,t.setAttribute("aria-haspopup","dialog"),t.setAttribute("aria-expanded","false"),t.addEventListener("click",a=>{if(tS===a){tS=null;return}vW(e,t)}),t}function EW(e){return(typeof e.mount=="function"?e.mount():e.mount?document.querySelector(e.mount):null)||null}function RW(e){const t={...e,config:mW(e)};jx.set(e.id,t);const a=EW(e),o=TW(t);return a&&(e.buttonPlacement==="last"?a.appendChild(o):a.insertBefore(o,a.firstChild)),{apply:c=>hI(e.id,c),config:()=>t.config}}window.wbColSettings={register:RW,apply:hI,configOf:gW,syncStaticHead:CW,close:wx};function Ja(){return window}const AW=new Set(["updateCheck"]);function xI(e){return(Array.isArray(e?.tasks)?e.tasks:[]).filter(a=>!AW.has(a.id))}const OW=2e4,bI=1,MW=" · ";function zu(e,t){Ja().wbApp?.toast?.(e,t)}function Sx(e){return e instanceof Error?e.message:String(e)}function vI(e){return r(e==="seconds"?"秒":"分钟")}function yI(e){const t=Number(e)||0;return t?new Date(t).toLocaleTimeString("zh-CN",{hour12:!1}):""}function jI(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 DW(e){const t=e.runner==="backend",a=[];if(e.lastRunAt){const o=yI(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:yI(e.nextRunAt),relative:jI(e.nextRunAt)})),t&&e.retryAt&&e.retryAt>Date.now()&&a.push(r("冷却中,{relative}重试",{relative:jI(e.retryAt)})),a.join(MW)}function IW(e,t){const a=String(t??"").trim(),o=vI(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 PW(e){const t=Ja();e.id==="logsAutoRefresh"?t.wbLogsPanel?.applyAutoRefresh?.(e):e.id==="requestsAutoRefresh"?t.wbRequestsPanel?.applyAutoRefresh?.(e):e.id==="reportAutoRefresh"&&t.wbReport?.applyAutoRefresh?.(e)}let sc=!1,Nx=null,sS=!1;async function wI(){if(!Nx){sS=!0;return}await Nx()}function _W(){const[e,t]=x.useState([]),[a,o]=x.useState(!1),[c,d]=x.useState(null),[f,p]=x.useState({});function g(I){p(M=>{if(!(I in M))return M;const O={...M};return delete O[I],O})}const v=x.useCallback(async()=>{const I=Ja().workbuddyDesktop;try{if(!I)throw new Error(r("后端桥不可用"));const M=await I.getScheduledTasks();t(xI(M)),o(!0)}catch(M){console.warn("读取定时任务失败:",Sx(M)),t([]),o(!0)}},[]),y=x.useCallback(async()=>{if(sc||document.hidden||Ja().wbApp?.currentPage!=="tasks")return;const I=Ja().workbuddyDesktop;if(I)try{const M=await I.getScheduledTasks();t(xI(M))}catch(M){console.warn("同步定时任务状态失败:",Sx(M))}},[]);x.useEffect(()=>{const I=window.setInterval(()=>{y()},OW);return()=>{window.clearInterval(I)}},[y]),x.useEffect(()=>{Ja().wbApp?.renderTopbarStatus?.()},[e,a]),x.useEffect(()=>(Nx=v,sS&&(sS=!1,v()),()=>{Nx=null}),[v]);async function b(I,M,O){if(sc)return;const _=Ja().workbuddyDesktop;if(_){sc=!0;try{const L=await _.saveScheduledTask(I,M);t(z=>z.map(U=>U.id===I?L:U)),PW(L),zu(r("✅ 已更新「{label}」",{label:O}))}catch(L){zu(r("保存失败:{reason}",{reason:Sx(L)}),"err"),await v()}finally{sc=!1}}}async function j(I,M){const O=IW(I,M);if(!O.ok){zu(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(sc)return;const M=Ja().workbuddyDesktop;if(M){sc=!0,d(I.id);try{const O=await M.runScheduledTask(I.id);if(O?.task){const _=O.task;t(L=>L.map(z=>z.id===I.id?_:z))}zu(r("✅ {task}:{summary}",{task:r(I.label),summary:O?.summary||r("已执行")})),I.id==="credentialMaintenance"&&await Ja().wbApp?.refresh?.()}catch(O){zu(r("执行失败:{reason}",{reason:Sx(O)}),"err"),await v()}finally{sc=!1,d(null)}}}function S(I){const M=vI(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(ps,{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:DW(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(Ye,{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:M,def:I.defaultInterval}),onChange:_=>{const L=_.currentTarget.value;p(z=>({...z,[I.id]:L}))},onBlur:_=>{j(I,_.currentTarget.value)},onKeyDown:_=>{_.key==="Enter"&&_.currentTarget.blur()}}),s.jsx("span",{className:"task-interval-unit",children:M})]}),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}),R=N?a?"destructive":"outline":k?"success":"outline",C=R==="destructive"?"bad":R==="success"?"ok":"",A=e.map(I=>S(I)),D=A.slice(bI);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:R,"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(()=>zu(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,bI),D.length?s.jsx("div",{className:"task-grid",children:D}):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 SI='.page[data-page="tasks"]';let NI=!1;function kI(){if(NI)return;const e=document.querySelector(SI);e&&(NI=!0,e.replaceChildren(),wn.createRoot(e).render(s.jsx(_W,{})))}document.querySelector(SI)?kI():document.addEventListener("DOMContentLoaded",kI,{once:!0}),window.wbTasksPanel={load:wI},Ja().wbApp?.currentPage==="tasks"&&wI();const CI="workbuddy-desktop-update-skip";function LW(){try{return localStorage.getItem(CI)||""}catch{return""}}function zW(e){try{localStorage.setItem(CI,e)}catch{}}let TI="";function kx(e,t){if(!e||e.hasUpdate!==!0||e.pendingRestart===!0)return;const a=String(e.latestVersion||"").trim();a&&Mn().wbApp?.currentPage!=="settings"&&(a===LW()||a===TI||(TI=a,EI(),Bu=document.createElement("div"),document.body.append(Bu),gp=wn.createRoot(Bu),gp.render(s.jsx(BW,{info:e,onGoUpdate:t,onClose:EI}))))}function BW({info:e,onGoUpdate:t,onClose:a}){const o=String(e.latestVersion||""),c=String(e.notes||"").trim(),d=c?s2(c):"";function f(){zW(o),a()}function p(){a();const g=Mn();g.wbApp?.showPage?.("settings"),g.wbSettingsPanel?.showCategory?.("about"),t(e)}return s.jsx(Kt,{open:!0,onOpenChange:g=>{g||a()},children:s.jsxs(Yt,{children:[s.jsx($t,{children:s.jsx(Ft,{children:r("检测到更新")})}),s.jsxs(_t,{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:r2,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(en,{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 gp=null,Bu=null;function EI(){gp&&(gp.unmount(),gp=null),Bu&&(Bu.remove(),Bu=null)}const RI="updateCheck",Hu=1,Cx=1440,HW="https://github.com/settings/tokens/new?description="+encodeURIComponent("Agent2API 更新检查");function UW(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 VW({open:e,onClose:t}){const[a,o]=x.useState(a2),[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=l2(a);x.useEffect(()=>{e&&(p(""),l9().then(o),(async()=>{try{d(await Mn().workbuddyDesktop?.getUpdateToken()??null)}catch{}})(),(async()=>{try{const L=((await Mn().workbuddyDesktop?.getScheduledTasks?.())?.tasks??[]).find(B=>B.id===RI),z=L?.enabled===!0,U=Math.max(Hu,Math.round(Number(L?.interval)||0));b({enabled:z,interval:U}),w(String(U))}catch{}})())},[e]);async function E(_){if(!S){N(!0);try{const L=await Mn().workbuddyDesktop?.saveScheduledTask?.(RI,_),z=L?.enabled===!0,U=Math.max(Hu,Math.round(Number(L?.interval)||0));b({enabled:z,interval:U}),w(String(U)),tr(r("✅ 自动检查更新已保存"))}catch(L){tr(r("保存失败:{error}",{error:Dr(L)}),"err")}finally{N(!1)}}}async function R(){const _=Math.round(Number(j));if(!Number.isFinite(_)||_Cx){tr(r("检查间隔必须是 {min} ~ {max} 分钟",{min:Hu,max:Cx}),"err");return}y&&_===y.interval||await E({interval:_})}async function C(_){const L=await o9(_);L&&o(z=>({...z,proxyChoice:L.choice}))}async function A(){const _=f.trim();if(!_){tr(r("请先粘贴 GitHub 令牌"),"err");return}v(!0);try{const L=await Mn().workbuddyDesktop?.setUpdateToken({token:_});d(L??null),p(""),L?.saved===!1?tr(r("令牌已生效,但写入磁盘失败(重启后会丢失)"),"err"):tr(r("✅ GitHub 令牌已保存(加密存储,界面不再显示)"))}catch(L){tr(r("保存失败:{error}",{error:Dr(L)}),"err")}finally{v(!1)}}async function D(){v(!0);try{const _=await Mn().workbuddyDesktop?.setUpdateToken({token:null});d(_??null),tr(r("✅ 已清除界面保存的 GitHub 令牌(环境变量若配置过则继续生效)"))}catch(_){tr(r("清除失败:{error}",{error:Dr(_)}),"err")}finally{v(!1)}}const I=UW(c),M=!!c?.error||c?.origin==="stored",O=c?.filled&&c?.origin!=="env"?r("已填写(粘贴新令牌可覆盖)"):r("粘贴 GitHub 令牌(ghp_… / github_pat_…)");return s.jsx(Kt,{open:e,onOpenChange:_=>{_||t()},children:s.jsxs(Yt,{className:"w-[min(460px,calc(100vw-48px))]",children:[s.jsx($t,{children:s.jsx(Ft,{children:r("更新设置")})}),s.jsxs(_t,{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(ps,{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(Ye,{type:"number",min:Hu,max:Cx,step:1,className:"w-[110px]",disabled:S||!y||y.enabled!==!0,value:j,onChange:_=>w(_.currentTarget.value),onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),R())},"aria-label":r("检查间隔(分钟)")}),s.jsx("span",{className:"text-[12px] text-subtle",children:r("分钟({min} ~ {max})",{min:Hu,max:Cx})}),s.jsx(se,{variant:"outline",size:"sm",disabled:S||!y||Math.round(Number(j))===y.interval,onClick:()=>{R()},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(ut,{value:k.current,onValueChange:_=>{C(String(_))},children:[s.jsx(ft,{className:Ve("w-full",k.broken&&"border-destructive-bd"),title:k.title,"aria-label":r("更新出网代理"),children:s.jsx(dt,{className:"min-w-0 truncate",children:k.selected?.label||r("直连")})}),s.jsx(pt,{children:k.items.map(_=>s.jsx(Xe,{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:()=>{n2(HW)},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(Ye,{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("保存")}),M?s.jsx(se,{variant:"outline",size:"sm",disabled:g,onClick:()=>{D()},children:r("清除")}):null]})]})]})]})})}function FW({open:e,onClose:t}){return s.jsx(Kt,{open:e,onOpenChange:a=>{a||t()},children:s.jsxs(Yt,{className:"w-[min(320px,calc(100vw-48px))]",children:[s.jsx($t,{children:s.jsx(Ft,{children:r("加入 QQ 群")})}),s.jsxs(_t,{className:"items-center gap-3 text-center",children:[s.jsx("img",{className:"qq-qr",src:a9,alt:r("QQ 群二维码")}),s.jsxs("div",{className:"qq-no",children:[s.jsx("span",{className:"k",children:r("群号")}),s.jsx("code",{children:Og}),s.jsx(se,{type:"button",size:"sm",variant:"ghost","data-copy":Og,children:r("复制")})]}),s.jsx("p",{className:"qq-hint",children:r("用手机 QQ 扫上面的二维码,或在 QQ 里搜索群号加入。")})]})]})})}const $W=1e3,AI=8,qW=10,GW=1e3,KW={"":"outline",ok:"success",warn:"warning",bad:"destructive"},YW={info:null,checkedAt:0,repository:"",badgeText:r("未检查"),badgeTone:"",stateText:r("点击「检查更新」查询最新发布版本。"),stateError:!1,percent:0,phase:"idle",readyPath:"",checking:!1,actionBusy:!1,restartSeconds:0};function Ml(e){return String(e).padStart(2,"0")}function XW(e){const t=new Date(String(e??""));return!e||Number.isNaN(t.getTime())?"":`${t.getFullYear()}-${Ml(t.getMonth()+1)}-${Ml(t.getDate())} ${Ml(t.getHours())}:${Ml(t.getMinutes())}`}function OI(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=`${Ml(t.getHours())}:${Ml(t.getMinutes())}:${Ml(t.getSeconds())}`;return o?c:`${Ml(t.getMonth()+1)}-${Ml(t.getDate())} ${c}`}function Tx(e){return e?.installerKind?e.installerKind==="dmg":/Mac|iPhone|iPad/.test(navigator.userAgent||"")}function Oa(e){return e?.selfUpdate===!0}function MI(e){return e?Oa(e)?e.serverAsset??null:e.asset??null:null}function QW(e){return Oa(e)?r("正在下载服务端更新包…(下载完成后由面板完成替换,重启容器内的服务后生效)"):Tx(e)?r("正在下载安装包…(下载完成后会挂载磁盘映像,把应用拖进「应用程序」即可完成安装)"):r("正在下载安装包…(下载完成后启动安装程序需要管理员权限,会弹出 UAC 确认框)")}function DI(e,t){return Oa(e)?r("更新包已就绪:{name}。点「安装并重启」后,面板会校验并替换容器内的程序与界面文件,然后重启服务(页面会自动刷新)。",{name:t}):Tx(e)?r("安装包已就绪:{name}。点击「打开安装包」后会挂载磁盘映像,把应用拖进「应用程序」即可完成安装。",{name:t}):r("安装包已就绪:{name}。点击「安装并重启」后需要管理员权限,会弹出 UAC 确认框。",{name:t})}function ZW(e){return Oa(e)?r("安装并重启"):Tx(e)?r("打开安装包"):r("安装并重启")}let da=YW;const rS=new Set;function aS(){return da}function WW(e){return rS.add(e),()=>{rS.delete(e)}}function _n(e){da={...da,...e};for(const t of rS)t()}let yr=!1,lS=null,Ex=null;function Uu(){Ex!==null&&(window.clearInterval(Ex),Ex=null)}function Cs(e,t=""){_n({badgeText:e,badgeTone:t})}function Cn(e,t=!1){_n({stateText:e,stateError:t})}function Rx(){const{info:e,checkedAt:t}=da;if(!e)return;const a=t?r("(检查于 {time})",{time:OI(t)}):"";if(e.pendingRestart===!0){Cs(r("待重启"),"warn"),Cn(r("更新已应用到容器内,重启服务后生效。{at}",{at:a}));return}if(e.hasUpdate===!0){if(Cs(r("有新版本"),"warn"),Oa(e)&&!e.serverAsset){Cn(r("发现新版本 {latest}(当前 {current}),但该版本没有提供容器内更新包;请在宿主机执行 docker compose pull && docker compose up -d 升级。{at}",{latest:String(e.latestVersion||""),current:String(e.currentVersion||""),at:a}));return}Cn(r("发现新版本 {latest}(当前 {current})。{at}",{latest:String(e.latestVersion||""),current:String(e.currentVersion||""),at:a}))}else e.hasUpdate===!1?(Cs(r("已是最新"),"ok"),Cn(r("当前已是最新版本({current})。{at}",{current:String(e.currentVersion||""),at:a}))):(Cs(r("无法比较"),"warn"),Cn(e.latestVersion?r("最新发布版本为 {latest},但当前版本号「{current}」无法解析,未做新旧判断。{at}",{latest:e.latestVersion,current:e.currentVersion||r("未知"),at:a}):r("仓库暂无发布版本。{at}",{at:a})))}function II(e){!e||e.checked===!1||(_n({info:e,checkedAt:Number(e.checkedAt)||0}),e.repository&&oS(e.repository),da.phase==="idle"&&Rx())}function oS(e){const t=String(e||"").trim();/^[\w.-]+\/[\w.-]+$/.test(t)&&_n({repository:t})}function iS(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 _n({phase:"downloading",percent:t}),Cs(r("下载中"),"warn"),Cn(r("正在下载 {name}:{percent}%({received} / {total} MB)",{name:e.filename||r("安装包"),percent:t,received:a.toFixed(1),total:o.toFixed(1)})),!0}if(Uu(),_n({percent:0}),e.error)return Cs(r("下载失败"),"bad"),Cn(r("下载失败:{error}",{error:e.error}),!0),_n({phase:"failed"}),!0;if(e.canceled)return Cs(r("已取消"),"warn"),Cn(Oa(da.info)?r("下载已取消,可重新点击「下载并更新」。"):r("下载已取消,可重新点击「下载并安装」。")),_n({phase:"idle"}),!0;if(e.done&&e.path){const t=e.path,a=e.filename||t;return Cs(r("可安装"),"ok"),_n({phase:"ready",readyPath:t}),Oa(da.info)?(Cn(DI(da.info,a)),!0):(t!==lS?(lS=t,Cn(Tx(da.info)?r("安装包已下载完成,正在挂载磁盘映像…"):r("安装包已下载完成,正在启动安装程序(需要管理员权限,会弹出 UAC 确认框)…")),_I(t)):Cn(DI(da.info,a)),!0)}return!1}async function JW(){try{const e=await Mn().workbuddyDesktop?.updateProgress();if(!e){Uu();return}iS(e)}catch(e){Uu(),Cn(r("读取下载进度失败:{error}",{error:Dr(e)}),!0)}}function PI(){Uu(),Ex=window.setInterval(()=>{JW()},$W)}async function _I(e){const t=Mn().workbuddyDesktop;if(t)try{const o=(await t.runInstaller(e,!0))?.restart!==!1;Cn(r(o?"安装程序已启动,本程序将退出以便完成覆盖安装。安装程序需要管理员权限,会弹出 UAC 确认框,请选择「是」。":"安装包已挂载,请在弹出的窗口里把应用拖进「应用程序」完成安装。安装完成后重新打开本程序即可。"))}catch(a){Cs(r("启动失败"),"bad"),Cn(r("启动安装程序失败:{error}",{error:Dr(a)}),!0)}}async function eJ(){const e=Mn().workbuddyDesktop;if(e?.installUpdate)try{Cs(r("安装中"),"warn"),Cn(r("正在校验并替换容器内的程序与界面文件…"));const t=await e.installUpdate(),a=String(t?.version||"").trim();Cn(a?r("已替换为 {version},正在重启服务…",{version:a}):r("替换完成,正在重启服务…")),await e.restartService?.().catch(()=>{}),cS(a)}catch(t){Cs(r("安装失败"),"bad"),Cn(r("安装失败:{error}",{error:Dr(t)}),!0)}}async function tJ(){const e=Mn().workbuddyDesktop;if(!(!e?.rollbackUpdate||yr)){yr=!0,_n({actionBusy:!0});try{Cs(r("回滚中"),"warn"),Cn(r("正在回滚到上一版本…")),await e.rollbackUpdate(),Cn(r("已还原上一版本,正在重启服务…")),await e.restartService?.().catch(()=>{}),cS("")}catch(t){Cs(r("回滚失败"),"bad"),Cn(r("回滚失败:{error}",{error:Dr(t)}),!0)}finally{yr=!1,_n({actionBusy:!1})}}}function cS(e){Uu(),_n({phase:"restarting",restartSeconds:AI,readyPath:""}),Cs(r("重启中"),"warn");let t=AI;const a=()=>{if(Cn(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),nJ();return}t-=1,_n({restartSeconds:t})},o=window.setInterval(a,1e3);a()}async function nJ(){for(let e=0;e{window.setTimeout(t,GW)})}window.location.reload()}async function LI(){if(yr)return null;yr=!0,_n({checking:!0}),Cs(r("检查中"),"warn"),Cn(r("正在查询 GitHub 上的最新发布版本…"));let e=null;try{const t=Mn().workbuddyDesktop;if(!t)throw new Error(r("后端桥不可用"));e=await t.checkUpdate()??null,_n({info:e,checkedAt:Number(e?.checkedAt)||Date.now()}),e?.repository&&oS(e.repository),Rx()}catch(t){e=null,_n({info:null,checkedAt:0}),Cs(r("检查失败"),"bad"),Cn(r("检查更新失败:{error}",{error:Dr(t)}),!0)}finally{yr=!1,_n({checking:!1})}return Mn().wbApp?.updateUpdateBadge?.(e),kx(e,xp),e}async function zI(){let e=null;try{e=await Mn().workbuddyDesktop?.getUpdateStatus()??null}catch{}if(e&&e.checked!==!1){II(e),Mn().wbApp?.updateUpdateBadge?.(e),kx(e,xp);return}da.info||(Cs(r("未检查")),Cn(r("点击「检查更新」查询 GitHub 上的最新发布版本。")))}async function uS(){if(yr)return;const e=aS();if(e.info?.pendingRestart===!0&&e.phase!=="downloading"){yr=!0,_n({actionBusy:!0});try{await Mn().workbuddyDesktop?.restartService?.().catch(()=>{}),cS("")}finally{yr=!1,_n({actionBusy:!1})}return}if(e.phase!=="downloading"&&e.readyPath){yr=!0,_n({actionBusy:!0});try{Oa(e.info)?await eJ():await _I(e.readyPath)}finally{yr=!1,_n({actionBusy:!1})}return}if(e.phase==="downloading"){try{await Mn().workbuddyDesktop?.cancelUpdate(),Cn(r("正在取消下载…"))}catch(a){tr(r("取消失败:{error}",{error:Dr(a)}),"err")}return}const t=MI(e.info);if(!t?.url){tr(Oa(e.info)?r("这一版没有提供容器内更新包"):r("没有可下载的安装包"),"err");return}if(HI(e)){yr=!0,_n({actionBusy:!0});try{await Mn().workbuddyDesktop?.downloadUpdate({url:t.url,name:t.name}),lS=null,_n({phase:"downloading",readyPath:"",percent:0}),Cs(r("下载中"),"warn"),Cn(QW(e.info)),PI()}catch(a){Cs(r("下载失败"),"bad"),Cn(r("下载失败:{error}",{error:Dr(a)}),!0)}finally{yr=!1,_n({actionBusy:!1})}}}async function BI(){Rx(),await zI();try{const e=await Mn().workbuddyDesktop?.updateProgress();if(e?.active){iS(e),PI();return}if(e?.done&&e.path){iS(e);return}}catch{}}async function xp(e){if(e?.pendingRestart===!0){await uS();return}e?.hasUpdate===!0&&(_n({info:e,checkedAt:Number(e.checkedAt)||da.checkedAt}),e.repository&&oS(e.repository),Rx(),Mn().wbApp?.updateUpdateBadge?.(e),kx(e,xp)),await BI();const t=aS();if(!(t.phase==="downloading"||t.readyPath)&&t.info?.hasUpdate)for(let a=0;a<3;a+=1){if(yr){await new Promise(o=>{window.setTimeout(o,400)});continue}await uS();return}}function HI(e){return e.phase==="restarting"?null:e.info?.pendingRestart===!0&&e.phase==="idle"?{label:r("立即重启"),disabled:e.actionBusy}:!(e.info?.hasUpdate===!0&&!!MI(e.info)?.url)&&e.phase!=="downloading"&&e.phase!=="ready"?null:{label:e.phase==="downloading"?r("取消下载"):e.phase==="failed"?r("重试下载"):e.phase==="ready"?ZW(e.info):Oa(e.info)?r("下载并更新"):r("下载并安装"),disabled:e.actionBusy}}function sJ(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=s2(o),d=t2(a?.pageUrl),f=XW(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:Og}),onClick:t,children:r("加入 QQ 群")})]})]})]})}function rJ(){const e=x.useSyncExternalStore(WW,aS),t=HI(e),[a,o]=x.useState(!1),[c,d]=x.useState(!1);x.useEffect(()=>()=>{Uu()},[]);const f=e.repository?`https://github.com/${e.repository}`:"",p=e.repository?`https://github.com/${e.repository.split("/")[0]}`:"",g=Oa(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:OI(e.checkedAt)}):""}`:"";return s.jsxs("section",{className:"panel",onClick:r2,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:KW[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:()=>{LI()},children:e.checking?r("检查中…"):r("检查更新")}),v?s.jsx(se,{id:"btn-update-rollback",variant:"outline",disabled:e.actionBusy,title:r("把容器内的程序与界面文件还原到更新前的版本,并重启服务"),onClick:()=>{tJ()},children:r("回滚到上一版本")}):null,t?s.jsx(se,{id:"btn-update-download",variant:"default",disabled:t.disabled,onClick:()=>{uS()},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(qd,{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:sJ(e,()=>d(!0))})]})]}),a?s.jsx(VW,{open:!0,onClose:()=>o(!1)}):null,c?s.jsx(FW,{open:!0,onClose:()=>d(!1)}):null]})}const UI='.settings-pane[data-cat="about"]';let dS=null;function VI(){if(dS)return;const e=document.querySelector(UI);e&&(e.replaceChildren(),dS=wn.createRoot(e),dS.render(s.jsx(rJ,{})))}document.querySelector(UI)?VI():document.addEventListener("DOMContentLoaded",VI,{once:!0}),window.wbUpdatePanel={load:BI,check:LI,syncFromCache:zI,openAndDownload:xp,applyStatus:II,showUpdateModal:e=>kx(e,xp)};const aJ="zcode.z.ai/billing",lJ={active:"success",pending:"warning",expired:"ghost",unknown:"outline"};function oJ(e){const t=String(e||"").trim().toLowerCase();return t==="daily"?r("每日"):t==="weekly"?r("每周"):t==="monthly"?r("每月"):""}function iJ(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 rc(e){const t=Number(e);return!Number.isFinite(t)||t<=0?"":Pe().wbApp?.formatTime?.(t*1e3)||new Date(t*1e3).toLocaleString()}function cJ(e){const t=iJ(e.grantUnits),a=String(e.unitType||"").trim(),o=t?[t,a].filter(Boolean).join(" "):"",c=oJ(e.period),d=[String(e.showName||"").trim(),o].filter(Boolean).join(" ");return d?c?r("{body}({period})",{body:d,period:c}):d:""}function FI(e){return(e.entitlements||[]).map(cJ).filter(Boolean).join(r("、"))}function uJ(e){const t=rc(e.startsAt),a=rc(e.endsAt);return t&&a?`${t} → ${a}`:a?r("到期 {time}",{time:a}):t?r("开始 {time}",{time:t}):""}function dJ(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}):rc(e)}function fJ(e){const t=[],a=Number(e.pendingUntil);if(Number.isFinite(a)&&a>0){const c=dJ(a);c&&t.push(r("待生效 {time}",{time:c}))}const o=rc(e.endsAt);if(o&&t.push(r("到期 {time}",{time:o})),t.length===0){const c=rc(e.startsAt);c&&t.push(r("开始 {time}",{time:c}))}return t.join(" · ")}function pJ({options:e,onClose:t}){const a=e.id,[,o]=x.useState(0);x.useEffect(()=>gR(()=>o(M=>M+1)),[]);const[c,d]=x.useState([]),[f,p]=x.useState({status:"loading"}),[g,v]=x.useState(""),y=Ta(a),b=String(y?.name||e.name||a),j=Rh(y),w=[...new Set([...j,...c])],S=y?.claimPlans&&typeof y.claimPlans=="object"&&!Array.isArray(y.claimPlans)?y.claimPlans:{},N=y?Ya(y):void 0,k=N&&typeof N=="object"&&!Array.isArray(N)?N:null,E=k&&Array.isArray(k.plans)?k.plans:[],R=w.filter(M=>M&&!E.some(O=>String(O.planId||"")===M)),C=Zs().usageInflight.has(a),A=Pe().wbZcodeClaim,D=x.useCallback(async()=>{if(!A?.preview){p({status:"error",message:r("当前环境不支持领取(桥接方法缺失)")});return}p({status:"loading"});try{const M=await A.preview(a);p({status:"ready",result:M||{}})}catch(M){p({status:"error",message:mt(M)})}},[A,a]);x.useEffect(()=>{D();const M=Ta(a);M&&Ya(M)===void 0&&Lh(a)},[a,D]);async function I(M){if(!(!A?.claim||g)){v(M);try{const O=await A.claim(a,M);if(O?.ok||O?.failure==="already_claimed"){const _=O.planId||M;_&&d(L=>L.includes(_)?L:[...L,_]),Lh(a),Pe().wbApp?.refresh?.(),D()}}finally{v("")}}}return s.jsx(Kt,{open:!0,onOpenChange:(M,O)=>{if(!M){if(g){O.cancel();return}t()}},children:s.jsxs(Yt,{className:"w-[min(560px,calc(100vw-48px))]",children:[s.jsx($t,{children:s.jsx(Ft,{children:r("ZCode 套餐明细 — {name}",{name:b})})}),s.jsxs(_t,{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($d,{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:()=>{D()},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(M=>{const O=String(M.planId||""),_=w.includes(O),L=FI(M),z=uJ(M);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:M.name||O||r("套餐")}),_?s.jsx(ze,{variant:"success",shape:"tag",children:r("今日已领")}):null]}),z?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:z}):null,L?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:L}):null,M.description?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:M.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||M.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:()=>{Lh(a)},children:r(C?"查询中…":"查询余额")})})]}),E.length>0?s.jsx("ul",{className:"m-0 list-none p-0",children:E.map(M=>{const O=String(M.planId||""),_=String(M.state||"unknown"),L=FI(M),z=fJ(M),U=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:M.name||O||r("套餐")}),s.jsx(ze,{variant:lJ[_]||"outline",shape:"tag",children:rR(_)})]}),z?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:z}):null,L?s.jsx("div",{className:"text-[12px] text-muted-foreground",children:L}):null]}),U>0?s.jsx("span",{className:"flex-none text-[11.5px] text-muted-foreground",children:r("本地领取于 {time}",{time:rc(U/1e3)})}):null]},O||M.name)})}):s.jsx("p",{className:"py-1 text-[12.5px] text-muted-foreground",children:N===void 0?r("还没有余额读数(已自动查询一次,稍候;也可以点右上角「查询余额」重读)"):k&&k.source&&k.source!==aJ?r("这个账号的余额走窗口限额通道(只配了编码套餐 API Key):只有每 N 小时的剩余比例,读不到套餐清单"):r("读数里没有套餐清单(免费账号、或套餐的上游状态还没刷新;可点右上角「查询余额」重读)")}),R.length>0?s.jsx("p",{className:"mt-1.5 text-[11.5px] text-muted-foreground",children:r("本地台账里今天还领过这些,但上面的读数里还没有:{plans}(读数刷新可能有延迟)",{plans:R.map(M=>{const O=Number(S[M])||0,_=O>0?rc(O/1e3):"";return _?r("{plan}({time} 领取)",{plan:M,time:_}):M}).join(r("、"))})}):null]})]}),s.jsxs(en,{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 bp=null,Vu=null;function $I(){bp&&(bp.unmount(),bp=null),Vu&&(Vu.remove(),Vu=null)}function mJ(e){e?.id&&($I(),Vu=document.createElement("div"),document.body.append(Vu),bp=wn.createRoot(Vu),bp.render(s.jsx(pJ,{options:e,onClose:$I})))}window.wbZcodePlans={open:mJ};const qI="w-auto flex-auto";function GI({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(ji,{className:Ve(qI,o),children:[s.jsx(Si,{ref:f,className:c,onInput:p,...d}),s.jsx(wi,{"aria-hidden":"true",children:a})]}):s.jsx(Ye,{ref:f,className:Ve(qI,c),onInput:p,...d})}function hJ(e,t){const a=wn.createRoot(e),o={current:null};return a.render(s.jsx(GI,{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 gJ=[["id","id"],["type","type"],["name","name"],["title","title"],["placeholder","placeholder"],["min","min"],["max","max"],["step","step"],["autocomplete","autoComplete"]];function xJ(e){const t={defaultValue:e.value||void 0,inputClassName:e.className||void 0};for(const[f,p]of gJ){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 KI(e){if(e.dataset.islandUpgraded)return;e.dataset.islandUpgraded="1";const t=xJ(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=wn.createRoot(o);Ns.flushSync(()=>{d.render(s.jsx(GI,{...t,domRef:c}))})}function YI(e=document){if(e instanceof HTMLInputElement&&e.matches("[data-island-input]")){KI(e);return}e.querySelectorAll("input[data-island-input]").forEach(KI)}function bJ(){YI();const e=new MutationObserver(t=>{for(const a of t)for(const o of a.addedNodes)o instanceof Element&&YI(o)});return e.observe(document.body,{childList:!0,subtree:!0}),e}function vJ(e,t){const a=wn.createRoot(e);let o={options:t.options,value:t.value,ariaLabel:t.ariaLabel,className:t.className};const c=()=>{a.render(s.jsx(Pn,{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:vJ},window.wbInput={mount:hJ},bJ()})();