@240xu/dsh-websearch 2.8.8 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js CHANGED
@@ -7,6 +7,11 @@ window.__ModuleLoader__.load({
7
7
  let react_jsx_runtime = require("react/jsx-runtime");
8
8
  let react = require("react");
9
9
 
10
+ /** Localized display label for a backend id (falls back to the id). */
11
+ function backendLabel(t, id) {
12
+ return t("backend" + id.charAt(0).toUpperCase() + id.slice(1));
13
+ }
14
+
10
15
  const NS = "websearch.settings";
11
16
  const PLUGIN_NS = "unified-search";
12
17
 
@@ -23,16 +28,29 @@ window.__ModuleLoader__.load({
23
28
  { id: "deepseek", keyEnv: "DEEPSEEK_API_KEY", label: "DeepSeek" },
24
29
  { id: "anthropic", keyEnv: "ANTHROPIC_API_KEY", label: "Anthropic" },
25
30
  { id: "openai", keyEnv: "OPENAI_API_KEY", label: "OpenAI" },
31
+ // these two are metered, opt-in backends. They are
32
+ // deliberately NOT in KEYLESS: listing them under "keyless, ready to
33
+ // use" would imply zero cost / zero limits, while the hosted keyless
34
+ // tier is rate limited and its exact ceiling is not published. They
35
+ // still accept an optional key (OPTIONAL_KEYS) to raise limits.
36
+ { id: "firecrawl", keyEnv: "FIRECRAWL_API_KEY", optionalKey: true, metered: true, label: "Firecrawl (免 Key · 有额度 · 默认关)" },
37
+ { id: "tinyfish", keyEnv: "TINYFISH_API_KEY", optionalKey: true, metered: true, label: "TinyFish (免 Key · 30/分·50/日 · 默认关)" },
26
38
  ];
27
39
  const GLOBAL_FIELDS = ["numResults", "concurrency", "backendTimeoutMs"];
28
40
  /** Enum-valued settings (validated client-side, saved as strings). */
29
41
  const SELECT_FIELDS = {
42
+ intervention: ["official", "balanced", "thorough"],
30
43
  recency: ["any", "day", "week", "month", "year"],
31
44
  dedupStrategy: ["url", "url+title"],
32
45
  };
33
46
  /** Boolean settings staged as "true"/"false" strings by the selects. */
34
- const BOOLEAN_FIELDS = ["rerank", "safeSearch", "resultTelemetry"];
35
- const KEYLESS = BACKENDS.filter((b) => !b.keyEnv || b.optionalKey);
47
+ const BOOLEAN_FIELDS = ["rerank", "safeSearch", "resultTelemetry", "resultHeader"];
48
+ // split metered, opt-in backends out of the
49
+ // "keyless / ready to use" group. They work without a key but are rate
50
+ // limited and default OFF, so a separate section with an explicit hint
51
+ // prevents the misleading impression of a free unlimited backend.
52
+ const METERED = BACKENDS.filter((b) => b.metered);
53
+ const KEYLESS = BACKENDS.filter((b) => (!b.keyEnv || b.optionalKey) && !b.metered);
36
54
  const KEYED = BACKENDS.filter((b) => b.keyEnv && !b.optionalKey);
37
55
  const OPTIONAL_KEYS = BACKENDS.filter((b) => b.keyEnv && b.optionalKey);
38
56
 
@@ -48,15 +66,34 @@ window.__ModuleLoader__.load({
48
66
  };
49
67
 
50
68
  const zh = {
69
+ backendExa: "Exa (MCP, 免费)",
70
+ backendParallel: "Parallel (MCP, 免费)",
71
+ backendDdg: "DuckDuckGo (HTML)",
72
+ backendSearxng: "SearXNG (元搜索)",
73
+ backendBrave: "Brave Search",
74
+ backendTavily: "Tavily (AI)",
75
+ backendSerper: "Serper.dev",
76
+ backendMojeek: "Mojeek",
77
+ backendDeepseek: "DeepSeek",
78
+ backendAnthropic: "Anthropic",
79
+ backendOpenai: "OpenAI",
80
+ backendFirecrawl: "Firecrawl (免 Key · 有额度 · 默认关)",
81
+ backendTinyfish: "TinyFish (免 Key · 30/分·50/日 · 默认关)",
51
82
  nav: "搜索",
52
83
  groupFree: "免密钥(开箱即用)",
53
84
  groupKeyed: "需要 API Key",
85
+ // metered/opt-in section copy (zh).
86
+ groupMetered: "计量型(免 Key 但有额度,默认关)",
87
+ meteredHint: "官方 hosted keyless tier 按 IP/日限额并可能返回 429;启用前请确认额度。填可选 Key 可提升限额。",
54
88
  statusEnabled: "已启用后端",
55
89
  statusKeys: "已配置密钥",
90
+ // status bar labels for the metered section.
91
+ statusMetered: "计量型",
92
+ statusOffByDefault: "默认关",
56
93
  keyMissing: "缺密钥",
57
94
  unsavedHint: "有未保存的修改", savedOk: "已保存 ✓",
58
95
  title: "统一搜索 (Unified Search)",
59
- description: "聚合网络搜索:11 个后端并发 fan-out、URL 去重合并。开关后端、填 API Key、调参数,保存即生效。",
96
+ description: "聚合网络搜索:多后端并发 fan-out、URL 去重合并(含 2 个默认关的计量型后端)。开关后端、填 API Key、调参数,保存即生效。",
60
97
  save: "保存",
61
98
  discard: "放弃修改",
62
99
  dirty: "有未保存修改",
@@ -67,12 +104,17 @@ window.__ModuleLoader__.load({
67
104
  overridden: "已自定义",
68
105
  keyLabel: "{id} API Key",
69
106
  getKey: "获取 Key ↗",
70
- keyHint: "填入后保存到凭证库(对应环境变量引用);留空表示不修改",
107
+ // the switch is immediate, the key needs Save.
108
+ keySaveModeHint: "开关即时生效;密钥填写后需点「保存」写入凭证库",
71
109
  keySet: "已配置",
72
110
  keyUnset: "未配置",
73
111
  togglesTitle: "启用后端",
74
112
  globalsTitle: "全局参数",
75
- keysTitle: "API 密钥(保存后写入凭证库,立即生效)",
113
+ numResultsLabel: "结果条数",
114
+ concurrencyLabel: "并发数",
115
+ timeoutLabel: "后端超时 (ms)",
116
+ saveFailed: "保存失败",
117
+ conflictHint: "其他端已修改,请先刷新",
76
118
  shapingTitle: "结果策略",
77
119
  recencyLabel: "时间范围",
78
120
  langLabel: "搜索语言",
@@ -90,22 +132,51 @@ window.__ModuleLoader__.load({
90
132
  dedupTitle: "链接 + 标题(合并转载)",
91
133
  langPlaceholder: "如 en、zh-CN,留空为默认",
92
134
  envProvided: "环境变量提供", readOnly: "只读,无需填写", conflict: "设置已在其他端被修改,请重试", keyFailed: "该 Key 保存失败",
135
+ keyReadFailed: "密钥状态读取失败,请稍后重试",
93
136
  telemetryLabel: "结果健康遥测",
94
- fallbackHint: "全部后端已关闭:搜索将回退到默认免 Key 后端",
137
+ resultHeaderLabel: "结果引用提示头",
138
+ fallbackHint: "全部后端已关闭:搜索将回退到默认免 Key 后端(计量型仍保持关闭)",
95
139
  invalidFields: "以下字段未通过校验:",
96
140
  readOnlyScope: "当前配置只读(可能由宿主锁定)",
97
- optionalTitle: "私有实例可选 Key",
141
+ interventionLabel: "搜索介入程度",
142
+ interventionOfficial: "官方(原样查询,不加结果头/遥测)",
143
+ interventionBalanced: "平衡(确定性去噪 + 去重/遥测,默认)",
144
+ interventionThorough: "彻底(相关性重排 + 深度覆盖)",
145
+ interventionHint: "official 把查询与结果呈现完全交给官方工具;balanced 只剥明确的口语前缀;thorough 会重排并扩大后端请求,延迟与额度消耗更高。内部多查询仍是独立开关。",
146
+ unavailable: "设置暂不可用:宿主没有返回配置快照(服务未就绪或路由未挂载)。",
147
+ retry: "重试",
148
+ toggleFailed: "开关未生效",
149
+ optionalTitle: "可选 Key(私有实例 / 提升计量型额度)",
98
150
  };
99
151
  const en = {
152
+ backendExa: "Exa (MCP, free)",
153
+ backendParallel: "Parallel (MCP, free)",
154
+ backendDdg: "DuckDuckGo (HTML)",
155
+ backendSearxng: "SearXNG (meta-search)",
156
+ backendBrave: "Brave Search",
157
+ backendTavily: "Tavily (AI)",
158
+ backendSerper: "Serper.dev",
159
+ backendMojeek: "Mojeek",
160
+ backendDeepseek: "DeepSeek",
161
+ backendAnthropic: "Anthropic",
162
+ backendOpenai: "OpenAI",
163
+ backendFirecrawl: "Firecrawl (keyless, metered, off by default)",
164
+ backendTinyfish: "TinyFish (keyless, 30/min · 50/day, off by default)",
100
165
  nav: "Web Search",
101
166
  groupFree: "Keyless (ready to use)",
102
167
  groupKeyed: "Requires API key",
168
+ // metered/opt-in section copy (en).
169
+ groupMetered: "Metered (keyless but rate limited, off by default)",
170
+ meteredHint: "The hosted keyless tier is limited per IP/day and may return 429; check quotas before enabling. An optional API key raises the limits.",
103
171
  statusEnabled: "Backends enabled",
104
172
  statusKeys: "Keys configured",
173
+ // status bar labels for the metered section.
174
+ statusMetered: "Metered",
175
+ statusOffByDefault: "off by default",
105
176
  keyMissing: "key missing",
106
177
  unsavedHint: "You have unsaved changes", savedOk: "Saved ✓",
107
178
  title: "Unified Search",
108
- description: "Aggregated web search: 11 backends fan out concurrently, URL-deduped. Toggle backends, set API keys, tune globals — saves apply immediately.",
179
+ description: "Aggregated web search: multiple backends fan out concurrently, URL-deduped (incl. 2 metered backends that are off by default). Toggle backends, set API keys, tune globals — saves apply immediately.",
109
180
  save: "Save",
110
181
  discard: "Discard",
111
182
  dirty: "Unsaved changes",
@@ -116,12 +187,17 @@ window.__ModuleLoader__.load({
116
187
  overridden: "customized",
117
188
  keyLabel: "{id} API Key",
118
189
  getKey: "Get key ↗",
119
- keyHint: "Stored into the credential store on save; leave blank to keep current",
190
+ // the switch is immediate, the key needs Save.
191
+ keySaveModeHint: "The switch applies immediately; the key is written to the credential store when you press Save",
120
192
  keySet: "configured",
121
193
  keyUnset: "not set",
122
194
  togglesTitle: "Enabled backends",
123
195
  globalsTitle: "Global parameters",
124
- keysTitle: "API keys (saved to the credential store, effective immediately)",
196
+ numResultsLabel: "Results",
197
+ concurrencyLabel: "Concurrency",
198
+ timeoutLabel: "Backend timeout (ms)",
199
+ saveFailed: "Save failed",
200
+ conflictHint: "Changed elsewhere — refresh first",
125
201
  shapingTitle: "Result shaping",
126
202
  recencyLabel: "Recency",
127
203
  langLabel: "Language",
@@ -142,15 +218,25 @@ window.__ModuleLoader__.load({
142
218
  readOnly: "read-only, nothing to fill",
143
219
  conflict: "Changed elsewhere - please retry",
144
220
  keyFailed: "failed to save this key",
221
+ keyReadFailed: "could not read key status, please retry later",
145
222
  telemetryLabel: "Result health telemetry",
146
- fallbackHint: "All backends off: search falls back to the default keyless four.",
223
+ resultHeaderLabel: "Citation header",
224
+ fallbackHint: "All backends off: search falls back to the default keyless four (metered backends stay off).",
147
225
  invalidFields: "Fields failed validation:",
148
226
  readOnlyScope: "Configuration is read-only (locked by host?)",
149
- optionalTitle: "Private instance optional keys",
227
+ interventionLabel: "Search intervention",
228
+ interventionOfficial: "Official (raw query, no header/telemetry)",
229
+ interventionBalanced: "Balanced (deterministic cleanup + dedupe/telemetry, default)",
230
+ interventionThorough: "Thorough (relevance rerank + deep coverage)",
231
+ interventionHint: "official leaves query construction and presentation to the host tool; balanced strips only explicit conversational prefixes; thorough reranks and widens backend requests, costing more latency and quota. Internal multi-query stays a separate opt-in.",
232
+ unavailable: "Settings are unavailable: the host returned no configuration snapshot (service not ready or route not mounted).",
233
+ retry: "Retry",
234
+ toggleFailed: "Toggle failed",
235
+ optionalTitle: "Optional keys (private instance / higher metered limits)",
150
236
  };
151
237
 
152
238
  //#region styles
153
- const css = ".wsc-card{display:flex;flex-direction:column;gap:14px}.wsc-sectionTitle{font-size:13px;font-weight:600;opacity:.75;margin:4px 0 0}.wsc-toggles{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:6px}.wsc-toggle{display:flex;align-items:center;gap:8px;padding:7px 10px;border-radius:10px;border:1px solid var(--dsw-alias-border-subtle);cursor:pointer;font-size:13px;color:var(--dsw-alias-label-primary);background:0 0}.wsc-toggle input{accent-color:var(--dsw-alias-accent-primary)}.wsc-input,.wsc-keyInput{box-sizing:border-box;width:100%;padding:8px 10px;border-radius:8px;border:1px solid var(--dsw-alias-border-subtle);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-size:13px;font-family:inherit}.wsc-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:10px}.wsc-fieldHead{display:flex;justify-content:space-between;align-items:center;margin-bottom:3px}.wsc-label{font-size:12px;opacity:.8}.wsc-badge{font-size:11px;padding:1px 8px;border-radius:999px;border:1px solid var(--dsw-alias-border-subtle)}.wsc-badgeOn{color:var(--dsw-alias-accent-primary);border-color:var(--dsw-alias-accent-primary)}.wsc-hint{font-size:11px;opacity:.55;margin:3px 0 0}.wsc-actions{display:flex;gap:8px;align-items:center}.wsc-btn{cursor:pointer;border:none;border-radius:10px;padding:8px 16px;font-size:13px;font-family:inherit;background:var(--dsw-alias-accent-primary);color:#fff}.wsc-btnGhost{background:0 0;color:var(--dsw-alias-label-primary);border:1px solid var(--dsw-alias-border-subtle)}.wsc-btn:disabled{opacity:.5;cursor:default}.wsc-status{font-size:12px;opacity:.7}";
239
+ const css = ".wsc-card{display:flex;flex-direction:column;gap:8px}.wsc-sectionTitle{margin:24px 0 0;font-size:14px;font-weight:500;line-height:20px;color:var(--dsw-alias-label-primary)}.wsc-toggles{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:6px}.wsc-toggle{display:flex;align-items:center;gap:8px;padding:7px 10px;border:.5px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-md);cursor:pointer;font-size:13px;color:var(--dsw-alias-label-primary);background:0 0;transition:background-color .16s,border-color .16s}@media (hover:hover){.wsc-toggle:hover{background:var(--dsw-alias-interactive-bg-hover)}}.wsc-toggle input{accent-color:var(--dsw-alias-brand-primary)}.wsc-toggle:has(input:focus-visible){outline:none;box-shadow:0 0 0 2px var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))}.wsc-toggle input:focus-visible{outline:none}.wsc-input,.wsc-keyInput{box-sizing:border-box;height:34px;width:100%;padding:0 12px;border:.5px solid var(--dsw-alias-border-l4);border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-size:13px;font-family:inherit}.wsc-input:focus,.wsc-keyInput:focus{outline:none;border-color:var(--dsw-alias-state-business-primary)}.wsc-input:disabled,.wsc-keyInput:disabled{opacity:.6;cursor:default}.wsc-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:10px}.wsc-fieldHead{display:flex;justify-content:space-between;align-items:center;margin-bottom:3px}.wsc-label{font-size:13px;font-weight:500;color:var(--dsw-alias-label-primary)}.wsc-badge{font-size:11px;padding:1px 8px;border-radius:var(--dsw-radius-xs);border:.5px solid var(--dsw-alias-border-l3);color:var(--dsw-alias-label-secondary)}.wsc-badgeOn{color:var(--dsw-alias-label-primary);border-color:var(--dsw-alias-state-success-primary)}.wsc-hint{font-size:12px;line-height:1.5;color:var(--dsw-alias-label-secondary);margin:3px 0 0}.wsc-error{color:var(--dsw-alias-state-error-primary);font-size:12px}.wsc-warn{color:var(--dsw-alias-state-warn-label);font-size:12px}.wsc-strip{border:.5px solid var(--dsw-alias-border-l2);border-radius:var(--dsw-radius-sm);background:var(--dsw-alias-bg-module-platform)}.wsc-keyCard{border:.5px solid var(--dsw-alias-settings-card-stroke);border-radius:var(--dsw-radius-xl);background:var(--dsw-alias-settings-card-fill)}.wsc-actions{position:sticky;bottom:0;display:flex;gap:8px;align-items:center;padding:8px 0;background:var(--dsw-alias-bg-layer-2);border-top:.5px solid var(--dsw-alias-border-l2)}.wsc-btn{box-sizing:border-box;cursor:pointer;border:none;border-radius:var(--dsw-radius-md);height:36px;padding:0 14px;font-size:14px;line-height:22px;font-family:inherit;background:var(--dsw-alias-button-primary-fill);color:var(--dsw-alias-label-primary-foreground)}.wsc-btn:hover:not(.wsc-btnGhost):not(:disabled){background:var(--dsw-alias-button-primary-hover)}.wsc-btn:focus-visible{outline:none;box-shadow:0 0 0 2px var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary))}.wsc-btnGhost{background:0 0;color:var(--dsw-alias-label-primary);border:.5px solid var(--dsw-alias-border-l3)}.wsc-btnGhost:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover-solid);color:var(--dsw-alias-label-primary)}.wsc-btn:disabled{opacity:.4;cursor:default}.wsc-status{font-size:12px;color:var(--dsw-alias-label-secondary)}.wsc-dot{width:8px;height:8px;border-radius:50%;display:inline-block}.wsc-dotOn{background:var(--dsw-alias-state-success-primary)}.wsc-dotWarn{background:var(--dsw-alias-state-warn-primary)}.wsc-dotOff{background:var(--dsw-alias-label-tertiary)}.wsc-link:hover{text-decoration:underline}.wsc-card fieldset[disabled] .wsc-toggle{opacity:.6;cursor:default}";
154
240
  if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=\"dsh-websearch/card\"]") === null) {
155
241
  const tag = document.createElement("style");
156
242
  tag.dataset.plugin = "@240xu/dsh-websearch";
@@ -188,17 +274,54 @@ window.__ModuleLoader__.load({
188
274
  user: undefined,
189
275
  revision: undefined,
190
276
  mode: "routes",
277
+ unavailable: false,
278
+ reason: undefined,
191
279
  });
280
+ // Serialise writes: a queued write must read the revision only
281
+ // when its turn comes, otherwise two concurrent toggles both
282
+ // send revision=0 and the second is rejected as a conflict.
283
+ this.writeQueue = Promise.resolve();
284
+ // A load starts before a write but can land after it; applying
285
+ // that snapshot would roll the UI back and restore a stale
286
+ // revision (the next write is then rejected as a conflict).
287
+ this.loadSeq = 0;
192
288
  }
193
289
 
194
290
  getSnapshot() { return this.store.getSnapshot(); }
195
291
  subscribe(listener) { return this.store.subscribe(listener); }
196
292
 
197
293
  accept(payload) {
198
- if (payload === null || typeof payload !== "object" || payload.ok !== true || payload.writable === false) {
199
- // Keep the card rendered (status ready) but read-only, so the section
200
- // explains itself instead of showing an endless loading ellipsis.
201
- this.store.set({ status: "ready", writable: false, value: {}, base: undefined, user: undefined, revision: undefined, mode: "routes" });
294
+ if (payload === null || typeof payload !== "object" || payload.ok !== true) {
295
+ // Keep the card rendered (status ready) but explain the actual state:
296
+ // a 404/503 is "settings unavailable", not "you configured nothing".
297
+ this.store.set({
298
+ status: "ready",
299
+ writable: false,
300
+ value: {},
301
+ base: undefined,
302
+ user: undefined,
303
+ revision: undefined,
304
+ mode: "routes",
305
+ unavailable: true,
306
+ reason: payload !== null && typeof payload === "object" && typeof payload.reason === "string"
307
+ ? payload.reason
308
+ : "settings-unavailable",
309
+ });
310
+ return;
311
+ }
312
+ if (payload.writable === false) {
313
+ // The host answered with a real snapshot but marked it read-only.
314
+ this.store.set({
315
+ status: "ready",
316
+ writable: false,
317
+ value: payload.value ?? {},
318
+ base: payload.base,
319
+ user: payload.user,
320
+ revision: payload.revision,
321
+ mode: "routes",
322
+ unavailable: false,
323
+ reason: payload.reason,
324
+ });
202
325
  return;
203
326
  }
204
327
  this.store.set({
@@ -209,20 +332,31 @@ window.__ModuleLoader__.load({
209
332
  user: payload.user,
210
333
  revision: payload.revision,
211
334
  mode: "routes",
335
+ unavailable: false,
336
+ reason: undefined,
212
337
  });
213
338
  }
214
339
 
215
340
  async load() {
341
+ const seq = ++this.loadSeq;
216
342
  try {
217
- const response = await fetch("/api/unified-search/settings", { credentials: "same-origin", headers: { accept: "application/json" } });
218
- const payload = await response.json().catch(() => undefined);
219
- this.accept(response.status === 404 ? undefined : payload);
343
+ const response = await fetch("/api/unified-search/settings", { credentials: "same-origin", headers: { accept: "application/json" } });
344
+ const payload = await response.json().catch(() => undefined);
345
+ if (seq !== this.loadSeq) return;
346
+ this.accept(response.status === 404 ? undefined : payload);
220
347
  } catch (_noRoutes) {
221
- this.accept(undefined);
348
+ if (seq === this.loadSeq) this.accept(undefined);
222
349
  }
223
350
  }
224
351
 
225
- async write(ops) {
352
+ write(ops) {
353
+ const run = () => this.writeNow(ops);
354
+ const result = this.writeQueue.then(run, run);
355
+ this.writeQueue = result.then(() => undefined, () => undefined);
356
+ return result;
357
+ }
358
+
359
+ async writeNow(ops) {
226
360
  const expectedRevision = this.store.getSnapshot().revision;
227
361
  const response = await fetch("/api/unified-search/settings", {
228
362
  method: "POST",
@@ -236,6 +370,7 @@ window.__ModuleLoader__.load({
236
370
  if (!response.ok || payload === undefined || payload.ok !== true) {
237
371
  throw new Error(payload !== undefined && payload.error !== undefined ? String(payload.error) : "settings request failed (" + response.status + ")");
238
372
  }
373
+ this.loadSeq += 1;
239
374
  this.accept(payload);
240
375
  }
241
376
 
@@ -247,6 +382,13 @@ window.__ModuleLoader__.load({
247
382
  * Card state machine: reads the bound settings scope snapshot, stages edits,
248
383
  * writes section fields through scope.set/unset and secrets via credentials.
249
384
  */
385
+ // Host errors can carry internal paths and reference names. Only a
386
+ // stable, shape-checked error code is safe to display in the card.
387
+ function safeFailureReason(err) {
388
+ const code = err && typeof err === "object" && typeof err.code === "string" ? err.code : "";
389
+ return /^[a-z][a-z0-9/_-]{0,60}$/i.test(code) ? code : "write rejected";
390
+ }
391
+
250
392
  class UnifiedSearchCardController {
251
393
  constructor(scope, connection, remote) {
252
394
  this.scope = scope;
@@ -258,11 +400,23 @@ window.__ModuleLoader__.load({
258
400
  this.saving = false;
259
401
  this.failed = false;
260
402
  this.conflict = false;
403
+ // A toggle write is independent of Save; its failure must not be
404
+ // cleared only by a later Save, nor persist after a retry succeeds.
405
+ this.toggleFailed = false;
406
+ this.toggleConflict = false;
407
+ this.toggleErrorId = null;
261
408
  this.failedKeys = new Map(); // envRef -> failure reason
409
+ // Credential READ failures, distinct from SAVE failures above.
410
+ // Only a fixed code is stored; raw host errors are never kept.
411
+ this.readErrors = new Map();
262
412
  this.failedFields = new Set();
263
413
  this.savedAt = 0;
414
+ // Per-ref read sequence: a describe() started before a successful
415
+ // write must not repaint that key as "not configured".
416
+ this.credSeq = new Map();
417
+ this.disposed = false;
264
418
  this.store = createStore(this.projection());
265
- this.scope.subscribe(() => this.republish());
419
+ this.unsubscribe = this.scope.subscribe(() => this.republish());
266
420
  }
267
421
 
268
422
  sectionValue(field) {
@@ -276,11 +430,19 @@ window.__ModuleLoader__.load({
276
430
  return { text: staged.clear ? "" : staged.text, overridden: !staged.clear };
277
431
  }
278
432
 
433
+ /**
434
+ * Project the controller state into the snapshot the card renders from.
435
+ * Everything the render layer needs is derived here, so the store never
436
+ * exposes the raw staging maps.
437
+ */
279
438
  projection() {
280
439
  const snap = this.scope.getSnapshot();
281
440
  return {
282
441
  ready: snap.status === "ready",
283
442
  writable: snap.writable,
443
+ unavailable: snap.unavailable === true,
444
+ reason: snap.reason,
445
+ revision: snap.revision,
284
446
  value: snap.value ?? {},
285
447
  keyState: Object.fromEntries(this.keyState),
286
448
  stagedKeys: Object.fromEntries([...this.stagedKeys].map(([k, v]) => [k, v.text])),
@@ -292,59 +454,156 @@ window.__ModuleLoader__.load({
292
454
  },
293
455
  conflict: this.conflict,
294
456
  failedKeys: [...this.failedKeys].map(([ref, reason]) => ({ ref, reason })),
457
+ readErrors: [...this.readErrors].map(([ref, reason]) => ({ ref, reason })),
295
458
  failedFields: [...this.failedFields],
296
459
  saving: this.saving,
297
460
  failed: this.failed,
461
+ toggleFailed: this.toggleFailed,
462
+ toggleConflict: this.toggleConflict,
463
+ toggleErrorId: this.toggleErrorId,
298
464
  version: (this.staged.size + ":" + [...this.staged.keys()].join(",")),
299
465
  };
300
466
  }
301
467
 
302
- republish() { this.store.set(this.projection()); }
468
+ /** Push the current projection to the store and notify subscribers. */
469
+ republish() {
470
+ if (this.disposed) return;
471
+ this.store.set(this.projection());
472
+ }
473
+
474
+ /** Detach from the host scope; late responses must not publish. */
475
+ dispose() {
476
+ this.disposed = true;
477
+ if (typeof this.unsubscribe === "function") this.unsubscribe();
478
+ }
303
479
 
480
+ /** Re-read the settings snapshot (used by the unavailable-state retry). */
481
+ reload() {
482
+ return typeof this.scope.load === "function" ? this.scope.load() : undefined;
483
+ }
484
+
485
+ /** Stage a field edit (clears the saved marker so the card shows "unsaved"). */
304
486
  edit(field, text) { this.savedAt = 0; this.staged.set(field, { text }); this.republish(); }
487
+ /** Drop a staged field edit; the stored value is untouched. */
305
488
  reset(field) { this.staged.delete(field); this.republish(); }
306
- editKey(envRef, text) { this.savedAt = 0; this.stagedKeys.set(envRef, { text }); this.republish(); }
489
+ /** Stage a credential draft; a blank draft is never staged so Save can drain. */
490
+ editKey(envRef, text) {
491
+ this.savedAt = 0;
492
+ // A blank draft is not a pending change; staging it would keep
493
+ // the Save button enabled with nothing to write.
494
+ if (String(text).trim() === "") this.stagedKeys.delete(envRef);
495
+ else this.stagedKeys.set(envRef, { text });
496
+ this.republish();
497
+ }
307
498
 
308
499
  /** Toggles write immediately (no staging); globals/keys stage + save. */
309
500
  async setToggle(id, checked) {
501
+ // A retry supersedes the previous toggle error. Keep the message
502
+ // while the new write is in flight so the card does not flicker.
503
+ this.toggleFailed = false;
504
+ this.toggleConflict = false;
505
+ this.toggleErrorId = null;
310
506
  try {
311
507
  await this.scope.set("enable" + id.charAt(0).toUpperCase() + id.slice(1), checked);
312
508
  } catch (err) {
313
- this.failed = true;
314
- this.conflict = String(err).includes("SETTINGS_CONFLICT");
509
+ this.toggleFailed = true;
510
+ this.toggleErrorId = id;
511
+ this.toggleConflict = String(err).includes("SETTINGS_CONFLICT");
512
+ // Do not erase a Save failure: two independent writes must
513
+ // keep their own error state.
514
+ // The host may have committed the write even when the
515
+ // response failed. Resync instead of leaving the stale
516
+ // pre-write value on screen. Report only the conflict
517
+ // classification, never the raw error text.
518
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
519
+ console.warn("websearch: toggle write failed", { conflict: this.conflict });
520
+ }
521
+ if (typeof this.scope.load === "function") {
522
+ try { await this.scope.load(); } catch { /* keep current snapshot */ }
523
+ }
315
524
  }
316
-
317
525
  this.republish();
318
526
  }
319
527
 
320
528
  async readCredential(ref) {
529
+ const seq = (this.credSeq.get(ref) ?? 0) + 1;
530
+ this.credSeq.set(ref, seq);
531
+ let readFailed = false;
532
+ let reason;
533
+ // A badge must not claim "not set" before the first read lands.
534
+ this.keyState.set(ref, { ...(this.keyState.get(ref) ?? {}), pending: true });
535
+ this.republish();
321
536
  try {
322
537
  let view;
323
- if (this.remote !== undefined && this.remote.credentials !== undefined && typeof this.remote.credentials.describe === "function") {
324
- // 0.2.x remote face: Record<ref, {configured, writable, source}> behind {ok, value}.
325
- const res = await this.remote.credentials.describe([ref]);
326
- const record = res !== null && typeof res === "object" && res.value !== undefined ? res.value : res;
327
- const byRef = record !== null && typeof record === "object" && record.credentials !== undefined ? record.credentials : record;
328
- view = byRef !== null && typeof byRef === "object" ? byRef[ref] : undefined;
538
+ // Guard the namespace access: an undeclared remote service throws on
539
+ // access, and a swallowed error would leave the configured badge dark.
540
+ let api;
541
+ try { api = this.remote === undefined ? undefined : this.remote.credentials; } catch { api = undefined; }
542
+ if (api !== undefined && typeof api.describe === "function") {
543
+ // 0.2.x remote face: RemoteResult<Record<ref, CredentialInfo>>.
544
+ const res = await api.describe([ref]);
545
+ // Judge the RemoteResult envelope before unwrapping: `ok:false` is a
546
+ // read failure, not an unconfigured credential. Do not fall
547
+ // through to the legacy connection branch, which could surface
548
+ // a stale value. failedKeys is reserved for save failures.
549
+ if (res !== null && typeof res === "object" && res.ok === false) {
550
+ readFailed = true;
551
+ reason = "credential/read-failed";
552
+ } else {
553
+ const record = res !== null && typeof res === "object" && res.value !== undefined ? res.value : res;
554
+ const byRef = record !== null && typeof record === "object" && record.credentials !== undefined ? record.credentials : record;
555
+ view = byRef !== null && typeof byRef === "object" ? byRef[ref] : undefined;
556
+ }
329
557
  }
330
- if (view === undefined && this.connection !== undefined && this.connection.api !== undefined && this.connection.api.credentials !== undefined) {
558
+ if (!readFailed && view === undefined && this.connection !== undefined && this.connection.api !== undefined && this.connection.api.credentials !== undefined) {
331
559
  // Older line: the connection controller's credentials API.
332
560
  const res = await this.connection.api.credentials.describe({ refs: [ref] });
333
561
  if (res?.result?.ok) view = res.result.value.credentials[ref];
334
562
  }
335
- if (view === undefined) return;
336
- this.keyState.set(ref, { configured: view.configured === true, writable: view.writable !== false });
337
- } catch { /* ignore */ }
338
- this.republish();
563
+ if (!readFailed && view !== undefined && seq === this.credSeq.get(ref)) {
564
+ this.keyState.set(ref, { configured: view.configured === true, writable: view.writable !== false, pending: false });
565
+ this.readErrors.delete(ref);
566
+ } else if (!readFailed && view === undefined && api === undefined
567
+ && !(this.connection !== undefined && this.connection.api !== undefined && this.connection.api.credentials !== undefined)) {
568
+ // No credentials face at all: report unavailable instead of
569
+ // silently painting every badge "not set".
570
+ reason = "credential/service-unavailable";
571
+ }
572
+ } catch {
573
+ reason = "credential/read-failed";
574
+ } finally {
575
+ // Only a fixed code is stored; host error text may contain
576
+ // internal paths or credential reference names.
577
+ if (reason !== undefined && seq === this.credSeq.get(ref)) {
578
+ this.readErrors.set(ref, safeFailureReason({ code: reason }));
579
+ }
580
+ if (seq === this.credSeq.get(ref)) {
581
+ this.keyState.set(ref, { ...(this.keyState.get(ref) ?? {}), pending: false });
582
+ }
583
+ this.republish();
584
+ }
339
585
  }
340
586
 
341
587
  async writeCredential(ref, value) {
342
- if (this.remote !== undefined && this.remote.credentials !== undefined && typeof this.remote.credentials.set === "function") {
343
- await this.remote.credentials.set(ref, value);
588
+ // The namespace access may throw on hosts that do not register
589
+ // `remote.credentials`; guard it so the older connection API can
590
+ // still serve as fallback. `set()` resolves with a RemoteResult
591
+ // envelope instead of throwing on rejection, so `ok === false`
592
+ // must be treated as a failure.
593
+ let api;
594
+ try { api = this.remote === undefined ? undefined : this.remote.credentials; } catch { api = undefined; }
595
+ if (api !== undefined && typeof api.set === "function") {
596
+ const res = await api.set(ref, value);
597
+ const rejected = res !== null && typeof res === "object" && res.ok === false;
598
+ if (rejected) throw new Error(res.error?.message ?? "credential write rejected");
599
+ this.credSeq.set(ref, (this.credSeq.get(ref) ?? 0) + 1);
344
600
  return;
345
601
  }
346
602
  if (this.connection !== undefined && this.connection.api !== undefined && this.connection.api.credentials !== undefined && typeof this.connection.api.credentials.set === "function") {
347
- await this.connection.api.credentials.set({ ref, value });
603
+ const res = await this.connection.api.credentials.set({ ref, value });
604
+ const rejected = res !== null && typeof res === "object" && (res.ok === false || res.result?.ok === false);
605
+ if (rejected) throw new Error(res.error?.message ?? res.result?.error?.message ?? "credential write rejected");
606
+ this.credSeq.set(ref, (this.credSeq.get(ref) ?? 0) + 1);
348
607
  return;
349
608
  }
350
609
  throw new Error("credentials service unavailable");
@@ -354,14 +613,33 @@ window.__ModuleLoader__.load({
354
613
  for (const b of BACKENDS) if (b.keyEnv) this.readCredential(b.keyEnv);
355
614
  }
356
615
 
616
+ /**
617
+ * Commit every staged field and credential draft.
618
+ *
619
+ * Entries are snapshotted before each await so an edit that arrives while a
620
+ * write is in flight keeps its own unsaved state instead of being deleted
621
+ * as if it had been saved. A second call while one is running is a no-op.
622
+ */
357
623
  async save() {
358
624
  if (this.saving) return;
359
625
  this.saving = true; this.failed = false;
360
626
  this.conflict = false; this.failedFields.clear(); this.republish();
361
627
  const doneFields = [];
362
628
  const doneKeys = [];
629
+ // Snapshot the staged entry object for each field/key we save.
630
+ // edit()/editKey() replace the entry with a NEW object, so comparing
631
+ // by identity tells us whether the user typed again while the
632
+ // awaits were in flight. Those newer edits must not be discarded
633
+ // or reported as saved.
634
+ const savedFieldRefs = new Map();
635
+ const savedKeyRefs = new Map();
363
636
  try {
364
637
  for (const [field, staged] of this.staged) {
638
+ // Snapshot the entry BEFORE any await. edit() replaces the staged
639
+ // entry with a new object, so identity comparison later detects an edit
640
+ // that arrived while the awaits were in flight. Recording after the
641
+ // await would capture the NEW edit and delete it as if saved.
642
+ savedFieldRefs.set(field, staged);
365
643
  // Empty draft clears the override so the schema default applies again.
366
644
  if (staged.clear || staged.text === "") { await this.scope.unset(field); doneFields.push(field); continue; }
367
645
  if (SELECT_FIELDS[field]) {
@@ -395,6 +673,8 @@ window.__ModuleLoader__.load({
395
673
  }
396
674
  }
397
675
  for (const [ref, staged] of this.stagedKeys) {
676
+ // Snapshot before any await, same reason as the field loop.
677
+ savedKeyRefs.set(ref, staged);
398
678
  const value = staged.text.trim();
399
679
  if (value !== "") {
400
680
  try {
@@ -405,22 +685,42 @@ window.__ModuleLoader__.load({
405
685
  } catch (keyErr) {
406
686
  // env-shadowed reference (fail-loud doctrine): isolate so other keys still land.
407
687
  this.failed = true;
408
- this.failedKeys.set(ref, String(keyErr && keyErr.message ? keyErr.message : keyErr).slice(0, 140));
688
+ this.failedKeys.set(ref, safeFailureReason(keyErr));
409
689
  void keyErr;
410
690
  }
691
+ } else {
692
+ // Consume a blank draft so the Save button drains.
693
+ doneKeys.push(ref);
411
694
  }
412
695
  }
413
- for (const f of doneFields) this.staged.delete(f);
414
- for (const k of doneKeys) this.stagedKeys.delete(k);
415
- if (!this.failed && (doneFields.length > 0 || doneKeys.length > 0)) this.savedAt = Date.now();
696
+ for (const f of doneFields) {
697
+ if (this.staged.get(f) === savedFieldRefs.get(f)) this.staged.delete(f);
698
+ }
699
+ for (const k of doneKeys) {
700
+ if (this.stagedKeys.get(k) === savedKeyRefs.get(k)) this.stagedKeys.delete(k);
701
+ }
702
+ // Only claim "saved" when nothing is left pending. An edit
703
+ // that arrived during the awaits keeps its own unsaved state.
704
+ if (!this.failed && (doneFields.length > 0 || doneKeys.length > 0)
705
+ && this.staged.size === 0 && this.stagedKeys.size === 0) this.savedAt = Date.now();
416
706
  } catch (err) {
417
707
  this.failed = true;
418
708
  this.conflict = String(err).includes("SETTINGS_CONFLICT");
709
+ // Without a reload the stale expectedRevision makes every
710
+ // subsequent Save fail the same way. Staged edits survive, so
711
+ // the user can inspect and retry after the refresh.
712
+ if (this.conflict) {
713
+ try { await this.reload(); } catch { /* keep the conflict notice */ }
714
+ }
419
715
  }
420
716
  this.saving = false;
421
717
  this.republish();
422
718
  }
423
719
 
720
+ /**
721
+ * Props handed to the settings section: the store as an observable hook
722
+ * plus the actions the card calls.
723
+ */
424
724
  inject() {
425
725
  // Slot contract: hooks.{name} must be an observable store; the renderer
426
726
  // converts it into props.use{Name} (observableHook). Actions go top-level.
@@ -431,12 +731,13 @@ window.__ModuleLoader__.load({
431
731
  reset: (f) => this.reset(f),
432
732
  editKey: (r, t) => this.editKey(r, t),
433
733
  save: () => this.save(),
434
- discard: () => { this.staged.clear(); this.stagedKeys.clear(); this.failed = false; this.conflict = false; this.failedKeys.clear(); this.republish(); },
734
+ retry: () => this.reload(),
735
+ discard: () => { this.staged.clear(); this.stagedKeys.clear(); this.failed = false; this.conflict = false; this.failedFields.clear(); this.failedKeys.clear(); this.republish(); },
435
736
  };
436
737
  }
437
738
  }
438
739
 
439
- /** Toggle row for one backend. */
740
+ /** Toggle row for one backend (keyless / metered backends). */
440
741
  function ToggleRow(props) {
441
742
  const b = props.backend;
442
743
  // The Host serves schema-resolved values, so defaults arrive materialized;
@@ -444,25 +745,77 @@ window.__ModuleLoader__.load({
444
745
  const checked = props.value === true;
445
746
  // Status dot: green keyless-or-keyed, amber enabled-but-key-missing.
446
747
  const needsKey = !!b.keyEnv && !b.optionalKey && !props.keyConfigured;
447
- const dotColor = needsKey ? (checked ? "#e6a700" : "#888") : "#2ea043";
748
+ const dotClass = "wsc-dot " + (needsKey ? (checked ? "wsc-dotWarn" : "wsc-dotOff") : "wsc-dotOn");
448
749
  return react_jsx_runtime.jsxs("label", { className: "wsc-toggle", style: { display: "flex", alignItems: "center", gap: 8, cursor: "pointer" }, children: [
449
750
  react_jsx_runtime.jsx("input", {
450
751
  type: "checkbox",
451
752
  checked,
452
753
  onChange: (e) => props.onChange(e.target.checked),
453
754
  }),
454
- react_jsx_runtime.jsx("span", { style: { width: 8, height: 8, borderRadius: "50%", background: dotColor, display: "inline-block" } }),
455
- react_jsx_runtime.jsx("span", { children: b.label }),
755
+ react_jsx_runtime.jsx("span", { className: dotClass }),
756
+ react_jsx_runtime.jsx("span", { children: props.t("backend" + b.id.charAt(0).toUpperCase() + b.id.slice(1)) }),
456
757
  needsKey && checked && react_jsx_runtime.jsx("span", { style: { fontSize: 10, opacity: .65 }, children: props.t("keyMissing") }),
457
758
  ] });
458
759
  }
459
760
 
761
+ /**
762
+ * Combined card for a key-gated backend: switch, status badge, get-key
763
+ * link, input, hint and per-key error in one place so the credential is
764
+ * matched to its toggle without scrolling.
765
+ *
766
+ * The switch writes immediately (setToggle), the key is staged until
767
+ * Save (editKey) — `keySaveModeHint` states this so the two behaviours
768
+ * are not mistaken for one atomic action.
769
+ */
770
+ function KeyedBackendCard(props) {
771
+ const b = props.backend;
772
+ const state = props.state;
773
+ const checked = props.value === true;
774
+ const configured = !!state.keyState[b.keyEnv]?.configured;
775
+ const readOnly = configured && state.keyState[b.keyEnv]?.writable === false;
776
+ // failedKeys is an array of { ref, reason }, NOT an array of strings.
777
+ const failure = (state.failedKeys ?? []).find((f) => f && f.ref === b.keyEnv);
778
+ const readFailure = (state.readErrors ?? []).find((f) => f && f.ref === b.keyEnv);
779
+ const needsKey = !configured;
780
+ const dotClass = "wsc-dot " + (needsKey ? (checked ? "wsc-dotWarn" : "wsc-dotOff") : "wsc-dotOn");
781
+ return react_jsx_runtime.jsxs("div", { className: "wsc-keyCard", style: { display: "flex", flexDirection: "column", gap: 6, padding: "9px 10px" }, children: [
782
+ react_jsx_runtime.jsxs("label", { className: "wsc-toggle", style: { display: "flex", alignItems: "center", gap: 8, cursor: "pointer", padding: 0, border: "none", borderRadius: 0 }, children: [
783
+ react_jsx_runtime.jsx("input", { type: "checkbox", checked, onChange: (e) => props.onToggle(e.target.checked) }),
784
+ react_jsx_runtime.jsx("span", { className: dotClass }),
785
+ react_jsx_runtime.jsx("span", { children: props.t("backend" + b.id.charAt(0).toUpperCase() + b.id.slice(1)) }),
786
+ needsKey && checked && react_jsx_runtime.jsx("span", { style: { fontSize: 10, opacity: .65 }, children: props.t("keyMissing") }),
787
+ ] }),
788
+ props.toggleError && react_jsx_runtime.jsx("p", { className: "wsc-hint wsc-error", children: props.t("toggleFailed") }),
789
+ react_jsx_runtime.jsxs("div", { style: { display: "flex", gap: 6, alignItems: "center", flexWrap: "wrap" }, children: [
790
+ react_jsx_runtime.jsx("span", { className: "wsc-badge" + (configured ? " wsc-badgeOn" : ""), children: state.keyState[b.keyEnv]?.pending === true ? props.t("keyChecking") : configured ? props.t("keySet") : props.t("keyUnset") }),
791
+ readOnly && react_jsx_runtime.jsx("span", { className: "wsc-badge", style: { opacity: .75 }, children: props.t("envProvided") }),
792
+ KEY_URLS[b.id] && react_jsx_runtime.jsx("a", {
793
+ href: KEY_URLS[b.id], target: "_blank", rel: "noreferrer",
794
+ style: { fontSize: 11, color: "var(--dsw-alias-link)", textDecoration: "none" },
795
+ children: props.t("getKey"),
796
+ }),
797
+ ] }),
798
+ react_jsx_runtime.jsx("input", {
799
+ className: "wsc-keyInput", type: "password", autoComplete: "off",
800
+ "aria-label": props.t("keyLabel", { id: props.t("backend" + b.id.charAt(0).toUpperCase() + b.id.slice(1)) }),
801
+ disabled: readOnly,
802
+ placeholder: readOnly ? props.t("readOnly") : b.keyEnv,
803
+ value: state.stagedKeys[b.keyEnv] ?? "",
804
+ onChange: (e) => props.onEditKey(b.keyEnv, e.target.value),
805
+ }),
806
+ react_jsx_runtime.jsx("p", { className: "wsc-hint", children: props.t("keySaveModeHint") }),
807
+ failure && react_jsx_runtime.jsx("p", { className: "wsc-hint wsc-error", children: props.t("keyFailed") + (failure.reason ? ": " + failure.reason : "") }),
808
+ readFailure && react_jsx_runtime.jsx("p", { className: "wsc-hint wsc-warn", children: props.t("keyReadFailed") }),
809
+ ] });
810
+ }
811
+
460
812
  /** Labeled <select> for enum / boolean settings. */
461
813
  function SelectField(props) {
462
814
  return react_jsx_runtime.jsxs("div", { children: [
463
815
  react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: props.label }) }),
464
816
  react_jsx_runtime.jsx("select", {
465
817
  className: "wsc-input",
818
+ "aria-label": props.label,
466
819
  value: props.value,
467
820
  onChange: (e) => props.onChange(e.target.value),
468
821
  children: props.options.map((o) =>
@@ -473,169 +826,251 @@ window.__ModuleLoader__.load({
473
826
  }
474
827
 
475
828
  /** The card root. */
476
- function UnifiedSearchSection(props) {
477
- const state = props.useUnifiedSearchCard((snapshot) => snapshot);
478
- const card = { edit: props.edit, setToggle: props.setToggle, reset: props.reset, editKey: props.editKey, save: props.save, discard: props.discard };
479
- // Occupants of settings.plugin.item render inside the tab's <ul>; use <li>.
480
- if (!state.ready) {
481
- return react_jsx_runtime.jsx("div", { className: "wsc-card", style: { fontSize: 12, opacity: .6 }, children: "…" });
482
- }
483
-
484
- const toggleField = (id) => "enable" + id.charAt(0).toUpperCase() + id.slice(1);
485
-
486
- // Status summary: enabled backends + configured keys at a glance.
487
- const enabledCount = BACKENDS.filter((b) => state.value[toggleField(b.id)] === true).length;
488
- const keyedBackends = BACKENDS.filter((b) => b.keyEnv && !b.optionalKey);
489
- const keysReady = keyedBackends.filter((b) => state.keyState[b.keyEnv]?.configured).length;
490
-
491
- const recencyOptions = [
492
- { value: "any", label: props.t("recencyAny") },
493
- { value: "day", label: props.t("recencyDay") },
494
- { value: "week", label: props.t("recencyWeek") },
495
- { value: "month", label: props.t("recencyMonth") },
496
- { value: "year", label: props.t("recencyYear") },
497
- ];
498
- const dedupOptions = [
499
- { value: "url", label: props.t("dedupUrl") },
500
- { value: "url+title", label: props.t("dedupTitle") },
501
- ];
502
- const boolOptions = [
503
- { value: "true", label: props.t("on") },
504
- { value: "false", label: props.t("off") },
505
- ];
506
- const selVal = (f, dflt) => state.stagedText(f) ?? String(state.value[f] ?? dflt);
507
-
508
- return react_jsx_runtime.jsxs("div", { className: "wsc-card", children: [
509
- react_jsx_runtime.jsx("div", { style: { display: "flex", gap: 14, alignItems: "center", padding: "10px 12px", marginBottom: 10, borderRadius: 8, background: "rgba(127,127,127,.08)", fontSize: 13 }, children: [
510
- react_jsx_runtime.jsxs("span", { children: [props.t("statusEnabled"), ": ", react_jsx_runtime.jsx("b", { children: enabledCount + "/" + BACKENDS.length })] }),
511
- react_jsx_runtime.jsxs("span", { children: [props.t("statusKeys"), ": ", react_jsx_runtime.jsx("b", { children: keysReady + "/" + keyedBackends.length })] }),
829
+ /**
830
+ * Status strip above the settings form: enabled / keyed counts plus the
831
+ * three advisories (all-off fallback, read-only scope, metered default-off).
832
+ * @param {object} props { state, enabledCount, keysReady, t }
833
+ */
834
+ function StatusSummary(props) {
835
+ const { state, enabledCount, keysReady, hasOverride, t } = props;
836
+ return react_jsx_runtime.jsxs(react_jsx_runtime.Fragment, { children: [
837
+ react_jsx_runtime.jsx("div", { className: "wsc-strip", style: { display: "flex", gap: 14, alignItems: "center", padding: "10px 12px" }, children: [
838
+ react_jsx_runtime.jsxs("span", { children: [t("statusEnabled"), ": ", react_jsx_runtime.jsx("b", { children: enabledCount + "/" + BACKENDS.length })] }),
839
+ react_jsx_runtime.jsxs("span", { children: [t("statusKeys"), ": ", react_jsx_runtime.jsx("b", { children: keysReady + "/" + KEYED.length })] }),
840
+ METERED.length > 0 && react_jsx_runtime.jsxs("span", { style: { opacity: .65 }, children: [
841
+ t("statusMetered"), ": ", METERED.length, " ", t("statusOffByDefault"),
842
+ ] }),
512
843
  ] }),
513
- react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, opacity: .65 }, children: props.t("description") }),
514
- (enabledCount === 0) && react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, color: "#e6a700" }, children: props.t("fallbackHint") }),
515
- (state.writable === false) && react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, color: "#e6a700" }, children: props.t("readOnlyScope") }),
516
- react_jsx_runtime.jsx("h5", { className: "wsc-sectionTitle", children: props.t("groupFree") }),
844
+ react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, opacity: .65 }, children: t("description") }),
845
+ (!hasOverride && enabledCount === 0) && react_jsx_runtime.jsx("p", { className: "wsc-warn", style: { margin: 0, fontSize: 12 }, children: t("fallbackHint") }),
846
+ (state.writable === false) && react_jsx_runtime.jsx("p", { className: "wsc-warn", style: { margin: 0, fontSize: 12 }, children: t("readOnlyScope") }),
847
+ ] });
848
+ }
849
+
850
+ /**
851
+ * The three backend groups: keyless toggles, keyed cards, and the metered
852
+ * opt-in section. The metered group keeps its own header and hint so it is
853
+ * never silently mixed into "keyless".
854
+ * @param {object} props { state, card, toggleField, t }
855
+ */
856
+ function BackendToggles(props) {
857
+ const { state, card, toggleField, t } = props;
858
+ return react_jsx_runtime.jsxs(react_jsx_runtime.Fragment, { children: [
859
+ react_jsx_runtime.jsx("h5", { className: "wsc-sectionTitle", children: t("groupFree") }),
517
860
  react_jsx_runtime.jsx("div", { className: "wsc-toggles", children: KEYLESS.map((b) =>
518
861
  react_jsx_runtime.jsx(ToggleRow, {
519
862
  backend: b,
520
863
  value: state.value[toggleField(b.id)],
521
864
  keyConfigured: true,
522
- t: props.t,
865
+ toggleError: state.toggleErrorId === b.id,
866
+ t,
523
867
  onChange: (checked) => card.setToggle(b.id, checked),
524
868
  }, b.id)
525
869
  ) }),
526
- react_jsx_runtime.jsx("h5", { className: "wsc-sectionTitle", children: props.t("groupKeyed") }),
527
- react_jsx_runtime.jsx("div", { className: "wsc-toggles", children: KEYED.map((b) =>
528
- react_jsx_runtime.jsx(ToggleRow, {
870
+ react_jsx_runtime.jsx("h5", { className: "wsc-sectionTitle", children: t("groupKeyed") }),
871
+ // The switch and the credential input are one card per backend.
872
+ react_jsx_runtime.jsx("div", { className: "wsc-grid", children: KEYED.map((b) =>
873
+ react_jsx_runtime.jsx(KeyedBackendCard, {
529
874
  backend: b,
875
+ state,
530
876
  value: state.value[toggleField(b.id)],
531
- keyConfigured: !!state.keyState[b.keyEnv]?.configured,
532
- t: props.t,
533
- onChange: (checked) => card.setToggle(b.id, checked),
877
+ t,
878
+ onToggle: (checked) => card.setToggle(b.id, checked),
879
+ onEditKey: (ref, text) => card.editKey(ref, text),
534
880
  }, b.id)
535
881
  ) }),
536
- react_jsx_runtime.jsx("h4", { className: "wsc-sectionTitle", children: props.t("globalsTitle") }),
882
+ METERED.length > 0 && react_jsx_runtime.jsxs(react_jsx_runtime.Fragment, { children: [
883
+ react_jsx_runtime.jsx("h5", { className: "wsc-sectionTitle", children: t("groupMetered") }),
884
+ react_jsx_runtime.jsx("p", { style: { margin: "0 0 6px", fontSize: 11, opacity: .6 }, children: t("meteredHint") }),
885
+ react_jsx_runtime.jsx("div", { className: "wsc-toggles", children: METERED.map((b) =>
886
+ react_jsx_runtime.jsx(ToggleRow, {
887
+ backend: b,
888
+ value: state.value[toggleField(b.id)],
889
+ keyConfigured: true,
890
+ toggleError: state.toggleErrorId === b.id,
891
+ t,
892
+ onChange: (checked) => card.setToggle(b.id, checked),
893
+ }, b.id)
894
+ ) }),
895
+ ] }),
896
+ ] });
897
+ }
898
+
899
+ /**
900
+ * Global limits and result-shaping fields (rendered as inputs and selects).
901
+ * @param {object} props { state, card, t }
902
+ */
903
+ function SettingsFields(props) {
904
+ const { state, card, t } = props;
905
+ const selVal = (f, dflt) => state.stagedText(f) ?? String(state.value[f] ?? dflt);
906
+ const recencyOptions = [
907
+ { value: "any", label: t("recencyAny") },
908
+ { value: "day", label: t("recencyDay") },
909
+ { value: "week", label: t("recencyWeek") },
910
+ { value: "month", label: t("recencyMonth") },
911
+ { value: "year", label: t("recencyYear") },
912
+ ];
913
+ const dedupOptions = [
914
+ { value: "url", label: t("dedupUrl") },
915
+ { value: "url+title", label: t("dedupTitle") },
916
+ ];
917
+ const boolOptions = [
918
+ { value: "true", label: t("on") },
919
+ { value: "false", label: t("off") },
920
+ ];
921
+ const interventionOptions = [
922
+ { value: "official", label: t("interventionOfficial") },
923
+ { value: "balanced", label: t("interventionBalanced") },
924
+ { value: "thorough", label: t("interventionThorough") },
925
+ ];
926
+ return react_jsx_runtime.jsxs(react_jsx_runtime.Fragment, { children: [
927
+ react_jsx_runtime.jsx("h4", { className: "wsc-sectionTitle", children: t("interventionLabel") }),
928
+ react_jsx_runtime.jsx("div", { className: "wsc-grid", children: react_jsx_runtime.jsx(SelectField, {
929
+ label: t("interventionLabel"),
930
+ value: selVal("intervention", "balanced"),
931
+ options: interventionOptions,
932
+ onChange: (v) => card.edit("intervention", v),
933
+ }) }),
934
+ react_jsx_runtime.jsx("p", { className: "wsc-hint", children: t("interventionHint") }),
935
+ react_jsx_runtime.jsx("h4", { className: "wsc-sectionTitle", children: t("globalsTitle") }),
537
936
  react_jsx_runtime.jsxs("div", { className: "wsc-grid", children: [
538
937
  react_jsx_runtime.jsxs("div", { children: [
539
- react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: "numResults" }) }),
540
- react_jsx_runtime.jsx("input", { className: "wsc-input", value: state.stagedText("numResults") ?? String(state.value.numResults ?? ""), onChange: e => card.edit("numResults", e.target.value), inputMode: "numeric" }),
938
+ react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: t("numResultsLabel") }) }),
939
+ react_jsx_runtime.jsx("input", { className: "wsc-input", "aria-label": t("numResultsLabel"), value: state.stagedText("numResults") ?? String(state.value.numResults ?? ""), onChange: (e) => card.edit("numResults", e.target.value), inputMode: "numeric" }),
541
940
  ] }),
542
941
  react_jsx_runtime.jsxs("div", { children: [
543
- react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: "concurrency" }) }),
544
- react_jsx_runtime.jsx("input", { className: "wsc-input", value: state.stagedText("concurrency") ?? String(state.value.concurrency ?? ""), onChange: e => card.edit("concurrency", e.target.value), inputMode: "numeric" }),
942
+ react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: t("concurrencyLabel") }) }),
943
+ react_jsx_runtime.jsx("input", { className: "wsc-input", "aria-label": t("concurrencyLabel"), value: state.stagedText("concurrency") ?? String(state.value.concurrency ?? ""), onChange: (e) => card.edit("concurrency", e.target.value), inputMode: "numeric" }),
545
944
  ] }),
546
945
  react_jsx_runtime.jsxs("div", { children: [
547
- react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: "backendTimeoutMs" }) }),
548
- react_jsx_runtime.jsx("input", { className: "wsc-input", value: state.stagedText("backendTimeoutMs") ?? String(state.value.backendTimeoutMs ?? ""), onChange: e => card.edit("backendTimeoutMs", e.target.value), inputMode: "numeric" }),
946
+ react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: t("timeoutLabel") }) }),
947
+ react_jsx_runtime.jsx("input", { className: "wsc-input", "aria-label": t("timeoutLabel"), value: state.stagedText("backendTimeoutMs") ?? String(state.value.backendTimeoutMs ?? ""), onChange: (e) => card.edit("backendTimeoutMs", e.target.value), inputMode: "numeric" }),
549
948
  ] }),
550
949
  ] }),
551
- react_jsx_runtime.jsx("h4", { className: "wsc-sectionTitle", children: props.t("shapingTitle") }),
950
+ react_jsx_runtime.jsx("h4", { className: "wsc-sectionTitle", children: t("shapingTitle") }),
552
951
  react_jsx_runtime.jsxs("div", { className: "wsc-grid", children: [
553
- react_jsx_runtime.jsx(SelectField, {
554
- label: props.t("recencyLabel"),
555
- value: selVal("recency", "any"),
556
- options: recencyOptions,
557
- onChange: (v) => card.edit("recency", v),
558
- }),
952
+ // A language tag is free text ("en", "zh-CN", …), not an enum: keeping
953
+ // it as a select with no options threw on render.
559
954
  react_jsx_runtime.jsxs("div", { children: [
560
- react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: props.t("langLabel") }) }),
955
+ react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: t("langLabel") }) }),
561
956
  react_jsx_runtime.jsx("input", {
562
957
  className: "wsc-input",
563
- placeholder: props.t("langPlaceholder"),
958
+ "aria-label": t("langLabel"),
959
+ placeholder: t("langPlaceholder"),
564
960
  value: state.stagedText("language") ?? String(state.value.language ?? ""),
565
- onChange: e => card.edit("language", e.target.value),
961
+ onChange: (e) => card.edit("language", e.target.value),
566
962
  }),
567
963
  ] }),
568
- react_jsx_runtime.jsx(SelectField, {
569
- label: props.t("dedupLabel"),
570
- value: selVal("dedupStrategy", "url"),
571
- options: dedupOptions,
572
- onChange: (v) => card.edit("dedupStrategy", v),
573
- }),
574
- react_jsx_runtime.jsx(SelectField, {
575
- label: props.t("rerankLabel"),
576
- value: selVal("rerank", "false"),
577
- options: boolOptions,
578
- onChange: (v) => card.edit("rerank", v),
579
- }),
580
- react_jsx_runtime.jsx(SelectField, {
581
- label: props.t("safeSearchLabel"),
582
- value: selVal("safeSearch", "true"),
583
- options: boolOptions,
584
- onChange: (v) => card.edit("safeSearch", v),
585
- }),
586
- react_jsx_runtime.jsx(SelectField, {
587
- label: props.t("telemetryLabel"),
588
- value: selVal("resultTelemetry", "true"),
589
- options: boolOptions,
590
- onChange: (v) => card.edit("resultTelemetry", v),
591
- }),
964
+ react_jsx_runtime.jsx(SelectField, { label: t("recencyLabel"), value: selVal("recency", "any"), options: recencyOptions, onChange: (v) => card.edit("recency", v) }),
965
+ react_jsx_runtime.jsx(SelectField, { label: t("dedupLabel"), value: selVal("dedupStrategy", "url"), options: dedupOptions, onChange: (v) => card.edit("dedupStrategy", v) }),
966
+ react_jsx_runtime.jsx(SelectField, { label: t("rerankLabel"), value: selVal("rerank", "false"), options: boolOptions, onChange: (v) => card.edit("rerank", v) }),
967
+ react_jsx_runtime.jsx(SelectField, { label: t("safeSearchLabel"), value: selVal("safeSearch", "true"), options: boolOptions, onChange: (v) => card.edit("safeSearch", v) }),
968
+ react_jsx_runtime.jsx(SelectField, { label: t("telemetryLabel"), value: selVal("resultTelemetry", "true"), options: boolOptions, onChange: (v) => card.edit("resultTelemetry", v) }),
969
+ react_jsx_runtime.jsx(SelectField, { label: t("resultHeaderLabel"), value: selVal("resultHeader", "true"), options: boolOptions, onChange: (v) => card.edit("resultHeader", v) }),
592
970
  ] }),
593
- react_jsx_runtime.jsx("h4", { className: "wsc-sectionTitle", children: props.t("keysTitle") }),
594
- react_jsx_runtime.jsx("div", { className: "wsc-grid", children: BACKENDS.filter((b) => b.keyEnv && !b.optionalKey).map((b) =>
595
- react_jsx_runtime.jsxs("div", { children: [
971
+ ] });
972
+ }
973
+
974
+ /**
975
+ * The optional-key grid (private instances / metered limits) and the save bar.
976
+ * @param {object} props { state, card, t }
977
+ */
978
+ function OptionalKeysAndActions(props) {
979
+ const { state, card, t } = props;
980
+ return react_jsx_runtime.jsxs(react_jsx_runtime.Fragment, { children: [
981
+ react_jsx_runtime.jsx("h5", { className: "wsc-sectionTitle", children: t("optionalTitle") }),
982
+ react_jsx_runtime.jsx("div", { className: "wsc-grid", children: OPTIONAL_KEYS.map((b) => {
983
+ // failedKeys is [{ref, reason}], not a string array: the old
984
+ // `.includes(b.keyEnv)` never matched, so failures stayed silent.
985
+ const failure = (state.failedKeys ?? []).find((f) => f && f.ref === b.keyEnv);
986
+ const readFailure = (state.readErrors ?? []).find((f) => f && f.ref === b.keyEnv);
987
+ return react_jsx_runtime.jsxs("div", { children: [
596
988
  react_jsx_runtime.jsxs("div", { className: "wsc-fieldHead", children: [
597
- react_jsx_runtime.jsx("span", { className: "wsc-label", children: props.t("keyLabel", { id: b.id }) }),
598
- react_jsx_runtime.jsxs("span", { className: "wsc-badges", style: { display: "flex", gap: 6, alignItems: "center" }, children: [
599
- KEY_URLS[b.id] && react_jsx_runtime.jsx("a", {
600
- href: KEY_URLS[b.id], target: "_blank", rel: "noreferrer",
601
- style: { fontSize: 11, color: "var(--dsw-alias-accent-primary)", textDecoration: "none" },
602
- children: props.t("getKey"),
603
- }),
604
- react_jsx_runtime.jsx("span", { className: "wsc-badge" + (state.keyState[b.keyEnv]?.configured ? " wsc-badgeOn" : ""), children: state.keyState[b.keyEnv]?.configured ? props.t("keySet") : props.t("keyUnset") }),
605
- state.keyState[b.keyEnv]?.configured && state.keyState[b.keyEnv]?.writable === false && react_jsx_runtime.jsx("span", { className: "wsc-badge", style: { opacity: .75 }, children: props.t("envProvided") }),
606
- ] }),
989
+ react_jsx_runtime.jsx("span", { className: "wsc-label", children: t("keyLabel", { id: t("backend" + b.id.charAt(0).toUpperCase() + b.id.slice(1)) }) }),
990
+ react_jsx_runtime.jsx("span", { className: "wsc-badge" + (state.keyState[b.keyEnv]?.configured ? " wsc-badgeOn" : ""), children: state.keyState[b.keyEnv]?.pending === true ? t("keyChecking") : state.keyState[b.keyEnv]?.configured ? t("keySet") : t("keyUnset") }),
607
991
  ] }),
608
992
  react_jsx_runtime.jsx("input", {
609
993
  className: "wsc-keyInput", type: "password", autoComplete: "off",
994
+ "aria-label": t("keyLabel", { id: t("backend" + b.id.charAt(0).toUpperCase() + b.id.slice(1)) }),
610
995
  disabled: state.keyState[b.keyEnv]?.configured && state.keyState[b.keyEnv]?.writable === false,
611
- placeholder: (state.keyState[b.keyEnv]?.configured && state.keyState[b.keyEnv]?.writable === false) ? props.t("readOnly") : b.keyEnv,
612
- value: state.stagedKeys[b.keyEnv] ?? "",
613
- onChange: (e) => card.editKey(b.keyEnv, e.target.value),
614
- }),
615
- react_jsx_runtime.jsx("p", { className: "wsc-hint", children: props.t("keyHint") }),
616
- state.failedKeys.includes(b.keyEnv) && react_jsx_runtime.jsx("p", { className: "wsc-hint", style: { color: "#e5534b" }, children: props.t("keyFailed") }),
617
- ] }, b.id)
618
- ) }),
619
- react_jsx_runtime.jsx("h5", { className: "wsc-sectionTitle", children: props.t("optionalTitle") }),
620
- react_jsx_runtime.jsx("div", { className: "wsc-grid", children: OPTIONAL_KEYS.map((b) =>
621
- react_jsx_runtime.jsxs("div", { children: [
622
- react_jsx_runtime.jsx("div", { className: "wsc-fieldHead", children: react_jsx_runtime.jsx("span", { className: "wsc-label", children: props.t("keyLabel", { id: b.id }) }) }),
623
- react_jsx_runtime.jsx("input", {
624
- className: "wsc-keyInput", type: "password", autoComplete: "off",
625
996
  placeholder: b.keyEnv,
626
997
  value: state.stagedKeys[b.keyEnv] ?? "",
627
998
  onChange: (e) => card.editKey(b.keyEnv, e.target.value),
628
999
  }),
629
- ] }, b.id),
630
- ) }),
631
- state.stagedCount > 0 && react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, opacity: .6 }, children: props.t("unsavedHint") }),
632
- react_jsx_runtime.jsxs("div", { className: "wsc-actions", children: [
633
- react_jsx_runtime.jsx("button", { className: "wsc-btn", disabled: state.saving || state.stagedCount === 0 || state.writable === false, onClick: () => card.save(), children: state.saving ? props.t("saving") : props.t("save") }),
634
- (state.stagedCount > 0) && react_jsx_runtime.jsx("button", { className: "wsc-btn wsc-btnGhost", onClick: () => card.discard(), children: props.t("discard") }),
635
- state.failed && react_jsx_runtime.jsx("span", { className: "wsc-status", style: { color: "#e5534b" }, children: props.t("failed") }),
636
- (state.failedFields.length > 0) && react_jsx_runtime.jsx("span", { className: "wsc-status", style: { color: "#e5534b", fontSize: 11 }, children: props.t("invalidFields") + ": " + state.failedFields.join(", ") }),
637
- state.conflict && react_jsx_runtime.jsx("span", { className: "wsc-status", style: { color: "#e6a700" }, children: props.t("conflict") }),
638
- !state.failed && !state.saving && state.savedAt > 0 && react_jsx_runtime.jsx("span", { className: "wsc-status", style: { color: "#2ea043" }, children: props.t("savedOk") }),
1000
+ react_jsx_runtime.jsx("p", { className: "wsc-hint", children: t("keySaveModeHint") }),
1001
+ failure && react_jsx_runtime.jsx("p", { className: "wsc-hint wsc-error", children: t("keyFailed") + (failure.reason ? ": " + failure.reason : "") }),
1002
+ readFailure && react_jsx_runtime.jsx("p", { className: "wsc-hint wsc-warn", children: t("keyReadFailed") }),
1003
+ ] }, b.id);
1004
+ }) }),
1005
+ state.stagedCount > 0 && react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, opacity: .65 }, children: t("unsavedHint") }),
1006
+ react_jsx_runtime.jsxs("div", { className: "wsc-actions", role: "status", "aria-live": "polite", children: [
1007
+ react_jsx_runtime.jsx("button", { className: "wsc-btn", disabled: state.saving || state.stagedCount === 0 || state.writable === false, onClick: () => card.save(), children: state.saving ? t("saving") : t("save") }),
1008
+ (state.stagedCount > 0) && react_jsx_runtime.jsx("button", { className: "wsc-btn wsc-btnGhost", disabled: state.saving, onClick: () => card.discard(), children: t("discard") }),
1009
+ state.failed && react_jsx_runtime.jsx("span", { className: "wsc-status wsc-error", children: state.conflict ? t("conflict") : t("saveFailed") }),
1010
+ state.toggleFailed && react_jsx_runtime.jsx("span", { className: "wsc-status wsc-error", children: t("toggleFailed") + (state.toggleConflict ? " — " + t("conflict") : "") }),
1011
+ (state.failedFields.length > 0) && react_jsx_runtime.jsx("span", { className: "wsc-status wsc-warn", children: t("invalidFields") + " " + state.failedFields.join(", ") }),
1012
+ state.conflict && react_jsx_runtime.jsx("span", { className: "wsc-status wsc-warn", children: t("conflictHint") }),
1013
+ !state.failed && !state.saving && state.savedAt > 0 && react_jsx_runtime.jsx("span", { className: "wsc-status", children: t("savedOk") }),
1014
+ ] }),
1015
+ ] });
1016
+ }
1017
+
1018
+ function UnifiedSearchSection(props) {
1019
+ const state = props.useUnifiedSearchCard((snapshot) => snapshot);
1020
+ const card = { edit: props.edit, setToggle: props.setToggle, reset: props.reset, editKey: props.editKey, save: props.save, discard: props.discard };
1021
+ // Occupants of settings.plugin.item render inside the tab's <ul>; use <li>.
1022
+ if (!state.ready) {
1023
+ return react_jsx_runtime.jsx("div", { className: "wsc-card", style: { fontSize: 12, opacity: .6 }, children: "…" });
1024
+ }
1025
+ // No snapshot at all (404/503): showing "0/13 enabled" plus live
1026
+ // controls would be a fabricated state. Explain it and offer a retry.
1027
+ if (state.unavailable) {
1028
+ return react_jsx_runtime.jsxs("div", { className: "wsc-card", children: [
1029
+ react_jsx_runtime.jsx("p", { style: { margin: 0, fontSize: 12, opacity: .75 }, children: props.t("unavailable") }),
1030
+ react_jsx_runtime.jsx("div", { className: "wsc-actions", children: react_jsx_runtime.jsx("button", { className: "wsc-btn", onClick: () => props.retry(), children: props.t("retry") }) }),
1031
+ ] });
1032
+ }
1033
+
1034
+ const toggleField = (id) => "enable" + id.charAt(0).toUpperCase() + id.slice(1);
1035
+
1036
+ // Status summary: enabled backends + configured keys at a glance.
1037
+ const override = Array.isArray(state.value.enabledBackends)
1038
+ ? state.value.enabledBackends.filter((id) => BACKENDS.some((b) => b.id === id))
1039
+ : [];
1040
+ // An explicit enabledBackends list wins over the toggles in the engine,
1041
+ // so the status strip and the all-off hint must describe that list, not
1042
+ // the toggle positions the engine ignores.
1043
+ const enabledCount = override.length > 0
1044
+ ? override.length
1045
+ : BACKENDS.filter((b) => state.value[toggleField(b.id)] === true).length;
1046
+ const keysReady = KEYED.filter((b) => state.keyState[b.keyEnv]?.configured).length;
1047
+
1048
+ const recencyOptions = [
1049
+ { value: "any", label: props.t("recencyAny") },
1050
+ { value: "day", label: props.t("recencyDay") },
1051
+ { value: "week", label: props.t("recencyWeek") },
1052
+ { value: "month", label: props.t("recencyMonth") },
1053
+ { value: "year", label: props.t("recencyYear") },
1054
+ ];
1055
+ const dedupOptions = [
1056
+ { value: "url", label: props.t("dedupUrl") },
1057
+ { value: "url+title", label: props.t("dedupTitle") },
1058
+ ];
1059
+ const boolOptions = [
1060
+ { value: "true", label: props.t("on") },
1061
+ { value: "false", label: props.t("off") },
1062
+ ];
1063
+ const selVal = (f, dflt) => state.stagedText(f) ?? String(state.value[f] ?? dflt);
1064
+
1065
+ return react_jsx_runtime.jsxs("div", { className: "wsc-card", children: [
1066
+ react_jsx_runtime.jsx(StatusSummary, { state, enabledCount, hasOverride: override.length > 0, keysReady, t: props.t }),
1067
+ // A read-only snapshot (scope locked by the host) must not render
1068
+ // live toggles: fieldset disabled disables every descendant input,
1069
+ // select and button without relying on each call site.
1070
+ react_jsx_runtime.jsxs("fieldset", { disabled: state.writable === false, style: { border: 0, margin: 0, padding: 0, minWidth: 0 }, children: [
1071
+ react_jsx_runtime.jsx(BackendToggles, { state, card, toggleField, t: props.t }),
1072
+ react_jsx_runtime.jsx(SettingsFields, { state, card, t: props.t }),
1073
+ react_jsx_runtime.jsx(OptionalKeysAndActions, { state, card, t: props.t }),
639
1074
  ] }),
640
1075
  ] });
641
1076
  }
@@ -646,7 +1081,12 @@ window.__ModuleLoader__.load({
646
1081
  * the 0.2.x line; the card binds whichever data source the build offers
647
1082
  * (see selectBridge) and registers the section unconditionally.
648
1083
  */
649
- const inject = ["slots", "locale", "connection", "remote"];
1084
+ // DSH 0.2.x registers each remote namespace as its own service key
1085
+ // (`remote.<namespace>`). Undeclared access throws instead of returning
1086
+ // undefined, so the namespace must be declared in inject for key saves
1087
+ // and credential reads. The official settings models plugin declares
1088
+ // the same key.
1089
+ const inject = ["slots", "locale", "connection", "remote", "remote.credentials"];
650
1090
  /**
651
1091
  * Resolve the settings data source for this build, in order:
652
1092
  * 1. the legacy `settingsScope` service (DSH <= 0.1.6 line, or a shim);
@@ -672,12 +1112,15 @@ window.__ModuleLoader__.load({
672
1112
  ctx.get("connection"),
673
1113
  ctx.get("remote"),
674
1114
  );
1115
+ // The store subscription and late fetch responses outlive the section
1116
+ // unless the controller is detached with the plugin.
1117
+ ctx.effect(() => () => controller.dispose(), "websearch: card controller");
675
1118
  // Credential invalidations: 0.2.x forwards `credentials/reference-updated`;
676
1119
  // older lines forwarded `credentials/updated`. Subscribe to whichever
677
1120
  // event face this build exposes; a missing face must not abort apply().
678
1121
  for (const event of ["credentials/reference-updated", "credentials/updated"]) {
679
1122
  try {
680
- ctx.effect(() => ctx.remote.$on(event, () => controller.refreshAllCredentials()), "websearch: credential invalidations");
1123
+ ctx.effect(() => ctx.remote.$on(event, (ref) => (typeof ref === "string" ? controller.readCredential(ref) : controller.refreshAllCredentials())), "websearch: credential invalidations");
681
1124
  } catch (_noEventFace) { /* this build does not forward that event */ }
682
1125
  }
683
1126
  // Re-read when another client saves this namespace (settings document
@@ -705,22 +1148,25 @@ window.__ModuleLoader__.load({
705
1148
  try {
706
1149
  if (window.__dshDevkit && typeof window.__dshDevkit.toast === "function") {
707
1150
  window.__dshDevkit.toast(hint, { kind: "info" });
708
- return;
1151
+ } else {
1152
+ console.info("[dsh-websearch] " + hint);
709
1153
  }
710
- } catch (e) { /* fall through */ }
711
- console.info("[dsh-websearch] " + hint);
1154
+ } catch (e) { /* best-effort notification */ }
1155
+ try {
1156
+ window.dispatchEvent(new CustomEvent("dsh-websearch:open-settings:ack"));
1157
+ } catch (e) { /* CustomEvent unavailable */ }
712
1158
  };
713
1159
  // Probe contract (devkit 0.1.1): ready flag + ack event, so the
714
1160
  // palette can tell "listener present" from "gracefully absent".
715
1161
  try {
716
1162
  window.__dshWebsearchSettingsReady = true;
717
- window.addEventListener("dsh-websearch:open-settings", (ev) => {
718
- onOpenSettings(ev);
719
- try {
720
- window.dispatchEvent(new CustomEvent("dsh-websearch:open-settings:ack"));
721
- } catch (e) { /* CustomEvent unavailable */ }
722
- });
723
- ctx.effect(() => () => window.removeEventListener("dsh-websearch:open-settings", onOpenSettings), "websearch: open-settings listener");
1163
+ // Remove the exact function that was added: an anonymous listener
1164
+ // cannot be removed, so every reload used to stack another one.
1165
+ window.addEventListener("dsh-websearch:open-settings", onOpenSettings);
1166
+ ctx.effect(() => () => {
1167
+ window.removeEventListener("dsh-websearch:open-settings", onOpenSettings);
1168
+ window.__dshWebsearchSettingsReady = false;
1169
+ }, "websearch: open-settings listener");
724
1170
  } catch (e) { /* non-window env */ }
725
1171
  }
726
1172