@lks347/dsh-oauth 0.0.0-stage → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +155 -0
- package/README.md +101 -2
- package/app.js +1045 -0
- package/auth.html +80 -0
- package/client.js +31 -0
- package/cordis.patch.yml +4 -0
- package/docs/CONNECTIONS.md +77 -0
- package/docs/LIVE-VALIDATION-1.0.1.md +100 -0
- package/docs/RELEASE-1.0.1.md +48 -0
- package/docs/RELEASE-1.0.2.md +8 -0
- package/docs/VALIDATION.md +59 -0
- package/docs/evidence/live-1.0.1.json +135 -0
- package/docs/evidence/release-1.0.1.json +38 -0
- package/index.html +43 -0
- package/package.json +64 -4
- package/providers.js +73 -0
- package/scripts/check-upstreams.mjs +27 -0
- package/scripts/link-peers.js +38 -0
- package/scripts/verify-browser.mjs +297 -0
- package/scripts/verify-host.mjs +431 -0
- package/scripts/verify-live.mjs +268 -0
- package/scripts/verify-package.mjs +168 -0
- package/scripts/verify-persistence.mjs +307 -0
- package/scripts/verify-subscriptions-ui.mjs +321 -0
- package/src/account.js +85 -0
- package/src/account.test.js +52 -0
- package/src/authorization.js +199 -0
- package/src/authorization.test.js +332 -0
- package/src/catalog.js +180 -0
- package/src/catalog.test.js +146 -0
- package/src/chat-recovery.js +110 -0
- package/src/chat-recovery.test.js +261 -0
- package/src/connection-runtime.js +129 -0
- package/src/connection-runtime.test.js +244 -0
- package/src/connections.js +70 -0
- package/src/grants.js +104 -0
- package/src/grants.test.js +340 -0
- package/src/index.js +676 -0
- package/src/local-imports.js +263 -0
- package/src/local-imports.test.js +201 -0
- package/src/media.js +152 -0
- package/src/models.js +610 -0
- package/src/models.test.js +503 -0
- package/src/profile-store.js +51 -0
- package/src/pulls.js +100 -0
- package/src/pulls.test.js +156 -0
- package/src/qwen.js +141 -0
- package/src/qwen.test.js +35 -0
- package/src/request-errors.js +50 -0
- package/src/request-errors.test.js +131 -0
- package/src/routes.js +47 -0
- package/src/routes.test.js +136 -0
- package/src/subscription-models.test.js +160 -0
- package/src/usage/aggregators.js +292 -0
- package/src/usage/aggregators.test.js +316 -0
- package/src/usage/core.js +68 -0
- package/src/usage/index.js +93 -0
- package/src/usage/official.js +339 -0
- package/src/usage/official.test.js +273 -0
- package/src/usage/service.test.js +89 -0
- package/src/xai-browser.js +272 -0
- package/src/xai-browser.test.js +256 -0
- package/src/xai-login.js +121 -0
- package/src/xai-login.test.js +259 -0
- package/styles.css +364 -0
- package/theme.js +118 -0
- package/upstreams.json +10 -0
package/app.js
ADDED
|
@@ -0,0 +1,1045 @@
|
|
|
1
|
+
const STORE_KEY = "dsh-oauth-preview-v1";
|
|
2
|
+
let locale = "zh";
|
|
3
|
+
try { locale = localStorage.getItem("dsh-oauth-locale") === "en" ? "en" : "zh"; } catch { /* Optional UI preference. */ }
|
|
4
|
+
const tr = (zh, en) => locale === "en" ? (en || zh) : zh;
|
|
5
|
+
const number = (value) => {
|
|
6
|
+
if (value === null || value === undefined || value === "") return tr("未知", "Unknown");
|
|
7
|
+
const parsed = Number(value);
|
|
8
|
+
return Number.isFinite(parsed) ? new Intl.NumberFormat(locale === "en" ? "en" : "zh-CN", { maximumFractionDigits: 6 }).format(parsed) : String(value);
|
|
9
|
+
};
|
|
10
|
+
const dateLabel = (value) => {
|
|
11
|
+
const date = new Date(value);
|
|
12
|
+
return value != null && Number.isFinite(date.getTime()) ? new Intl.DateTimeFormat(locale === "en" ? "en" : "zh-CN", { dateStyle: "medium", timeStyle: "short" }).format(date) : tr("未知", "Unknown");
|
|
13
|
+
};
|
|
14
|
+
const usageResults = new Map();
|
|
15
|
+
const usageBusy = new Set();
|
|
16
|
+
const usageOpen = new Set();
|
|
17
|
+
const revisions = new Map();
|
|
18
|
+
let connectionTarget = null;
|
|
19
|
+
let localTarget = null;
|
|
20
|
+
let pullModels = [];
|
|
21
|
+
let pullError = "";
|
|
22
|
+
let pullSaving = false;
|
|
23
|
+
let modalReturnFocus = null;
|
|
24
|
+
let modalSerial = 0;
|
|
25
|
+
|
|
26
|
+
function modalStart() {
|
|
27
|
+
if (document.querySelector("#modal").hidden) modalReturnFocus = document.activeElement;
|
|
28
|
+
}
|
|
29
|
+
function focusDialog() {
|
|
30
|
+
const dialog = document.querySelector("#modal .dialog");
|
|
31
|
+
if (!dialog) return;
|
|
32
|
+
dialog.setAttribute("tabindex", "-1");
|
|
33
|
+
if (!dialog.querySelector("[data-modal-locale]")) {
|
|
34
|
+
const label = document.createElement("label");
|
|
35
|
+
label.className = "locale-label modal-locale";
|
|
36
|
+
label.innerHTML = `${tr("语言", "Language")} <select data-modal-locale aria-label="${tr("界面语言", "Interface language")}"><option value="zh">简体中文</option><option value="en">English</option></select>`;
|
|
37
|
+
label.querySelector("select").value = locale;
|
|
38
|
+
dialog.append(label);
|
|
39
|
+
}
|
|
40
|
+
if (!dialog.contains(document.activeElement)) dialog.focus?.();
|
|
41
|
+
}
|
|
42
|
+
function closeModal() {
|
|
43
|
+
const root = document.querySelector("#modal");
|
|
44
|
+
root.hidden = true;
|
|
45
|
+
root.innerHTML = "";
|
|
46
|
+
connectionTarget = null;
|
|
47
|
+
localTarget = null;
|
|
48
|
+
pullTarget = null;
|
|
49
|
+
pendingDisconnect = null;
|
|
50
|
+
modalSerial++;
|
|
51
|
+
if (modalReturnFocus?.isConnected) modalReturnFocus.focus?.();
|
|
52
|
+
}
|
|
53
|
+
function invalidateUsage(id) {
|
|
54
|
+
revisions.set(id, (revisions.get(id) || 0) + 1);
|
|
55
|
+
usageResults.delete(id);
|
|
56
|
+
usageBusy.delete(id);
|
|
57
|
+
}
|
|
58
|
+
function requestError(body, fallback) {
|
|
59
|
+
return body?.message || body?.error || fallback || tr("请求失败,请重试。", "Request failed. Please try again.");
|
|
60
|
+
}
|
|
61
|
+
async function post(path, body) {
|
|
62
|
+
const response = await fetch(`/oauth/api/${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
63
|
+
let result;
|
|
64
|
+
try { result = await response.json(); } catch { throw new Error(tr("服务返回了无效响应。", "The service returned an invalid response.")); }
|
|
65
|
+
if (!response.ok) throw new Error(requestError(result));
|
|
66
|
+
return result;
|
|
67
|
+
}
|
|
68
|
+
function updateStaticText() {
|
|
69
|
+
document.documentElement.lang = locale === "en" ? "en" : "zh-CN";
|
|
70
|
+
document.title = tr("dsh-oauth · 订阅连接", "dsh-oauth · Subscription connections");
|
|
71
|
+
const set = (selector, text) => { const node = document.querySelector(selector); if (node) node.textContent = text; };
|
|
72
|
+
set("#page-kicker", tr("设置 · 订阅连接", "Settings · Subscriptions"));
|
|
73
|
+
set("#page-title", tr("OAuth 认证", "OAuth authentication"));
|
|
74
|
+
set("#providers-title", tr("提供商登录与订阅", "Provider connections & subscriptions"));
|
|
75
|
+
set("#reset", tr("恢复示例", "Reset examples"));
|
|
76
|
+
const nav = document.querySelectorAll(".nav button");
|
|
77
|
+
[tr("密钥", "API keys"), "OAuth", tr("模型路由", "Model routing")].forEach((text, i) => { if (nav[i]) nav[i].textContent = text; });
|
|
78
|
+
document.querySelector("#refresh")?.setAttribute("aria-label", tr("刷新连接状态", "Refresh connections"));
|
|
79
|
+
const selector = document.querySelector("#locale");
|
|
80
|
+
if (selector) selector.value = locale;
|
|
81
|
+
}
|
|
82
|
+
const hostedPanel = /^\/oauth(?:\/|$)/.test(location.pathname);
|
|
83
|
+
let apiMode = hostedPanel ? "checking" : "preview";
|
|
84
|
+
|
|
85
|
+
const seedStatus = () => ({
|
|
86
|
+
"openai-codex": {
|
|
87
|
+
loggedIn: true,
|
|
88
|
+
tokenPreview: "示例,无真实凭据",
|
|
89
|
+
sourceLabel: "静态预览",
|
|
90
|
+
expiresAt: Date.now() + 5 * 60 * 60 * 1000,
|
|
91
|
+
error: "",
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
function loadState() {
|
|
96
|
+
try {
|
|
97
|
+
const raw = localStorage.getItem(STORE_KEY);
|
|
98
|
+
if (raw) return JSON.parse(raw);
|
|
99
|
+
} catch {
|
|
100
|
+
/* keep the seed */
|
|
101
|
+
}
|
|
102
|
+
return seedStatus();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
let status = apiMode === "preview" ? loadState() : {};
|
|
106
|
+
let toastTimer = 0;
|
|
107
|
+
let pendingId = null;
|
|
108
|
+
let authPopup = null;
|
|
109
|
+
let popupWatch = 0;
|
|
110
|
+
let activeLogin = null;
|
|
111
|
+
let loginPoll = 0;
|
|
112
|
+
let loginRenderKey = "";
|
|
113
|
+
let unloaded = false;
|
|
114
|
+
|
|
115
|
+
function save() {
|
|
116
|
+
localStorage.setItem(STORE_KEY, JSON.stringify(status));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function toast(message) {
|
|
120
|
+
const node = document.querySelector("#toast");
|
|
121
|
+
node.textContent = message;
|
|
122
|
+
node.hidden = false;
|
|
123
|
+
window.clearTimeout(toastTimer);
|
|
124
|
+
toastTimer = window.setTimeout(() => {
|
|
125
|
+
node.hidden = true;
|
|
126
|
+
}, 2400);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function expiresLabel(at) {
|
|
130
|
+
if (!at) return "";
|
|
131
|
+
const diff = new Date(at).getTime() - Date.now();
|
|
132
|
+
if (diff < 0) return "expired";
|
|
133
|
+
const mins = Math.floor(diff / 60000);
|
|
134
|
+
if (mins < 60) return tr(`${number(mins)} 分钟后过期`, `expires in ${number(mins)} minutes`);
|
|
135
|
+
const hours = Math.floor(mins / 60);
|
|
136
|
+
if (hours < 24) return tr(`${number(hours)} 小时后过期`, `expires in ${number(hours)} hours`);
|
|
137
|
+
return tr(`${number(Math.floor(hours / 24))} 天后过期`, `expires in ${number(Math.floor(hours / 24))} days`);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function shield(on) {
|
|
141
|
+
const stroke = "currentColor";
|
|
142
|
+
if (on) {
|
|
143
|
+
return `<svg class="mark on" viewBox="0 0 24 24" fill="none" stroke="${stroke}" stroke-width="1.8"><path d="M12 3 5 6v6c0 4.2 2.8 7.4 7 9 4.2-1.6 7-4.8 7-9V6l-7-3Z"/><path d="m9 12 2 2 4-4"/></svg>`;
|
|
144
|
+
}
|
|
145
|
+
return `<svg class="mark off" viewBox="0 0 24 24" fill="none" stroke="${stroke}" stroke-width="1.8"><path d="M12 3 5 6v6c0 4.2 2.8 7.4 7 9 4.2-1.6 7-4.8 7-9V6l-7-3Z"/><path d="m9.5 9.5 5 5M14.5 9.5l-5 5"/></svg>`;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function connectedCount() {
|
|
149
|
+
return PROVIDERS.filter((provider) => status[provider.id]?.loggedIn).length;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
let remote = null;
|
|
153
|
+
|
|
154
|
+
async function refreshRemote() {
|
|
155
|
+
if (!hostedPanel) return false;
|
|
156
|
+
try {
|
|
157
|
+
const response = await fetch("/oauth/api/providers", { cache: "no-store" });
|
|
158
|
+
if (!response.ok) throw new Error(`提供商接口返回 ${response.status}`);
|
|
159
|
+
const body = await response.json();
|
|
160
|
+
if (!Array.isArray(body.providers)) throw new Error("提供商接口返回格式不正确");
|
|
161
|
+
apiMode = "live";
|
|
162
|
+
for (const previous of remote || []) {
|
|
163
|
+
const next = body.providers.find((item) => item.id === previous.id);
|
|
164
|
+
if (!next?.loggedIn || JSON.stringify(previous.connection) !== JSON.stringify(next.connection)) invalidateUsage(previous.id);
|
|
165
|
+
}
|
|
166
|
+
remote = body.providers;
|
|
167
|
+
status = {};
|
|
168
|
+
for (const provider of remote) {
|
|
169
|
+
status[provider.id] = {
|
|
170
|
+
loggedIn: Boolean(provider.loggedIn),
|
|
171
|
+
|
|
172
|
+
sourceLabel: provider.sourceLabel || "本机登录",
|
|
173
|
+
expiresAt: provider.expiresAt,
|
|
174
|
+
error: provider.error || "",
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
renderList();
|
|
178
|
+
return true;
|
|
179
|
+
} catch {
|
|
180
|
+
apiMode = "unavailable";
|
|
181
|
+
renderList();
|
|
182
|
+
return false;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function pullSummary(pulled, provider) {
|
|
187
|
+
if (!pulled.length && provider?.pullable === false) return provider.supportReason === "host-oauth-model-integration-unavailable"
|
|
188
|
+
? tr("可查询套餐用量;当前宿主尚未接入此来源的模型调用。", "Plan usage can be queried; model access for this source is not integrated with the current host.")
|
|
189
|
+
: tr("此来源暂不支持保存模型配置。", "Saving model configuration is not available for this source.");
|
|
190
|
+
if (!pulled.length) return tr("尚未保存模型。连接后可获取模型与能力。", "No models saved. Fetch models and capabilities after connecting.");
|
|
191
|
+
return tr(`已保存 ${pulled.length} 个模型:`, `Models saved: ${pulled.length} · `) + pulled.map((model) => escapeHtml(model.name || model.id)).join(locale === "en" ? ", " : "、");
|
|
192
|
+
}
|
|
193
|
+
function providerConnectionHint(provider) {
|
|
194
|
+
if (provider.sourceStatus) return provider.sourceStatus === "source-reauth-required"
|
|
195
|
+
? tr("本机授权已到期,请在源 CLI 中续期。", "Local authorization expired. Renew it in the source CLI.")
|
|
196
|
+
: tr("本机授权来源不可用,请重新选择或断开连接。", "Local authorization is unavailable. Select a source again or disconnect.");
|
|
197
|
+
if (provider.supportReason === "gemini-consumer-retired") return tr(
|
|
198
|
+
"Gemini CLI 个人订阅登录已停用。个人 Google 订阅请在 Antigravity CLI 中登录。",
|
|
199
|
+
"Gemini CLI consumer sign-in ended. Use Antigravity CLI for a personal Google subscription.",
|
|
200
|
+
);
|
|
201
|
+
if (provider.supportReason === "qwen-legacy-oauth") return tr(
|
|
202
|
+
"此入口保留已有的旧版 OAuth。新连接请使用阿里云 Token Plan。",
|
|
203
|
+
"This entry retains existing legacy OAuth connections. Use Alibaba Cloud Token Plan for new connections.",
|
|
204
|
+
);
|
|
205
|
+
if (provider.id === "anthropic") return tr(
|
|
206
|
+
"使用 Claude Console API Key 连接。Claude Code 订阅由其官方客户端管理。",
|
|
207
|
+
"Connect with a Claude Console API key. The official client manages Claude Code subscriptions.",
|
|
208
|
+
);
|
|
209
|
+
if (provider.keyConnect) return tr("可使用套餐密钥连接。调用与用量查询可能需要不同权限。", "Connect with a plan key. Model access and usage queries may require different permissions.");
|
|
210
|
+
return provider.pullable === false
|
|
211
|
+
? tr("未连接。可用功能以此来源与宿主的支持范围为准。", "Not connected. Available features depend on this source and the host integration.")
|
|
212
|
+
: tr("未连接。登录后可获取模型与套餐信息。", "Not connected. Sign in to fetch models and plan information.");
|
|
213
|
+
}
|
|
214
|
+
function shownProviders() { return remote === null ? PROVIDERS : remote; }
|
|
215
|
+
function flowLabel(provider) {
|
|
216
|
+
if (provider.authMethods?.length === 0) return tr("连接待支持", "Connection unavailable");
|
|
217
|
+
if (provider.authMethods?.includes("key") && !provider.authMethods.includes("oauth")) return tr("密钥连接", "API key");
|
|
218
|
+
if (provider.flow === "device_code") return tr("设备码登录", "Device code");
|
|
219
|
+
if (provider.flow === "external" || provider.authMethods?.[0] === "local") return tr("本机授权", "Local authorization");
|
|
220
|
+
return tr("浏览器登录", "Browser login");
|
|
221
|
+
}
|
|
222
|
+
function usageStatus(value) {
|
|
223
|
+
return ({ fresh: tr("已更新", "Updated"), partial: tr("部分数据可用", "Partial data"), stale: tr("上次成功数据 · 本次更新失败", "Last successful data · refresh failed"), unsupported: tr("此来源暂不提供用量", "Usage unavailable for this source"), "reauth-required": tr("需要重新授权", "Authorization required"), "needs-permission": tr("需要查询权限", "Usage permission required"), "needs-configuration": tr("需要补充查询配置", "Usage configuration required"), "rate-limited": tr("查询被限速", "Usage query rate-limited"), unavailable: tr("暂时无法查询", "Temporarily unavailable") })[value] || tr("尚未查询", "Not queried yet");
|
|
224
|
+
}
|
|
225
|
+
function unitLabel(unit, currency) {
|
|
226
|
+
return currency || ({ percent: "%", requests: tr("次请求", "requests"), tokens: "tokens", credits: tr("积分", "credits"), points: tr("积分", "points"), flows: "Flows", money: tr("金额", "amount") })[unit] || unit || "";
|
|
227
|
+
}
|
|
228
|
+
function usageNote(note) {
|
|
229
|
+
const value = typeof note === "string" ? note : note.message || note.code || "";
|
|
230
|
+
const labels = {
|
|
231
|
+
"management-balance-has-independent-account-scope": ["管理密钥余额属于该密钥账户,可能与调用密钥范围不同。", "The management-key balance belongs to its own account and may differ from the model key's scope."],
|
|
232
|
+
"account-balance-needs-permission": ["账户余额需要额外查询权限。", "Account balance requires additional permission."],
|
|
233
|
+
"account-balance-unavailable": ["账户余额暂不可用。", "Account balance is unavailable."],
|
|
234
|
+
"subscription-active": ["订阅有效。", "Subscription active."],
|
|
235
|
+
"subscription-inactive": ["订阅未启用。", "Subscription inactive."],
|
|
236
|
+
"subscription-quota-unknown": ["订阅可用额度未知。", "Available subscription quota is unknown."],
|
|
237
|
+
"subscription-detail-unavailable": ["未提供订阅明细。", "Subscription details are unavailable."],
|
|
238
|
+
"payg-balance-unavailable": ["按量付费余额暂不可用。", "PAYG balance is unavailable."],
|
|
239
|
+
"monthly-usage-not-provided": ["未提供本月用量。", "Monthly usage was not provided."],
|
|
240
|
+
"per-model-budget-details-unavailable": ["未提供逐模型预算明细。", "Per-model budget details are unavailable."],
|
|
241
|
+
"workspace-wallet-not-included": ["此结果不包含工作区钱包余额。", "This result does not include the workspace wallet balance."],
|
|
242
|
+
"credit-balance-unavailable": ["积分余额暂不可用。", "Credit balance is unavailable."],
|
|
243
|
+
"pass-detail-unavailable": ["未提供订阅 Pass 明细。", "Subscription Pass details are unavailable."],
|
|
244
|
+
"internal-billing-api": ["数据来自此平台的内部账单接口。", "Data comes from the platform's internal billing API."],
|
|
245
|
+
"points-balance-not-currency": ["此余额以积分计量,并非货币余额。", "This balance is measured in points, not currency."],
|
|
246
|
+
"subscription-split-and-reset-not-provided": ["未提供订阅与充值分项或重置时间。", "Subscription/top-up breakdown and reset time were not provided."],
|
|
247
|
+
"incremental-regeneration-not-full-reset": ["恢复时间表示部分额度补充,并非全部重置。", "Recovery time indicates a partial refill, not a full reset."],
|
|
248
|
+
"legacy-quota-schema": ["提供商返回旧版额度格式。", "The provider returned its legacy quota format."],
|
|
249
|
+
"no-subscription": ["未检测到订阅。", "No subscription was reported."],
|
|
250
|
+
"payg-balance-not-provided": ["未提供按量付费余额。", "PAYG balance was not provided."],
|
|
251
|
+
"allowance-is-payg-equivalent-not-wallet": ["此额度按按量价格等值计量,并非钱包余额。", "This allowance uses PAYG-equivalent units; it is not a wallet balance."],
|
|
252
|
+
"four-hour-fixed-server-bucket": ["此窗口按服务端固定的 4 小时时段统计。", "This window follows a fixed four-hour server interval."],
|
|
253
|
+
"daily-request-quota-not-included": ["此结果不包含每日请求数额度。", "This result does not include the daily request allowance."],
|
|
254
|
+
"billing-route-subscription": ["提供商建议使用订阅计费。", "The provider recommends subscription billing."],
|
|
255
|
+
"billing-route-paygo": ["提供商建议使用按量计费。", "The provider recommends PAYG billing."],
|
|
256
|
+
"billing-route-unavailable": ["提供商未报告可用计费路径。", "The provider reports no available billing route."],
|
|
257
|
+
"The provider reports an exhausted allowance.": ["提供商报告此项额度已用尽。", "The provider reports an exhausted allowance."],
|
|
258
|
+
"Extra usage amounts are converted from cents; the response did not identify a currency.": ["额外用量金额已从分换算;提供商没有返回币种。", "Extra usage amounts are converted from cents; the response did not identify a currency."],
|
|
259
|
+
"Copilot reports AI-credit billing; this is not a premium-request count.": ["Copilot 返回 AI 积分账单,此数值不是高级请求次数。", "Copilot reports AI-credit billing; this is not a premium-request count."],
|
|
260
|
+
"A service not included in this plan was omitted.": ["已略去此套餐不包含的服务。", "A service not included in this plan was omitted."],
|
|
261
|
+
"MiniMax legacy counters are interpreted as remaining counts.": ["MiniMax 旧版计数字段按剩余次数解释。", "MiniMax legacy counters are interpreted as remaining counts."],
|
|
262
|
+
"Read-only remote quota summary; no project onboarding is performed.": ["这是只读远程额度摘要,不会为项目开通服务。", "Read-only remote quota summary; no project onboarding is performed."],
|
|
263
|
+
"Total usable credits overlap the component balances; do not add them together.": ["可用积分总额与分项余额重叠,请勿相加。", "Total usable credits overlap the component balances; do not add them together."],
|
|
264
|
+
};
|
|
265
|
+
if (labels[value]) return tr(...labels[value]);
|
|
266
|
+
const limited = /^(rolling|weekly|monthly)-rate-limited$/.exec(value);
|
|
267
|
+
if (limited) return tr(`${({ rolling: "滚动", weekly: "每周", monthly: "每月" })[limited[1]]}窗口已触及限额。`, `${limited[1]} window is rate-limited.`);
|
|
268
|
+
const multiplier = /^Weekly allowance multiplier: ([0-9.]+)\. Percentages retain the provider's base allowance\.$/.exec(value);
|
|
269
|
+
return multiplier ? tr(`每周额度倍数为 ${number(multiplier[1])};百分比仍以提供商基础额度为基准。`, value) : value;
|
|
270
|
+
}
|
|
271
|
+
function usageHtml(provider) {
|
|
272
|
+
if (!usageOpen.has(provider.id)) return "";
|
|
273
|
+
const result = usageResults.get(provider.id);
|
|
274
|
+
const snapshot = result?.snapshot;
|
|
275
|
+
const busy = usageBusy.has(provider.id);
|
|
276
|
+
const windows = Array.isArray(snapshot?.windows) ? snapshot.windows : [];
|
|
277
|
+
const balances = Array.isArray(snapshot?.balances) ? snapshot.balances : [];
|
|
278
|
+
const plan = typeof snapshot?.plan === "string" ? snapshot.plan : snapshot?.plan?.name || snapshot?.plan?.id;
|
|
279
|
+
const source = snapshot?.source;
|
|
280
|
+
const sourceText = typeof source === "string" ? source : source?.kind;
|
|
281
|
+
return `<section class="usage-panel" aria-label="${tr("套餐与用量", "Plan and usage")}" data-usage-panel="${escapeHtml(provider.id)}">
|
|
282
|
+
<div class="usage-heading"><strong>${escapeHtml(plan || tr("套餐信息未提供", "Plan information not provided"))}</strong><span class="badge ${result?.status === "fresh" ? "ok" : ""}">${busy ? tr("正在查询…", "Checking…") : usageStatus(result?.status)}</span></div>
|
|
283
|
+
${snapshot?.plan?.renewsAt ? `<p class="quota-foot">${tr("套餐续期", "Plan renews")}: ${escapeHtml(dateLabel(snapshot.plan.renewsAt))}</p>` : ""}
|
|
284
|
+
${windows.map((window) => {
|
|
285
|
+
const percent = Number.isFinite(window.usedPercent) ? window.usedPercent : Number.isFinite(window.remainingPercent) ? 100 - window.remainingPercent : null;
|
|
286
|
+
const quantities = [["used", tr("已用", "Used")], ["remaining", tr("剩余", "Remaining")], ["limit", tr("上限", "Limit")]].filter(([key]) => window[key] !== undefined && window[key] !== null).map(([key, title]) => `${title} ${number(window[key])} ${unitLabel(window.unit, window.currency)}`).join(" · ");
|
|
287
|
+
const label = window.label || window.id || tr("额度", "Quota");
|
|
288
|
+
const reset = window.resetAt || window.resetsAt;
|
|
289
|
+
return `<div class="quota-item ${percent > 100 ? "over" : ""}" data-window-id="${escapeHtml(window.id || "")}">
|
|
290
|
+
<div class="quota-line"><span>${escapeHtml(label)}</span><span>${window.unlimited ? tr("无此项上限", "No limit on this metric") : percent !== null ? escapeHtml(tr(`已用 ${number(percent)}%`, `${number(percent)}% used`)) : tr("用量比例未知", "Usage percentage unknown")}</span></div>
|
|
291
|
+
${percent !== null && !window.unlimited ? `<div class="quota-meter" role="meter" aria-label="${escapeHtml(label)}" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${Math.max(0, Math.min(100, percent))}" aria-valuetext="${escapeHtml(tr(`已用 ${number(percent)}%`, `${number(percent)}% used`))}"><span style="width:${Math.max(0, Math.min(100, percent))}%"></span></div>` : ""}
|
|
292
|
+
${quantities ? `<p class="quota-foot">${escapeHtml(quantities)}</p>` : ""}
|
|
293
|
+
${window.scope ? `<p class="quota-foot">${tr("适用范围", "Scope")}: ${escapeHtml(typeof window.scope === "string" ? window.scope : JSON.stringify(window.scope))}</p>` : ""}
|
|
294
|
+
${reset ? `<p class="quota-foot">${tr("额度重置", "Quota resets")}: ${escapeHtml(dateLabel(reset))}</p>` : ""}
|
|
295
|
+
${window.nextRegenAt ? `<p class="quota-foot">${tr("下次部分恢复", "Next partial recovery")}: ${escapeHtml(dateLabel(window.nextRegenAt))}${Number.isFinite(window.nextRegenPercent) ? ` · ${number(window.nextRegenPercent)}%` : ""}</p>` : ""}
|
|
296
|
+
</div>`;
|
|
297
|
+
}).join("")}
|
|
298
|
+
${balances.length ? `<dl class="usage-balances">${balances.map((balance) => `<div><dt>${escapeHtml(balance.label || balance.kind || balance.id || tr("余额", "Balance"))}${balance.scope ? ` · ${escapeHtml(balance.scope)}` : ""}</dt><dd>${escapeHtml(number(balance.amount))} ${escapeHtml(unitLabel(balance.unit, balance.currency))}${balance.expiresAt ? `<p class="quota-foot">${tr("到期", "Expires")}: ${escapeHtml(dateLabel(balance.expiresAt))}</p>` : ""}</dd></div>`).join("")}</dl>` : ""}
|
|
299
|
+
${snapshot && !windows.length && !balances.length ? `<p class="hint">${tr("服务端没有提供可显示的额度或余额。", "The service did not provide quota or balance values.")}</p>` : ""}
|
|
300
|
+
${(Array.isArray(snapshot?.notes) ? snapshot.notes : []).map((note) => `<p class="hint">${escapeHtml(usageNote(note))}</p>`).join("")}
|
|
301
|
+
${result?.status === "needs-permission" || result?.status === "needs-configuration" ? `<p class="hint">${tr("请在「连接配置」中补充查询授权或账户、工作区、项目范围。调用授权仍保持连接。", "Add the usage credential or account, workspace and project scope in Connection settings. Model authorization remains connected.")}</p>` : ""}
|
|
302
|
+
${result?.message ? `<p class="hint">${escapeHtml(result.message)}</p>` : ""}
|
|
303
|
+
${snapshot ? `<p class="quota-foot">${tr("数据时间", "Observed")}: ${escapeHtml(dateLabel(snapshot.observedAt || snapshot.fetchedAt))}${sourceText ? ` · ${tr("来源", "Source")}: ${escapeHtml(sourceText)}` : ""}</p>` : ""}
|
|
304
|
+
${result?.lastAttemptAt ? `<p class="quota-foot">${tr("最近查询", "Last attempt")}: ${escapeHtml(dateLabel(result.lastAttemptAt))}${result.lastErrorStatus ? ` · ${escapeHtml(usageStatus(result.lastErrorStatus))}` : ""}</p>` : ""}
|
|
305
|
+
${result?.retryAt ? `<p class="quota-foot">${tr("可重试时间", "Retry after")}: ${escapeHtml(dateLabel(result.retryAt))}</p>` : ""}
|
|
306
|
+
<button class="btn" type="button" data-usage="${escapeHtml(provider.id)}" ${busy || apiMode !== "live" ? "disabled" : ""}>${tr("刷新用量", "Refresh usage")}</button>
|
|
307
|
+
</section>`;
|
|
308
|
+
}
|
|
309
|
+
function renderList() {
|
|
310
|
+
const providers = shownProviders();
|
|
311
|
+
const connected = providers.filter((provider) => status[provider.id]?.loggedIn).length;
|
|
312
|
+
document.querySelector("#count").textContent = apiMode === "preview"
|
|
313
|
+
? tr(`静态示例 · ${connected}/${providers.length} 个示例连接。演示操作不会登录账号或保存真实凭据。`, `Static examples · ${connected}/${providers.length} connected. Demo actions do not sign in or save real credentials.`)
|
|
314
|
+
: apiMode === "checking" ? tr("正在连接本机 OAuth 服务…", "Connecting to the local OAuth service…")
|
|
315
|
+
: apiMode === "unavailable" ? tr("本机 OAuth 服务不可用。请检查 Harness 服务后刷新;当前显示上次读取的状态。", "Local OAuth service unavailable. Check Harness and refresh. Previously read status is shown.")
|
|
316
|
+
: tr(`已连接 ${connected}/${providers.length} 个提供商。凭据由本机服务保存。`, `${connected}/${providers.length} providers connected. Credentials are stored by the local service.`);
|
|
317
|
+
document.querySelector("#reset").hidden = apiMode !== "preview";
|
|
318
|
+
const lead = document.querySelector(".lead");
|
|
319
|
+
if (lead) lead.textContent = apiMode === "preview"
|
|
320
|
+
? tr("这是 dsh-oauth 的静态预览。示例授权和连接状态只用于查看界面,不会访问提供商或写入本机凭据。", "This is a static dsh-oauth preview. Example connections do not access providers or save credentials.")
|
|
321
|
+
: tr("连接订阅账号或套餐密钥,保存可用模型与能力,并查询提供商实际返回的套餐用量。", "Connect subscription accounts or plan keys, save models and capabilities, and view usage reported by the provider.");
|
|
322
|
+
document.querySelector("#rows").innerHTML = providers.map((provider) => {
|
|
323
|
+
const id = escapeHtml(provider.id);
|
|
324
|
+
const row = status[provider.id] || {};
|
|
325
|
+
const loggedIn = Boolean(row.loggedIn);
|
|
326
|
+
const browserReady = provider.id !== "xai" || apiMode === "preview" || provider.loginMethods?.includes("browser");
|
|
327
|
+
const oauth = !provider.authMethods || provider.authMethods.includes("oauth");
|
|
328
|
+
const pullExpiry = provider.pullExpiresAt ? expiresLabel(provider.pullExpiresAt) : "";
|
|
329
|
+
const pulled = Array.isArray(provider.pulledModels) ? provider.pulledModels : [];
|
|
330
|
+
const badges = [`<span class="badge">${flowLabel(provider)}</span>`, loggedIn ? `<span class="badge ok">${apiMode === "preview" ? tr("示例连接", "Example") : tr("已连接", "Connected")}</span>` : "", provider.pullPermanent && pulled.length ? `<span class="badge">${tr("模型持续启用", "Models stay enabled")}</span>` : "", pullExpiry === "expired" ? `<span class="badge bad">${tr("模型配置已到期", "Model configuration expired")}</span>` : pullExpiry ? `<span class="badge">${escapeHtml(pullExpiry)}</span>` : ""].join("");
|
|
331
|
+
const connection = provider.connection || {};
|
|
332
|
+
const context = [connection.label, connection.sourceLabel || provider.sourceLabel, connection.region, connection.organizationId, connection.workspaceId, connection.projectId].filter(Boolean);
|
|
333
|
+
const detail = loggedIn ? `<span class="meta connection-summary">${escapeHtml(context.join(" · ") || tr("授权已保存", "Authorization saved"))}</span><span class="meta">${pullSummary(pulled, provider)}</span>`
|
|
334
|
+
: `<span class="hint">${providerConnectionHint(provider)}</span>${provider.cli ? `<div class="cli"><code>${escapeHtml(provider.cli)}</code><button class="btn" type="button" data-copy="${id}">${tr("复制", "Copy")}</button></div>` : ""}`;
|
|
335
|
+
const disabled = pendingId || apiMode === "checking" || apiMode === "unavailable";
|
|
336
|
+
const action = loggedIn
|
|
337
|
+
? `${provider.pullable === false ? "" : `<button class="btn solid" type="button" data-pull="${id}" ${apiMode !== "live" || pendingId ? "disabled" : ""}>${tr("拉取模型", "Fetch models")}</button>`}${apiMode === "live" ? `<button class="btn" type="button" data-configure="${id}">${tr("连接配置", "Connection settings")}</button>${!usageOpen.has(provider.id) ? `<button class="btn" type="button" data-usage="${id}" ${usageBusy.has(provider.id) ? "disabled" : ""}>${tr("套餐与用量", "Plan & usage")}</button>` : ""}` : ""}<button class="btn" type="button" data-disconnect="${id}" ${disabled ? "disabled" : ""}>${apiMode === "preview" ? tr("移除示例", "Remove example") : tr("断开连接", "Disconnect")}</button>`
|
|
338
|
+
: `${oauth ? `<button class="btn solid" type="button" data-login="${id}" ${disabled || !browserReady ? "disabled" : ""}>${pendingId === provider.id ? tr("登录中", "Signing in") : apiMode === "preview" ? tr("演示登录", "Demo sign-in") : provider.id === "xai" ? tr("浏览器登录", "Browser sign-in") : tr("登录", "Sign in")}</button>` : ""}${provider.keyConnect && apiMode === "live" ? `<button class="btn ${oauth ? "" : "solid"}" type="button" data-connect="${id}" ${disabled ? "disabled" : ""}>${tr("连接密钥", "Connect key")}</button>` : ""}${provider.id === "xai" && apiMode !== "preview" ? `<button class="btn" type="button" data-login="xai" data-login-method="device" ${disabled ? "disabled" : ""}>${tr("设备码备用", "Use device code")}</button>` : ""}${provider.authMethods?.includes("local") && apiMode === "live" ? `<button class="btn" type="button" data-local="${id}">${tr("复用本机授权", "Reuse local authorization")}</button>` : ""}${!oauth && !provider.keyConnect && !provider.authMethods?.includes("local") && !provider.supportReason ? `<span class="hint">${tr("此来源尚未支持连接", "Connection not available for this source")}</span>` : ""}`;
|
|
339
|
+
return `<div class="row" data-provider="${id}"><div class="identity">${shield(loggedIn)}<div><div class="name-line"><span class="name">${escapeHtml(provider.name)}</span>${badges}</div>${detail}${row.error ? `<span class="err">${escapeHtml(row.error)}</span>` : ""}${!browserReady && apiMode === "live" ? `<span class="hint">${tr("当前服务尚未加载浏览器登录,请重新启动 DSH 以启用新版路线。", "Restart DSH to load browser sign-in support.")}</span>` : ""}${loggedIn ? usageHtml(provider) : ""}</div></div><div class="actions">${provider.docs && safeAuthorizationUrl(provider.docs) ? `<a class="icon-btn" href="${escapeHtml(provider.docs)}" target="_blank" rel="noopener noreferrer" aria-label="${escapeHtml(tr(`打开 ${provider.name} 文档`, `Open ${provider.name} documentation`))}">↗</a>` : ""}${action}${provider.cliCatalog && apiMode === "live" ? `<button class="btn" type="button" data-pull="${id}">${tr("查看 AGY CLI 模型", "View AGY CLI models")}</button>` : ""}${!loggedIn && provider.sourceStatus && provider.credentialConfigured ? `<button class="btn" type="button" data-disconnect="${id}">${tr("断开连接", "Disconnect")}</button>` : ""}</div></div>`;
|
|
340
|
+
}).join("");
|
|
341
|
+
}
|
|
342
|
+
async function refreshUsage(id) {
|
|
343
|
+
const provider = shownProviders().find((item) => item.id === id);
|
|
344
|
+
if (!provider || !status[id]?.loggedIn || apiMode !== "live" || usageBusy.has(id)) return;
|
|
345
|
+
usageOpen.add(id);
|
|
346
|
+
if (provider.usageSupported === false) {
|
|
347
|
+
usageResults.set(id, { status: "unsupported" }); renderList(); return;
|
|
348
|
+
}
|
|
349
|
+
const revision = revisions.get(id) || 0;
|
|
350
|
+
const previous = usageResults.get(id);
|
|
351
|
+
usageBusy.add(id); renderList();
|
|
352
|
+
try {
|
|
353
|
+
const result = await post("usage", { provider: id, force: Boolean(previous) });
|
|
354
|
+
if ((revisions.get(id) || 0) !== revision || !status[id]?.loggedIn) return;
|
|
355
|
+
usageResults.set(id, result);
|
|
356
|
+
} catch (error) {
|
|
357
|
+
if ((revisions.get(id) || 0) !== revision || !status[id]?.loggedIn) return;
|
|
358
|
+
usageResults.set(id, { status: previous?.snapshot ? "stale" : "unavailable", ...(previous?.snapshot ? { snapshot: previous.snapshot } : {}), message: error.message, lastAttemptAt: new Date().toISOString() });
|
|
359
|
+
} finally {
|
|
360
|
+
if ((revisions.get(id) || 0) === revision) usageBusy.delete(id);
|
|
361
|
+
renderList();
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function defaultLoginOpener(provider, preview = false) {
|
|
366
|
+
const url = new URL("auth.html", location.href);
|
|
367
|
+
url.searchParams.set("provider", provider.id);
|
|
368
|
+
url.searchParams.set("locale", locale);
|
|
369
|
+
if (preview) url.searchParams.set("preview", "1");
|
|
370
|
+
return provider.id === "xai" && !preview
|
|
371
|
+
? window.open(url.href, "_blank")
|
|
372
|
+
: window.open(url.href, "dsh-oauth-auth", "popup=yes,width=520,height=720");
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function safeAuthorizationUrl(value) {
|
|
376
|
+
try {
|
|
377
|
+
const url = new URL(value);
|
|
378
|
+
return url.protocol === "https:" || url.protocol === "http:" ? url.href : "";
|
|
379
|
+
} catch { return ""; }
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
function renderAuthorization() {
|
|
383
|
+
if (!activeLogin) return;
|
|
384
|
+
const { provider, snapshot = {}, uiError = "" } = activeLogin;
|
|
385
|
+
const key = JSON.stringify([locale, snapshot, uiError, activeLogin.popupClosed, activeLogin.popupBlocked]);
|
|
386
|
+
if (key === loginRenderKey) return;
|
|
387
|
+
loginRenderKey = key;
|
|
388
|
+
const root = document.querySelector("#modal");
|
|
389
|
+
const oldInput = root.querySelector("#authorization-answer");
|
|
390
|
+
const oldPromptId = oldInput?.dataset.promptId;
|
|
391
|
+
const oldValue = oldInput?.value;
|
|
392
|
+
const inputWasFocused = oldInput && document.activeElement === oldInput;
|
|
393
|
+
const selection = oldInput?.selectionStart;
|
|
394
|
+
const prompt = snapshot.prompt;
|
|
395
|
+
const terminal = snapshot.status && snapshot.status !== "pending";
|
|
396
|
+
const url = safeAuthorizationUrl(snapshot.url);
|
|
397
|
+
let input = "";
|
|
398
|
+
if (prompt) {
|
|
399
|
+
input = `<form id="authorization-form"><label class="expiry-label" for="authorization-answer">${escapeHtml(prompt.message)}</label>`;
|
|
400
|
+
if (prompt.kind === "select") {
|
|
401
|
+
input += `<select class="field" id="authorization-answer" data-prompt-id="${escapeHtml(prompt.id)}">${(prompt.options || []).map((option) => `<option value="${escapeHtml(option.id)}">${escapeHtml(option.label)}${option.description ? ` · ${escapeHtml(option.description)}` : ""}</option>`).join("")}</select>`;
|
|
402
|
+
} else {
|
|
403
|
+
input += `<input class="field" id="authorization-answer" data-prompt-id="${escapeHtml(prompt.id)}" type="${prompt.kind === "secret" ? "password" : "text"}" autocomplete="off" spellcheck="false" placeholder="${escapeHtml(prompt.placeholder || tr("粘贴提供商返回的授权信息", "Paste authorization information from the provider"))}" />`;
|
|
404
|
+
}
|
|
405
|
+
input += `<div class="row-actions"><button class="btn solid" type="submit" id="submit-authorization-answer">${tr("提交授权输入", "Submit authorization input")}</button></div></form>`;
|
|
406
|
+
}
|
|
407
|
+
const message = snapshot.status === "authorized" ? tr("本次授权已完成,正在刷新本机凭据状态。", "Authorization completed. Refreshing locally saved credentials.")
|
|
408
|
+
: snapshot.status === "cancelled" ? tr("本次登录已取消。", "This sign-in was cancelled.")
|
|
409
|
+
: snapshot.status === "error" ? tr("本次登录失败。", "This sign-in failed.")
|
|
410
|
+
: snapshot.message || tr("正在启动提供商登录,请稍候。", "Starting provider sign-in. Please wait.");
|
|
411
|
+
modalStart();
|
|
412
|
+
root.hidden = false;
|
|
413
|
+
root.innerHTML = `<div class="overlay"><div class="dialog pull-dialog" role="dialog" aria-modal="true" aria-labelledby="authorization-title">
|
|
414
|
+
<h2 id="authorization-title">${escapeHtml(tr(`登录 ${provider.name}`, `Sign in to ${provider.name}`))}</h2>
|
|
415
|
+
<p class="hint" role="status">${escapeHtml(message)}</p>
|
|
416
|
+
${snapshot.code ? `<p class="hint">${tr("在提供商页面输入设备码:", "Enter this device code on the provider page: ")}<code style="user-select:all;font-size:18px">${escapeHtml(snapshot.code)}</code></p>` : ""}
|
|
417
|
+
${url && !terminal ? `<p><a class="btn" href="${escapeHtml(url)}" target="_blank" rel="noopener noreferrer">${tr("打开提供商授权页", "Open provider authorization")}</a></p>` : ""}
|
|
418
|
+
${url && !terminal && provider.id === "xai" ? `<p class="hint">${activeLogin.method === "device" ? tr("正在使用设备码备用路线。若审批页无法验证浏览器,可取消后改用浏览器登录。", "Using the device-code fallback. If browser verification fails, cancel and use browser sign-in.") : tr("正在使用浏览器 PKCE 登录。若浏览器仍无法验证,可复制此链接到另一个常用浏览器中打开,完成后会自动返回本机。", "Using browser PKCE sign-in. You can copy the link into another browser; authorization will return to this local service.")}</p><p><button class="btn" type="button" id="copy-authorization-url">${tr("复制授权链接", "Copy authorization link")}</button></p>` : ""}
|
|
419
|
+
${activeLogin.popupBlocked && !terminal ? `<p class="hint">${tr("浏览器拦截了弹窗。授权链接就绪后可点上方按钮继续。", "The browser blocked the popup. Use the link above when it is ready.")}</p>` : ""}
|
|
420
|
+
${activeLogin.popupClosed && !terminal ? `<p class="hint">${tr("授权窗口已关闭。仍可在这里粘贴授权信息,或取消本次登录。", "The authorization window closed. You can still enter authorization information here or cancel.")}</p>` : ""}
|
|
421
|
+
${input}
|
|
422
|
+
${snapshot.error || uiError ? `<p class="err" role="alert">${escapeHtml(uiError || snapshot.error)}</p>` : ""}
|
|
423
|
+
<div class="row-actions"><button class="btn" type="button" id="${terminal ? "close-authorization" : "cancel-authorization"}">${terminal ? tr("关闭", "Close") : tr("取消登录", "Cancel sign-in")}</button></div>
|
|
424
|
+
</div></div>`;
|
|
425
|
+
const newInput = root.querySelector("#authorization-answer");
|
|
426
|
+
if (newInput && oldPromptId === prompt?.id && oldValue !== undefined) {
|
|
427
|
+
newInput.value = oldValue;
|
|
428
|
+
if (inputWasFocused) { newInput.focus?.(); if (typeof selection === "number" && newInput.type !== "select-one") newInput.setSelectionRange?.(selection, selection); }
|
|
429
|
+
}
|
|
430
|
+
focusDialog();
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function cleanupLogin(closePopup = false) {
|
|
434
|
+
window.clearTimeout(loginPoll);
|
|
435
|
+
window.clearInterval(popupWatch);
|
|
436
|
+
if (closePopup && authPopup && !authPopup.closed) authPopup.close();
|
|
437
|
+
pendingId = null;
|
|
438
|
+
activeLogin = null;
|
|
439
|
+
loginRenderKey = "";
|
|
440
|
+
renderList();
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
async function acceptLoginSnapshot(login, snapshot) {
|
|
444
|
+
if (activeLogin !== login || unloaded) return;
|
|
445
|
+
login.snapshot = snapshot;
|
|
446
|
+
login.uiError = "";
|
|
447
|
+
const url = safeAuthorizationUrl(snapshot.url);
|
|
448
|
+
if (snapshot.status === "pending" && url && login.openedUrl !== url && authPopup && !authPopup.closed) {
|
|
449
|
+
try {
|
|
450
|
+
authPopup.location.replace(url);
|
|
451
|
+
login.openedUrl = url;
|
|
452
|
+
} catch { login.popupBlocked = true; }
|
|
453
|
+
}
|
|
454
|
+
renderAuthorization();
|
|
455
|
+
if (snapshot.status === "authorized") {
|
|
456
|
+
const refreshed = await refreshRemote();
|
|
457
|
+
if (activeLogin !== login) return;
|
|
458
|
+
if (refreshed && status[login.provider.id]?.loggedIn) {
|
|
459
|
+
cleanupLogin(true);
|
|
460
|
+
closeModal();
|
|
461
|
+
toast(tr(`${login.provider.name} 已连接`, `${login.provider.name} connected`));
|
|
462
|
+
} else {
|
|
463
|
+
login.uiError = tr("授权已结束,但尚未读取到本机凭据。请刷新提供商状态确认。", "Authorization ended, but local credentials have not been confirmed. Refresh the provider status.");
|
|
464
|
+
pendingId = null;
|
|
465
|
+
renderAuthorization();
|
|
466
|
+
renderList();
|
|
467
|
+
}
|
|
468
|
+
return;
|
|
469
|
+
}
|
|
470
|
+
if (snapshot.status && snapshot.status !== "pending") {
|
|
471
|
+
pendingId = null;
|
|
472
|
+
window.clearInterval(popupWatch);
|
|
473
|
+
if (authPopup && !authPopup.closed) authPopup.close();
|
|
474
|
+
await refreshRemote();
|
|
475
|
+
renderList();
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
loginPoll = window.setTimeout(() => void pollLogin(login), 1000);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
async function pollLogin(login) {
|
|
482
|
+
if (activeLogin !== login || unloaded) return;
|
|
483
|
+
try {
|
|
484
|
+
const response = await fetch(`/oauth/api/login/status?provider=${encodeURIComponent(login.provider.id)}`, { cache: "no-store" });
|
|
485
|
+
const body = await response.json();
|
|
486
|
+
if (!response.ok) throw new Error(body.error || tr("无法读取登录状态", "Could not read sign-in status"));
|
|
487
|
+
await acceptLoginSnapshot(login, body);
|
|
488
|
+
} catch (error) {
|
|
489
|
+
if (activeLogin !== login) return;
|
|
490
|
+
login.uiError = `${error.message || tr("无法读取登录状态", "Could not read sign-in status")} ${tr("可稍后重试或取消。", "Retry later or cancel.")}`;
|
|
491
|
+
renderAuthorization();
|
|
492
|
+
loginPoll = window.setTimeout(() => void pollLogin(login), 2000);
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
async function openLogin(id, method = "browser") {
|
|
497
|
+
const provider = shownProviders().find((item) => item.id === id);
|
|
498
|
+
if (!provider || pendingId || apiMode === "checking" || apiMode === "unavailable") return;
|
|
499
|
+
if (id === "xai" && method === "browser" && apiMode === "live" && !provider.loginMethods?.includes("browser")) {
|
|
500
|
+
toast(tr("请重新启动 DSH,以加载新版浏览器登录路线", "Restart DSH to load browser sign-in support"));
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
if (authPopup && !authPopup.closed) authPopup.close();
|
|
504
|
+
const preview = apiMode === "preview";
|
|
505
|
+
const custom = preview ? window.DshOAuth.loginOpener() : null;
|
|
506
|
+
// This call must remain in the click stack, before any awaited API request.
|
|
507
|
+
authPopup = custom ? custom(provider) : defaultLoginOpener(provider, preview);
|
|
508
|
+
pendingId = id;
|
|
509
|
+
renderList();
|
|
510
|
+
if (preview) {
|
|
511
|
+
if (!authPopup) {
|
|
512
|
+
pendingId = null;
|
|
513
|
+
renderList();
|
|
514
|
+
toast(tr("浏览器拦截了示例窗口", "The browser blocked the example window"));
|
|
515
|
+
return;
|
|
516
|
+
}
|
|
517
|
+
window.clearInterval(popupWatch);
|
|
518
|
+
popupWatch = window.setInterval(() => {
|
|
519
|
+
if (authPopup?.closed && pendingId === id) {
|
|
520
|
+
window.clearInterval(popupWatch);
|
|
521
|
+
pendingId = null;
|
|
522
|
+
renderList();
|
|
523
|
+
}
|
|
524
|
+
}, 400);
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
const login = { provider, method, snapshot: { status: "pending" }, popupBlocked: !authPopup };
|
|
528
|
+
activeLogin = login;
|
|
529
|
+
renderAuthorization();
|
|
530
|
+
window.clearInterval(popupWatch);
|
|
531
|
+
popupWatch = window.setInterval(() => {
|
|
532
|
+
if (activeLogin !== login) return window.clearInterval(popupWatch);
|
|
533
|
+
if (authPopup?.closed && !login.popupClosed) {
|
|
534
|
+
login.popupClosed = true;
|
|
535
|
+
renderAuthorization();
|
|
536
|
+
}
|
|
537
|
+
}, 400);
|
|
538
|
+
try {
|
|
539
|
+
const response = await fetch("/oauth/api/login", {
|
|
540
|
+
method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ provider: id, ...(id === "xai" ? { method } : {}) }),
|
|
541
|
+
});
|
|
542
|
+
const body = await response.json();
|
|
543
|
+
if (!response.ok) throw new Error(body.error || tr("登录没有开始", "Sign-in did not start"));
|
|
544
|
+
await acceptLoginSnapshot(login, body);
|
|
545
|
+
} catch (error) {
|
|
546
|
+
if (activeLogin !== login) return;
|
|
547
|
+
await acceptLoginSnapshot(login, { status: "error", error: error.message || tr("登录没有开始", "Sign-in did not start") });
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
async function submitAuthorization(event) {
|
|
552
|
+
if (event.target.id !== "authorization-form") return;
|
|
553
|
+
event.preventDefault();
|
|
554
|
+
const login = activeLogin;
|
|
555
|
+
const prompt = login?.snapshot?.prompt;
|
|
556
|
+
if (!prompt) return;
|
|
557
|
+
const input = document.querySelector("#authorization-answer");
|
|
558
|
+
const value = input.value;
|
|
559
|
+
const button = document.querySelector("#submit-authorization-answer");
|
|
560
|
+
button.disabled = true;
|
|
561
|
+
window.clearTimeout(loginPoll);
|
|
562
|
+
try {
|
|
563
|
+
const response = await fetch("/oauth/api/login/answer", {
|
|
564
|
+
method: "POST", headers: { "content-type": "application/json" },
|
|
565
|
+
body: JSON.stringify({ provider: login.provider.id, attemptId: login.snapshot.attemptId, promptId: prompt.id, value }),
|
|
566
|
+
});
|
|
567
|
+
const body = await response.json();
|
|
568
|
+
if (!response.ok) throw new Error(body.error || tr("授权输入没有提交", "Authorization input was not submitted"));
|
|
569
|
+
input.value = "";
|
|
570
|
+
await acceptLoginSnapshot(login, body);
|
|
571
|
+
} catch (error) {
|
|
572
|
+
if (activeLogin !== login) return;
|
|
573
|
+
login.uiError = error.message || tr("授权输入没有提交", "Authorization input was not submitted");
|
|
574
|
+
renderAuthorization();
|
|
575
|
+
loginPoll = window.setTimeout(() => void pollLogin(login), 1000);
|
|
576
|
+
} finally { if (button.isConnected) button.disabled = false; }
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
async function cancelAuthorization() {
|
|
580
|
+
const login = activeLogin;
|
|
581
|
+
if (!login) return;
|
|
582
|
+
if (!login.snapshot.attemptId) {
|
|
583
|
+
login.uiError = tr("登录仍在启动,请等待服务返回后再取消。", "Sign-in is still starting. Wait for the service before cancelling.");
|
|
584
|
+
renderAuthorization();
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
window.clearTimeout(loginPoll);
|
|
588
|
+
try {
|
|
589
|
+
const response = await fetch("/oauth/api/login/cancel", {
|
|
590
|
+
method: "POST", headers: { "content-type": "application/json" },
|
|
591
|
+
body: JSON.stringify({ provider: login.provider.id, attemptId: login.snapshot.attemptId }),
|
|
592
|
+
});
|
|
593
|
+
const body = await response.json();
|
|
594
|
+
if (!response.ok) throw new Error(body.error || tr("未能取消登录", "Could not cancel sign-in"));
|
|
595
|
+
await acceptLoginSnapshot(login, body);
|
|
596
|
+
} catch (error) {
|
|
597
|
+
if (activeLogin !== login) return;
|
|
598
|
+
login.uiError = error.message || tr("未能取消登录", "Could not cancel sign-in");
|
|
599
|
+
renderAuthorization();
|
|
600
|
+
loginPoll = window.setTimeout(() => void pollLogin(login), 1000);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
window.addEventListener("message", async (event) => {
|
|
605
|
+
const sameOrigin = location.protocol === "file:" ? event.origin === "null" : event.origin === location.origin;
|
|
606
|
+
if (apiMode !== "preview" || !sameOrigin || event.source !== authPopup) return;
|
|
607
|
+
const data = event.data;
|
|
608
|
+
if (!data || data.type !== "dsh-oauth-preview") return;
|
|
609
|
+
const provider = PROVIDERS.find((item) => item.id === data.provider);
|
|
610
|
+
if (!provider || pendingId !== provider.id) return;
|
|
611
|
+
if (!data.ok) {
|
|
612
|
+
pendingId = null;
|
|
613
|
+
renderList();
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
const allowed = await window.DshOAuth.runAuthorizeHooks(provider);
|
|
617
|
+
pendingId = null;
|
|
618
|
+
window.clearInterval(popupWatch);
|
|
619
|
+
if (allowed) {
|
|
620
|
+
status[provider.id] = { loggedIn: true, tokenPreview: "示例,无真实凭据", sourceLabel: "静态预览", error: "" };
|
|
621
|
+
save();
|
|
622
|
+
}
|
|
623
|
+
renderList();
|
|
624
|
+
toast(allowed ? tr(`${provider.name} 示例已连接,未登录真实账号`, `${provider.name} example connected. No real account was signed in.`) : tr("示例连接未保存", "Example connection was not saved"));
|
|
625
|
+
});
|
|
626
|
+
|
|
627
|
+
window.addEventListener("pagehide", () => {
|
|
628
|
+
unloaded = true;
|
|
629
|
+
window.clearTimeout(loginPoll);
|
|
630
|
+
window.clearInterval(popupWatch);
|
|
631
|
+
const login = activeLogin;
|
|
632
|
+
if (login?.snapshot.status === "pending" && login.snapshot.attemptId) {
|
|
633
|
+
const body = JSON.stringify({ provider: login.provider.id, attemptId: login.snapshot.attemptId });
|
|
634
|
+
let sent = false;
|
|
635
|
+
try { sent = Boolean(navigator.sendBeacon?.("/oauth/api/login/cancel", new Blob([body], { type: "application/json" }))); } catch { /* Use keepalive when Beacon is unavailable. */ }
|
|
636
|
+
if (!sent) void fetch("/oauth/api/login/cancel", { method: "POST", headers: { "content-type": "application/json" }, body, keepalive: true }).catch(() => {});
|
|
637
|
+
}
|
|
638
|
+
});
|
|
639
|
+
window.addEventListener("pageshow", (event) => {
|
|
640
|
+
if (event.persisted) {
|
|
641
|
+
unloaded = false;
|
|
642
|
+
cleanupLogin(true);
|
|
643
|
+
closeModal();
|
|
644
|
+
void refreshRemote();
|
|
645
|
+
}
|
|
646
|
+
});
|
|
647
|
+
|
|
648
|
+
let pendingDisconnect = null;
|
|
649
|
+
|
|
650
|
+
function escapeHtml(value) {
|
|
651
|
+
return String(value).replace(/[&<>"']/g, (ch) => ({
|
|
652
|
+
"&": "&",
|
|
653
|
+
"<": "<",
|
|
654
|
+
">": ">",
|
|
655
|
+
"\"": """,
|
|
656
|
+
"'": "'",
|
|
657
|
+
})[ch]);
|
|
658
|
+
}
|
|
659
|
+
|
|
660
|
+
function localStamp(date) {
|
|
661
|
+
const pad = (value) => String(value).padStart(2, "0");
|
|
662
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
function capabilitySummary(model) {
|
|
666
|
+
const items = [];
|
|
667
|
+
const modalities = (values) => (Array.isArray(values) ? values : []).map((value) => ({ text: tr("文本", "text"), image: tr("图像", "image"), video: tr("视频", "video"), audio: tr("音频", "audio"), file: tr("文件", "file") })[value] || value).join(" / ");
|
|
668
|
+
if (model.input?.length) items.push(tr("输入", "Input") + ": " + modalities(model.input));
|
|
669
|
+
if (model.output?.length) items.push(tr("输出", "Output") + ": " + modalities(model.output));
|
|
670
|
+
if (typeof model.tools === "boolean") items.push(model.tools ? tr("支持工具", "Tools supported") : tr("不支持工具", "No tools"));
|
|
671
|
+
if (model.contextWindow) items.push(tr("上下文", "Context") + ": " + number(model.contextWindow));
|
|
672
|
+
if (model.maxTokens) items.push(tr("最大输出", "Max output") + ": " + number(model.maxTokens));
|
|
673
|
+
const reasoning = Array.isArray(model.reasoningEfforts) ? model.reasoningEfforts : model.reasoningEfforts && typeof model.reasoningEfforts === "object" ? Object.keys(model.reasoningEfforts) : [];
|
|
674
|
+
if (reasoning.length) items.push(tr("推理", "Reasoning") + ": " + reasoning.join(" / "));
|
|
675
|
+
else if (model.reasoningEfforts === false) items.push(tr("不支持可选推理档位", "No selectable reasoning levels"));
|
|
676
|
+
return items.join(" · ") || tr("能力信息未提供", "Capabilities not provided");
|
|
677
|
+
}
|
|
678
|
+
function modelEvidence(model) {
|
|
679
|
+
const source = typeof model.source === "string" ? model.source : model.source?.kind;
|
|
680
|
+
const entitlement = model.entitlement;
|
|
681
|
+
const known = entitlement === "included" || entitlement === "verified" || entitlement === true;
|
|
682
|
+
const text = entitlement === "account" ? tr("账户接口返回的目录;实际调用仍受账户权限和额度限制", "Account catalog; access remains subject to account permissions and allowance")
|
|
683
|
+
: entitlement === "subscription" ? tr("订阅接口返回的目录;实际调用仍受套餐权限和额度限制", "Subscription catalog; access remains subject to plan permissions and allowance")
|
|
684
|
+
: known ? tr("已由来源确认权益", "Entitlement confirmed by source") : tr("套餐权益未确认", "Plan entitlement unconfirmed");
|
|
685
|
+
return (source ? `${tr("目录来源", "Catalog source")}: ${source} · ` : "") + text;
|
|
686
|
+
}
|
|
687
|
+
function renderPull(provider, models, error) {
|
|
688
|
+
const root = document.querySelector("#modal");
|
|
689
|
+
root.hidden = false;
|
|
690
|
+
if (provider.cliCatalog) {
|
|
691
|
+
root.innerHTML = `<div class="overlay" data-backdrop="1"><div class="dialog pull-dialog" role="dialog" aria-modal="true" aria-labelledby="pull-title">
|
|
692
|
+
<h2 id="pull-title">${tr("AGY CLI 模型目录", "AGY CLI model catalog")}</h2>
|
|
693
|
+
<p class="hint">${tr("目录由 AGY CLI 返回。通过 AGY 使用这些模型,在 CLI 中输入 /usage 查看套餐用量。", "Use these models with AGY CLI. Enter /usage there for plan quota.")}</p>
|
|
694
|
+
${error ? `<p class="err" role="alert">${escapeHtml(error)}</p>` : `<ul class="choices">${models.map(model => `<li class="choice"><span>${escapeHtml(model.name)}</span><code>${escapeHtml(model.id)}</code></li>`).join("")}</ul>`}
|
|
695
|
+
<div class="row-actions"><button class="btn" type="button" id="cancel-pull">${tr("关闭", "Close")}</button></div></div></div>`;
|
|
696
|
+
focusDialog();
|
|
697
|
+
return;
|
|
698
|
+
}
|
|
699
|
+
const chat = models.filter((model) => !model.role || model.role === "chat");
|
|
700
|
+
const media = models.filter((model) => model.role === "image" || model.role === "video");
|
|
701
|
+
const selected = new Set((provider.pulledModels || []).map((model) => model.id));
|
|
702
|
+
const choices = error ? "" : chat.map((model) => `<label class="choice"><input type="checkbox" value="${escapeHtml(model.id)}" ${selected.size === 0 || selected.has(model.id) ? "checked" : ""} /><span>${escapeHtml(model.name || model.id)}</span><code>${escapeHtml(model.id)}</code><span class="model-capabilities">${escapeHtml(capabilitySummary(model))}</span><span class="model-capabilities">${escapeHtml(modelEvidence(model))}</span></label>`).join("");
|
|
703
|
+
root.innerHTML = `<div class="overlay" data-backdrop="1"><div class="dialog pull-dialog" role="dialog" aria-modal="true" aria-labelledby="pull-title">
|
|
704
|
+
<h2 id="pull-title">${escapeHtml(tr(`从 ${provider.name} 拉取模型`, `Fetch models from ${provider.name}`))}</h2>
|
|
705
|
+
<p class="hint">${tr("模型能力按来源返回的信息显示。公共目录不代表当前套餐已包含,也不会发推理请求来验证。", "Capabilities are shown as reported by the source. A public catalog does not confirm plan entitlement; no inference is sent to test access.")}</p>
|
|
706
|
+
${media.length ? `<p class="hint">${tr("媒体模型将自动配置:", "Media models are configured automatically: ")}${media.map((model) => escapeHtml(model.name || model.id)).join(", ")}</p>${media.map((model) => `<p class="hint">${escapeHtml(model.name || model.id)} · ${escapeHtml(capabilitySummary(model))}</p>`).join("")}` : ""}
|
|
707
|
+
${error ? `<p class="err" role="alert">${escapeHtml(error)}</p>` : `<div class="select-tools"><span class="hint">${tr(`选择对话模型(${chat.length})`, `Select chat models (${chat.length})`)}</span><button class="btn" type="button" id="toggle-models">${tr("全选 / 清空", "Select all / clear")}</button></div><div class="choices">${choices || `<p class="hint">${tr("此来源未返回对话模型。", "This source returned no chat models.")}</p>`}</div>`}
|
|
708
|
+
<label class="retention-option"><input type="radio" name="retention" value="permanent" id="pull-permanent" ${provider.pullExpiresAt && !provider.pullPermanent ? "" : "checked"} />${tr("持续启用(默认)", "Keep enabled (default)")}</label>
|
|
709
|
+
<label class="retention-option"><input type="radio" name="retention" value="until" id="pull-until" ${provider.pullExpiresAt && !provider.pullPermanent ? "checked" : ""} />${tr("保留至指定时间", "Keep until a selected date")}</label>
|
|
710
|
+
<label class="expiry-label" for="pull-expiry">${tr("模型配置到期时间", "Model configuration expiry")}</label><input class="field" id="pull-expiry" type="datetime-local" />
|
|
711
|
+
<p class="hint">${tr("持续启用只保留本机模型配置,不保证永久免登录。凭据由本机服务保存;授权撤销或失效时仍需重新连接。", "Keeping models enabled preserves local configuration. Credentials remain in the local service; revoked or expired authorization can still require reconnecting.")}</p>
|
|
712
|
+
<div class="chips"><button class="btn" type="button" data-hours="24">${tr("1 天", "1 day")}</button><button class="btn" type="button" data-hours="168">${tr("7 天", "7 days")}</button><button class="btn" type="button" data-hours="720">${tr("30 天", "30 days")}</button></div>
|
|
713
|
+
<p class="err form-error" id="pull-error" role="alert"></p><div class="row-actions"><button class="btn" type="button" id="cancel-pull">${tr("取消", "Cancel")}</button><button class="btn solid" type="button" id="confirm-pull" ${error || !chat.length || pullSaving ? "disabled" : ""}>${tr("写入所选模型", "Save selected models")}</button></div>
|
|
714
|
+
</div></div>`;
|
|
715
|
+
const field = document.querySelector("#pull-expiry");
|
|
716
|
+
field.value = localStamp(provider.pullExpiresAt ? new Date(provider.pullExpiresAt) : new Date(Date.now() + 24 * 60 * 60 * 1000));
|
|
717
|
+
syncRetention(); focusDialog();
|
|
718
|
+
}
|
|
719
|
+
function syncRetention() {
|
|
720
|
+
const field = document.querySelector("#pull-expiry");
|
|
721
|
+
if (field) field.disabled = Boolean(document.querySelector("#pull-permanent")?.checked);
|
|
722
|
+
}
|
|
723
|
+
async function openPull(id) {
|
|
724
|
+
const provider = shownProviders().find((item) => item.id === id);
|
|
725
|
+
if (!provider || apiMode !== "live") return;
|
|
726
|
+
modalStart();
|
|
727
|
+
pullSaving = false;
|
|
728
|
+
const serial = ++modalSerial;
|
|
729
|
+
const root = document.querySelector("#modal");
|
|
730
|
+
root.hidden = false;
|
|
731
|
+
root.innerHTML = `<div class="overlay"><div class="dialog" role="dialog" aria-modal="true" aria-labelledby="loading-title"><h2 id="loading-title">${escapeHtml(tr(`正在拉取 ${provider.name}`, `Fetching ${provider.name}`))}</h2><p class="hint">${tr("正在读取模型目录与能力信息。", "Reading the model catalog and capabilities.")}</p></div></div>`;
|
|
732
|
+
focusDialog();
|
|
733
|
+
let models = [], error = "";
|
|
734
|
+
try { const body = await post("models", { provider: id, ...(provider.cliCatalog ? { source: "agy" } : {}) }); models = Array.isArray(body.models) ? body.models : []; }
|
|
735
|
+
catch (cause) { error = cause.message; }
|
|
736
|
+
if (serial !== modalSerial) return;
|
|
737
|
+
pullModels = models; pullError = error;
|
|
738
|
+
renderPull(provider, models, error);
|
|
739
|
+
}
|
|
740
|
+
async function confirmPull(id) {
|
|
741
|
+
if (pullSaving) return;
|
|
742
|
+
const serial = modalSerial;
|
|
743
|
+
const provider = shownProviders().find((item) => item.id === id);
|
|
744
|
+
const picked = [...document.querySelectorAll(".choice input:checked")].map((input) => input.value);
|
|
745
|
+
const permanent = document.querySelector("#pull-permanent")?.checked;
|
|
746
|
+
const raw = document.querySelector("#pull-expiry")?.value;
|
|
747
|
+
const expiresAt = permanent ? null : raw ? new Date(raw).getTime() : NaN;
|
|
748
|
+
const errorNode = document.querySelector("#pull-error");
|
|
749
|
+
if (!permanent && (!Number.isFinite(expiresAt) || expiresAt <= Date.now() || expiresAt > Date.now() + 366 * 24 * 60 * 60 * 1000)) { errorNode.textContent = tr("请选择未来 366 天内的到期时间。", "Choose an expiry date within the next 366 days."); return; }
|
|
750
|
+
if (!picked.length) { errorNode.textContent = tr("请至少选择一个对话模型。", "Select at least one chat model."); return; }
|
|
751
|
+
pullSaving = true;
|
|
752
|
+
const button = document.querySelector("#confirm-pull"); button.disabled = true;
|
|
753
|
+
try {
|
|
754
|
+
const body = await post("pull", { provider: id, models: picked, expiresAt });
|
|
755
|
+
if (serial === modalSerial) closeModal();
|
|
756
|
+
await refreshRemote();
|
|
757
|
+
toast(tr(`${provider?.name || id} 已写入 ${body.models?.length || picked.length} 个模型`, `Models saved for ${provider?.name || id}: ${body.models?.length || picked.length}`));
|
|
758
|
+
} catch (error) { if (serial === modalSerial) document.querySelector("#pull-error").textContent = error.message; }
|
|
759
|
+
finally { pullSaving = false; if (serial === modalSerial) { const current = document.querySelector("#confirm-pull"); if (current) current.disabled = false; } }
|
|
760
|
+
}
|
|
761
|
+
let pullTarget = null;
|
|
762
|
+
|
|
763
|
+
function renderConnection() {
|
|
764
|
+
const { provider, configure } = connectionTarget;
|
|
765
|
+
const connection = provider.connection || {};
|
|
766
|
+
const field = (id, label, value = "", placeholder = "") => `<label class="expiry-label" for="connection-${id}">${label}</label><input class="field" id="connection-${id}" name="${id}" value="${escapeHtml(value)}" placeholder="${escapeHtml(placeholder)}" maxlength="200" autocomplete="off" />`;
|
|
767
|
+
const root = document.querySelector("#modal"); root.hidden = false;
|
|
768
|
+
root.innerHTML = `<div class="overlay" data-backdrop="1"><div class="dialog pull-dialog" role="dialog" aria-modal="true" aria-labelledby="connection-title"><h2 id="connection-title">${escapeHtml(configure ? tr(`${provider.name} 连接配置`, `${provider.name} connection settings`) : tr(`连接 ${provider.name}`, `Connect ${provider.name}`))}</h2>
|
|
769
|
+
<form id="connection-form" class="connection-form">
|
|
770
|
+
${!configure ? `<label class="expiry-label" for="connection-access">${tr("调用密钥或访问令牌", "Model API key or access token")}</label><input class="field" id="connection-access" name="access" type="password" required autocomplete="new-password" spellcheck="false" /><p class="hint">${tr("只保存到本机凭据服务,不在页面或浏览器存储中保留。", "Saved in the local credential service, not in browser storage.")}</p>` : `<p class="hint">${tr("调用授权已保存。这里可补充用量查询授权和账号范围。", "Model authorization is saved. Add usage-query credentials and account scope here.")}</p>`}
|
|
771
|
+
<label class="expiry-label" for="connection-billing">${tr("用量查询密钥(可选)", "Usage-query key (optional)")}</label><input class="field" id="connection-billing" name="billingAccess" type="password" autocomplete="new-password" spellcheck="false" placeholder="${provider.billingCredentialConfigured ? tr("已配置,留空保留", "Configured; leave blank to keep") : tr("仅查询接口需要独立权限时填写", "Only if usage queries need a separate credential")}" />
|
|
772
|
+
<p class="hint">${tr("例如 ZenMux 需要 Management key;查询权限不代表模型调用权限。请使用同一账户或所选组织。", "For example, ZenMux requires a Management key. Usage permission and model access are separate. Use the same account or selected organization.")}</p>
|
|
773
|
+
${configure && provider.authMethods?.includes("local") ? `<button class="btn" type="button" data-local="${escapeHtml(provider.id)}">${tr("改用本机 CLI 管理的授权", "Use CLI-managed authorization")}</button>` : ""}
|
|
774
|
+
${provider.id === "new-api" ? `<label class="expiry-label" for="connection-baseURL">${tr("部署 API 地址(必填)", "Deployment API URL (required)")}</label><input class="field" id="connection-baseURL" name="baseURL" type="url" required value="${escapeHtml(connection.baseURL || "")}" placeholder="https://api.example.com/v1" autocomplete="off" spellcheck="false" /><p class="hint">${tr("填写你信任的公网 HTTPS API 根地址,包含 /v1。此地址将接收调用密钥。", "Enter the public HTTPS API root you trust, including /v1. Your model key will be sent to this host.")}</p>` : ""}
|
|
775
|
+
${field("label", tr("连接名称(可选)", "Connection label (optional)"), connection.label || "")}
|
|
776
|
+
<details class="scope-fields" ${[connection.region, connection.organizationId, connection.workspaceId, connection.projectId].some(Boolean) ? "open" : ""}><summary>${tr("地区、组织与项目范围(按提供商要求)", "Region, organization and project scope (when required)")}</summary>
|
|
777
|
+
<label class="expiry-label" for="connection-region">${tr("地区(与界面语言无关)", "Region (independent of interface language)")}</label><select class="field" id="connection-region" name="region"><option value="global" ${!connection.region || connection.region === "global" ? "selected" : ""}>${tr("国际 / Global(默认)", "Global (default)")}</option><option value="cn" ${connection.region === "cn" ? "selected" : ""}>${tr("中国 / China", "China")}</option>${connection.region && !["global", "cn"].includes(connection.region) ? `<option selected value="${escapeHtml(connection.region)}">${escapeHtml(connection.region)}</option>` : ""}</select>
|
|
778
|
+
${field("organizationId", tr("组织 ID", "Organization ID"), connection.organizationId || "")}
|
|
779
|
+
${field("workspaceId", tr("工作区 ID", "Workspace ID"), connection.workspaceId || "")}
|
|
780
|
+
${field("projectId", tr("项目 ID", "Project ID"), connection.projectId || "")}
|
|
781
|
+
</details><p class="err form-error" id="connection-error" role="alert"></p><div class="row-actions"><button class="btn" type="button" id="cancel-connection">${tr("取消", "Cancel")}</button><button class="btn solid" type="submit" id="save-connection" ${connectionTarget.saving ? "disabled" : ""}>${configure ? tr("保存配置", "Save settings") : tr("保存并连接", "Save and connect")}</button></div>
|
|
782
|
+
</form></div></div>`;
|
|
783
|
+
focusDialog();
|
|
784
|
+
}
|
|
785
|
+
function openConnection(id, configure) {
|
|
786
|
+
const provider = shownProviders().find((item) => item.id === id);
|
|
787
|
+
if (!provider || apiMode !== "live" || pendingId) return;
|
|
788
|
+
modalStart(); ++modalSerial; connectionTarget = { provider, configure }; renderConnection();
|
|
789
|
+
}
|
|
790
|
+
async function saveConnection(event) {
|
|
791
|
+
if (event.target.id !== "connection-form") return;
|
|
792
|
+
event.preventDefault();
|
|
793
|
+
const target = connectionTarget;
|
|
794
|
+
if (!target) return;
|
|
795
|
+
const form = event.target;
|
|
796
|
+
const data = new FormData(form);
|
|
797
|
+
const body = { provider: target.provider.id };
|
|
798
|
+
for (const key of ["access", "billingAccess", "label", "region", "organizationId", "workspaceId", "projectId", "baseURL"]) {
|
|
799
|
+
const raw = data.get(key);
|
|
800
|
+
if (typeof raw !== "string") continue;
|
|
801
|
+
const value = raw.trim();
|
|
802
|
+
if (["access", "billingAccess"].includes(key)) { if (value) body[key] = value; }
|
|
803
|
+
else if (target.configure ? value !== (target.provider.connection?.[key] || (key === "region" ? "global" : "")) : value) body[key] = value;
|
|
804
|
+
}
|
|
805
|
+
if (target.provider.id === "new-api") {
|
|
806
|
+
try {
|
|
807
|
+
const endpoint = new URL(data.get("baseURL"));
|
|
808
|
+
if (endpoint.protocol !== "https:" || endpoint.username || endpoint.password || endpoint.search || endpoint.hash) throw new Error();
|
|
809
|
+
} catch { form.querySelector("#connection-error").textContent = tr("请输入不含认证信息、查询参数或片段的 HTTPS API 地址。", "Enter an HTTPS API URL without credentials, query parameters or a fragment."); return; }
|
|
810
|
+
}
|
|
811
|
+
if (target.provider.id === "zai" && Boolean(body.organizationId ?? target.provider.connection?.organizationId) !== Boolean(body.projectId ?? target.provider.connection?.projectId)) {
|
|
812
|
+
form.querySelector("#connection-error").textContent = tr("团队查询需要同时填写组织 ID 和项目 ID。", "Team queries require both organization ID and project ID."); return;
|
|
813
|
+
}
|
|
814
|
+
if (target.saving) return;
|
|
815
|
+
target.saving = true;
|
|
816
|
+
const button = form.querySelector("#save-connection"); button.disabled = true;
|
|
817
|
+
try {
|
|
818
|
+
await post(target.configure ? "connection" : "connect", body);
|
|
819
|
+
form.querySelectorAll('input[type="password"]').forEach((input) => { input.value = ""; });
|
|
820
|
+
invalidateUsage(target.provider.id);
|
|
821
|
+
if (connectionTarget === target || localTarget === target) closeModal();
|
|
822
|
+
await refreshRemote();
|
|
823
|
+
toast(tr("连接配置已保存。", "Connection settings saved."));
|
|
824
|
+
} catch (error) {
|
|
825
|
+
if (connectionTarget === target) document.querySelector("#connection-error").textContent = error.message;
|
|
826
|
+
} finally { target.saving = false; if (connectionTarget === target) { const current = document.querySelector("#save-connection"); if (current) current.disabled = false; } }
|
|
827
|
+
}
|
|
828
|
+
async function openLocal(id) {
|
|
829
|
+
const provider = shownProviders().find((item) => item.id === id);
|
|
830
|
+
if (!provider || apiMode !== "live") return;
|
|
831
|
+
modalStart(); const serial = ++modalSerial;
|
|
832
|
+
connectionTarget = null; pullTarget = null;
|
|
833
|
+
localTarget = { provider, sources: [], loading: true };
|
|
834
|
+
renderLocal();
|
|
835
|
+
try {
|
|
836
|
+
const response = await fetch("/oauth/api/import/sources", { cache: "no-store" });
|
|
837
|
+
const body = await response.json();
|
|
838
|
+
if (!response.ok) throw new Error(requestError(body));
|
|
839
|
+
if (serial !== modalSerial) return;
|
|
840
|
+
localTarget.sources = Array.isArray(body.sources) ? body.sources : [];
|
|
841
|
+
} catch (error) { if (serial === modalSerial) localTarget.error = error.message; }
|
|
842
|
+
if (serial === modalSerial) { localTarget.loading = false; renderLocal(); }
|
|
843
|
+
}
|
|
844
|
+
function localSourceStatus(source, item) {
|
|
845
|
+
if (source.available && item.available) return tr("可复用", "Available");
|
|
846
|
+
if (item.reasonCode === "source-does-not-export-credentials") return tr(
|
|
847
|
+
"AGY 通过系统钥匙串管理登录,暂无法在此导入。请在 agy 中输入 /usage 查看套餐用量。",
|
|
848
|
+
"AGY manages sign-in in the system keyring. To view plan usage, enter /usage in agy.",
|
|
849
|
+
);
|
|
850
|
+
if (item.reasonCode === "ambiguous-source") return tr("源 CLI 有多个账号,请保留明确的授权来源。", "The source CLI has several accounts. Select a single authorization source.");
|
|
851
|
+
if (item.reasonCode === "unsupported-provider") return tr("此授权类型与该提供商的接入方式不兼容。", "This authorization type is unsupported for the provider.");
|
|
852
|
+
return tr("未找到可用授权,请先在源 CLI 登录", "No usable authorization; sign in in the source CLI first");
|
|
853
|
+
}
|
|
854
|
+
function renderLocal() {
|
|
855
|
+
const { provider, sources, loading, error } = localTarget;
|
|
856
|
+
const choices = sources.flatMap((source) => (source.providers || []).filter((item) => item.provider === provider.id).map((item) => ({ source, item })));
|
|
857
|
+
const root = document.querySelector("#modal"); root.hidden = false;
|
|
858
|
+
root.innerHTML = `<div class="overlay" data-backdrop="1"><div class="dialog" role="dialog" aria-modal="true" aria-labelledby="local-title"><h2 id="local-title">${escapeHtml(tr(`复用 ${provider.name} 本机授权`, `Reuse local ${provider.name} authorization`))}</h2><p class="hint">${tr("可复用授权的续期由源 CLI 管理。授权过期时,请在对应 CLI 中续期。", "The source CLI manages renewal for reusable credentials. Renew expired authorization in that CLI.")}</p><form id="local-form"><div class="choices">${loading ? `<p class="hint">${tr("正在检查本机来源…", "Checking local sources…")}</p>` : choices.length ? choices.map(({ source, item }) => `<label class="choice"><input type="radio" name="source" id="local-source-${escapeHtml(source.id)}" value="${escapeHtml(source.id)}" ${source.available && item.available ? "" : "disabled"} required /><span>${escapeHtml(source.label || source.id)}</span><span class="model-capabilities">${escapeHtml(localSourceStatus(source, item))}</span></label>`).join("") : `<p class="hint">${tr("没有找到此提供商支持的本机授权来源。", "No supported local authorization source was found for this provider.")}</p>`}</div><p class="err form-error" id="local-error" role="alert">${escapeHtml(error || "")}</p><div class="row-actions"><button class="btn" type="button" id="cancel-local">${tr("取消", "Cancel")}</button><button class="btn solid" id="save-local" type="submit" ${loading || localTarget.saving || !choices.some(({ source, item }) => source.available && item.available) ? "disabled" : ""}>${tr("确认复用此来源", "Use selected source")}</button></div></form></div></div>`;
|
|
859
|
+
focusDialog();
|
|
860
|
+
}
|
|
861
|
+
async function saveLocal(event) {
|
|
862
|
+
if (event.target.id !== "local-form") return;
|
|
863
|
+
event.preventDefault();
|
|
864
|
+
const target = localTarget;
|
|
865
|
+
const source = new FormData(event.target).get("source");
|
|
866
|
+
if (!target || !source || target.saving) return;
|
|
867
|
+
target.saving = true;
|
|
868
|
+
const button = document.querySelector("#save-local"); button.disabled = true;
|
|
869
|
+
try {
|
|
870
|
+
await post("import", { source, provider: target.provider.id });
|
|
871
|
+
invalidateUsage(target.provider.id);
|
|
872
|
+
if (connectionTarget === target || localTarget === target) closeModal();
|
|
873
|
+
await refreshRemote();
|
|
874
|
+
toast(tr("已连接本机 CLI 管理的授权。", "Connected using CLI-managed authorization."));
|
|
875
|
+
} catch (error) { if (localTarget === target) document.querySelector("#local-error").textContent = error.message; }
|
|
876
|
+
finally { target.saving = false; if (localTarget === target) { const current = document.querySelector("#save-local"); if (current) current.disabled = false; } }
|
|
877
|
+
}
|
|
878
|
+
function disconnect(id) {
|
|
879
|
+
pendingDisconnect = shownProviders().find((item) => item.id === id);
|
|
880
|
+
if (!pendingDisconnect) return;
|
|
881
|
+
modalStart();
|
|
882
|
+
const root = document.querySelector("#modal"); root.hidden = false;
|
|
883
|
+
root.innerHTML = `<div class="overlay" data-backdrop="1"><div class="dialog" role="dialog" aria-modal="true" aria-labelledby="disconnect-title"><h2 id="disconnect-title">${escapeHtml(tr(`断开 ${pendingDisconnect.name}?`, `Disconnect ${pendingDisconnect.name}?`))}</h2><p class="hint">${tr("这会删除本机服务保存的授权。其他使用同一共享凭据的配置也可能受影响;之后需要重新连接。", "This removes authorization saved by the local service. Other configurations using the same shared credential may also be affected. You will need to reconnect.")}</p><div class="row-actions"><button class="btn" type="button" id="cancel-disconnect">${tr("取消", "Cancel")}</button><button class="btn solid" type="button" id="confirm-disconnect">${tr("断开连接", "Disconnect")}</button></div></div></div>`;
|
|
884
|
+
focusDialog();
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
document.querySelector("#refresh").addEventListener("click", () => {
|
|
888
|
+
if (hostedPanel) void refreshRemote();
|
|
889
|
+
else { status = loadState(); renderList(); }
|
|
890
|
+
});
|
|
891
|
+
|
|
892
|
+
document.querySelector("#reset").addEventListener("click", () => {
|
|
893
|
+
if (apiMode !== "preview") return;
|
|
894
|
+
status = seedStatus();
|
|
895
|
+
save();
|
|
896
|
+
renderList();
|
|
897
|
+
toast(tr("已恢复示例数据", "Example data restored"));
|
|
898
|
+
});
|
|
899
|
+
|
|
900
|
+
document.querySelector("#rows").addEventListener("click", async (event) => {
|
|
901
|
+
const target = event.target.closest("button");
|
|
902
|
+
if (!target) return;
|
|
903
|
+
if (target.dataset.login) openLogin(target.dataset.login, target.dataset.loginMethod || "browser");
|
|
904
|
+
if (target.dataset.pull) {
|
|
905
|
+
pullTarget = target.dataset.pull;
|
|
906
|
+
void openPull(target.dataset.pull);
|
|
907
|
+
}
|
|
908
|
+
if (target.dataset.disconnect) disconnect(target.dataset.disconnect);
|
|
909
|
+
if (target.dataset.connect) openConnection(target.dataset.connect, false);
|
|
910
|
+
if (target.dataset.configure) openConnection(target.dataset.configure, true);
|
|
911
|
+
if (target.dataset.usage) void refreshUsage(target.dataset.usage);
|
|
912
|
+
if (target.dataset.local) void openLocal(target.dataset.local);
|
|
913
|
+
if (target.dataset.copy) {
|
|
914
|
+
const provider = shownProviders().find((item) => item.id === target.dataset.copy);
|
|
915
|
+
await navigator.clipboard.writeText(provider.cli);
|
|
916
|
+
toast(tr("已复制", "Copied"));
|
|
917
|
+
}
|
|
918
|
+
});
|
|
919
|
+
|
|
920
|
+
document.querySelector("#modal").addEventListener("submit", submitAuthorization);
|
|
921
|
+
document.querySelector("#modal").addEventListener("submit", saveConnection);
|
|
922
|
+
document.querySelector("#modal").addEventListener("submit", saveLocal);
|
|
923
|
+
document.querySelector("#modal").addEventListener("change", syncRetention);
|
|
924
|
+
|
|
925
|
+
document.querySelector("#modal").addEventListener("click", async (event) => {
|
|
926
|
+
if (event.target.dataset.local) { void openLocal(event.target.dataset.local); return; }
|
|
927
|
+
if (event.target.id === "cancel-local" || (event.target.dataset.backdrop && localTarget)) { closeModal(); return; }
|
|
928
|
+
if (event.target.id === "cancel-connection" || (event.target.dataset.backdrop && connectionTarget)) { closeModal(); return; }
|
|
929
|
+
if (event.target.id === "toggle-models") {
|
|
930
|
+
const inputs = [...document.querySelectorAll(".choice input")];
|
|
931
|
+
const all = inputs.every((input) => input.checked);
|
|
932
|
+
inputs.forEach((input) => { input.checked = !all; }); return;
|
|
933
|
+
}
|
|
934
|
+
if (event.target.id === "copy-authorization-url") {
|
|
935
|
+
const url = safeAuthorizationUrl(activeLogin?.snapshot?.url);
|
|
936
|
+
if (!url) return;
|
|
937
|
+
try { await navigator.clipboard.writeText(url); toast(tr("授权链接已复制,可在常用浏览器中打开", "Authorization link copied. Open it in your preferred browser.")); }
|
|
938
|
+
catch { toast(tr("无法写入剪贴板,可使用上方授权链接", "Could not copy. Use the authorization link above.")); }
|
|
939
|
+
return;
|
|
940
|
+
}
|
|
941
|
+
if (event.target.id === "cancel-authorization") { await cancelAuthorization(); return; }
|
|
942
|
+
if (event.target.id === "close-authorization") {
|
|
943
|
+
cleanupLogin(true);
|
|
944
|
+
closeModal();
|
|
945
|
+
return;
|
|
946
|
+
}
|
|
947
|
+
const hours = event.target.dataset?.hours;
|
|
948
|
+
if (hours) {
|
|
949
|
+
const field = document.querySelector("#pull-expiry");
|
|
950
|
+
if (field) field.value = localStamp(new Date(Date.now() + Number(hours) * 60 * 60 * 1000));
|
|
951
|
+
const until = document.querySelector("#pull-until");
|
|
952
|
+
if (until) until.checked = true;
|
|
953
|
+
syncRetention();
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
if (event.target.id === "cancel-pull" || (event.target.dataset.backdrop && pullTarget && !pendingDisconnect)) {
|
|
957
|
+
closeModal();
|
|
958
|
+
return;
|
|
959
|
+
}
|
|
960
|
+
if (event.target.id === "confirm-pull" && pullTarget) {
|
|
961
|
+
await confirmPull(pullTarget);
|
|
962
|
+
return;
|
|
963
|
+
}
|
|
964
|
+
if (event.target.id === "cancel-disconnect" || (event.target.dataset.backdrop && pendingDisconnect)) {
|
|
965
|
+
closeModal();
|
|
966
|
+
return;
|
|
967
|
+
}
|
|
968
|
+
if (event.target.id === "confirm-disconnect" && pendingDisconnect) {
|
|
969
|
+
const provider = pendingDisconnect;
|
|
970
|
+
const button = event.target;
|
|
971
|
+
button.disabled = true;
|
|
972
|
+
if (apiMode === "live") {
|
|
973
|
+
try {
|
|
974
|
+
const response = await fetch("/oauth/api/logout", {
|
|
975
|
+
method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ provider: provider.id }),
|
|
976
|
+
});
|
|
977
|
+
const body = await response.json();
|
|
978
|
+
if (!response.ok) throw new Error(body.error || tr("断开连接失败", "Could not disconnect"));
|
|
979
|
+
invalidateUsage(provider.id); usageOpen.delete(provider.id);
|
|
980
|
+
await refreshRemote();
|
|
981
|
+
} catch (error) {
|
|
982
|
+
button.disabled = false;
|
|
983
|
+
toast(error.message || tr("断开连接失败", "Could not disconnect"));
|
|
984
|
+
return;
|
|
985
|
+
}
|
|
986
|
+
} else if (apiMode === "preview") {
|
|
987
|
+
delete status[provider.id];
|
|
988
|
+
save();
|
|
989
|
+
} else {
|
|
990
|
+
button.disabled = false;
|
|
991
|
+
toast(tr("本机 OAuth 服务不可用,请刷新后重试", "The local OAuth service is unavailable. Refresh and try again."));
|
|
992
|
+
return;
|
|
993
|
+
}
|
|
994
|
+
closeModal();
|
|
995
|
+
renderList();
|
|
996
|
+
toast(apiMode === "preview" ? tr(`${provider.name} 示例已移除`, `${provider.name} example removed`) : tr(`${provider.name} 已断开`, `${provider.name} disconnected`));
|
|
997
|
+
}
|
|
998
|
+
});
|
|
999
|
+
|
|
1000
|
+
document.addEventListener("dsh-oauth-providers", () => renderList());
|
|
1001
|
+
|
|
1002
|
+
function changeLocale(event) {
|
|
1003
|
+
const root = document.querySelector("#modal");
|
|
1004
|
+
const focused = document.activeElement?.id;
|
|
1005
|
+
const drafts = [...root.querySelectorAll("input, select")].map((input) => ({ id: input.id, value: input.value, checked: input.checked }));
|
|
1006
|
+
const choices = [...root.querySelectorAll(".choice input")].filter((input) => input.checked).map((input) => input.value);
|
|
1007
|
+
locale = event.target.value === "en" ? "en" : "zh";
|
|
1008
|
+
try { localStorage.setItem("dsh-oauth-locale", locale); } catch { /* UI preference is optional. */ }
|
|
1009
|
+
updateStaticText(); renderList();
|
|
1010
|
+
try { if (authPopup && !authPopup.closed) authPopup.postMessage({ type: "dsh-oauth-locale", locale }, location.protocol === "file:" ? "*" : location.origin); } catch { /* Provider-owned pages do not use panel locale. */ }
|
|
1011
|
+
if (activeLogin) { loginRenderKey = ""; renderAuthorization(); }
|
|
1012
|
+
else if (localTarget) renderLocal();
|
|
1013
|
+
else if (connectionTarget) renderConnection();
|
|
1014
|
+
else if (pullTarget) { const provider = shownProviders().find((item) => item.id === pullTarget); if (provider) renderPull(provider, pullModels, pullError); }
|
|
1015
|
+
else if (pendingDisconnect) disconnect(pendingDisconnect.id);
|
|
1016
|
+
for (const draft of drafts) {
|
|
1017
|
+
if (!draft.id) continue;
|
|
1018
|
+
const input = root.querySelector(`#${draft.id}`);
|
|
1019
|
+
if (input) { input.value = draft.value; if (typeof draft.checked === "boolean") input.checked = draft.checked; }
|
|
1020
|
+
}
|
|
1021
|
+
if (pullTarget) root.querySelectorAll(".choice input").forEach((input) => { input.checked = choices.includes(input.value); });
|
|
1022
|
+
syncRetention();
|
|
1023
|
+
if (focused) document.getElementById(focused)?.focus?.();
|
|
1024
|
+
}
|
|
1025
|
+
document.querySelector("#locale")?.addEventListener("change", changeLocale);
|
|
1026
|
+
document.querySelector("#modal").addEventListener("change", (event) => { if (event.target.hasAttribute("data-modal-locale")) changeLocale(event); });
|
|
1027
|
+
document.addEventListener("keydown", (event) => {
|
|
1028
|
+
const root = document.querySelector("#modal");
|
|
1029
|
+
if (root.hidden) return;
|
|
1030
|
+
if (event.key === "Escape") {
|
|
1031
|
+
event.preventDefault();
|
|
1032
|
+
if (activeLogin?.snapshot?.status === "pending") void cancelAuthorization();
|
|
1033
|
+
else { if (activeLogin) cleanupLogin(true); closeModal(); }
|
|
1034
|
+
}
|
|
1035
|
+
if (event.key === "Tab") {
|
|
1036
|
+
const nodes = [...root.querySelectorAll('button:not([disabled]), a[href], input:not([disabled]), select:not([disabled]), summary, [tabindex="0"]')].filter((node) => node.getClientRects().length);
|
|
1037
|
+
const first = nodes[0], last = nodes[nodes.length - 1];
|
|
1038
|
+
if (!first) { event.preventDefault(); return; }
|
|
1039
|
+
if (event.shiftKey && (document.activeElement === first || !nodes.includes(document.activeElement))) { event.preventDefault(); last.focus(); }
|
|
1040
|
+
else if (!event.shiftKey && (document.activeElement === last || !nodes.includes(document.activeElement))) { event.preventDefault(); first.focus(); }
|
|
1041
|
+
}
|
|
1042
|
+
});
|
|
1043
|
+
updateStaticText();
|
|
1044
|
+
renderList();
|
|
1045
|
+
void refreshRemote();
|